texts:
I have been working my way through the exercises in the book Cracking the Coding Interview.  I wanted to get feedback for the following exercise.

  Write a method to replace all spaces in a string with '%20'.  You may assume that the string has sufficient space at the end to hold the additional characters and that you are given the true length of the string.

  Example:

  Input: "Mr_John_Smith____ ", 13
  Output: "Mr%20John%20Smith"

  Note: I am using '_' to represent spaces above because I could not get spaces to format nicely.

I would be interested in feedback on my code and time/space complexity computation below, and would also be interested to know if there is any way to improve the time or space complexity of my code.

def urlify(in_string, in_string_length):
    in_string = list(in_string)
    for position, character in reversed(list(enumerate(in_string[0:in_string_length]))):
        if character == ' ':
            in_string[position + 3:in_string_length + 2] = in_string[position + 1:in_string_length]
            in_string[position:position + 3] = '%20'
            in_string_length += 2
    return ''.join(in_string)

My guess is that the time complexity of the code above is \$O(1(n - s) +sn)\$ where \$n\$ is the length of the input string, \$ s\$ is the number of spaces in the input string (not including trailing spaces).

My reasoning is that if there are 0 spaces then the for loop will only do constant work checking the if statement and then perform the join at the end which all together is \$O(n)\$ whereas in the other extreme case where there are \$n\$ spaces, the work done will be \$O(n^{2})\$.  Lastly I think the space complexity is \$O(n).\$


texts:
I have this code in my ViewModel which searches a List of Items, the OnSearchAsync(string searchQuery) gets executed by a Command which is bound to TextChanged Entry Event

The ObservableCollection<Items> Collection is bound to CollectionView. There are 200 Items max in this Collection

I'm wondering if my Code could be improved or if I'm doing this wrong.

private async void OnSearchAsync(string searchQuery)
{
    if (string.IsNullOrEmpty(searchQuery) || searchQuery.Length < 2)
    {
        if (Items?.Count == _backupItems.Count)
        {
            return;
        }

        Items = new ObservableCollection<Item>(_backupItems);
        await RaisePropertyChanged(nameof(Items));
        return;
    }

    try
    {
        await Task.Run(async () =>
        {
            var result = Search(searchQuery);
            if (result == null)
            {
                Items = null;
                return;
            }

            var results = result.ToList();
            if (results.Count == 0)
            {
                Items = null;
                return;
            }

            Items = new ObservableCollection<Item>(results);
            await RaisePropertyChanged(nameof(Items));

        }
        catch (Exception ex)
        {
            _logger.Error(this, ex);
        }
}

   public IEnumerable<Item> Search(string text)
   {
        try
        {
            return _backupItems.Where(x => x.Property1.Text.CaseContains(text) ||
                                        x.Property2.Text.CaseContains(text) ||
                                        x.Property3.Text.CaseContains(text) ||
                                        x.Property4.Text.CaseContains(text));
        }
        catch (Exception ex)
        {
            _logger.Error(this, ex);
        }
        return null;
 }


texts: Functional abstraction to find nth root of a number - Newton raphson

texts:
Below is the solution:

def approx_deriv(fn, x, dx=0.00001):
    return (fn(x + dx) - fn(x))/dx

def improve(update, isdone, guess=1, max_iterations=100):
    def recur_improve(guess, i):
        if i > max_iterations or isdone(guess):
           return guess
        else:
           return recur_improve(update(guess), i + 1)
    return recur_improve(guess, 1)

def newtons_method(fn, guess =1, max_iterations=100):
    def newtons_update(guess):
        return guess - fn(guess) / approx_deriv(fn, guess)
    def newtons_isdone(guess):
        ALLOWED_ERROR_MARGIN = 0.0000001
        return abs(fn(guess)) <= ALLOWED_ERROR_MARGIN
    return improve(newtons_update,
                        newtons_isdone,
                        max_iterations)

def nth_root(rootfunc, x):
    return rootfunc(x)

Test output:

>python -i nth_root.py
>>> def cuberoot(x):
...     return newtons_method(lambda y: y * y * y - x)
...
>>> result = nth_root(cuberoot, 27)
>>> result
3.000000000000141
>>>

My question:

Above is the functional abstraction for finding the \$n_{th}\$ root of a number. Is it possible to improve this abstraction?


texts: Counting first letter of title and printing letters from a to z

texts:
I am trying to count the titles according to the first letter and filter it by the tag.

I tried for ages and I am not sure if I can write this query in a better way.
Can you please advise me.

Here is the sqlfiddle link:
http://sqlfiddle.com/#!9/3155cd/2

My query:

SELECT letter.letter as firstLetter, COUNT(item_tag.id) AS itemCount
        FROM letter
        left outer join item
             on left(item.title, 1) = letter.letter
        left outer join item_tag
            ON item_tag.item_id = item.id
        AND item_tag.tag_id = 1
        GROUP BY letter.letter

Here is my tables:

Item:

+----+-----------------+
| id |      title      |
+----+-----------------+
|  1 | title goes here |
+----+-----------------+

tag:

+----+----------+
| id |   name   |
+----+----------+
|  1 | tag name |
+----+----------+

item_tag

+----+--------+---------+
| id | tag_id | item_id |
+----+--------+---------+
|  1 |      1 |       1 |
+----+--------+---------+

letter:

+----+--------+
| id | letter |
+----+--------+
| 1  | A      |
| 2  | B      |
| .  | .      |
+----+--------+


texts: Confusion over using generics in MVC project

texts:
Consider the following:

Remote service accepts SecondAction=Search and SecondAction=Update. For SecondAction=Search sending a Query parameter is sufficient enough. For SecondAction=Update, I need to send back a set of additional parameters named AdditionalQuery1 and AdditionalQuery2.

The ApiKey and Action properties are always the same. The SecondAction is different. I want the model to be as reusable as possible and use less code as possible.

I want to be able to reuse the the majority of the Request and only have it to SpecialData instead of Data to send those AdditionalQueries for when I have to do a SecondAction=Update.

public class Request<T>
{
    public string ApiKey { get; set; }
    public Details<T> Details { get; set; }
}

public class Details<T> {
    public string Action { get; set; }
    public string SecondAction { get; set; }
    public MoreDetails<T> MoreDetails { get; set; }
}

public class MoreDetails<T> {
    public T Data { get; set; }
}

public class Data {
    public string Query { get; set; }
}

public class SpecialData : Data {
    public string AdditionalQuery1 { get; set; }
    public string AdditionalQuery2 { get; set; }
}

I've confused myself to the point I'm creating it like

 var Obj = new Request<Details<MoreDetails<SpecialData>>> {
      ApiKey = "12345",
      Details = new Details<MoreDetails<Data>>() {
           Action = "Search"
      }

doesn't look right. It doesn't seem right that I have to make all the others a generic type as well.


texts:
I apologize in advance for my English.
I have a user search method. It's parameters - login and strict. The last one determines, which method should have been used for search - Equals (strict is true) or Contains (strict is false). How should I implement it? I could do two different methods, but I think it would be code repeating.
    public async Task<List<UserFindInfoDTO>> FindUserByLoginAsync(string login, bool strict)
    {
        var users = await context.Users
            .Where(u => u.Nickname.Equals(login)) // change on "Contains" if strict is false
            .Select(u => new UserFindInfoDTO
            {
                Status  = u.Status,
                Id = u.Id,
                MiniAvatar =  u.Image,
                Nickname = u.Nickname
            })
            .ToListAsync();
            ...
        return users;
    }


texts: Creating a masonry effect with varying height rectangles

texts:
The following is used to create a masonry effect with varying height rectangles. How can I simplify and make this more elegant in Unity?

private float startX = 0.0f;
private float startY = 0.0f;
private float posX = 0.0f;
private float posY = 0.0f;
private float prevWidth = 0;
private float prevHeight = 0;
private int index = 0;
private int currentCol = 0;

private void AddCard(int index, int col, float width, float height)
{
    GameObject goCard = (GameObject)GameObject.Instantiate(pfCard00);
    PackedSprite psCard = goCard.GetComponentInChildren<PackedSprite>();

    goCard.name = "QuestItemCard" + index.ToString();
    goCard.transform.parent = goCardContainer.transform;
    psCard.height = height;

    if (currentCol != col)
    {
        posX += width;

        posY = 0;
        prevHeight = 0;
    }

    // placement
    posY += (prevHeight / 2) + (height / 2);
    goCard.transform.localPosition = new Vector3(startX + posX, startY - posY, goCard.transform.position.z);

    if (currentCol != col)
    {
        prevWidth = width;

        currentCol = col;
    }

    prevHeight = height;
}

Usage:

AddCard(0, 0, 100, 100);
AddCard(1, 0, 100, 100);
AddCard(2, 0, 100, 100);
AddCard(3, 0, 100, 200);

AddCard(4, 1, 100, 100);
AddCard(5, 1, 100, 100);
AddCard(6, 1, 100, 100);
AddCard(7, 1, 100, 200);


texts:
Is this a bad solution to the FizzBuzz thing?

I decided to make it print "Fizz Buzz" for the numbers divisible by 3 and 5 just for practice/understanding.

for (var n = 1; n <= 100; n++) {
var output = "";
if (n % 3 == 0)
    output += "fizz";

if (n % 5 == 0)
    output += "buzz";

if (n % 5 == 0 && n % 3 == 0)
    output = "fizz buzz";

console.log(output || n);
};


texts: Speed up javascript code to convert csv to geojson

texts:
I'm using a script that converts a CSV file into GeoJSON in order to display it on a map. You can see it for yourself here. The CSV has about four thousand rows. It's quite slow. I'm wondering what is slowing it down and how I can speed it up.
function latLonColumnsToNumbers(data, latName, lonName) {
  return data.map(function(item) {
    if (item.hasOwnProperty(latName)) {
         item[latName] = parseFloat(item[latName]);
         if (isNaN(item[latName])) { //check if row has blank lat/long, and if so, flag it
            var latFlag = 1;
         } else {
             latFlag = 0;
         }
      }
    if (item.hasOwnProperty(lonName)) {
         item[lonName] = parseFloat(item[lonName]);
         if (isNaN(item[lonName])) {
             var lonFlag = 1;
         } else {
             lonFlag = 0;
         }
    }
    if (latFlag == 1 || lonFlag == 1) { //if row has no lat/long, then assign it to the approximate center of the map
        item[latName] = 42.2;
        item[lonName] = ~83.6;
        return item;
     }
    else {
        return item;
    }
  });

I know that a faster way to do this would be to turn the CSV into a sql database and call it with PHP but that involves using a lot of server-side stuff like NodeJS, Ajax, etc that I am not (yet) familiar with. So I would like to keep using the CSV for now until I learn how to do that.


texts:
I've implemented simple +-*/ calculator in WPF. I know that here are few implementations of the same thing, but each is different, with different advantages or disadvantages against this one. Can you suggest me, what could be improved in my code?

// calculator operations
public enum CalcOperator
{
    None,
    Plus,
    Minus,
    Times,
    Divide
}

public partial class Calculator : Window
{
    // decimal separator of current culture
    char decimSepar = Convert.ToChar
        (CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);

    private double a = 0;    // the first number
    private double b = 0;    // second number

    // last selected operation
    private CalcOperator lastOper = CalcOperator.None;

    public Calculator()
    {
        InitializeComponent();
    }

    // handle single digit (button)
    public void HandleDigit(int i)
    {
        string str = txtDisp.Text;

        if (lastOper == CalcOperator.None && a != Convert.ToDouble(str) ||
            lastOper != CalcOperator.None && b != Convert.ToDouble(str) ||
            str == "0")
        {
            str = string.Empty;
        }

        str += i.ToString();

        if (lastOper == CalcOperator.None)
            a = Convert.ToDouble(str);
        else
            b = Convert.ToDouble(str);

        txtDisp.Text = str;
    }

    // handle calculator operation (button)
    public void HandleOperator(CalcOperator oper)
    {
        txtDisp.Text = b.ToString();
        lastOper = oper;
    }

    // handle decimal separator selection (button)
    public void HandleDecimal()
    {
        if (!txtDisp.Text.Contains(decimSepar))
            txtDisp.Text += decimSepar;
    }

    // compute the result
    public void Compute()
    {
        double result = 0.0;

        switch (lastOper)
        {
            case CalcOperator.Plus:
                result = a + b;
                break;
            case CalcOperator.Minus:
                result = a - b;
                break;
            case CalcOperator.Times:
                result = a * b;
                break;
            case CalcOperator.Divide:
                if (b == 0.0)
                    result = 0.0;
                else
                    result = (double)a / b;
                break;
        }

        txtDisp.Text = result.ToString();
        lastOper = CalcOperator.None;
        a = 0;
        b = 0;
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        btnPlus.Tag = CalcOperator.Plus;
        btnMinus.Tag = CalcOperator.Minus;
        btnTimes.Tag = CalcOperator.Times;
        btnDivide.Tag = CalcOperator.Divide;
    }

    private void OnClickDigit(object sender, RoutedEventArgs e)
    {
        Button btn = sender as Button;
        HandleDigit(Convert.ToInt16(btn.Content.ToString()));
    }

    private void OnClickOperator(object sender, RoutedEventArgs e)
    {
        Button btn = sender as Button;
        HandleOperator((CalcOperator)btn.Tag);
    }

    private void btnEqual_Click(object sender, RoutedEventArgs e)
    {
        Compute();
    }

    private void btnDot_Click(object sender, RoutedEventArgs e)
    {
        HandleDecimal();
    }

}


texts: Write a program to find the longest word made of other words

texts:
This is my solution to the problem in the title. The code is pretty straightforward. The one problem is with substring; it's \$O(n)\$ in .Net and creates garbage. Any other improvements?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LongestWordFromWords
{
    internal class Program
    {
        public static string FindLongestWords(string[] listOfWords)
        {
            if (listOfWords == null) throw new ArgumentException("listOfWords");
            var sortedWords = listOfWords.OrderByDescending(word => word.Length).ToList();
            var dict = new HashSet<String>(sortedWords);
            foreach (var word in sortedWords)
            {
                if (isMadeOfWords(word, dict))
                {
                    return word;
                }
            }
            return null;
        }

        private static bool isMadeOfWords(string word, HashSet<string> dict)
        {
            if (String.IsNullOrEmpty(word)) return false;
            if (word.Length == 1)
            {
                if (dict.Contains(word)) return true;
                else return false;
            }
            foreach (var pair in generatePairs(word))
            {
                if (dict.Contains(pair.Item1))
                {
                    if (dict.Contains(pair.Item2))
                    {
                        return true;
                    }
                    else
                    {
                        return isMadeOfWords(pair.Item2, dict);
                    }
                }
            }
            return false;
        }

        private static List<Tuple<string, string>> generatePairs(string word)
        {
            var output = new List<Tuple<string, string>>();
            for (int i = 1; i < word.Length; i++)
            {
                output.Add(Tuple.Create(word.Substring(0, i), word.Substring(i)));
            }
            return output;
        }

        private static void Main(string[] args)
        {
            string[] listOfWords = { "ala", "ma", "kota", "aa", "aabbb", "bbb", "cccc", "aabbbmacccc", "aabbbmaxxcccc" };
            string longest = FindLongestWords(listOfWords);
            Console.WriteLine(longest);
            string[] listOfWords2 = { "cat", "cats", "catsdogcats", "catxdogcatsrat", "dog", "dogcatsdog",
                                      "hippopotamuses", "rat", "ratcatdogcat" };
            Console.WriteLine(FindLongestWords(listOfWords2));
        }
    }
}


texts: Quickly passing and parsing variable length float arrays

texts:
I have this code for parsing for parsing a list of floats of variable length.

on_message = function(event_data) {
    var data = event_data.split(" ").map(parseFloat)
    var size = data.shift() + 1;
    while (data.length >= size) {
        // put the data in a buffer
        // could be replace by console.log() for testing purposes
        // each data chunk needs to be pushed separately
        this.data_store.push(data.slice(0, size));
        data = data.slice(size);
        size = data.shift() + 1;
    }
    // start displaying stuff to the user ASAP
    this.schedule_update();
}

At this point, the data is formatted in the following manner when a single "chunk" is sent:

[length data_1 data_2 etc etc]

However, because the back-end that sends these updates can sometimes be faster than the front-end, multiple "chunks" can be sent at the same:

[length_1 data_1_1 data_1_2 etc_1 etc_1 length_2 data_2_1 data_2_2 etc_2]

As mentioned before, all values in event_data are floats, except for the length which is an int.

The format of the data packet is not set, although the fact that more than one "chunk" can be sent at a time and the chunks are different sizes cannot be changed. I would just like to be able to send a variable length array of floats to a buffer quickly and efficiently. Right now, this code is taking really long. What can I do to speed it up?


texts:
I am creating a system for a client that loads information from an XML file and then parses the information where needed. For this, I have got this class:

<?php
class Config
{
    private static $init;
    private static $link;

    private static $db_hostname;
    private static $db_username;
    private static $db_password;
    private static $db_database;

    public static $ABSPATH;
    public static $GWPATH;
    public static $CONFIGPATH;
    public static $CONNECTIONPATH;

    public static $configfile;
    public static $connectionfile;

    private static $cfg;

    const CONFIGFILEPATH = "E:/projects/php/_site/_site/_include/Config/web.config.xml";

    /** Private to implement singleton pattern */
    private function __construct() {  }

    /** @return Config */
    public static function Init()
    {
        return static::$init = (
            null === static::$init ? new self() : static::$init
        );
    }

    public function RequireFiles()
    {
        require_once static::$connectionfile;
        require_once static::$GWPATH . 'libraries/functions/user.loggedin.php';
    }

    public function LoadConfig()
    {
        static::$cfg = simplexml_load_file(self::CONFIGFILEPATH);

        $path = static::$cfg->paths;
        $database = static::$cfg->database;

        static::$ABSPATH = (string) $path->abs;
        static::$GWPATH = (string) $path->gwpath;
        static::$CONFIGPATH = (string) $path->configpath;
        static::$configfile = (string) $path->configfile;
        static::$CONNECTIONPATH = (string) $path->connectionpath;
        static::$connectionfile = (string) $path->connectionfile;

        static::$db_hostname = (string) $database->hostname;
        static::$db_username = (string) $database->username;
        static::$db_password = (string) $database->password;
        static::$db_database = (string) $database->name;
    }

    public function GetLink()
    {
        if (empty(static::$link) || null === static::$link)
            $this->SetLink();
        return static::$link;
    }

    public function SetLink()
    {
        static::$link =
            new Database($this->GetDBHostname(), $this->GetDBUsername(), $this->GetDBPassword(), $this->GetDBDatabase())
                or die("Failed to connect to the server. Error: " . static::$link->connect_error);
    }

            private function GetDBHostname()
    {
        return static::$db_hostname;
    }

    private function GetDBUsername()
    {
        return static::$db_username;
    }

    private function GetDBPassword()
    {
        return static::$db_password;
    }

    private function GetDBDatabase()
    {
        return static::$db_database;
    }

    public function GetConfigXML($do = false)
    {
        if ($do == true)
            return static::$cfg;
        return null;
    }
}

This is working for me, but I wanted to know if there is a better way to do this?

Info:
This is used in this way:

$config = Config::Init();
$config->LoadConfig();
$config->RequireFiles();
$link = $config->GetLink();


texts: Create an array with at least a given number of bits

texts:
I use this declaration for an array which must contain a bit for every minute in a day:

UCHAR minutesOfDay[(60 * 24 / CHAR_BIT) + (((60 * 24) % CHAR_BIT) ? 1 : 0)];

However, this look pretty awful. Is there a simpler way to state the same? It can be in C or C++.


texts:
I have implemented the atof function. Here is my implementation

double atof(const char *str)
{
    double a;           /* the a value in a*10^b */
    double decplace;    /* number to divide by if decimal point is seen */
    double b;           /* The b value (exponent) in a*10^b */

    int sign = 1;       /* stores the sign of a */
    int bsign = 1;      /* stores the sign of b */

    while (*str && isspace(*str))
        ++str;

    if (*str == '+')
        ++str;
    if (*str == '-') {
        sign = -1;
        ++str;
    }
    if ((*str == 'n' || *str == 'N') &&
       (str[1] == 'a' || str[1] == 'A')
       && (str[2] == 'n' || str[2] == 'N'))
            return NAN * sign;
    if ((*str == 'i' || *str == 'I') && (str[1] == 'n' || str[1] == 'N') &&
        (str[2] == 'f' || str[2] == 'F'))
              return INFINITY * sign;

    for (a = 0; *str && isdigit(*str); ++str)
        a = a * 10 + (*str - '0');

    if (*str == '.')
        ++str;
    for (decplace = 1.; *str && isdigit(*str); ++str, decplace *= 10.)
        a = a * 10. + (*str - '0');

    if (*str == 'e' || *str == 'E') {
        /* if the user types a string starting from e, make the base be 1 */
        if (a == 0)
            a = 1;
        ++str;
        if (*str == '-') {
            bsign = -1;
            ++str;
        }
        if (*str == '+')
            ++str;
        for (b = 0; *str && isdigit(*str); ++str)
            b = b * 10 + (*str - '0');

        b *= bsign;
    }
    else
        b = 0;

    return (a * sign / decplace) * pow(10, b);
}


texts: Find all the numbers within a range whose digits add up to a certain target

texts:
In an interview I was asked the following problem:

  Given a range of numbers (0 - 100) or (0 - 1000), find all the numbers whose digit add up to 5.

I started off with a brute force way to iterate over all the numbers and filter out numbers whose digits do not add up to 5. The numbers remaining will be the answer.

It seems like that wasn't the desired solution. After thinking about the problem a little bit I realized another approach would be to use recursion to generate all the numbers until a particular "digit-size".

For example, if we are asked to generate all the numbers that between 0 and 100 that add up to 5, we can generate all numbers from 'digit-size=1' to 'digit-size=3' that add up to 5.

It will be great if this approach could be reviewed.

    public class FindAllNumbersWithCertainDigitSum {
       public List<Integer> getAllNumbersThatSumToTarget(int digitSize, int target) {
          List<Integer> candidates = new ArrayList<>();
          int accumulatedSum = 0;
          helper(digitSize, target, candidates, accumulatedSum);
          return candidates;
     }

     private void helper(int digitSize, int target, List<Integer> candidates, int accumulatedSum) {
         //Base case: No more digits to consider and nothing else to add
         if(digitSize == 0 && target == 0) {
             candidates.add(accumulatedSum);
         }
       //There is nothing else to add but there are more digits to consider that will be multiples of 10
       else if(digitSize != 0 && target == 0) {
             helper(digitSize - 1, target, candidates, accumulatedSum * 10);
         }
      //The digits did not add up to the target, return without doing anything
      else if(digitSize == 0 && target != 0) {
             return;
         } else {
            //Iterate from target down to zero and recursively get the remaining digits if the first digit is the target.
             for(int current = target; current >= 0; current--) {
                 helper(digitSize - 1, target - current, candidates, accumulatedSum*10 + current);
             }
         }

      }

     public static void main(String[] args) {
        FindAllNumbersWithCertainDigitSum s = new FindAllNumbersWithCertainDigitSum();
        //Get all numbers from 0 - 999(maxDigitSize == 3) that add up to 5
        s.getAllNumbersThatSumToTarget(3, 5)
         .stream()
         .forEach(System.out::println);
      }
}


texts: How to improve WCF client proxy based on CreateChannel (not generated from WSDL) in C#

texts:
When invoking a Web Service from C# (where the external service might be WCF, ASMX, Java, etc. - you just don't know), it is common practice to point your modern development tool of choice (Visual Studio in my case) at the service's WSDL to generate a proxy class for calling the service. You can also create a proxy "by hand" using CreateChannel. This code review posting is to seek feedback on a simple proxy class built using CreateChannel. A couple of supporting classes are shown for completeness & context.

Interface for Service & Proxy:

This interface is also passsed to ChannelFactory.

public interface IService
{
   ServiceResponse DoSomething(ServiceRequest request);
}

Example usage:

var proxy = new ServiceProxy("http://123.45.67.89/foo");
var request = new ServiceRequest { Number = 33, Name = "Larry Bird" };
ServiceResponse response = proxy.DoSomething(request);

Code of interest:  - Any comments/improvements/feedback appreciated

For readers wondering about the use of factory.Abort in the finally block, see answer to this question. Regarding the following casting business (which appears twice): ((IClientChannel)service).Close(); see MSDN document on How To: Use the ChannelFactory which demonstrates its use. The two are hacks that appear to be related and date from early WCF/Indigo days.

public class ServiceProxy : IService
{
   public string EndpointUrl { get; set; }
   public ServiceProxy(string endpointUrl) { EndpointUrl = endpointUrl; }

   public ServiceResponse DoSomething(ServiceRequest request)
   {
      Contract.Requires(request != null);
      Contract.Requires(! String.IsNullOrEmpty(EndpointUrl));

      var endpointAddress = new EndpointAddress(EndpointUrl);
      ChannelFactory<IService> factory = null;
      IService service = null;

      try
      {
         // Just picking a simple binding here to focus on other aspects
         Binding binding = new BasicHttpBinding();
#if DEBUG // boost timeouts, otherwise can cause lots of timeouts in the debugger
         binding.SendTimeout = binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
#endif
         factory = new ChannelFactory<IService>(binding);
         service = factory.CreateChannel(endpointAddress);
         if (service == null)
         {
             throw new CommunicationException(
                String.Format("Unable to connect to service at {0}", endpointUrl));
         }

         ServiceResponse response = service.DoSomething(request);
         ((IClientChannel)service).Close();

         service = null;
         factory.Close();
         factory = null;

         return response;
      }
      finally
      {
         if (service != null) ((IClientChannel)service).Close();
         if (factory != null) factory.Abort();
      }
   }
}

Supporting Objects (for completeness)

Not much of interest in ServiceRequest and ServiceResponse classes, other than this is the prevailing style of calling services - one object in, one object out.

public class ServiceRequest // stuff we send to the service
{
   public int Number { get; set; }
   public string Name { get; set; }
}

public class ServiceResponse // stuff we get back from the service
{
   public int SomeStat { get; set; }
   public string SomeString { get; set; }
}


texts: How skinny should controllers be, how fat should models be in CakePHP?

texts:
I know it's a good idea to put all data-related logic in your models in CakePHP, but what would you say about keeping every Model::find() and its particular params in the model? Is this good practice, or just taking things too far?

For example, is this:

PostsController:

function index() {
    $posts = $this->Post->getLatest();
    $this->set(compact('posts'));
}

Post model:

function getLatest() {
    $params = array(
        'conditions' => array('published' => 1),
        'limit' => 5,
        'order' => 'publish_date DESC'
    );
    return $this->find('all', $params);
}

Better than this:

PostsController:

function index() {
    $params = array(
        'conditions' => array('published' => 1),
        'limit' => 5,
        'order' => 'publish_date DESC'
    );
    $posts = $this->Post->find('all', $params);
    $this->set(compact('posts'));
}

Any thoughts? Which is better architecturally?


texts: BASH correct usage of single/double quotes when writing variables to file

texts:
(running Ubuntu 16.04.3)
I created small script with tasks I do every time I upgrade/change Ubuntu version. One of the tasks is to write script to file, this is actual written file:

#!/bin/bash

if [ "$1" == "eno1" ]; then
 case "$2" in
  up) nmcli radio wifi off
      notify-send "cable network detected, turning WIFI off" -u low -t 10;;
  down) nmcli radio wifi on
      notify-send "cable network unplugged, turning WIFI on" -u low -t 10;;
  esac
fi

And this is how I write it from another script:

MY_FILE="/etc/NetworkManager/dispatcher.d/99-wlan"
ni="$(nmcli dev status | grep ethernet | awk '{ print $1 }')"
echo -e '#!/bin/bash\n\nif [ "$1" == "'"$ni"'" ]; then\n case "$2" in\n'\
  ' up) nmcli radio wifi off\n      notify-send "cable network detected, turning WIFI off" --urgency critical --expire-time 6;;\n'\
  ' down) nmcli radio wifi on\n      notify-send "cable network unplugged, turning WIFI on" --urgency critical --expire-time 6;;\n'\
  ' esac\nfi' | sudo tee -a "$MY_FILE" > /dev/null
sudo chmod +x "$MY_FILE"

My question is, if syntax I'm using is correct. When I check it with shellcheck utility, it complaints about first line:

echo -e '#!/bin/bash\n\nif [ "$1" == "'"$ni"'" ]; then\n case "$2" in\n'\
        ^-- SC2016: Expressions don't expand in single quotes, use double quotes for that.
                                            ^-- SC2016: Expressions don't expand in single quotes, use double quotes for that.

can I ignore this warnings or is there a better how to write it ? Keep in mind I'm using variable $ni when I'm writing to file.


texts: Classes to manage perks to be added and removed

texts:
I am looking for code correctness and design usage as I think I might be over doing it in the class department.

There are two things I'm mostly concerned with.

The possible redundancy of classes derived from IPerks. As
CommonPerks, UncommonPerks, etc, all look identical except for
the rows/columns in its internal perk list. I'm thinking I should
just have a concrete PerksList class instead.
The use of an enum to keep track of constant values for the
    different indices associated with the perkList. All perkList's
    will follow the same order, so the indices will always mean the same
    thing regardless of which IPerks derived class is being used.

PerkSlotEnums.h

enum class PERK_SLOTS
{
    COMMON_SLOT_COLUMNS = 1,
    COMMON_SCOPE_PERK_COUNT = 2,
    SCOPE_SLOT_INDEX =0,
    STATS_UPGRADE_A_SLOT_INDEX = 1,
    UNIQUE_PERK_A_SLOT_INDEX = 2,
    STATS_UPGRADE_B_SLOT_INDEX = 3,
    UNIQUE_PERK_B_SLOT_INDEX = 4,
    STATS_UPGRADE_C_SLOT_INDEX = 5,
    UNIQUE_PERK_C_SLOT_INDEX = 6
};

IPerks.h

#pragma once
#include "IPerk.h"
#include "IComponent.h"
#include <vector>

class IPerks : public IComponent
{

public:
    IPerks(void);
    virtual ~IPerks(void);
    virtual void AddPerk(IPerk* perk, int column, int row) = 0;
    virtual void RemovePerk(unsigned int index_1, unsigned int index2) =0;
    virtual IPerk* GetPerk(unsigned int perkId) const = 0;
};

CommonPerks.cpp

#include "CommonPerks.h"
#include "PerkSlotEnums.h"

CommonPerks::CommonPerks(void)
{
    perkList.resize((int)PERK_SLOTS::COMMON_SLOT_COLUMNS);
    perkList[(int)PERK_SLOTS::SCOPE_SLOT_INDEX].resize((int)PERK_SLOTS::COMMON_SCOPE_PERK_COUNT);
}

CommonPerks::~CommonPerks(void)
{
}

void CommonPerks::AddPerk(IPerk* perk, int column, int row)
{
    perkList[column][row] = perk;
}

void CommonPerks::RemovePerk(unsigned int index_1, unsigned int index_2)
{
    if(index_1 < perkList.size())
    {
        if(index_2 < perkList.at(index_1).size())
        {
            perkList.at(index_1).at(index_2) = nullptr;
        }
    }
}

IPerk* CommonPerks::GetPerk(unsigned int index_1, unsigned int index_2) const
{
    if(index_1 < perkList.size())
    {
        if(index_2 < perkList.at(index_1).size())
        {
            return perkList.at(index_1).at(index_2);
        }
    }

    return nullptr;
}


texts:
I have an class that cheaply imitates a lazy evaluation scheme. The class is for representing a file and additionally providing meta data on the file.  Some of the meta-data can be expensive to evaluate so I only want to evaluate it when requested, and only evaluate it once.

My implementation is such: All private members are stored in an EnumMap and each member is associated with a value in the enum Field.

private enum Field {
    FILE_CODE
    //, ...
};
private Map<Field, Optional> lazyAttributes = new EnumMap<Field, Optional>(Field.class);

The values in the EnumMap are Optionals in case evaluation failed (value not in database etc.)  Accessors methods get the member by providing the Field value associated with the member and a Supplier which will evaluate member if it hasn't yet been evaluated.

private <T> Optional<T> lazyLookup(Field field, Supplier<Optional<T>> answer) {
    if (lazyAttributes.containsKey(field)) { // field was already evaluated, get answer.
        return lazyAttributes.get(field);    // unchecked Optional to Optional<T>
    } else {                                 // field is unevaluated;
        Optional result = answer.get();      // evaluate,
        lazyAttributes.put(field, result);   // then store
        return result;                       // unchecked Optional to Optional<T>
    }
}

This is an example of what an accessor looks like.

public Optional<String> getFileCode() {
    return lazyLookup(Field.FILE_CODE,
            () -> FileCodeKeyWords.apply(getName())); // consider this expensive
}

I am concerned about the unchecked operations in lazyLookup and it seems to be an overly complicated setup.  I can provide the rest of the class if requested.


texts:
I don't yet see a code review for a number-guessing game in Rust. Since I am just learning the language, and since the number-guessing game is part of the official Rust tutorial, I thought it would be beneficial both for me and for this site to open a code review request.

I've started with the official tutorial and then built upon it using the basic language constructs (functions, conditionals, loops) to add some error checking and break common logic into reusable functions.

My background is mostly in C and Java development. This is the final example I've come up with after spending about 5 hours reading the book. What I'm interested to learn is whether I'm using the language's unique features in the expected ways and if I'm re-inventing the wheel in any parts.

extern crate rand;

use std::io;
use std::cmp::Ordering;
use rand::Rng;

fn read_i32() -> i32 {
    loop {
        let mut input = String::new();
        io::stdin().read_line(&mut input)
            .expect("Failed to read line.");
        let input: i32 = match input.trim().parse() {
            Ok(n) => n,
            Err(_) => {
                println!("Please input a number.");
                continue;
            },
        };
        return input;
    }
}

fn read_guess(min: i32, max: i32) -> i32 {
    let mut guess: i32;
    loop {
        guess = read_i32();
        if guess < min {
            println!("Please input a number that is at least {}.", min);
        } else if guess > max {
            println!("Please input a number that is no larger than {}.", max);
        } else {
            break;
        }
    }
    guess
}

fn main() {
    println!("Guess the number!");
    let (min, max) = (1, 10);
    let secret_number = rand::thread_rng().gen_range(min, max+1);
    loop {
        println!("Please input your guess, between {} and {}.", min, max);
        let guess = read_guess(min, max);
        match guess.cmp(&secret_number) {
            Ordering::Less    => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal   => {
                println!("You win!");
                break;
            },
        };
    }
}


texts: Calculator Program which can operate on multiple numbers

texts:
All the calculator programs I have seen so far seem long, complicated and they can only operate on two numbers. I am trying to write one that is simple, short, and it can operate on as many numbers as you want. After implementing suggestions from my previous question regarding use of operator.XXX and functools.reduce I've got a new version for review:

import operator
import functools
amount_of_numbers = int(input("How many numbers?"))
my_operator = input("Which operator (*, /, +, -)?")
if my_operator == "/":
    numbers=[float(input("Number: ")) for _ in range(amount_of_numbers)]
else:
    numbers = [int(input("Number: ")) for _ in range(amount_of_numbers)]

OPERATORS = {
    '+': operator.add,
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.floordiv
}

INIT_VALUE = {
    '-': 0,
    '/': 1.00,
    '+': 0,
    '*': 1
}
result = functools.reduce(OPERATORS[my_operator], numbers, INIT_VALUE[my_operator])
print (result)


texts: Test whether two strings are anagrams of each other

texts:
What is the time/space complexity of this algorithm which checks if two strings are anagrams? My guess is that time is \$O(n)\$ and space \$O(1)\$ but I am not sure.  Can it be improved?

def anagram(str1, str2):
    s1 = list(str1)
    s2 = list(str2)
    freq1 = {}
    freq2 = {}

    for pos in s1:
        freq1[pos] = s1.count(pos)
    for pos in s2:
        freq2[pos] = s2.count(pos)
    if freq1 == freq2:
        return True
    else:
        return False


texts: Integer factoring in C using GMP for numbers

texts:
This code performs integer factoring using the GMP library, and can also use OpenMP for parallel computation.

I compile it using: gcc -lgmp -fopenmp and whatever optimization flags I wish to try.

#include <stdio.h>
#include <gmp.h>

void next_prime(MP_INT *x) {
    MP_INT r;
    mpz_init(&r);
    if (!mpz_probab_prime_p(x, 128u)) {
        mpz_mod_ui(&r, x, 2ul);
        if (mpz_cmp_ui(&r, 0ul) == 0)
            mpz_add_ui(x, x, 1ul);
        else
            mpz_add_ui(x, x, 2ul);
        while (!mpz_probab_prime_p(x, 128u)) {
            mpz_add_ui(x, x, 2ul);
        }
    }
    mpz_clear(&r);
}

void prev_prime(MP_INT *x) {
    MP_INT r;
    mpz_init(&r);
    if (!mpz_probab_prime_p(x, 128u)) {
        mpz_mod_ui(&r, x, 2ul);
        if (mpz_cmp_ui(&r, 0ul) == 0)
            mpz_sub_ui(x, x, 1ul);
        else
            mpz_sub_ui(x, x, 2ul);
        while (!mpz_probab_prime_p(x, 128u)) {
            mpz_sub_ui(x, x, 2ul);
        }
    }
    mpz_clear(&r);
}

unsigned long mp_log(MP_INT *x, MP_INT *base) {
    MP_INT r;
    mpz_init(&r);
    unsigned long lg = 0;
    mpz_set(&r, x);
    if (base != NULL) {
        while (mpz_cmp_ui(&r, 0ul) != 0) {
            mpz_div(&r, &r, base);
            lg += 1;
        }
    }
    else {
        while (mpz_cmp_ui(&r, 0ul) != 0) {
            mpz_div_ui(&r, &r, 2ul);
            lg += 1;
        }
    }
    mpz_clear(&r);
    return lg;
}

void factor(MP_INT *x, MP_INT *n, MP_INT *base) {
    /* Initialize variables. */
    MP_INT s;
    MP_INT r;
    mpz_init(&s);
    mpz_init(&r);
    /* Compute stuff. */
    mpz_set(x, n);
    if (mpz_probab_prime_p(n, 128u)) {
        goto end;
    }
    mpz_set(&s, base);
    mpz_mod(&r, n, &s);
    if (mpz_cmp_ui(&r, 0ul) == 0) {
        mpz_set(x, &s);
        goto end;
    }
    unsigned long k = mp_log(n, base);
    unsigned long a = mp_log(n, NULL);
    if (mpz_cmp(x, n) == 0) {
        /* Try different powers of n. */
        MP_INT p;
        mpz_init(&p);
        mpz_pow_ui(&p, &s, k);
        unsigned long i = 1ul;
        while (mpz_cmp(x, n) == 0) {
            #pragma omp parallel for
            for (unsigned long j = i; j < i + 2*a*a; ++j) {
                if (mpz_cmp(x, n) == 0) {
                    MP_INT g;
                    mpz_init(&g);
                    mpz_powm_ui(&g, n, j, &p);
                    mpz_gcd(&g, &g, n);
                    if (mpz_cmp_ui(&g, 1ul) != 0 && mpz_cmp(&g, n) != 0) {
                        mpz_set(x, &g);
                    }
                    mpz_clear(&g);
                }
            }
            i += 2*a*a;
        }
        mpz_clear(&p);
    }
    /* Clear variables. */
    end:
    mpz_clear(&s);
    mpz_clear(&r);
}

int main() {
    char str [65536];
    char bas [65536];
    while (fscanf(stdin, "%s %s", str, bas) != EOF) {
        MP_INT n;
        MP_INT base;
        mpz_init(&n);
        mpz_init(&base);
        mpz_set_str(&n, str, 10u);
        mpz_set_str(&base, bas, 10u);
        mpz_out_str(stdout, 10u, &n);
        int p = mpz_probab_prime_p(&n, 128u);
        printf(" %d ", p);
        mpz_out_str(stdout, 10u, &base);
        printf("\n");
        while (!p) {
            MP_INT x;
            mpz_init(&x);
            factor(&x, &n, &base);
            mpz_out_str(stdout, 10u, &x);
            printf(" ");
            mpz_div(&n, &n, &x);
            p = mpz_probab_prime_p(&n, 128u);
            mpz_clear(&x);
        }
        mpz_out_str(stdout, 10u, &n);
        printf("\n");
        mpz_clear(&n);
        mpz_clear(&base);
    }
    return 0;
}


texts:
I'm starting with object oriented programming, but I know PHP procedural style "pretty well" I'd say. I'm working on a ticket support site for this website.

This mysqliSingleton class was in a question I previously visited. I only added the set_charset() method to feet my database. By the way, should that line be in the __constructor or in the init method?

class mysqliSingleton {
private static $instance;
private $connection;

private function __construct() {
    $this->connection = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
    $this->connection->set_charset('utf8');
}

public static function init() {
    if(is_null(self::$instance)) {
        self::$instance = new mysqliSingleton();
    }
    return self::$instance;
}

public function __call($name, $args) {
    if(method_exists($this->connection, $name)) {
         return call_user_func_array(array($this->connection, $name), $args);
    } else {
         trigger_error('Unknown Method ' . $name . '()', E_USER_WARNING);
         return false;
    }
}
}

This is a piece of my ticket class which also has other methods delete, getFromUser, getAll, and some others:

class Ticket extends mysqliSingleton {
private $mysqli;
public function __construct() {
    $this->mysqli = mysqliSingleton::init();//Singleton db
}
//Submit a ticket
public function submitTicket($idusuario, $problem,$moreinfo){
    $query = "INSERT INTO tbl_name (tbl_field,tbl_problem,tbl_moreinfo) VALUES (?,?,?)";
    $stmt = $this->mysqli->prepare($query) or die($this->mysqli->error);
    if ($stmt) {
        $stmt->bind_param('iss',$idusuario,$problem,htmlentities($moreinfo));
        if ($stmt->execute()) {
            return true;
        } else return false;//Problem sql
    }
}
}

Am I using the singleton pattern right? But (unfortunately) after I code that, I starting reading more about abstract classes and Interfaces, and I've started to doubt if this is right. By the way, the ticket class is one of many classes that will extend to mysqliSingleton.


texts: List files and folders in current dir with special handling for tty

texts:
I want to write a custom ls command to learn rust.

This is what I've done as for the version 1.0. This display files and folders in a cyan or white if it's on a TTY. Otherwise I just print them.

I'm using atty and crossterm crates.

What I want reviewed

Is there a better way to deal with OsStr?
Is there a better way to convert OsStr to print-able strings?
Is there a better way to handle errors?
Any other area is fair game too.
Is my enum use good?

use std::fs::{self, DirEntry};
use std::path::Path;

use atty::Stream;
use crossterm::{Color, Colored};

enum FileEntryType {
    File,
    Dir,
}

fn main() {
    // WHY: no need to print colours on non tty
    if atty::is(Stream::Stdout) {
        visit_location(Path::new("."), &color_print);
    } else {
        visit_location(Path::new("."), &normal_print);
    }
}

fn visit_location(dir: &Path, cb: &dyn Fn(FileEntryType, &DirEntry)) {
    if !dir.is_dir() {
        return;
    }

    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries {
            if let Ok(entry) = entry {
                let path = entry.path();
                if path.is_dir() {
                    cb(FileEntryType::Dir, &entry);
                } else {
                    cb(FileEntryType::File, &entry);
                }
            }
        }
    } else {
        println!("Failed to list {}", dir.as_os_str().to_str().unwrap());
    }
}

fn color_print(file_kind: FileEntryType, p: &DirEntry) {
    match file_kind {
        FileEntryType::File => println!("{}{}", Colored::Fg(Color::White), p.file_name().as_os_str().to_str().unwrap()),
        FileEntryType::Dir => println!("{}{}", Colored::Fg(Color::Cyan), p.file_name().as_os_str().to_str().unwrap())
    }
}

fn normal_print(_: FileEntryType, p: &DirEntry) {
    println!("{}", p.file_name().as_os_str().to_str().unwrap());
}

How it looks like


texts:
I have the ToHtml() Extension Method

public static class StringMethodExtensions
{
    private static string _paraBreak = "\r\n\r\n";
    private static string _link = "{1}";
    private static string _linkNoFollow = "{1}";

    ///
    /// Returns a copy of this string converted to HTML markup.
    ///
    public static string ToHtml(this string s)
    {
        return ToHtml(s, false);
    }

    ///
    /// Returns a copy of this string converted to HTML markup.
    ///
    /// <param name="nofollow">If true, links are given "nofollow"
    /// attribute</param>
    public static string ToHtml(this string s, bool nofollow)
    {
        StringBuilder sb = new StringBuilder();

        int pos = 0;
        while (pos < s.Length)
        {
            // Extract next paragraph
            int start = pos;
            pos = s.IndexOf(_paraBreak, start);
            if (pos < 0)
                pos = s.Length;
            string para = s.Substring(start, pos - start).Trim();

            // Encode non-empty paragraph
            if (para.Length > 0)
                EncodeParagraph(para, sb, nofollow);

            // Skip over paragraph break
            pos += _paraBreak.Length;
        }
        // Return result
        return sb.ToString();
    }

    ///
    /// Encodes a single paragraph to HTML.
    ///
    /// <param name="s">Text to encode</param>
    /// <param name="sb">StringBuilder to write results</param>
    /// <param name="nofollow">If true, links are given "nofollow"
    /// attribute</param>
    private static void EncodeParagraph(string s, StringBuilder sb, bool nofollow)
    {
        // Start new paragraph
        sb.AppendLine("
");

        // HTML encode text
        s = HttpUtility.HtmlEncode(s);

        // Convert single newlines to

        s = s.Replace(Environment.NewLine, "
\r\n");

        // Encode any hyperlinks
        EncodeLinks(s, sb, nofollow);

        // Close paragraph
        sb.AppendLine("\r\n
");
    }

    ///
    /// Encodes [[URL]] and [[Text][URL]] links to HTML.
    ///
    /// <param name="text">Text to encode</param>
    /// <param name="sb">StringBuilder to write results</param>
    /// <param name="nofollow">If true, links are given "nofollow"
    /// attribute</param>
    private static void EncodeLinks(string s, StringBuilder sb, bool nofollow)
    {
        // Parse and encode any hyperlinks
        int pos = 0;
        while (pos < s.Length)
        {
            // Look for next link
            int start = pos;
            pos = s.IndexOf("[[", pos);
            if (pos < 0)
                pos = s.Length;
            // Copy text before link
            sb.Append(s.Substring(start, pos - start));
            if (pos < s.Length)
            {
                string label, link;

                start = pos + 2;
                pos = s.IndexOf("]]", start);
                if (pos < 0)
                    pos = s.Length;
                label = s.Substring(start, pos - start);
                int i = label.IndexOf("][");
                if (i >= 0)
                {
                    link = label.Substring(i + 2);
                    label = label.Substring(0, i);
                }
                else
                {
                    link = label;
                }
                // Append link
                sb.Append(String.Format(nofollow ? _linkNoFollow : _link, link, label));

                // Skip over closing "]]"
                pos += 2;
            }
        }
    }
}

Do you see any improvement / issue?


texts: Updating entities with EF (Delete, Add, Update) with one method

texts:
I have a WCF service, which has a method for updating a EF entity. The update method works just fine but looks ugly. I think due to some EF design I have to manually set the change tracker state to Modified or Deleted or Added. The update method in the server side looks like this:

public Event UpdateEvent(Guid sessionID, Event _event)
{
    Session session = IFSHelperClass.CheckSession(sessionID);

    try
    {
         using (IFSDB ifsdb = new IFSDB())
         {
             ifsdb.Events.Attach(_event);
             ifsdb.ObjectStateManager.ChangeObjectState(_event, System.Data.EntityState.Modified);

             // mark the modified and added items
             // for the navigation property 'EventPersons'
             foreach (var p in _event.EventPersons)
             {
                if (p.ChangeTracker.State == IFSEntities.ObjectState.Added)
                    ifsdb.ObjectStateManager.ChangeObjectState(p, System.Data.EntityState.Added);

                 if (p.ChangeTracker.State == IFSEntities.ObjectState.Modified)
                    ifsdb.ObjectStateManager.ChangeObjectState(p, System.Data.EntityState.Modified);
             }

             // since the deleted items will not be available in the
             // navigation property, delete them manually from the
             // ChangeTracker object.
             if (_event.ChangeTracker.ObjectsRemovedFromCollectionProperties.Count > 0)
             {
                 var personsToDelete = _event.ChangeTracker.ObjectsRemovedFromCollectionProperties.Where(t => t.Key == "EventPersons").Select(t => t.Value)
                     .FirstOrDefault()
                     .ToList();

                foreach (EventPerson p in personsToDelete)
                {
                  ifsdb.EventPersons.Attach(p);
                  ifsdb.EventPersons.DeleteObject(p);
                }
            }

            // save all changes and accept them
            ifsdb.SaveChanges();
            _event.AcceptChanges();
            foreach (var p in _event.EventPersons)
                p.AcceptChanges();

            return _event;
          }
      }
      catch (Exception ex)
      {
          Logger.LogError("UpdateEvent()", ex.Message, ex.ToString(), session.User.UserID);
          throw ex;
      }
 }

As you can see, II iterate through the navigation property items to check for updates or deletes and mark them manually.

Is this the way? or am I doing something ugly here?


texts:
Follow-up up on Parsing oscilloscope binary data.
I wrote a simple parser for Tektronix's internal file format .isf.
I revised my code to the following:

import numpy as np
import os.path

def parse_curve(isf_file):
    """
    Reads one tektronix .isf file and returns a dictionary containing
    all tags as keys. The actual data is stored in the key "data".
    """
    extensions = set([".isf"])
    if os.path.splitext(isf_file)[-1].lower() not in extensions:
        raise ValueError("File type unkown.")

    with open(isf_file, 'rb') as ifile:
        # read header
        header = {}
        while True:
            name = _read_chunk(ifile, " ")
            if name != ":CURVE":
                value = _read_chunk(ifile, ";")

                assert name not in header
                header[name] = value
            else:
                # ":CURVE " is the last tag of the header, followed by
                # '#XYYY' with X being the number of bytes of YYY.
                # YYY is the length of the datastream following in bytes.
                value = ifile.read(2)
                y_str = ifile.read(int(value[-1]))
                value += y_str

                # the number of bytes might be present with or without the
                # preceding header ":WFMPRE:"
                nobytes = header.get("BYT_NR",
                                     header.get(":WFMPRE:BYT_NR", "0")
                                     )
                assert int(y_str) == int(header["NR_PT"]) * int(nobytes)
                header[name] = value
                currentposition = ifile.tell()
                break

        assert header["ENCDG"] == "BINARY"

        # read data as numpy array
        header["data"] = _read_data(ifile, currentposition, header)

    return header

def _read_chunk(headerfile, delimiter):
    """
    Reads one chunk of header data. Based on delimiter, this may be a tag
    (ended by " ") or the value of a tag (ended by ";").
    """
    prior_delimiter = None
    chunk = []
    while True:
        c = headerfile.read(1)
        if c != delimiter:
            chunk.append(c)
            if c == '"':
                # switch delimiter to make sure to parse the whole string
                # enclosed in '"'.
                delimiter, prior_delimiter = c, delimiter
        elif prior_delimiter:
            # switch back delimiter
            chunk.append(c)
            delimiter, prior_delimiter = prior_delimiter, None
        else:
            return "".join(chunk)

def _read_data(bfile, position, header):
    """
    Reads in the binary data as numpy array.
    Apparently, there are only 1d-signals stored in .isf files, so a 1d-array
    is read.
    """
    # determine the datatype from header tags
    datatype = ">" if header["BYT_OR"] == "MSB" else "<"
    if header["BN_FMT"] == "RI":
        datatype += "i"
    else:
        datatype += "u"
    # BYT_NR might be present with preceding header ":WFMPRE:BYT_NR"
    nobytes = header.get("BYT_NR",
                         header.get(":WFMPRE:BYT_NR", "")
                         )
    datatype += nobytes
    assert len(datatype) >= 3

    bfile.seek(position)
    data = np.fromfile(bfile, datatype)
    assert data.size == int(header["NR_PT"])

    # calculate true values
    data = data * float(header["YMULT"]) + float(header["YZERO"])

    return data

In the original question, _read_data did a little more, this part was now moved to another module.

One concern I still have, is whether the assert part when reading the ":CURVE" tag is the best solution:

nobytes = header.get("BYT_NR",
                     header.get(":WFMPRE:BYT_NR", "0")
                     )
assert int(y_str) == int(header["NR_PT"]) * int(nobytes)


texts: Find the best pairs of elements based on match weight

texts:
While answering this question on SO I came up with a very simple solution and I wanted to know if there were improvements that could be made to it.

The function takes an array of participants as inputs, generates a list of pairs using the array of participants with an associated score (to be generated by a function comparing the elements but for now using rand()), then finds the the best possible match and return the results as an array (imagine students being matched for a team assignment).

function generatePairs($elements) {
    // $elements = [
    //     1,2,3,4,5,6
    // ];

    $elementCount = count($elements);
    $output = [];

    // build an array with every unique possible pair
    $possiblePairs = [];
    for($i = 1; $i <= $elementCount; $i++) {
        for($j = $i + 1; $j <= $elementCount; $j++) {
            $possiblePairs[] = [
                'values' => [$elements[$i - 1], $elements[$j - 1]],
                'score' => rand(1, 100) // this would be replaced by a function calculating how closely the current elements match
            ];
        }
    }

    // puts the "best" pairs on top
    usort($possiblePairs, function($a, $b) {
        return $b['score'] <=> $a['score'];
    });

    $used = [];
    foreach($possiblePairs as $key => $pair) {
        if($pair['score'] !== 0 &&
            !in_array($pair['values'][0], $used) &&
            !in_array($pair['values'][1], $used))
        {
            // save the pair to the output array
            $output[] = $pair['values'];
            // store the elements that have already been used
            array_push($used, $pair['values'][0], $pair['values'][1]);
        }
    }

    return $output;
}


texts:
I just watched a Khan Academy video on Insertion Sort and I've tried to write an implementation in Python. Please suggest corrections or improvements on this program:

unsorted_list=[45,99,1,-22,7,3,294,10,36]

def insertion_sort(unsorted):
    for i in range(1,len(unsorted)):
        for j in range(i):
            if unsorted[i]<unsorted[j]:
                temp = unsorted[j]
                unsorted[j]=unsorted[i]
                unsorted[i]=temp

    return unsorted

print insertion_sort(unsorted_list)


texts: Checking if a list of coordinates defines a closed, exact rectangle

texts:
I have to determine if an N sized list of coordinates defines a closed, exact rectangle.

I start with the question "How do I check if a list of coordinates is in the shape of a rectangle?"

The answer is:

First and last element in cordX and cordY have to be equal.
Difference between another key should be equal to 1.
Value for key <1:size-2> has to be const.

Could you tell me if this is elegant and efficient code?

public class BoardPosition {
        private int x;
        private int y;

        public int getX() {
                return x;
        }

        void setX(int x) {
                this.x = x;
        }

        public int getY() {
                return y;
        }

        void setY(int y) {
                this.y = y;
        }

        public BoardPosition(int pX, int pY) {
                y = pY;
                x = pX;
        }
}

private boolean checkifIsRectangle(ArrayList<BoardPosition> lettersPosition) {
        TreeMap<Integer, Integer> cordsX = new TreeMap<Integer, Integer>();
        TreeMap<Integer, Integer> cordsY = new TreeMap<Integer, Integer>();

        for (BoardPosition b : lettersPosition) {
            if (!cordsX.containsKey(b.getX())) cordsX.put(b.getX(), 1);
            else {
                cordsX.put(b.getX(), cordsX.get(b.getX()) + 1);
            }

            if (!cordsY.containsKey(b.getY())) cordsY.put(b.getY(), 1);
            else {
                cordsY.put(b.getY(), cordsY.get(b.getY()) + 1);
            }
        }
        boolean xIsValid = true;
        boolean yIsValid = true;

        //1
        if (cordsX.values().toArray()[0] != cordsX.values().toArray()[cordsX.values().toArray().length - 1])
            xIsValid = false;
        if (cordsY.values().toArray()[0] != cordsY.values().toArray()[cordsY.values().toArray().length - 1])
            yIsValid = false;

        //2
        int xKeyTest = -1;
        for (Integer i : cordsX.keySet()) {
            if (xKeyTest == -1) {
                xKeyTest = i;
                continue;
            }
            if ((i - xKeyTest) != 1) {
                xIsValid = false;
                break;
            }
            xKeyTest = i;
        }

        int yKeyTest = -1;
        for (Integer i : cordsY.keySet()) {
            if (yKeyTest == -1) {
                yKeyTest = i;
                continue;
            }
            if ((i - yKeyTest) != 1) {
                yIsValid = false;
                break;
            }
            yKeyTest = i;
        }

        //3
        ArrayList<Integer> xValueArray = new ArrayList<Integer>(cordsX.values());
        int xTestValue = -1;
        for (int i = 1; i < xValueArray.size() - 2; i++) {
            if (xTestValue == -1) {
                xTestValue = xValueArray.get(i);
                continue;
            }
            if (xTestValue != xValueArray.get(i)) {
                xIsValid = false;
                break;
            }
        }

        ArrayList<Integer> yValueArray = new ArrayList<Integer>(cordsY.values());
        int yTestValue = -1;
        for (int i = 1; i < yValueArray.size() - 2; i++) {
            if (yTestValue == -1) {
                yTestValue = yValueArray.get(i);
                continue;
            }
            if (yTestValue != yValueArray.get(i)) {
                yIsValid = false;
                break;
            }
        }

        return (xIsValid && yIsValid);
    }


texts:
I came across this problem:

  The following iterative sequence is defined for the set of positive
  integers:

    n → n/2 (n is even)
    n → 3n + 1 (n is odd)

  Using the rule above and starting with 13, we generate the following
  sequence:

  13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

  It can be seen that this sequence (starting at 13 and finishing at 1)
  contains 10 terms. Although it has not been proved yet (Collatz
  Problem), it is thought that all starting numbers finish at 1.

  Which starting number, under one million, produces the longest chain?

and to this I gave this solution:

def number(n):
    ctr = 1
    if n % 2 == 0:
       k = n / 2
       ctr += 1
    else:
       k = 3 * n + 1
       ctr += 1
    while k > 1:
       if k % 2 == 0:
           k /= 2
           ctr += 1
       else:
           k = k * 3 + 1
           ctr += 1
    return ctr

def k(upto):
    largest_number=0
    last_ctr=0
    for num in range(1,upto):
         if number(num)>last_ctr:
            last_ctr=number(num)
            largest_number=num
    return largest_number

print k(999999)

I am new to Python and don't think this is a  good solution to this problem and  maybe its complexity is \$\mathcal{O}(n^2)\$. So what is the best code for this problem if the number is really huge? How do I reduce the complexity?

And yes I read other questions related to this topic but they were not satisfactory answers to this in Python.


texts:
I have a list of error messages:

def errorMessages = ["Line : 1 Invoice does not foot Reported"
                     "Line : 2 Could not parse INVOICE_DATE value"
                     "Line 3 : Could not parse ADJUSTMENT_AMOUNT value"
                     "Line 4 : MATH ERROR"
                     "cl_id is a required field"
                     "File Error : The file does not contain delimiters"
                     "lf_name is a required field"]

I am trying to create a new list which doesn't match the regex "^Line\\s(?:(\\d+)\\s)?\\s*:\\s+(\\d+)?.+" but has the text Invoice does not foot Reported.

My desired new list should be like this:

def headErrors= ["Line : 1 Invoice does not foot Reported"
                 "cl_id is a required field"
                 "File Error : The file does not contain delimiters"
                 "lf_name is a required field"]

This is what I am doing for now:

regex = "^Line\\s(?:(\\d+)\\s)?\\s*:\\s+(\\d+)?.+"
errorMessages.each{
    if(it.contains('Invoice does not foot Reported'))
        headErrors.add(it)
    else if(!it.matches(regex)
        headErrors.add(it)
}

Is there a way it can be done just using regex instead of if else?


texts:
Please, review the code:

const callback = (...args) => {
  console.count('callback throttled with arguments:', args);
}

const debounce = (callback, delay) => {
  let timeoutHandler = null
  return (...args) => {
    if (timeoutHandler) {
      clearTimeout(timeoutHandler)
    }
    timeoutHandler = setTimeout(() => {
      callback(...args)
      timeoutHandler = null
    }, delay)
  }
}

window.addEventListener('oninput', debounce(callback, 100))

P.S. As @Anshul explained: Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called."


texts: Solving the sliding pyramid problem in Python3

texts:
A simple set of functions which solves the sliding pyramid problem. In summary, the task is to find the path from top to bottom of a triangular grid of numbers that has the smallest sum. The program uses the file input.txt as input.

from time import time

def build_tree():
    with open("input.txt", "r") as file:
        lines = file.readlines()
    list_tree = []
    for line in lines[1:]:
        list_tree.append([int(n) for n in line.strip().split(" ")])

    return list_tree

def min_sum(tree):
    doug = list(reversed(tree))
    above = doug[0]
    for row in doug[1:]:
        below = row
        for index, n in enumerate(below):
            below[index] += min(above[index],above[index+1])
        above = below

    return above[0]

if __name__ == "__main__":
    a = time()
    tree = build_tree()
    print(min_sum(tree), time() - a)

These samples are simple, but I appreciate any feedback.


texts: react string replace {image0} with actual image ramda?

texts:
I can feel the following is definitely not the optimal nor the cleanest way to do this. But I'm not quite sure how to refactor this.
const formatBtnText = (txt, color, image) => {
  const regex = /{image[\d]*}/g;
  const matches = [...txt.matchAll(regex)];

  if (!matches) {
    return <Text style={[styles.buttonText, { color }]}>{txt}</Text>;
  }

  const strings = txt.split(regex);
  let strIndex = 0;
  let matchIndex = 0;

  const res = [];
  for (let i = 0; i < strings.length + matches.length; i++) {
    if (i % 2 === 0) {
      // every even is string
      if (strings[strIndex] !== '') {
        res.push(
          <Text key={`${strIndex}_string`} style={[styles.buttonText, { color }]}>
            {strings[strIndex]}
          </Text>
        );
      }
      strIndex++;
    } else {
      // every other is match
      res.push(
        <Image
          key={`${matchIndex}_image`}
          source={{ uri: image.uri }}
          style={[styles.buttonImage, { width: (12 * image.width) / image.height }]}
        />
      );
      matchIndex++;
    }
  }
  return res;
};


texts: Find a specific file, or find all executable files within the system path

texts:
I wrote a function to find a specific file, or all the executable files with a given name and accessing flag, and I want to make sure it is as cross-platform as possible. Currently, I'm using the PATHEXT environment variable to get the extensions for files that the operating system considers executable.

import os

class CytherError(Exception):
    def __init__(self, message):
        Exception.__init__(self, message)
        self.message = 'CytherError: {}'.format(repr(message))

def where(name, flags=os.F_OK):
    result = []
    extensions = os.environ.get('PATHEXT', '').split(os.pathsep)
    if not extensions:
        raise CytherError("The 'PATHEXT' environment variable doesn't exist")

    paths = os.environ.get('PATH', '').split(os.pathsep)
    if not paths:
        raise CytherError("The 'PATH' environment variable doesn't exist")

    for path in paths:
        path = os.path.join(path, name)
        if os.access(path, flags):
            result.append(os.path.normpath(path))
        for ext in extensions:
            whole = path + ext
            if os.access(whole, flags):
                result.append(os.path.normpath(whole))
    return result

Usage:

In[-]: where('python')

Out[-]: "C:\Python35\python.exe"

Please be brutal in pointing out anything you find, except for:

Commenting
Docstrings
PEP 8 spacing

I will have these things covered later.


texts:
I'm quite new to C++ and want to focus on writing performant multithreaded code because I will try to port our company internal GUI framework which is currently implemented in C#. So I'd love to get some recommendations about code style and Performance on a reader-writer spin lock that favors writers I wrote:

namespace UI
{
    namespace Threading
    {
        /**
         * \brief ReaderWriterSpinLock which favors writers
         */
        class ReaderWriterSpinLock
        {
        public:
            ReaderWriterSpinLock() = default;
            ~ReaderWriterSpinLock() = default;
            ReaderWriterSpinLock(ReaderWriterSpinLock&) = delete;
            ReaderWriterSpinLock(ReaderWriterSpinLock&&) = delete;
            ReaderWriterSpinLock& operator =(ReaderWriterSpinLock&) = delete;
            ReaderWriterSpinLock& operator =(ReaderWriterSpinLock&&) = delete;

            void AcquireReaderLock()
            {
                int computedValue, initialValue;
                do
                {
                    int count{0};
                    while (m_waitingWriters != 0 || (initialValue = m_lockCount) < 0)
                    {
                        if (++count % MAX_SPIN_COUNT == 0)
                            std::this_thread::yield();
                    }
                    computedValue = initialValue + 1;
                }
                while (!m_lockCount.compare_exchange_strong(initialValue, computedValue));
            }

            void ReleaseReaderLock()
            {
                assert(m_lockCount > 0);
                --m_lockCount;
            }

            void AcquireWriterLock()
            {
                int computedValue, initialValue;
                ++m_waitingWriters;
                do
                {
                    int count{0};
                    while (m_lockCount != 0)
                    {
                        if (++count % MAX_SPIN_COUNT == 0)
                            std::this_thread::yield();
                    }
                    initialValue = 0;
                    computedValue = -1;
                }
                while (!m_lockCount.compare_exchange_strong(initialValue, computedValue));
                --m_waitingWriters;
            }

            void ReleaseWriterLock()
            {
                assert(m_lockCount == -1);
                ++m_lockCount;
            }

        private:
            static constexpr int MAX_SPIN_COUNT = 1000;
            std::atomic<int> m_lockCount{0};
            std::atomic<int> m_waitingWriters{0};
        };
    }
}

Explanation: A negative m_lockCount denotes the active writers (because there can only be one writer at a time the minimum is -1) and a positive count denotes the active readers. When aquiring the reader lock it spins (and yields every MAX_SPIN_COUNT spins) until there are no waiting writers (because it should favor those) and there are no active writers (m_lockCount >= 0), then it tries to update the lock count and repeats the process if it fails. When releasing the lock, the lock count can get decremented without further checks. The methods for the writer lock are quite similar with the difference of temporarily incrementing the m_waitingWriters instead of checking them in the acquire method.

I know that you should normally rely on library functions but in my test it was ten times faster for acquiring the writer lock and twice as fast for readers+writers (with four readers trying to acquire the reader lock in a loop) than the boost::shared_mutex in combination with the boost::shared_lock and boost::unique_lock. So it would actually be worth it.

Also in my application the thread count equals the processor count so the yield should rarely be necessary and the spin lock will only be used for methods which only need a few cycles.

I also wanted to explicitly delete the move and copy constructors because it makes sense for such a class (even though they are deleted implicitly because of the atomic fields). Is this a good idea?


texts: Merge Sort Implementation Efficiency In Python

texts:
I wasn't able to find a standardized source for a working example of Merge Sort.

Each learning site had a slightly different take on the algorithm implementation, disregarding the bottom-top implementation.

I wrote my own code for this but unsure if it's the most efficient or if efficiency can be improved?

Any other syntax/logic improvements are welcomed to be pointed out.

def merge(left, right):
    i = 0 #left index
    j = 0 #right index

    sorted_list = []

    while len(left) > i and len(right) > j:
        if left[i] > right[j]:
            sorted_list.append(right[j])
            j += 1
        else:
            sorted_list.append(left[i])
            i += 1

    sorted_list += left[i:] + right[j:]

    return sorted_list

def MergeSort(MyList):
    if len(MyList) > 1:
        mid = len(MyList) // 2
        left = MyList[mid:]
        right = MyList[:mid]

        left = MergeSort(left)
        right = MergeSort(right)

        sorted_list = merge(left, right)

        return sorted_list
    return MyList

Also, a source where I can find standardized code for most algorithms in Python would be nice?
By standardized; I mean code that is deemed efficient and the most up-to-date by the Python community.


texts: Initializing connection to a MySQL database in PHP

texts:
I wanted to get some feedback on this way of initializing a connection to a MySQL database.

File includes/db.php:

<?php
$config_path = __DIR__ .  '/../config/database.ini';

$db_ini = parse_ini_file($config_path , true);
$db_info['db_host'] = $db_ini['db_data_source_name']['host'];
$db_info['db_user'] = $db_ini['db_general']['user'];
$db_info['db_pass'] = $db_ini['db_general']['password'];
$db_info['db_name'] = $db_ini['db_data_source_name']['dbname'];

foreach($db_info as $key => $value) {
    $upper_key = strtoupper($key);
    if (!defined($upper_key)) {
        define($upper_key, $value);
    }
}

$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

?>

Is there anything wrong with the file above being included in other php files as needed?

Thank you!


texts: Event emitter in JavaScript without using Node's built in class or any additional libraries

texts:
I need to create this eventEmitter class with the functions listed below. I think I could clean the code a little but don't really know where to start.

var eventEmitter =function  (){
  this.listeners = 0;
  this.events = {};
  return this;
};

eventEmitter.prototype.on = function(ev, cb) {
  if (typeof ev !== 'string') throw new TypeError("Event should be type string", "index.js", 6);
  if (typeof cb !== 'function' || cb === null || cb === undefined) throw new TypeError("callback should be type function", "index.js", 7);

  if (this.events[ev]){
    this.events[ev].push(cb);
  } else {
    this.events[ev] = [cb];
  }

  this.listeners ++;
  return this;
};

eventEmitter.prototype.emit = function(eventType) {

  if (typeof eventType !== 'string') throw new TypeError("Event type should be type string", "index.js", 6);
  var handlerFunctions = this.events[eventType];

  if (handlerFunctions) {
    var self = this;

    for (var i = 0; i < handlerFunctions.length; i++) {
      var handler = handlerFunctions[i];

      if (arguments.length > 0) {
        var args = Array.prototype.slice.call(arguments).slice(1, arguments.length);
        handler.apply(self, args);
      } else{
        handler.call(self);
      }
    }
  }
  return this;
};

eventEmitter.prototype.off = function(eventType, handlers) {

  if ( arguments.length > 0 && (eventType === 'undefined' || typeof eventType !== 'string')) throw TypeError('listener must be a function');

  if (arguments.length > 1) {
    if ( typeof handlers !== 'function' || handlers === 'undefined') throw TypeError('handler must be a function string or object');
  }

  switch(arguments.length) {
    case 0:
      this.listeners = 0;
      this.events = {};
      break;
    case 1:
      if (this.events[eventType]) {
        this.listeners = this.listeners - this.events[eventType].length;
        delete this.events[eventType];
      }
      break;

    case 2:

      if (this.events[eventType]) {
        for (var i = 0; i < this.events[eventType].length; i++) {
           if (handlers.toString() == this.events[eventType][i].toString()){
             this.events[eventType].splice( i, 1 );
             this.listeners --;
             i --;
           }
        }
      }
      break;
  }
  return this;
};

module.exports = eventEmitter;


texts:
I just recently learned how to use Bit Field Structures in C++, and I was thinking of applying it to a project. It would certainly make the project code much easier to work with. So, I typed up a quick test program to see if it would work as I expected, and it does. But, I'm not 100% convinced that it is safe.

I am fairly confident my CRC16 union is Endianess specific, but I'm not sure about the Bit Field struct, I suspect it is... Can anyone confirm this?

Is this usage of a bit field struct safe?
Can it be made safer?
Is it Endianess specific?

Note: So far, I have only tested this on 64 bit Linux.

#include <stdint.h>
#include <cstring>
#include <iostream>
#include <iomanip>

typedef union
{
    int16_t Value;
    struct
    {
        int8_t Lo;
        int8_t Hi;
    } Bytes; //This is all I could think of to call this. If you can think of something better, let me know.
} CRC16;

#ifdef _MSC_VER
#pragma pack(push, 1)
#endif
typedef struct
{
    uint8_t SOH;
    uint16_t Count : 14;
    uint16_t Select : 1;
    uint16_t Qsync : 1;
    uint8_t Resp;
    uint8_t Num;
    uint8_t Addr;
    CRC16 Blck;
#ifdef _MSV_VER
} DataHeader;
#pragma pack(pop)
#else
}  __attribute__((packed)) DataHeader;
#endif

template<typename T>
void PrintHex(std::string Description, T Value, long Mask = -1)
{
    using namespace std;
    cout << hex
         << setiosflags(ios_base::showbase)
         << Description
         << " = "
         << (static_cast<unsigned short>(Value) & Mask)
         << resetiosflags(ios_base::showbase)
         << endl;
}

int main()
{

    DataHeader test;
    int8_t packet[8] = {0x64,0x42,0x81,0x42,0x43,0x01,0x32,0x97};

    //this is the most important part, as this structure would be
    //passed to Windows API calls, potentially file and socket I/O
    //functions, etc.
    memcpy(&test, packet, sizeof(packet));

    std::cout << "sizeof(DataHeader) = " << sizeof(DataHeader) << std::endl;
    PrintHex("SOH", test.SOH);
    PrintHex("Count", test.Count);
    PrintHex("Select", test.Select);
    PrintHex("Qsync", test.Qsync);
    PrintHex("Resp", test.Resp);
    PrintHex("Num", test.Num);
    PrintHex("Addr", test.Addr);
    PrintHex("Blck.Value", test.Blck.Value);
    PrintHex("Blck.Bytes.Lo", test.Blck.Bytes.Lo, 0xFF);
    PrintHex("Blck.Bytes.Hi", test.Blck.Bytes.Hi, 0xFF);

    return 0;

}

Output

  sizeof(DataHeader) = 8
  SOH = 0x64
  Count = 0x142
  Select = 0
  Qsync = 0x1
  Resp = 0x42
  Num = 0x43
  Addr = 0x1
  Blck.Value = 0x9732
  Blck.Bytes.Lo = 0x32
  Blck.Bytes.Hi = 0x97


texts: Sort, slice and rebuild new object with array data

texts:
I'm using the matomo reports api to pull out some data in js.
For some charts, I'm in the need to sort the array data based on inner property value ("val"), further to get only the 3 highest (Hong Kooong, Munich, Tokyo). Finally, this data should be used for the creation of a new key/val object (newObj).

This is what my code looks like what does what it should. I would be interested if it can be optimized using es6 syntax.

    let data = {
      0 : {"label":"New York", "val": 20},
      1 : {"label":"Rio", "val": 10},
      3 : {"label":"Tokyo", "val": 50},
      4 : {"label":"Santiago", "val": 20},
      5 : {"label":"Hong Kooong", "val": 100},
      6 : {"label":"Munich", "val": 90},
    }

    let compare = (a, b)  => {
      let valA = a.val;
      let valB = b.val;
      let c = 0;

      if (valA > valB) {
        c = 1;
      } else if (valA < valB) {
        c = -1;
      }
      return c * -1;
    }

    let dataArray = Object.values(data).sort(compare)
    dataArray = dataArray.slice(0, 3)

    let newLabel = []
    let newValue = []
    Object.keys(dataArray).map(function(key, index) {
      newLabel.push(dataArray[index]['label'])
      newValue.push(dataArray[index]['val'])
    });

    let newObj = {}
    newObj.data = {}
    newObj.data.labels = newLabel
    newObj.data.values = newValue

    console.log(newObj)


texts:
I'm writing a routing system that may or may not be part of a public API later for a personal project. A main part of the routing system is a response object for the user to send headers, status code, and the body of the response that is sent from the server.

I've created a response class that I think covers everything the user would want to do with the response (it could use a few more "convenience" functions however). I wanted to post it here to make sure my code is clean, and that I didn't miss anything that the end user might want to do.

An instance of the request class is provided to the user when a request is made to a specified URL (see my last code review)

I present my response class:

    class Response {

    private $headers = array();
    private $code = 200;
    private $body = '';
    private $sent = false;

    private $log;

    public function __construct() {
        $this->log = Logger::getLogger(get_class($this));
    }

    public function headers ($headers) { // Add some headers to the headers array
        $this->headers = array_merge($this->headers, $headers);
        return $this;
    }

    public function header ($key, $value) { // set a single header in the headers array
        $this->headers[$key] = $value;
        return $this;
    }

    public function code ($code) { // Set the status code
        $this->code = $code;
        return $this;
    }

    public function status ($code) { // Alternate method for setting the status code
        return $this->code($code);;
    }

    public function json($str) { // respond with json, set the body text and set the content-type header
        $this->header('Content-Type', 'application/json');
        if(is_array($str)) { // handle either raw JSON text, or php arrays
            $this->body = json_encode($str);
        } else {
            $this->body = $str;
        }
        return $this;
    }

    public function html ($str){ // respond with HTML
        $this->header('Content-Type', 'text/html');
        $this->body = $str;
        return $this;
    }

    public function form ($str) { // Respond with form data
        $this->header('Content-Type', 'application/x-www-form-urlencoded');
        // TODO: Allow the user to user an array
        $this->body = $str;
        return $this;
    }

    public function render ($file){ // Render an HTML file from the templates folder
        //TODO: Restrict to templates folder open
        //TODO: Add server-side rendering code
        $this->body = file_get_contents($file);
        return $this;
    }

    public function sent() { // Check if the request has been sent
        return $this->sent;
    }

    public function send () { // send the request
        if($this->sent()){
            $log->error('Attempted to call send on a sent response!');
            exit('Attempted to call send on a sent response!');
        }
        // Log the request for debugging
        $this->log->info($this->headers);
        $this->log->info('HTTP Responce Code: ' . $this->code);
        $this->log->info($this->body);
        // Set the headers
        foreach($this->headers as $key => $value) {
            header($key .': ' . $value);
        }
        // Set the status code
        http_response_code($this->code);

        // Send out the body
        echo $this->body;

        // Set the sent variable
        $this->sent = true;
    }
}

EDIT:
The idea with the short and clear function names that all return $this is to be able to have clear and simple chainable responses. (e.g $res->code(200)->json(... Json...);)


texts:
I have an extension method that does this:

public static IEnumerable<T> ToIEnumerable<T>(this T source) where T : new()
{
    return new[] { source };
}

I need to be able to convert any object to an IEnumerable.

For example when I use the .NET Except method:

public static IEnumerable<TSource> Except<TSource>(this IEnumerable<TSource> first)

I can call Except by doing the following:

return objects.Except(this.ToIEnumerable());

Is ToIEnumerable<T> good practice or should I solve the problem in differently?


texts: How to get two JavaScript classes to talk to each other?

texts:
I'm a budding JavaScript programmer, working on an exercise where I'm trying to create two classes (Books and Shelf) and need to have a shelf know what books are on it. I'm pretty new to OOP so I know I'm missing a crucial step (or three). I probably already ran off the rails, but any point in the right direction would be greatly appreciated.

<!DOCTYPE HTML>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Library</title>


texts: Efficiently performing multiple nested grouping and mapping in Javascript

texts:
I have an array of log objects with log_types and dates, like this:
[
  {
    log_type: 'eventOne',
    date: '2020-08-27T00:00:00+00:00'
  },
  {
    log_type: 'eventOne',
    date: '2020-08-27T00:00:00+00:00'
  },
  {
    log_type: 'eventTwo',
    date: '2020-08-27T00:00:00+00:00'
  },
  {
    log_type: 'eventTwo',
    date: '2020-08-27T00:00:00+00:00'
  },
  {
    log_type: 'eventTwo',
    date: '2020-08-27T00:00:00+00:00'
  },
  {
    log_type: 'eventOne',
    date: '2020-08-27T00:00:00+00:00'
  },
]

For charting purposes, I need group all these logs by their log_types. Then I need to take all the logs for each log type, and group them by date. These will be formatted where t is the date and y is the count of that date occurring. Like this:
{
  eventOne: [
    { x: 2020-08-21T04:00:00.000Z, y: 0 },
    { x: 2020-08-22T04:00:00.000Z, y: 6 },
    { x: 2020-08-23T04:00:00.000Z, y: 0 },
    { x: 2020-08-24T04:00:00.000Z, y: 16 },
    { x: 2020-08-25T04:00:00.000Z, y: 0 },
    { x: 2020-08-26T04:00:00.000Z, y: 0 },
    { x: 2020-08-27T04:00:00.000Z, y: 22 }
  ],
  eventTwo: [
    { x: 2020-08-21T04:00:00.000Z, y: 0 },
    { x: 2020-08-22T04:00:00.000Z, y: 0 },
    { x: 2020-08-23T04:00:00.000Z, y: 1 },
    { x: 2020-08-24T04:00:00.000Z, y: 0 },
    { x: 2020-08-25T04:00:00.000Z, y: 0 },
    { x: 2020-08-26T04:00:00.000Z, y: 0 },
    { x: 2020-08-27T04:00:00.000Z, y: 17 }
  ]
}

So in plain english the goal is to get the number of events that were logged for each day, for each log type.
I've accomplished this, but it is a series of mangled lodash functions to where any sense of readability or efficiency has gone out the window.
// First group by log_type
const logTypes = _.groupBy(logs, 'log_type');

const mappedLogs = {};
// Iterate through each log type
_.forOwn(logTypes, (value, key) => {
  const logDates = _.chain(value)
     // For each log type, group by date
     .groupBy('date')
     // Then map each log to the correct format
     .map((logValue, logKey) => ({ t: logKey, y: logValue.length }))
     .value();
  // Once we get the final mapped date values, assign them to the final object
  mappedLogs[key] = logDates;
});

I'm really hoping to find a way to do this more efficiently, I'm having trouble determining the efficiency of this current algorithm but I know the initial _groupBy touches each log O(n), the second _forOwn plus _groupBy I believe is another O(n), then the final mapping to correct format would own another O(n).
This is an application where there could be many thousands of logs so that is not an ideal efficiency.


texts: Creating a real unit test in Karma for Angular code

texts:
This is a piece of test code made for the Angular application.

The router object is a mock provided by the RouterTestingModule dependency. I wonder if such a test can be considered a unit test (because it actually tests only one element and the fact that it calls some method - without checking its result), or should it be called an integration test (due to the fact that it still call external dependence)?

it('should trigger the navigation to `/home`', async(() => {
  const link = fixture.debugElement.nativeElement.querySelector('.home-link');

  link.click();

  expect(router.navigateByUrl).toHaveBeenCalled();
}))


texts: How can this rails controller test be cleaner refactored?

texts:
I tend to write quite explicit tests for my rails controllers exposing APIs with two seperate concerns:

meeting the defined API-Response with headers headers and the response itself
ensuring the right calls to underlaying methods/objects are made

However when the calls are not simply executable in a test the controller tends to get bloated.
This is due to the fact that when the calls are stubbed out the execution order of the two test concerns is reversed:

for the api calls:

first stub the call method (since we don't want this to be run)
make the request
test the response

for the method calls

define the receive-expectations
make the request

Example Code:

require 'spec_helper'

describe ItemsController do
  render_views

  shared_examples :empty_success_response do
    it { expect(response.status).to eql(202) }
    it { expect(response.content_type).to eql('application/json')}

    it 'returns error message' do
      json = JSON.parse(response.body)
      expect(json).to be_blank
    end
  end

  context 'a single item' do
    subject { FactoryGirl.create(:item) }

    describe '#destroy' do
      let(:do_action) do
        delete :destroy, id: subject.id.to_s
      end

      describe 'response' do
        before do
          controller.stub!(:destroy_item)
          do_action
        end

        it_behaves_like :empty_success_response
      end

      it 'makes the call' do
        expect(controller).to receive(:destroy_item).once.times.with(subject.id.to_s)
        do_action
      end
    end

    # ...

  end

end

Note: The destroy_item method is just a stand in, the actual method makes more sense ;)

The code in the example works nicely, and is even fairly dry (mostly because the request is moved into a let), but feels still very chunky and bloated - especially if we consider this is just one simple actions, with a usual controller having quite a few more real logic to test.

Does anyone have an idea how to make this code more readable?

Or does it maybe make sense to split the 2 kinds of tests completely? This would however mean quite a bit of duplication since we have the same caller-code in 2 places.


texts: Run the most recently requested action after finishing current, skip middle tasks

texts:
The goals for the code below are in the class summary below. Can anyone see that the code fails at any of those goals? I'm unsure how to thoroughly test it. Is there a way to keep the Queue method thread-safe and remove the lock? Is that lock even necessary?

/// <summary>
/// The goals: only run the most recently queued action.
/// Do not run any actions simultaneously.
/// Skip any tasks that were unstarted if we get a new one.
/// Cancel the currently running task (without aborting the thread).
/// (Rely upon the code in the action to bail early).
/// Support the "IsCanceled" flag on any task that was canceled or skipped.
/// </summary>
public class SingleTaskQueue
{
    private Task _task = TaskUtilities.FromResult(false); // using Task.FromResult in .NET 4.5
    private CancellationTokenSource _cts = new CancellationTokenSource();
    private Action<CancellationToken> _action;
    public Task Queue(Action<CancellationToken> action) // this needs to be thread-safe
    {
        lock (_task) // yes, this changes with each call to Queue
        {
            _action = action;
            var newSource = new CancellationTokenSource();
            var tokenSource = Interlocked.Exchange(ref _cts, newSource);
            tokenSource.Cancel();
            var ret = _task.ContinueWith(justFinished => ProcessLastAction(newSource.Token), newSource.Token);
            _task = ret;
            return ret;
        }
    }

    private void ProcessLastAction(CancellationToken token)
    {
        if (!token.IsCancellationRequested)
        {
            Action<CancellationToken> last = Interlocked.Exchange(ref _action, null);
            if (last != null)
                last.Invoke(token);
        }
    }
}


texts:
I want to get latest time slots for 2 cases based on doorman true for false based on logged in user.

Cases are:

If doorman is true, the query will be the same
if doorman is false, then I need to add a parameter in the query for doorman that its is false so give me only records having none in them

So, it's the same query almost that will work for both cases with little modification.

def self.latest_pickup_date current_zone,doorman
    if doorman
      latest_timeslot = Timeslot.where(dropoff_slots: '-1', zone_id: current_zone).order(:slot_date).last
      // it is working fine
    else
      latest_timeslot = Timeslot.where(dropoff_slots: '-1', zone_id: current_zone, doorman_type: "none").order(:slot_date).last
      // it also does the same job but need to need check if doorman is none, so need refactoring my queries to use one query for both cases
    end
    latest_timeslot.nil? ? Date.current : latest_timeslot.slot_date
  end

I would like to refactor my code and the query in a way to use the approach of DRY.

I do not want to write these queries twice in both cases. I need a better solution using code practices. Or if I am doing this right way, you can advice as well. Plus, I need good professional code practices and code refactoring as well.


texts:
Given an array of integers and an integer k, you need to find the
  total number of continuous subarrays whose sum equals to k.

  For example:

  Input: nums = [1,1,1], k = 2

  Output: 2

  The length of the array is in range [1, 20,000]. The range of numbers
  in the array is [-1000, 1000] and the range of the integer k is [-1e7,
  1e7].

I came up with the following solution, which fails for a list with a 10,000 elements due to maximum recursion depth.

What changes can I make in the following code to improve it? Also, I am learning to use recursion, so what best practices can I employ for problems of this kind?

class Solution(object):
    def subarraySum(self, nums, k):  #driver method
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if k==0:
            return 0
        return self.func2(0,nums,k,[],0)

    def func2(self,index,nums, k, path, cnt):
        """
        index= index of the array
        nums=input array
        k=sum
        path=elements seen so far in contiguous manner whose sum is less than or equal to k
        cnt=counter of no of subarrays found so far
        """
        if index==len(nums):
            return cnt
        if nums[index]+sum(path)<k: #if total sum is less than k
            path.append(nums[index])
            cnt=self.func2(index+1,nums,k,path, cnt)
        elif nums[index]+sum(path)==k: #if total sum is equal to k
            path.append(nums[index])
            path=path[1:]
            cnt+=1
            cnt=self.func2(index+1,nums,k,path,cnt)
        else: #if total sum > k
            path=path[1:]
            if len(path)>0:
                cnt=self.func2(index,nums,k,path,cnt)
            else:
                cnt=self.func2(index+1,nums,k,path,cnt)
        return cnt