texts:
My aim is to prevent authenticated users from voting more than once. I am using angularfire2. The code gives me the expected behavior and I was wondering the better way of doing this. The rateStatus(status: Status) function works, but is there any better way I would or should write this?

service.ts

@Injectable()
export class StatusService {
path:any;
urlService: 'eStatus';
_uid;
_username;
user: {};
_tags;
private isloggedIn = new BehaviorSubject(false);
statusList: FirebaseListObservable<any[]>;
  constructor(
    private storeHelper: StoreHelper,
    private af: AngularFire,
    private _http: Http
  ) {

    this.af.auth.subscribe(user => {
       if(user) {
           this._uid = user.uid;
           this._username = user.auth.displayName;
       }});

    this.statusList = this.af.database.list('eStatus',  {
      query: {
        orderByChild: 'createdAt'
      }
    });

  }

  rateStatus(status: Status) {
    this.path = this.af.database.object(`eStatus/${status.sid}`);
    let rStatusUser = this.af.database.object(`eRatingUsers/${status.sid}`);
    rStatusUser.subscribe(value => {
      if(value.uid == this._uid){
        console.log("already voted");
      } else {
         return rStatusUser.set({
          uid: this._uid
        })
        .then(_ =>  this.path.update({ rating: status.rating + 1 }))
        .catch(err => console.log(err, 'You dont have access!'));
      }

    });

  }

}


texts:
This is my first major project in F#, looking for any critique on how I can make it more standard or more concise.
Some things I feel like I could have done better are the command flag parsing and the actual crypto random generation itself. I do know that crypto generators are slower than pseudo rng but I figure that a crytpo generator is better for generating something that should be secure.

open System.Security.Cryptography
open System.Text
open System

[<EntryPoint>]
let main argv =
    let rec contains item list : bool =
        match list with
        | [] -> false
        | head::tail -> (head = item) || contains item tail

    let strContainsOnlyNumber (s:string) = System.UInt32.TryParse s |> fst

    let rec buildChars chars (args: string list) : char list =
        let numbers = ['0'..'9']
        let lower = ['a'..'z']
        let upper = ['A'..'Z']
        let special = ['!' .. '/'] @ ['@']
        match args with
        | [] -> lower @ upper @ numbers
        | head::_ when args.Length = 1 && strContainsOnlyNumber head -> (chars @ lower @ upper @ numbers)
        | head::tail when head = "-l" || head = "--lower" ->if tail.Length > 0 then buildChars (chars @ lower) tail else chars @ lower
        | head::tail when head = "-u" || head = "--upper" -> if tail.Length > 0 then buildChars (chars @ upper) tail else chars @ upper
        | head::tail when head = "-s" || head = "--special" -> if tail.Length > 0 then buildChars (chars @ special) tail else chars @ special
        | head::tail when head = "-n" || head = "--numeric" -> if tail.Length > 0 then buildChars (chars @ numbers) tail else chars @ numbers
        | _::tail when chars.Length = 1 && tail.Length = 0 -> lower @ upper @ numbers
        | _::tail when chars.Length = 1 -> buildChars chars tail
        | _ -> chars

    let rec buildString  (bytes: byte list) (chars: char list) (builder: StringBuilder) : string =
        match bytes with
        | [] -> builder.ToString()
        | head::tail -> buildString tail chars <| builder.Append chars.[(int) head % chars.Length]

    use rng = new RNGCryptoServiceProvider()
    let bytes : byte array = Array.zeroCreate <| if strContainsOnlyNumber(argv.[0]) then Convert.ToInt32 argv.[0] else 16
    rng.GetBytes(bytes)
    let byteList : byte list = bytes |> Array.toList

    let characters = (buildChars [' '] (argv |> Array.toList)).Tail

    let sb = StringBuilder()
    let pass = buildString byteList characters sb

    printfn "%s" <| pass

    0


texts: Using Autofac to do DI in a static factory method

texts:
I'm using Autofac to create one of my classes inside of a static factory method Create. This code is working and I haven't noticed any side effects yet. Admittedly, I've only used it in unit-tests so far but I'm wondering whether there could be any issues with it later when I take it into production code?

public static ICommandLineExecutor Create(ILogger logger)
{
    var containerBuilder = new ContainerBuilder();

    containerBuilder
        .RegisterType<CommandLineTokenizer>()
        .As<ICommandLineTokenizer>();

    containerBuilder
        .RegisterType<CommandLineParser>()
        .As<ICommandLineParser>();

    containerBuilder
        .RegisterType<CommandParameterFactory>()
        .WithParameter(new TypedParameter(typeof(TypeConverter), CommandParameterFactory.DefaultConverter))
        .As<ICommandParameterFactory>();

    containerBuilder
        .RegisterType<CommandLineExecutor>()
        .WithParameter(new TypedParameter(typeof(ILogger), logger))
        .As<ICommandLineExecutor>();

    using (var container = containerBuilder.Build())
    using (var scope = container.BeginLifetimeScope())
    {
        return scope.Resolve<ICommandLineExecutor>();
    }
}


texts: Clean up this Ruby code under DRY principle

texts:
I've got the following code, which works, but seems repetitive. Under DRY principle, how can I clean this up?

puts "Blurt out a word"
word = gets.chomp
word_list = []
word_list.push word

until word == ""
  word = gets.chomp
  word_list.push word
end

puts word_list.sort


texts: How can I optimize this hash string function?

texts:
I'm writing a function which gets two strings and a number k as an input, and outputs a string with length k which is present in both strings.  I want to do this using the function hash_sequence().

I need my code to be as efficient as possible because my inputs are very large strings.

def hash_sequence(string, k):

    dictionary={}
    for i in range(len(string)-(k-1)):
        triplet = string[i:i+k]
        dictionary.setdefault(triplet,[]).append(i)
    return dictionary

def intersects(string1, string2, k):
    itr=min(len(hash_sequence(string1,k)),len(hash_sequence(string2,k)))
    for i in range(itr):
        if list(hash_sequence(string1,k))[i] in hash_sequence(string2,k):
            return list(hash_sequence(string1,k))[i]
    return None


texts: Solution to Google Code Jam 2008 round 1C problem B

texts:
This is my solution to Google Code Jam 2008 round 1C problem B (Ugly Numbers). I think it's very elegant. However, I wonder if it's too concise. What could I improve here?

The problem:

  Once upon a time in a strange situation, people called a number ugly
  if it was divisible by any of the one-digit primes (2, 3, 5 or 7).
  Thus, 14 is ugly, but 13 is fine. 39 is ugly, but 121 is not. Note
  that 0 is ugly. Also note that negative numbers can also be ugly; -14
  and -39 are examples of such numbers.

  One day on your free time, you are gazing at a string of digits,
  something like:

  123456

  You are amused by how many possibilities there are if you are allowed
  to insert plus or minus signs between the digits. For example you can
  make

  1 + 234 - 5 + 6 = 236

  which is ugly. Or

  123 + 4 - 56 = 71

  which is not ugly.

  It is easy to count the number of different ways you can play with the
  digits: Between each two adjacent digits you may choose put a plus
  sign, a minus sign, or nothing. Therefore, if you start with D digits
  there are 3^D-1 expressions you can make.

  Note that it is fine to have leading zeros for a number. If the string
  is "01023", then "01023", "0+1-02+3" and "01-023" are legal
  expressions.

  Your task is simple: Among the 3^D-1 expressions, count how many of
  them evaluate to an ugly number.

  Input

  The first line of the input file contains the number of cases, N. Each
  test case will be a single line containing a non-empty string of
  decimal digits.

  Output

  For each test case, you should output a line

  Case #X: Y

  where X is the case number, starting from 1, and Y is the number of
  expressions that evaluate to an ugly number.

Code:

from functools import lru_cache

M = 2*3*5*7
uglies = list(filter(lambda n: (int(n)%2 == 0 or
                                int(n)%3 == 0 or
                                int(n)%5 == 0 or
                                int(n)%7 == 0),
                     range(M)))

@lru_cache(maxsize=None)
def f(line, k=None):
    if k == None:
        return sum([f(line, k) for k in uglies])

    return sum([
        (1 if (int(line) % M) == k else 0),

        sum([f(line[:p],
               (k-int(line[p:])) % M)
             for p in range(1, len(line))]),

        sum([f(line[:p],
               (k+int(line[p:])) % M)
             for p in range(1, len(line))]),
        ])

if __name__ == '__main__':
    import sys
    data = sys.stdin.read().splitlines()[1:]
    case = 1
    for line in data:
        print('{:.0%}'.format(case/len(data)), file=sys.stderr)
        print('Case #{}: {}'.format(case,
                                    f(line)))
        case += 1


texts: Is this a fair use for a factory pattern?

texts:
class AcmeFactory
{
   public static function anvil()
   {
      $crud           = new Crud;
      $productTypes   = new ProductTypes($crud);
      $productImages  = new ProductImages($crud);
      $product        = new Anvils ($crud, $productImages);
      $productManager = new ProductManager ($productTypes, $product);

      return $productManager;
   }

   public static function jetPack()
   {
      $crud           = new Crud;
      $productTypes   = new ProductTypes($crud);
      $productImages  = new ProductImages($crud);
      $product        = new JetPacks ($crud, $productImages);
      $productManager = new ProductManager ($productTypes, $product);

      return $productManager;
   }
}

I know the above code works, but am I using the factory pattern correctly?

The intended result is this:

$anvil = new AcmeFactory::anvil();
$anvil->create($weight);
$anvil->display($id);
.....


texts: Represent a Class which holds translation Strings

texts:
I have a class which represents some translations of a keyword.

public abstract class Name {

    private String name;
    private String name_de;
    private String name_it;
    private String name_fr;
    private String name_hu;
    private String name_cs;

    public Name(String name_key, String name_de, String name_it, String name_fr, String name_hu, String name_cs) {
        super();
        this.name = name_key;
        this.name_de = name_de;
        this.name_it = name_it;
        this.name_fr = name_fr;
        this.name_hu = name_hu;
        this.name_cs = name_cs;
    }

Each translation has to be an own field because of saving purpose. The problem here is that I cant make sure that for instance the german translation is really the second parameter.

I was thinking about to create an own Object for each translation, but seems a litte bit of overhead. Are there any other options to represent a translation class?


texts:
I am considering

        <input type="checkbox" name="arConfig[3]" value="payout"
            <cfif ListFind(attributes.config[3], "payout") NEQ 0>checked="checked"</cfif>  /> Payout

        <input type="checkbox" name="arConfig[3]" value="points"
            <cfif ListFind(attributes.config[3], "points") NEQ 0>checked="checked"</cfif>  /> Points

        <input type="checkbox" name="arConfig[3]" value="quarter"
            <cfif ListFind(attributes.config[3], "quarter") NEQ 0>checked="checked"</cfif>  /> Quarter

Vs

        <input type="checkbox" name="arConfig[3]" value="payout"
             <cfif ListFind(attributes.config[3], "payout") GT 0>checked="checked"</cfif>  /> Payout

        <input type="checkbox" name="arConfig[3]" value="points"
             <cfif ListFind(attributes.config[3], "points") GT 0>checked="checked"</cfif>  /> Points

        <input type="checkbox" name="arConfig[3]" value="quarter"
             <cfif ListFind(attributes.config[3], "quarter") GT 0>checked="checked"</cfif>  /> Quarter

Which is clearer the NEQ 0 or the GT 0 ?


texts:
I tried to look up and suck in most of the information about optimizing this operation and this is what I came up with. As it's pretty much core of the game, I really would like to have it performant as much as I can. I would appreciate if someone can take a look at this and possibly find weak spots.

Note: I am using Browserify, hence that module.exports. Don't get confused, it is supposed to run in the browser.

module.exports = (tickModule, app) ->

    # Function to retrieve current timestamp, hopefully using window.performance object
    getTime = if (perf = window.performance)? then -> perf.now() else Date.now

    # Store the reference so there is no need for scope lookup in every tick
    raf = window.requestAnimationFrame

    # Indicates if module is running
    running = false

    # Holds identifier for cancelAnimationFrame call
    requestId = null

    # Timestamp of the last run of the tick
    previous = 0

    # Run the tick loop
    tick = ->
        return unless running

        # Request frame and store identifier
        requestId = raf tick

        # Retrieve current timestamp
        timestamp = getTime()

        # Calculate number of seconds from last tick
        delta = (timestamp - previous) * 0.001

        # Store the timestamp for the next round
        previous = timestamp

        # Emit event with delta
        app.land.emit 'tick', delta, timestamp

    # Start ticking when module start
    tickModule.addInitializer ->
        previous = getTime()
        running = true
        tick()

    # Stop ticking when module stops
    tickModule.addFinalizer ->
        running = false
        window.cancelAnimationFrame requestId

I am thinking about removing that requestId and running, since I am not really planning to stop the ticking once it starts. It was made merely like nice gesture, but it's not that useful for the game I suppose.


texts: Generic getting single value from DB in C#

texts:
Few months ago I posted my code Getting a single value from the DB. I implemented suggested changes and this is how it looks like right now:

public class DataBase : Page
{

    protected static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    protected static string ConnectionString;

    public DataBase()
    {
        ConnectionString = GetConnectionString();
    }

    public static String GetConnectionString()
    {
        return ConfigurationManager.ConnectionStrings["abc"].ConnectionString;
    }

    public static T GetValue<T>(string query)
        where T : IComparable, IConvertible, IEquatable<T>
    {
        Object value = GetValue(query);
        if (Convert.IsDBNull(value))
            return GetDefaultValue<T>();
        return (T)Convert.ChangeType(value, typeof(T));
    }

    public static T GetDefaultValue<T>()
        where T : IComparable, IConvertible, IEquatable<T>
    {
        if (typeof(T) == typeof(String))
            return (T)(object)String.Empty;
        return default(T);
    }

private static Object GetValue(string query)
    {
        try
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            using (SqlCommand command = new SqlCommand(query, connection))
            {
                connection.Open();
                return command.ExecuteScalar();
            }
        }
        catch (Exception e)
        {
            LogQueryError(query, e);
            return DBNull.Value;
        }
    }

protected static void LogQueryError(string query, Exception e)
    {
        log.Error(string.Format("Error while executing Query ({0}): {1}", query, e.Message));
    }
}

One explanation. The purpose of where T : IComparable, IConvertible, IEquatable<T> is to have single method for value types and strings. (inspired by C# Generic constraints to include value types AND strings

What do you think about this piece of code?


texts: Static ConcurrentDictionary to maintain static objects

texts:
I am using following code to maintain some static information. The problem I see with it is that, if the information retrieved using GeKeysFromCache is modified without using lock keyword it may lead to exceptions in a multithreaded environment. Is there a way to improve this implementation?

public class CacheHelper
{
    private static ConcurrentDictionary<string, List<InstanceField>> m_InstancesCached = new ConcurrentDictionary<string, List<InstanceField>>();
    private static readonly Object _entriesLock = new object();

    public List<InstanceField> GeKeysFromCache(string cacheKey)
    {
        return m_InstancesCached.GetOrAdd(cacheKey, (key) =>
        {
            return new List<InstanceField>();
        });
    }

    public void AddKeysToCache(string cacheKey, List<InstanceField> inputs)
    {
        m_InstancesCached.AddOrUpdate(cacheKey, inputs, (key, oldValue) =>
        {
            lock (_entriesLock)
            {
                oldValue.AddRange(inputs);
                return oldValue;
            }
        });
    }
}

Test Code: Without lock keyword it fails

public class ThreadSafeCachingTest
{
    private static readonly Object _entriesLock = new object();
    public ThreadSafeCachingTest()
    {
    }

    public void Invoke()
    {
        var thread1Completed = false;
        var thread2Completed = false;
        var thread3Completed = false;
        var threadList = new List<Thread>();

        var instanceName = "MyInstance";
        var beforeCachingData = (new CacheHelper()).GeKeysFromCache(instanceName);

        threadList.Add(new Thread(() =>
        {
            //lock (_entriesLock)
            //{
            var instanceFields1 = (new CacheHelper()).GeKeysFromCache(instanceName);
            instanceFields1 = instanceFields1 ?? new List<InstanceField>();

            for (int i = 0; i < 10000; i++)
            {
                instanceFields1.Add(new InstanceField() { FieldName = "FieldName-" + i.ToString() });
            }
            thread1Completed = true;
            //}
        }));

        threadList.Add(new Thread(() =>
        {
            //lock (_entriesLock)
            //{
            var instanceFields2 = (new CacheHelper()).GeKeysFromCache(instanceName);
            instanceFields2 = instanceFields2 ?? new List<InstanceField>();

            for (int i = 10000; i < 20000; i++)
            {
                instanceFields2.Add(new InstanceField() { FieldName = "FieldName-" + i.ToString() });
            }
            thread2Completed = true;
            //}
        }));

        threadList.Add(new Thread(() =>
        {
            //lock (_entriesLock)
            //{
            while (!(thread1Completed && thread2Completed && thread3Completed))
            {
                var instanceFields3 = (new CacheHelper()).GeKeysFromCache(instanceName);
                if (instanceFields3.Count > 0)
                {
                    instanceFields3.RemoveAt(0);
                }
                else
                {
                    thread3Completed = true;
                }
                //}
            }
        }));

        foreach (Thread t in threadList) t.Start();
        foreach (Thread t in threadList) t.Join();

        var afterCachingData = (new CacheHelper()).GeKeysFromCache(instanceName);
    }
}

public class InstanceField
{
    public string FieldName { get; set; }
}


texts:
I'm trying to randomly shuffle an collection of integers within a List and I have came up with two shuffling method that does the job. However, I'm not sure which one works better. Does any one have any comments or suggestions?

public class TheCollectionInterface {

    public static <E> void swap(List<E> list1, int i, int j){
        E temp = list1.get(i);
        list1.set(i, list1.get(j));
        list1.set(j, temp);
    }

//alternative version
//    public static void shuffling(List<?> list, Random rnd){
//        for(int i = list.size(); i >= 1; i--){
//            swap(list, i - 1, rnd.nextInt(i));
//        }
//    }

    public static <E> void shuffling(List<E> list1, Random rnd){
        for(int i = list1.size(); i >= 1; i--){
            swap(list1, i - 1, rnd.nextInt(list1.size()));
        }
    }

    public static void main(String[] args) {

        List<Integer> li2 = Arrays.asList(1,2,3,4,5,6,7,8,9);

        Random r1 = new Random();

        TheCollectionInterface.shuffling(li2, r1);

        System.out.println(li2);
    }
}


texts:
Write a function that takes 2 inputs:

a matrix, for example 2-dimensional array, and
indices, for example [row, col]

This function should return the sum of all the second input's neighbors (up, down, left, right, diagonals).

Below is my solution. Just wanted to know if there is a better way to solve this problem. And also wanted to know if I am covering all the edge cases.

function findingNeibors(myArray, i,j) {

let rowLimit = myArray.length-1;
let columnLimit= myArray[0].length-1;
let sum = 0;

if(i<0 || j< 0) {
    console.log("invalid Index")
    return
  };

if(i>rowLimit || j> columnLimit){
    console.log("You are Out Of Bound");
    return;
}

  for(let x = Math.max(0,i-1); x<=Math.min(i+1,rowLimit); x++){
  for(let y = Math.max(0,j-1); y<=Math.min(j+1,columnLimit); y++){
    if(x!==i || y!==j){
        console.log(myArray[x][y]);
        sum+=myArray[x][y];
    }
    }
  }
  return sum;
}

let input = [
  [0,1,2,3,4],
  [1,2,3,4,5],
  [2,3,4,5,6]
]

findingNeibors(input,0,0);
findingNeibors(input,2,2,0);
findingNeibors(input,-1,3);
findingNeibors(input,3,4);

```


texts:
Here is the code and it is really slow, like seconds slow to render about 25 labels.

extension UILabel{
    func deBlur(){
        for subview in self.subviews {
            if (subview.tag == 99999) {
                subview.removeFromSuperview()
            }
        }
    }

    func blur(){
        let  blurRadius:CGFloat = 5.1

        UIGraphicsBeginImageContext(bounds.size)
        layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        let blurFilter = CIFilter(name: "CIGaussianBlur")
        blurFilter?.setDefaults()
        let imageToBlur = CIImage(cgImage: (image?.cgImage)!)
        blurFilter?.setValue(imageToBlur, forKey: kCIInputImageKey)
        blurFilter?.setValue(blurRadius, forKey: "inputRadius")
        let outputImage: CIImage? = blurFilter?.outputImage
        let context = CIContext(options: nil)
        let cgimg = context.createCGImage(outputImage!, from: (outputImage?.extent)!)
        layer.contents = cgimg!
    }
}

So this takes way too much time. For 20 labels it takes seconds on the simulator.


texts: How to make this random number game better?

texts:
I'm a newbie trying to teach myself Python. Could somebody tell me if there is a better way to write this?  I am also curious as to whether or not there is anything I should not do.  This code does work, but some indentation may have been lost when I pasted it.

import random

def game():
    yes = ['y', 'Y', 'Yes', 'yes']
    number = random.randint(1, 20)
    numAttempts = 0
    print('')
    name = input('What is your name? ')

    print('')
    print('Nice to meet you', name, '! I am going to guess a random number! You will have 3 tries to guess it. '
                                'Good luck!')

    while numAttempts < 3:
        print('')
        guess = int(input('Guess the number I have chosen between 1 and 20. '))
        numAttempts += 1
        if guess == number:
            print('')
            print('You guessed correctly! The number was', number, "!", 'Great Job', name, '!')
            break
        elif guess > number:
            print('')
            print('The number is lower than', guess, "!")
        elif guess < number:
            print('')
            print('The number is Higher than', guess, "!")
    else:
        print('')
        print('Sorry, the number I chose was', number, 'but you have used all 3 tries', name, '!')

    print('')
    gameover = input("Would you like to play again? Yes or No? ")
    while gameover in yes:
        game()
    else:
        print('')
        print('You should have chose yes. You computer will now explode!')

game()


texts: increase the efficiency of a matching algorithm

texts:
I'm trying to create an algorithm that will match one set of objects with another.  Each of the objects from one group can be matched with some of the objects from another group. Once an item has been matched, it cannot be matched to another item.  My current implementation iterates over each of the objects and attempts to find a solution where each object has a match. I've done this recursively, but this method quickly becomes unusable as the processing time increases exponentially.  Here is a trivial example of what I've written:

def demo_match():
    possible_matches = {
        "x": {1, 2},
        "y": {2, 3},
        "z": {1, 2}
    }

    used_numbers = set()

    matched = {}

    def match_items(remaining_items_to_match):

        for letter in remaining_items_to_match:
            possible_numbers = possible_matches[letter]
            available_numbers = possible_numbers.difference(used_numbers)
            print(f"can match '{letter}' with {available_numbers}")
            if not available_numbers:
                raise ValueError(f"there are no possible matches for {letter}")
            for possible_match in available_numbers:
                try:
                    used_numbers.add(possible_match)
                    matched[letter] = possible_match
                    print(f"'{letter}' has been matched with {possible_match}")
                    if len(remaining_items_to_match) is 1:
                        return matched
                    # remove this item and process the remaining
                    next_remaining_items = remaining_items_to_match[1:]
                    return match_items(next_remaining_items)
                except ValueError:
                    print(f"***** found a dead end, unmatching '{letter}' and {possible_match} *****")
                    used_numbers.remove(possible_match)
                    del matched[letter]
            raise ValueError("ran out of available numbers to match")

    print(f"\nMatch Solution: {match_items(list(possible_matches.keys()))}")

The actual implementation assigns weights to the possible matches, meaning that matching 1 item would be preferred, but if it results in a dead end it tries the next match.  I feel like there is a better implementation of this out there, maybe involving sets to find where items overlap and determining the critical path. I just haven't been able to come up with a decent alternative other than this exhaustive search.

------- Update ------

After researching the algorithms suggested in the answers I decided to go with the munkres algorithm. It allows weighting of items in the vertex.

It accepts a matrix of items, where the rows represent 1 item, the columns another, and where they intersect is the cost when those items are paired. The common example uses people and jobs as the items. This algorithm will find the pair of items with the least cost. To prevent an item from being paired, set the cost in the matrix to float('inf')
eg:

         Janitor     Teacher     Doctor
Bob       9           5          1
Dick      1           4          6
Sally     5           3          7

would be represented by:

[
[9,5,1],
[1,4,6],
[5,3,7]
]

and would return [0,1,2], [2,0,1] where the first list represents the row indices and the second list represents the index of columns that would be matched with the rows
I ended up converting the two lists into a dictionary of people to their corresponding job via

>>> def match():
    from munkres import Munkres
    people = ["bob", "dick", "sally"]
    jobs = ["janitor", "teacher", "doctor"]
    matrix = [
               [9,5,1],
               [1,4,6],
               [5,3,7]
              ]

    m = Munkres()
    indexes = m.compute(matrix)

    matches = {}
    for p, j in indexes:
        person = people[p]
        job = jobs[j]
        matches[person] = job
    return matches

>>> match()
{'bob': 'doctor', 'dick': 'janitor', 'sally': 'teacher'}

matches will be a dictionary of people to their matched job


texts: What is the best implementation of a ignore case dictionary In C#

texts:
Imagine we have a custom dictionary class which is derived from Dictionary<string, object>. Dictionary is case-insensitive about keys and elements arrange is not important.
So what is the most optimized way to compare two instance of this class, or in another word what is the best override of
Equals method in this class.
I tried to use these two ways to implement this class. But i'm not sure which way is better than the other.
Please help me to choose the best way or correct me if i made any mistake.
First implementation:
public class CustomeDictionary : Dictionary<string, object>
{
    public CustomeDictionary() :
     base(StringComparer.InvariantCultureIgnoreCase)
    {
    }

    public CustomeDictionary(CustomeDictionary CustomeDictionary) :
     base(CustomeDictionary, StringComparer.InvariantCultureIgnoreCase)
    {
    }

    public bool Equals(CustomeDictionary other)
    {
        if (other is null)
            return false;

        if (Count != other.Count)
            return false;

        foreach (var (key, value) in this)
            if (!other.ContainsKey(key) || !value.Equals(other[key]))
                return false;

        return true;
    }

    public override bool Equals(object? obj)
    {
        return Equals(obj as CustomeDictionary);
    }

    public override int GetHashCode()
    {
        return this.Sum(i => (i.Key.ToLower(), i.Value).GetHashCode());
    }
}

The second way was to use another class which is an implementation of
IEqualityComparer<KeyValuePair<string, object>> which can help to use some efficient Linq methods like
Except to override the Equals and overload ==.
The EqualityComparer CustomClass
public class CustomKeyValuePair : IEqualityComparer<KeyValuePair<string, object>>
{
    public bool Equals(KeyValuePair<string, object> x, KeyValuePair<string, object> y)
        => x.Equals(y);

    public int GetHashCode(KeyValuePair<string, object> obj)
    {
        var (key, value) = obj;
        return (key.ToLower(), value).GetHashCode();
    }
}

and I have used it like below in Equals:
   public bool Equals(CustomHashTable other)
   {
      return this.Except(other, new CustomKeyValuePair()).Any();
   }

Please help me to improve and refactor the code.


texts: I think I'm not using Try Except properly in this Python code

texts:
Please offer some advice for this code.  It all works, but I know that its messy and I don't think the Exception catching is doing what I want it to.  Thanks in advance for any and all advice...

def main():
    # loop over this forever
    while True:
        print '--- Getting next job for Device: %s' % device['Name']
        # get a job from the db
        try:
            job = db.JobQ.find_one({'DeviceName':device['Name'],'Status':u'ToDo'})
        except Exception as e:
            print '!!! Error getting job for Device: %s' % device['Name']
        if job:
            # if there's a job, get all the other jobs for the same file
            try:
                job_list = [
                        j for j in db.JobQ.find(
                            {'Filename':job['Filename'],'Status':u'Todo'}
                            ).sort('Created',ASCENDING)
                        ]
            except Exception as e:
                print '!!! Error getting job list for Filename: %s' % job['Filename']

            for job in job_list:
                # mark the job 'InProgress'
                job = db.JobQ.find_and_modify(
                        {'_id':ObjectId(job['_id'])},
                        {'$set':{
                            'Status':u'InProgress','Started':datetime.now()
                            }},new=True
                        )
                print '--- Performing %s on %s' % (job['Type'], job['Filename'])
                # try to do the job.. each job raises its own exceptions
                try:
                    perform_job(job)
                    job['Status'] = u'Done'
                    job['Finished'] = datetime.now()
                    db.JobQ.save(job,safe=True)
                except Exception as e:
                    # if any job fails, ditch the rest of the jobs and move on
                    print '!!! Error performing job: %s' % e
                    print 'Subsequent jobs for this filename will not run: %s'\
                            % job['Filename']
                    for job in job_list:
                        job['Finished'] = datetime.now()
                        job['Status'] = u'Failed'
                        db.JobQ.save(job,safe=True)
        else:
            print '--- No more jobs for Device: %s' % device['Name']

        sleep(device['CycleTime'])

if __name__ == '__main__':
    main()


texts:
As usual, please be brutally honest with your opinion of my code, and how you would judge it if I were to code this at a top-tier tech company for an interview(think Google, MSFT, Facebook, etc). My algorithm is has a worst time complexity of O(n).

Question:
Given an unsorted integer array, find the first missing positive integer.
For example,

Given [1,2,0] return 3,
and [3,4,-1,1] return 2.*

My code(coded in 22 minutes, with all test cases passed, devised initial algorithm in 2-5 minutes)

  public int firstMissingPositive(int[] A) {
        int minVal=0;
        if(A.length==0){
            return 1;
        }
        Hashtable<Integer, Integer> myTable = new Hashtable<Integer, Integer>();
        for(int i : A){
            if(i<minVal && i>0){
                minVal = i;
            }
            myTable.put(i, i);
        }

        for(int i=0; i<=A.length; i++){
           if( (!myTable.containsKey(minVal-1)) && minVal-1>0){
                return minVal-1;
            }
            else if(!myTable.containsKey(minVal+1)){
                return minVal+1;
            }
            minVal++;
        }
        return minVal;
    }


texts: Get all combination of a nested object with arbitrary levels

texts:
I have a JSON data which can be an object/array of recursively nested object or array. The value of an array can not be null, but an value in a object can be null. I would like to return all combination of these keys and values through depth first search.

For example:

var data = {
  "title": {
     "original": "Hitchhiker",
     "more": ["HGTTG"],
     "link": null
  },
  "date": ["20150101", "20160101"]
}

The data's length and depth is arbitrary, and the combination result I want is something like this:

["title-original-Hitchhiker", "title-more-HTTG", "title-link", "date-20150101", "date-20160101"]

What I came up with is recursive:

function nestedObjectToArray(obj) {
  if (typeof(obj) != "object"){
    return [obj];
  }
  var result = [];
  if (obj.constructor == Array){
    for (var i = 0; i <obj.length; i++){
      if (obj[i]){
        var temp = nestedObjectToArray(obj[i]);
        for (var j = 0; j < temp.length; j++){
          result.push(temp[j]);
        }
      }
    }
  } else {
    for (var i in obj){
      if (obj.hasOwnProperty(i)) {
        if (obj[i] == null){
          result.push(i);
        } else {
          var temp = nestedObjectToArray(obj[i]);
          for (var j = 0; j < temp.length; j++){
            result.push(i+"-"+temp[j]);
          }
        }
      }
    }
  }
  return result;
}

Would you have a better/more elegant solution then this chunk of conditions, loops and recursion? I can use any lib if it's more convenient.


texts: Is this a valid implementation of a 'future'?

texts:
I'm not very experienced in C++, but I am trying to circumvent a kind of 'constructor order' situation, where I have class A wants class B in its constructor, and vice versa. They don't really want eachother, but both implement an interface and need each other. I decided to give object A a future. Is this even remotely good practice in C++11?

I'm thinking that the code below should be fine - the shared_ptr simply serves to make the future passable by value - multiple future objects can represent the same 'future'. Since I am not experienced in C++, I'm not sure of any potential trouble. I think that I don't need to declare any special copy constructor or such, since I don't do any allocation and std::shared_ptr should be copy-constructible automatically.

What do you think?

#ifndef LIB_FUTURE
#define LIB_FUTURE

#include <stdexcept>
#include <memory>

namespace lib {
    template <typename TValue>
    class future
    {
    public:
      future() : value_ptr(std::make_shared<TValue*>())
      { }

      void set(TValue &value)
      {
        *value_ptr.get() = &value;
      }

      TValue& get()
      {
        assert_valid_access();
        return **value_ptr;
      }

      TValue* operator->()
      {
        assert_valid_access();
        return *value_ptr;
      }

      bool has_value()
      {
        return value_ptr.get() != nullptr;
      }

    private:
      std::shared_ptr<TValue*> value_ptr;

      void assert_valid_access()
      {
        if(!has_value())
          throw std::runtime_error("Attempting to access a non-set value from a future");
      }
    };

  }

#endif

UPDATE
The use case I have is a little more complicated than the above though. Here goes:

class view : public log_sink
{
    view(tcp_client &client);
    virtual sink members...
};

class tcp_client
{
    tcp_client(log) //a sink should be provided before this, since it will do some logging.
};

class log
{
  log(log_sink sink); //So this one needs view.
};

int main()
{
     log log(view);
     tcp_client client(log);
     view the_view(client);
}

The above is not possible. View needs client, but client needs log, but log needs access to an interface on view.

Instead, I opted to give log a promise of a sink in the future. Log implements a tiny buffering mechanism, on the off chance that it doesn't have a sink by the time someone wants logging done. When it finally gets a sink, everything works fine. :)

Like this:

int main()
{
  future<log_sink> promise;
  log log(promise);
  tcp_client client(log);
  view the_view(client);

  promise.set(view);
}


texts:
I'm learning Rust and looking for better/cleaner ways to list all file names that do not start with filter, given a pathname as a parameter.

    fn list_files(&self, pathname: &PathBuf, filter: &str) -> Result<Vec<PathBuf>, Error> {
        fs::read_dir(pathname).map(|read_dir| {
            read_dir
                .filter_map(|res| {
                    res.map(|entry| {
                        entry
                            .path()
                            .strip_prefix(pathname)
                            .ok()
                            .map(|path| {
                                if path.starts_with(filter) {
                                    None
                                } else {
                                    Some(path.to_path_buf())
                                }
                            })
                            .flatten()
                    })
                    .ok()
                    .flatten()
                })
                .collect()
        })
    }


texts: Is this a good way for Controller to interact with Model ? (MVC)

texts:
In my controller I had the idea to do something like the following:

// retrieve fields from form
$firstname = $form->getInput('firstname');
$lastname = $form->getInput('lastname');
[...]
// create Member object
$member = new Member($firstname, $lastname, [...]);
// save Member in DB
$this->_daoFactory->get('Member')->save($member);

In this example, the DAO factory would create an instance of the MemberDAO class, which (I guess) acts like a data mapper? And allows me to save the Member object in DB, to update a Member, get a Member from id, and other db requests probably.

What do you think about this code?

Thank you for your review!


texts:
FileVersionInfo.GetVersionInfo(typeof(Program).Assembly.CodeBase.Replace("file:///", "")).ProductVersion

That code, is a one-liner, but has quite a lot of steps for it to return the File Version. Is there maybe a AppDomain way to get the File Version? (Or in general a shorter way)

(The code DOES work - I dont know why its being voted to close as "Broken Code")


texts:
I'm executing a cursor. I have cut off the code how the procedure is called and executed. This part is efficient. At last I have a small cursor. I'm calling the procedure, which returns this cursor many times on the page and I need to create a multidimensional array from it.

This array should look like the following:

$ret = oci_execute($outrefc) ;
while ($row = @oci_fetch_array($outrefc))
{
        foreach (array_keys($row) as $key)
        {

                 $res[$i][$key] = $row[$key];

        }
        $i++;
}

I have also tried like this:

  oci_fetch_all($outrefc, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW+OCI_NUM);

Is there any way to make the upper snippet faster? The multidimensional array should stay as it is. I only wonder if I could create it in any more efficient way.

DB query:

select code, texttext, id, text
  from text,
       lang,
       client,
       cls,
       (select id, order, texttext text
          from sgr, text, lang
         where id = textid
           and textlngid = lngid
           and lngcode in ('en'))
 where 1 = 1
   and textcliid = cliid
   and textlngid = lngid
   and textclsid = clsid
   and sgrid(+) = clssgrid
   and nvl(showheadlinefrom, to_date('03.07.2016', 'dd.mm.yyyy')) <=
       to_date('03.07.2016', 'dd.mm.yyyy')
   and nvl(showheadlinetill, to_date('03.07.2016', 'dd.mm.yyyy')) >=
       to_date('03.07.2016', 'dd.mm.yyyy')
   and flgshowheadline in ('J')
   and lngcode in ('en')
   and clicode in ('mycode')
 order by order;


texts:
Im not that good at C, so go easy on me, but I wanted to be able to have individual bit access in C without using a ton of functions to do bit manipulation on a uint8_t.  Tell me where I could improve upon it
#include <stdio.h>

#pragma pack(1)
union bit_array {
    struct {
        unsigned char b8:1, b7:1, b6:1, b5:1, b4:1, b3:1, b2:1, b1:1;
    } bits;
    unsigned char value;
};

int main() {
    // Creates char with binary value 11111111
    union bit_array test = { 1, 1, 1, 1, 1, 1, 1, 1 };

    // Displays 11111111 (255)
    printf("%u\n", test.value);

    // Sets 8th bit of binary value to 0
    // 11111111 (255) -> 11111110 (254)
    test.bits.b8 = 0;

    // Displays 11111110 (254)
    printf("%u\n", test.value);

    return 0;
}


texts: Asking user input until a valid datetime is given (bloated try-except blocks)

texts:
Originally asked this on SO but was redirected here.

I have a script that's asking the user to input a lot of dates, mostly in functions similar to the one below. These need to account for invalid date formats:

import numpy as np
import pandas as pd
import xlwings as xw
import datetime as dtt

def week_init():
        """Creates an initial week datetime and determines what the checking cutoff
        'beforeday' to be used in Stage 2 is."""
        week = input('Week to check: MM/DD/YYYY\n')
        switch = 1
        while switch == 1:
            try:
                week = dtt.datetime.strptime(week,'%m/%d/%Y') #turns input to a datetime
                switch = 0
            except ValueError: #couldn't parse as a date MM/DD/YYYY
                week = input('Unrecognized date format, please try again: MM/DD/YYYY\n')
        beforeday = (input('Check days before date (Press enter to use today): MM/DD/YYYY\n')
            or dtt.date.today())
        if (beforeday != dtt.date.today()):
            switch = 1
            while switch == 1:
                try:
                    beforeday = dtt.datetime.strptime(beforeday,'%m/%d/%Y')
                    switch = 0
                except ValueError: #couldn't parse as a date MM/DD/YYYY
                    beforeday = input('Unrecognized date format, please try again: MM/DD/YYYY\n')
        return week, beforeday

There are also functions that check an index for a given date, and have to deal with a given date not matching any of the indices:

def spotmap(week, bam, pt):
    """Maps the pivoted data for the chosen week to the BAM dataframe's SD column."""
    print('Mapping data to BAM... ',end=''),
    switch = 1
    while switch == 1:
        try:
            bam['SD'] = bam.index.to_series().map(pt.fillna(0)['len',week])
            switch = 0
        except KeyError: #date doesn't match any of the pivot table's columns
            print('Invalid date, please try again.')
            week = input('Week start date (Sunday): MM/DD/YYYY\n')
    print('Done')
    return bam

As the script has a lot of things to do after it gets these dates, I don't want it to crash when it has a problem, but it can't proceed without correct date inputs so I currently have it looping with those "switch" variables controlling when it is willing to move on with a valid date. As you can see, though, these try/except blocks are rapidly bloating the otherwise straightforward code. Is there a way to condense these things? Also, a better method than the switches?

https://stackoverflow.com/questions/9386592/repetitive-try-and-except-clauses

The answers here suggested decorators, but as far as I can tell from the documentation and pages like this, those are for wrapping functions, not for replacing interior code blocks. Also I'm not sure how useful they'd be, because the try/except blocks are mostly unique in what they're trying to accomplish (ie, which variable they're changing or whether they're checking against an index). I guess I'm really just hoping for some better general exception-handling syntax.


texts:
Here is the problem, any advice about code improvement, more efficient implementation in terms of time complexity, functional bugs, etc. are appreciated.

  Given an unsorted integer array, find the first missing positive
  integer.

  For example,
  Given [1,2,0] return 3,
  and [3,4,-1,1] return 2.

  Your algorithm should run in O(n) time and use constant space.

def firstMissingPositive(nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    if not nums:
        return 1
    for i,v in enumerate(nums):
        if v > len(nums):
            nums[i]=-1
        elif v <= 0:
            nums[i]=-1
        else:
            while i+1 != nums[i] and 0<nums[i]<=len(nums):
                #print i, nums[i]-1, nums[i], nums[nums[i]-1]
                v = nums[i]
                nums[i] = nums[v-1]
                nums[v-1] = v
                #nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
            if nums[i] > len(nums) or nums[i] <=0:
                nums[i] = -1
    for i,v in enumerate(nums):
        if nums[i] != i+1:
            return i+1
    return len(nums)+1

if __name__ == "__main__":
    print firstMissingPositive([1,2,0])
    print firstMissingPositive([3,4,-1,1])


texts: Django query_set filtering in the template

texts:
Can I make my template syntax simpler? I'm hoping to eliminate the if and maybe also the for block.

This worked in the shell but I can't figure out the template syntax.

recipes[0].recipephotos_set.get(type=3).url

model.py

class Recipe(models.Model):
    ....

class RecipePhotos(models.Model):
    PHOTO_TYPES = (
    ('3', 'Sub Featured Photo: 278x209'),
    ('2', 'Featured Photo: 605x317'),
    ('1', 'Recipe Photo 500x358'),
    )
    recipe = models.ForeignKey(Recipe)
    url = models.URLField(max_length=128,verify_exists=True)
    type =  models.CharField("Type", max_length=1, choices=PHOTO_TYPES)

view.py

recipes = Recipe.objects.filter(recipephotos__type=3)

template.html

{% for recipe in recipes %}

      {% for i in recipe.recipephotos_set.all %}
          {% if i.type == '3' %}
              {{ i.url }}
          {% endif %}
      {% endfor %}

  {{ recipe.recipe_name }}

{% empty %}


texts: Suggestion on Single Level Of Abstraction per Function - Java

texts:
I followed the SLAP principle in the below code.
But with "Mixing Level Of Abstraction" (refer below code) I can avoid the single line methods.
My question is - is it good to avoid the single line method in this case? But I believe the code with "SLAP Principle" has better readability than the other one. Please share your suggestions.
SLAP Principle:
public class TestAccount {
    private static final String DEFAULT_VALUE = "test_default";

    public void modify(Creditor creditor) {
        PartyDetails partyDetails = generatePartyDetails();
        assignPartyDetails(creditor, partyDetails);
    }

    private PartyDetails generatePartyDetails() {
        PartyDetails partyDetails = new PartyDetails();
        OrganisationIdentification orgId = generateOrgIdDetails();
        assignOrgIdValueToId(orgId, party6Choice);
        return partyDetails;
    }

    private OrganisationIdentification generateOrgIdDetails() {
        OrganisationIdentification orgId = new OrganisationIdentification();
        OtherIssueDetails otherIssuerDetails = generateIssuerDetails();
        assignOtherIssuerDetailsToOrgIdList(otherIssuerDetails, orgId);
        return orgId;
    }

    private OtherIssuerDetails generateIssuerDetails() {
        OtherIssuerDetails otherIssuerDetails =
                new OtherIssuerDetails();
        otherIssuerDetails.setIssr(DEFAULT_VALUE);
        return otherIssuerDetails;
    }

    private void assignOtherIssuerDetailsToOrgIdList(OtherIssuerDetails
                                                             otherIssuerDetails,
                                                     OrganisationIdentification
                                                             orgId) {
        orgId.getOthr().add(otherIssuerDetails);
    }

    private void assignOrgIdValueToId(OrganisationIdentification orgId,
                                      PartyDetails id) {
        id.setOrgId(orgId);
    }

    private void assignPartyDetails(Creditor creditor,
                                    PartyDetails partyDetails) {
        creditor.setId(partyDetails);
    }
}

Mixed Level Of Abstraction:
public class TestAccount {
    private static final String DEFAULT_VALUE = "test_default";

    public void modify(final Creditor creditor) {
        PartyDetails partyDetails = generatePartyDetails();
        creditor.setId(partyDetails);
    }

    private PartyDetails generatePartyDetails() {
        PartyDetails partyDetails = new PartyDetails();
        OrganisationIdentification orgId = generateOrgIdDetails();
        id.setOrgId(orgId);
        return partyDetails;
    }

    private OrganisationIdentification generateOrgIdDetails() {
        OrganisationIdentification orgId = new OrganisationIdentification();
        OtherIssuerDetails otherIssuerDetails = generateIssuerDetails();
        orgId.getOthr().add(otherIssuerDetails);
        return orgId;
    }

private OtherIssuerDetails generateIssuerDetails() {
        OtherIssuerDetails otherIssuerDetails =
                new OtherIssuerDetails();
        otherIssuerDetails.setIssr(DEFAULT_VALUE);
        return otherIssuerDetails;
    }
}


texts: Computing predicates of multiple items avoiding duplication of iteration code

texts:
I am breaking my head with how to get rid of semantic duplication(Code that is syntactically the same but does different things).

I can't find anywhere a post or something that mentions a bit how to refactor this kind of duplication. All I found was this:
Duplicate Code and Ceremony in Java but it does not go into detail on how to refactor it.

This is the code that is causing me problem:

public class TeamValidator {

      public boolean isThereALeader(List<Member> team) {
           Iterator<Member> iterator = team.iterator();
           while(iterator.hasNext()) {
              Member member = iterator.next();
              String role = member.getRole();
              if(role.equals("Leader"))
                return true;
           }
           return false;
      }

      public boolean areThereAtLeast2NewJoiners(List<Member> team) {
            int amountOfNewJoiners = 0;
            for(Member member:team) {
                if(amountOfNewJoiners == 2)
                    return true;
                DateTime aMonthAgo = DateTime.now().minusMonths(1);
                if(member.startingDate().isAfter(aMonthAgo)) {
                   amountOfNewJoiners++;
                }
            }
            return false;
      }
}

In these two methods there is semantic duplication, because both iterate a list and also check some condition/s. Any idea how could I make this semantic duplication disappear?
I would really appreciate some tip or suggestion on how to refactor this.


texts:
I have the following C++ program:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>

void printVector (std::vector<int>& vec)
{
    for (int a = 0; a < vec.size(); a++)
        std::cout << (char)vec[a] << ", ";
}

int main ()
{
    const std::string HANGMAN[] = {"\n------+",
                                  "\n      |\n      |\n      |\n      |\n      |\n------+",
                                  "\n   ---+\n      |\n      |\n      |\n      |\n      |\n------+",
                                  "\n   ---+\n   |  |\n      |\n      |\n      |\n      |\n------+",
                                  "\n   ---+\n   |  |\n   O  |\n      |\n      |\n      |\n------+",
                                  "\n   ---+\n   |  |\n   O  |\n   |  |\n      |\n      |\n------+",
                                  "\n   ---+\n   |  |\n   O  |\n  /|  |\n      |\n      |\n------+",
                                  "\n   ----\n   |  |\n   O  |\n  /|\\ |\n      |\n      |\n-------",
                                  "\n   ----\n   |  |\n   O  |\n  /|\\ |\n  /   |\n      |\n-------",
                                  "\n   ----\n   |  |\n   O  |\n  /|\\ |\n  / \\ |\n      |\n-------"};
    const std::string WORDS[] = {"zigzagging", "wigwagging", "grogginess", "beekeeping", "mummifying",
                                 "fluffiness", "fulfilling", "shabinness", "revivified", "kobnobbing",
                                 "beekeepers", "wheeziness", "shagginess", "sleeveless", "parallaxes",
                                 "woolliness", "chumminess", "skyjacking", "grubbiness", "wobbliness",
                                 "feebleness", "jaywalking", "alkalizing", "blabbering", "overjoying"};
    srand(time(0));
    std::string compWord = WORDS[rand() % 25];
    char compHiddenWord[] = "----------";
    int hangmanPos = 0;
    std::vector<int> guessed;
    char userGuess;
    bool letterCorrect;
    while (hangmanPos != 9)
    {
        std::cout << "\nThis is your hangman:\n" << HANGMAN[hangmanPos] <<
                     "\n\nThese are the letters you've already guessed:\n\n";
        printVector(guessed);
        std::cout << "\n\nThis is my word:\n\n" << compHiddenWord <<
                     "\n\nGuess a letter: ";
        std::cin >> userGuess;
        guessed.push_back(userGuess);
        letterCorrect = false;
        for (int a = 0; a < compWord.size(); a++)
            if (compWord[a] == userGuess)
            {
                if (letterCorrect == false)
                {
                    std::cout << userGuess << " is in my word!\n\n\n";
                    letterCorrect = true;
                }
                compHiddenWord[a] = userGuess;
            }
        if (letterCorrect == false)
        {
            std::cout << "Oops! " << userGuess << " is not in my word.";
            hangmanPos++;
        }
        else
            for (int a = 0; a < compWord.size(); a++)
                if (compWord == compHiddenWord)
                {
                    std::cout << "Well done, " << compWord << " was my word!";
                    return 0;
                }
    }
    std::cout << "\nOh Dear! Looks like you've been hanged. My word was actually " << compWord << ".";
}

Which is supposed to replicate the classic game of hangman visually. Is the code fully optimized? Is there an other way I could improve it?


texts: Codewars: "Twice linear" is running too long

texts:
I am doing one kata on codewars:

  Consider a sequence u where u is defined as follows:

  The number u(0) = 1 is the first one in u. For each x in u, then y = 2
  * x + 1 and z = 3 * x + 1 must be in u too. There are no other numbers in u. Ex: u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]

  1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13, then 7 gives
  15 and 22 and so on...

  Task: Given parameter n the function dbl_linear (or dblLinear...) returns the element u(n) of the ordered (with <) sequence u.

  Example: dbl_linear(10) should return 22

  Note: Focus attention on efficiency

So far I did this algorithm but it's too slow and it times out. I do not really know how to refactor it. Can anyone help me? Maybe some another concept how to approach to solve it?

function dblLinear(n) {
   let arrOfResult = [1];
   const set = new Set();
   set.add(1);
   let nextInvoker = 0;

    while (arrOfResult.length <= n) {
       let y = 2 * arrOfResult[nextInvoker] + 1;
       let z = 3 * arrOfResult[nextInvoker] + 1;

       set.add(y);
       set.add(z);

       arrOfResult = Array.from(set).sort((a, b) => a - b);

       nextInvoker++;
  }

   arrOfResult.forEach(element => {
       let y = 2 * element + 1;
       let z = 3 * element + 1;

       set.add(y);
       set.add(z);
   });

   const result = Array.from(set).sort((a, b) => a - b);

   return result[n];
}


texts: JavaScript reducer that updates a deep value in a hash

texts:
I've been roughing out a proof of concept enabling admin staff to flag submitted applications with issues as needed. We have many forms some of which are nested. So we end up with these big hashes to validate. Primarily we have issues with uploaded images (too blurry, too dark etc) but it could be any field.

So admin may see a field verified_documents -> drivers_licence -> front_image. If an issue is raised we end up with a hash to store.

{
    verified_documents: {
        drivers_licence: {
            front_image: ['Image is too blurry', 'Image is too dark']
        }
    }
}

The code works but is very smelly. The function in question is updateIssue. Which accepts a string representation of the path "verified_documents.drivers_licence.front_image" and an array of selected options from a dropdown.

The function's intentions:

Take a copy of current issues, an attempt to be pure and return a new object.
Split the string into an array.
Iterate over each value in the path array.
If path length is the last set its value to the array of issues.
If the value is an empty array set the value to undefined (only happens if an issue is removed).
If the key can't be found, create the next level as a child hash.
Returning the next level of nested object if no other condition is met.

I'm happy I was able to get it all working, but now it's not readable. Readability over performance is my objective, as this code is likely to change.

import { merge, isEmpty } from "lodash";

let Issues = undefined;

const getNestedValue = (nestedObj, pathArr) => {
  return pathArr.reduce(
    (obj, key) => (obj && obj[key] !== "undefined" ? obj[key] : undefined),
    nestedObj
  );
};

export class IssuesData {
  static updateIssue = (path, value) => {
    const valueObj = merge({}, Issues);
    const pathArr = path.split(".");
    pathArr.reduce((obj, key, i) => {
      if (pathArr.length - 1 === i) {
        if (isEmpty(value)) {
          return (obj[key] = undefined);
        }
        return (obj[key] = value);
      }

      if (obj[key] === undefined) {
        return (obj[key] = {});
      }
      return obj[key];
    }, valueObj);
    Issues = valueObj;
  };

  static getIssueByKey = path => {
    return getNestedValue(Issues, path.split("."));
  };

  static getIssues() {
    return Issues;
  }

  static setIssues(issues) {
    if (!Issues) {
      Issues = issues;
    }
  }
}

UPDATE:

After sleeping on it I managed to clean it up a little. This is more readable but there are still multiple return. If anyone has advice on cleaning it up further it'll be welcomed. I think I'll turn my attention to converting the static methods to instance methods now.

  static updateIssue = (path, value) => {
    const valueObj = merge({}, Issues);
    const pathArray = path.split(".");

    pathArray.reduce((obj, key, i) => {
      if (isLast(pathArray, i)) {
        if (isEmpty(value)) {
          return delete obj[key];
        }
        return (obj[key] = value);
      }
      return obj[key];
    }, valueObj);
    Issues = valueObj;
  };


texts: Given two int values, return the one closer to 10

texts:
I did the exercise below to practice. Can someone help me to shorten or improve the code in a simple way for a beginner?

The exercise is:

  Given 2 int values, return whichever value is nearest to the value 10,
  or return 0 in the event of a tie.

public int Closer(int a, int b)
{
     Console.WriteLine(Closer(8, 13));    // output: 8
     Console.WriteLine(Closer(13, 8));    // output: 8
     Console.WriteLine(Closer(13, 7));    // output: 0
}

My solution:

namespace Closer
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine(Closer(13,15));    // output : 13
                Console.WriteLine(Closer(13, 13));   // output : 0
                Console.WriteLine(Closer(3,5));      // output : 5
                Console.WriteLine(Closer(13, 7));    // output : 0
                Console.WriteLine(Closer(-3, -5));   // output : -3
                Console.WriteLine(Closer(-3, -1));   // output : -1
                Console.ReadLine();
            }
            public static int Closer(int a, int b)
            {
                int calcA = a - 10;
                int calcB = b - 10;
                if (Math.Abs(calcA) == Math.Abs(calcB))
                {
                    return 0;
                }
                else if ((a >= 10 || b >= 10) && a < b )
                {
                    return a;
                }
                else if ((a >= 10 || b >= 10) && b < a)
                {
                    return b;
                }
                else if (calcB > calcA && Math.Abs(a)!= Math.Abs(b))
                {
                    return b;
                }
                else if ((calcA < 0 || calcB < 0) && (calcA > calcB && Math.Abs(a) != Math.Abs(b)))
                {
                    return a;
                }
                else return Closer(a,b);
            }
        }
    }


texts: Simple inheritance with functions in subclasses

texts:
It seems like there are many ways implementing inheritance in JavaScript. Which version do you prefer or would you suggest another solution?

The code should run in IE8+ so my first version would not fit…

function Animal(name) {
    this.name = name
}
Animal.prototype = {
    eat: function() {
        console.log(this.name + ': *eat*')
    }
}

function Cat(name) {
    Animal.call(this, name);
}
Cat.prototype = Object.create(Animal.prototype, {
    miaou: {
        value: function() {
            console.log(this.name + ': *miaou*')
        }
    }
})

var garfield = new Cat("Garfield");
garfield.eat();     // Garfield: *eat*
garfield.miaou();   // Garfield: *miaou*

// ------------
//
// possible alternative:

// […] see http://ejohn.org/blog/simple-javascript-inheritance/ for definition
// of Class

var Animal2 = Class.extend({
    init: function(name) {
        this.name = name
    },
    eat: function() {
        console.log(this.name + ': *eat*')
    }
});

var Cat2 = Animal2.extend({
    init: function(name) {
        this._super(name)
    },
    miaou: function() {
        console.log(this.name + ': *miaou*')
    }
});

var garfield2 = new Cat("Garfield2");
garfield2.eat();        // Garfield: *eat*
garfield2.miaou();      // Garfield: *miaou*


texts: Optimize simple C++ function to minimize copying

texts:
I've been coding C for almost 20 years and figured I should learn C++. As a starting point I wrote the following trivial code to generate the powerset of a set. I'm hoping that some experienced C++ coder could help me with three things:

Identify non-idiomatic constructions.
Explain where I'm doing unnecessary copying of objects
Any other simplifying comments.

#include <iostream>
#include <vector>

using namespace std;

template<typename T>
vector<vector<T>> powerset(vector<T> s)
{
  // Return the powerset containing the empty set
  if(s.size() == 0) {
    vector<int> dummy;
    return vector<vector<T>> { dummy };
  }

  T v = s.back();
  s.pop_back();

  // Recursively generate powerset for s setminus v
  vector<vector<T>> pss = powerset<T>(s);
  // This is the basis for the current powerset set
  vector<vector<T>> ps = pss;

  for(auto&& i : pss) {
    // Add a set with v added for each set
    i.push_back(v);
    ps.push_back(i);
  }

  return ps;
}

int main(void)
{
  vector<int> v = {1,2,3,4};

  vector<vector<int>> ps = powerset<int>(v);

  cout << "Powerset contains the following elements:" << endl;
  for(auto&& i : ps) {
    for(auto&& j : i) {
      cout << j << " ";
    }
    cout << endl;
  }

  return 0;
}


texts: Improving my Tic Tac Toe Solution in Scala

texts:
I'm relatively new to Scala and made a small TicTacToe in a functional Style.
Any improvement options would be highly appreciated.
There are some things which I am unsure of if they are made in an optimal way.

Error Handling in the readMove Function
If i should incorporate types like (type Player = Char, type Field = Int) and if they would benefit the code
The printBoard function looks unclean and I can't yet figure out how to best change it.
board(nextMove) = nextPlayer(board) seems to break the style of immutable values.

This is already an improvement from my first version

import scala.annotation.tailrec
import scala.io.StdIn.readLine

object TicTacToeOld {
  val startBoard: Array[Char] = Array('1', '2', '3', '4', '5', '6', '7', '8', '9')
  val patterns: Set[Set[Int]] = Set(
    Set(0, 1, 2),
    Set(3, 4, 5),
    Set(6, 7, 8),
    Set(0, 3, 6),
    Set(1, 4, 7),
    Set(2, 5, 8),
    Set(0, 4, 8),
    Set(2, 4, 6)
  )

  def main(args: Array[String]): Unit = {
    startGame()
  }

  def startGame(): Unit ={
    println("Welcome to TicTacToe!")
    println("To play, enter the number on the board where you want to play")
    printBoard(startBoard)
    nextTurn(startBoard)
  }

  @tailrec
  private def nextTurn(board: Array[Char]): Unit = {
    val nextMove = readMove(board)
    board(nextMove) = nextPlayer(board)
    printBoard(board)
    if (!isWon(board)) {
      nextTurn(board)
    }
  }

  @tailrec
  private def readMove(board: Array[Char]): Int ={
    try {
      val input = readLine("Input next Turn: ").toInt-1
      if(input<0 || input>8 || !board(input).toString.matches("[1-9]")) {
        throw new Exception
      }
      input
    } catch {
      case _: Exception => readMove(board)
    }
  }

  private def nextPlayer(board: Array[Char]): Char = {
    val remainingTurns = board.count(_.toString.matches("[1-9]"))
    if(remainingTurns%2 == 0) 'x' else 'o'
  }

  private def printBoard(board: Array[Char]): Unit = {
    print(
      0 to 2 map { r =>
        0 to 2 map { c =>
          board(c + r*3)
        } mkString "|"
      } mkString ("__________\n", "\n------\n", "\n")
    )
    println("Next Player is " + nextPlayer(board))
  }

  private def isWon(board: Array[Char]): Boolean = {
    patterns.foreach(pattern=>{
      if(pattern.forall(board(_) == board(pattern.head))) {
        print("Winner is " + board(pattern.head))
        return true
      }
    })
    false
  }
}


texts: List the combinations that add up to 0 from a vector of numbers

texts:
I'm writing a function that, given a Vec<i32> of numbers, lists the combinations that add up to 0. The code works, but it feels amateurish.

Specifically, the inside of the loop looks really ugly -- there must be a simpler way of doing this that avoids unwrap() and the repetition. Maybe with match?

fn calc_zer(input: Vec<i32>) -> Vec<(i32, i32, i32)> {
    let mut output: Vec<(i32, i32, i32)> = Vec::new();
    for a in (0..input.len() - 2) {
        for b in (a+1..input.len() -1) {
            for c in (b+1..input.len()) {
                if (input.get(a).unwrap() + input.get(b).unwrap() + input.get(c).unwrap() == 0) {
                    output.push((*input.get(a).unwrap(), *input.get(b).unwrap(), *input.get(c).unwrap()));
                }
            }
        }
    }
    output
}


texts:
I'm solving HackerRank "Ransom Note" challenge. The code runs fine and cracks it, but I have an issue with its performance. It times out in some cases.

  A kidnapper wrote a ransom note but is worried it will be traced back
  to him. He found a magazine and wants to know if he can cut out whole
  words from it and use them to create an untraceable replica of his
  ransom note. The words in his note are case-sensitive and he must use
  whole words available in the magazine, meaning he cannot use
  substrings or concatenation to create the words he needs.

  Given the words in the magazine and the words in the ransom note,
  print Yes if he can replicate his ransom note exactly using whole
  words from the magazine; otherwise, print No.

  Input Format

  The first line contains two space-separated integers describing the
  respective values of (the number of words in the magazine) and (the
  number of words in the ransom note).

  The second line contains space-separated strings denoting the words
  present in the magazine.

  The third line contains space-separated strings denoting the words
  present in the ransom note.

My implementation:

def ransom_note(magazine, ransom):
    for word in ransom:
        if word in magazine:
            magazine.remove(word)
        else:
            return False
    return True

m, n = map(int, input().strip().split(' '))
magazine = input().strip().split(' ')
ransom = input().strip().split(' ')
answer = ransom_note(magazine, ransom)
if(answer):
    print("Yes")
else:
    print("No")

It's timing out when there are too many items (30.000) on magazine or ransom. Performance talking, what can I improve here?


texts: Optimize MySQL double select inside for-loop

texts:
I want to get the number if items with state 4 and 1 from my database for each day between a certain date. Is there a smarter and more performative way than this one?

I am aware that I should use MySQLi and that MySQL is deprecated.

Code explanation:

the for loop is to go through everyday between 2 dates
$sql_condition is in case the query has a specific item, otherwise empty variable

My code:

for( $thisDay = $start; $thisDay <= $end; $thisDay = $thisDay + 86400){

    $formatedDate = date('Y-m-d', $thisDay);
    // booked houses
    $sql="SELECT id FROM ".T_BOOKINGS." WHERE id_state=1 ".$sql_condition." AND the_date='".$formatedDate."'";
    $res=mysql_query($sql) or die("Error getting states
".mysql_Error());

    //reserved houses
    $sql2="SELECT id FROM ".T_BOOKINGS." WHERE id_state=4 ".$sql_condition." AND the_date='".$formatedDate."'";
    $res2=mysql_query($sql2) or die("Error getting states
".mysql_Error());

    $bookings['booked'][] = mysql_num_rows($res);
    $bookings['reserved'][] = mysql_num_rows($res2);
    $dates[] = $formatedDate;

}


texts: Finding the best matching block/patch in Python

texts:
I wish to locate the closest matching NxN block within a WxW window centred at location (x,y) of a larger 2D array. The code below works fine but is very slow for my needs as I need to run this operation many times.

Is there a better way to do this?

Here N = 3, W = 15, x =15, y = 15 and (bestx, besty) is the centre of the best matching block

import numpy as np

## Generate some test data
CurPatch = np.random.randint(20, size=(3, 3))
Data = np.random.randint(20,size=(30,30))

# Current Location
x,y = 15,15
# Initialise Best Match
bestcost = 999.0
bestx = 0;besty=0

for Wy in xrange(-7,8):
    for Wx in xrange(-7,8):
            Ywj,Ywi = y+Wy,x+Wx

            cost = 0.0
            for py in xrange(3):
                for px in xrange(3):
                    cost += abs(Data[Ywj+py-1,Ywi+px-1] - CurPatch[py,px])
                    if cost >= bestcost:
                       break

            if cost < bestcost:
                bestcost = cost
                besty,bestx = Ywj,Ywi

print besty,bestx


texts:
To continue learning I decided to try solving some of project Euler problems. Here is the first solution.

The things I'm interested the most from the review are:

The performance of the code
Overall review of the code structure, styling rules and naming conventions.

Problem: 1

  Find the sum of all the multiples of 3 or 5 below 1000.

#----------------------------------------------------------------------------------
def calculate_the_sum(threshold = 10):
    """Calculates the sum of all multiples of 3 or 5
    below the provided threshold.

    Arguments:
       type:<int> -Preforms the calculations on all values up to this value.
    Return:
       type:<int> -The sum of numbers that are multiples of 3 or 5..
    """
    return sum(n for n in range(threshold) if n % 3 == 0 or n % 5 == 0)

#----------------------------------------------------------------------------------
def main():

    threshold = 1000
    print(' Calculates the sum of all numbers that are multiples of 3 or 5')
    print(' The Sum of numbers below {} is: {}'.format(threshold,calculate_the_sum(threshold)))

#----------------------------------------------------------------------------------
if __name__ == "__main__":
    main()


texts: Trying to improve and better understand Intel SSE intrinsics

texts:
I've been writing a collection of signal processing function optimized with SSE intrinsics (mostly for audio processing). Here is a linear interpolation function I wrote. It works well and is quite fast (much better than straight lerp), but I'm using the full 8 registers available, and I'm wondering if there's something I'm not seeing that would improve its efficiency.

void SSE_vInterpLinear (const float *sourceX, const float *sourceY, float *resultY, const int lengthX)
{
    assert(lengthX % 4 == 0);

    __m128 *mXphases = (__m128*)sourceX;
    __m128 *mYresult = (__m128*)resultY;
    __m128 mX0, mY0, mY1, mYtemp, mXtemp, mtemp;
    __declspec(align(16)) float pos[4];

    for (int i = 0; i < lengthX; i+=4) {
        // floor the values in X to get indexing positions at X0, and add 1 for X1 index positions
        mX0 = _mm_floor_ps(*mXphases);
        _mm_store_ps(pos, mX0);
        mY0 = _mm_set_ps(sourceY[(int)pos[3]], sourceY[(int)pos[2]], sourceY[(int)pos[1]], sourceY[(int)pos[0]]);
        mY1 = _mm_set_ps(sourceY[(int)pos[3]+1], sourceY[(int)pos[2]+1], sourceY[(int)pos[1]+1], sourceY[(int)pos[0]+1]);

        mYtemp = _mm_sub_ps(mY1, mY0);
        mXtemp = _mm_sub_ps(*mXphases, mX0);
        mtemp = _mm_mul_ps(mYtemp, mXtemp);
        *mYresult = _mm_add_ps(mY0, mtemp);

        mXphases++;
        mYresult++;
    }
}


texts: How to improve method of opening file in python then writing to another?

texts:
Very simple I want to edit a virtual host files and replace the tags I made with some actual data:

import os, re
with open('virt_host', 'r+') as virtual
    file = virtual.read()
    file = re.sub('{{dir}}', '/home/richard', file)
    file = re.sub('{{user}}', 'richard', file)
    file = re.sub('{{domain_name}}', 'richard.com', file)

with open('new_virt', 'w+') as new_file
    new_file.write(file)
    new_file.close()

Is this the best way?


texts: Getting SharePoint users and comparing them with SPList

texts:
I have a custom SPList that has a field Assigned To, now I can add as many items as I want, and they can have same title and same User they are assigned to, but what I want is a script so that I only get the distinct number of user's email address, e.g. if a user is assigned to more then 1 item, I will get there email address just once, here is the code I wrote down but I don't think if its good enough.

using (SPSite site = new SPSite("www.local.com"))
    using (SPWeb web = site.OpenWeb())
    {
        SPList mySourceList = web.Lists["ListName"];

        SPQuery mySourceListQuery = new SPQuery();

        mySourceListQuery.Query =

            "<OrderBy><FieldRef Name='AssignedTo' />" +
                     "<FieldRef Name='Title' />" +
            "</OrderBy>";

        SPListItemCollection mySourceItemColl = mySourceList.GetItems(mySourceListQuery);

        foreach (SPUser user in web.Users)
        {
            foreach (SPListItem mySourceListItem in mySourceItemColl)
            {
                name = mySourceListItem["AssignedTo"].ToString();

                name = name.Substring(name.IndexOf("#") + 1);

                if (user.Name == name)
                {
                    Console.WriteLine(user.Email);
                }
            }
        }


texts: Passing an array of values in Url.Action

texts:
I need to pass an array of values in Url.Action.

Currently I'm doing:

var redirectUrl = Url.Action("search", new {
        q = criteria.Q,
        advanced = criteria.Advanced,
        salaryfrom = criteria.SalaryFrom,
        salaryto = criteria.SalaryTo,
    });

if (criteria.JobTypes != null)
    redirectUrl += criteria.JobTypes.Aggregate(string.Empty, (a, x) => a += "&jobTypes=" + x);

To give me something like:

/search?q=developer&advanced=false&salaryfrom=20000&salaryto=80000&jobTypes=Full%20Time&jobTypes=Contract

Is there a nicer/cleaner approach?


texts:
I'm posting my code for a LeetCode problem copied here. If you have time and would like to review, please do so. Thank you!
Problem

Given a binary tree, return all duplicate subtrees. For each kind of
duplicate subtrees, you only need to return the root node of any one
of them.
Two trees are duplicate if they have the same structure with same node
values.
Example 1:
        1
       / \
      2   3
     /   / \
    4   2   4
       /
      4

The following are two duplicate subtrees:
      2
     /
    4

and
    4

Therefore, you need to return above trees' root in the form of a list.

Code
#include <vector>
#include <unordered_map>
#include <string>

class Solution {
public:
    std::vector<TreeNode *> findDuplicateSubtrees(TreeNode *root) {
        std::unordered_map<string, std::vector<TreeNode *>> nodes_map;
        std::vector<TreeNode *> duplicates;
        this->serialize(root, nodes_map);

        for (auto iter = nodes_map.begin(); iter != nodes_map.end(); iter++) {
            if (iter->second.size() > 1) {
                duplicates.push_back(iter->second[0]);
            }
        }

        return duplicates;
    }

private:
    std::string serialize(TreeNode *node, std::unordered_map<std::string, std::vector<TreeNode *>> &nodes_map) {
        if (!node) {
            return "";
        }

        std::string serialized = "[" + serialize(node->left, nodes_map) + std::to_string(node->val) + serialize(node->right, nodes_map) + "]";
        nodes_map[serialized].push_back(node);
        return serialized;
    }

};

Reference
LeetCode has a template for answering questions. There is usually a class named Solution with one or more public functions which we are not allowed to rename. For this question, the template is:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {

    }
};

Problem

Solution

Discuss

Tree Data Structure


texts: Binding Lists of Commits to a DataGridView in Winforms with an MVP architecture

texts:
I'm using Winforms and I find this pattern showing up in my code a lot. It works, but I'm unsure if it's best. The goal is to pass an IList of items through a view interface and then bind that list to a DataGridView in the concrete GUI class. I've been accomplishing this by keeping a private BindingList<T> in the control, and converting the IList when getting/setting the properties. I can't help but feel that there's a better way to do this databinding.

The GUI looks like this.

The View interface.

public interface IUnSyncedCommitsView
{
    event EventHandler<EventArgs> Fetch;
    event EventHandler<EventArgs> Pull;
    event EventHandler<EventArgs> Push;
    event EventHandler<EventArgs> Sync;

    IList<ICommit> IncomingCommits { get; set; }
    IList<ICommit> OutgoingCommits { get; set; }
}

The UserControl code behind.

[ExcludeFromCodeCoverage]
public partial class UnSyncedCommitsControl : UserControl, IUnSyncedCommitsView
{
    public UnSyncedCommitsControl()
    {
        InitializeComponent();

        SetText();
    }

    private void SetText()
    {
        CurrentBranchLabel.Text = RubberduckUI.SourceControl_CurrentBranchLabel;
        FetchIncomingCommitsButton.Text = RubberduckUI.SourceControl_FetchCommitsLabel;
        PullButton.Text = RubberduckUI.SourceControl_PullCommitsLabel;
        PushButton.Text = RubberduckUI.SourceControl_PushCommitsLabel;
        SyncButton.Text = RubberduckUI.SourceControl_SyncCommitsLabel;

        IncomingCommitsBox.Text = RubberduckUI.SourceControl_IncomingCommits;
        OutgoingCommitsBox.Text = RubberduckUI.SourceControl_OutgoingCommits;
    }

    private BindingList<ICommit> _incomingCommits;
    public IList<ICommit> IncomingCommits
    {
        get { return _incomingCommits; }
        set
        {
           _incomingCommits = new BindingList<ICommit>(value);
            this.IncomingCommitsGrid.DataSource = _incomingCommits;
        }
    }

    private BindingList<ICommit> _outgoingCommits;
    public IList<ICommit> OutgoingCommits
    {
        get { return _outgoingCommits; }
        set
        {
            _outgoingCommits = new BindingList<ICommit>(value);
            this.OutgoingCommitsGrid.DataSource = _outgoingCommits;
        }
    }

    public event EventHandler<EventArgs> Fetch;
    private void FetchIncomingCommitsButton_Click(object sender, EventArgs e)
    {
        var handler = Fetch;
        if (handler != null)
        {
            handler(this, e);
        }
    }

    public event EventHandler<EventArgs> Pull;
    private void PullButton_Click(object sender, EventArgs e)
    {
        var handler = Pull;
        if (handler != null)
        {
            handler(this, e);
        }
    }

    public event EventHandler<EventArgs> Push;
    private void PushButton_Click(object sender, EventArgs e)
    {
        var handler = Push;
        if (handler != null)
        {
            handler(this, e);
        }
    }

    public event EventHandler<EventArgs> Sync;
    private void SyncButton_Click(object sender, EventArgs e)
    {
        var handler = Sync;
        if (handler != null)
        {
            handler(this, e);
        }
    }
}

This is the pattern in particular that I'm really worried about.

    private BindingList<ICommit> _incomingCommits;
    public IList<ICommit> IncomingCommits
    {
        get { return _incomingCommits; }
        set
        {
           _incomingCommits = new BindingList<ICommit>(value);
            this.IncomingCommitsGrid.DataSource = _incomingCommits;
        }
    }


texts: Fast canonical indexing of elements in array

texts:
Given two arrays of elements:

aaabbccdefaa
zzzccddafgzz

I want to check whether these two arrays are equivalent up to a relabeling.
My strategy is to map them into a canonical form and then check whether they share the same canonical form:
# Convert aaabbccdefaa -> 000112234500
canonical <- function(input){
  output <- input
  labels <- unique(input)
  nlabels <- length(labels)
  for (i in 1:nlabels){
    output[grep(labels[i], input)] <- i
  }
  return(output)
}

# try it
input <- c("a","a","a","b","b","c","c","d","e","f","a","a")
canonical(input)

> [1] "1" "1" "1" "2" "2" "3" "3" "4" "5" "6" "1" "1"

Can this R function be faster?


texts: Populating dropdowns that are based on others

texts:
I created two dropdowns, a dadand a son that are populated based on two arrays that, hypothetically, can't be changed.

When you choose a dad with the code x it generates the son's drop-down with the options containing the code x.

var dadArray = [
  [1, 'Dad1'],
  [2, 'Dad2'],
  [3, 'Dad3']
];
var sonArray = [
  [1, 'Son1'],
  [1, 'Son2'],
  [3, 'Son3'],
  [2, 'Son4']
];

function sortArray(dad, dadID) {
  for (var i = 0; i < dad.length; i++) {
    $(dadID).html($(dadID).html() + '<option value="' + dad[i][0] + '">' + dad[i][1] + '</option>');
  }
  var selDad = $('#dadDrop option:selected').val();
  for (i = 0; i < sonArray.length; i++) {
    if (sonArray[i][0] == selDad) {
      $('#sonDrop').html($('#sonDrop').html() + '<option value="' + sonArray[i][0] + '">' + sonArray[i][1] + '</option>');
    }
  }
}

sortArray(dadArray, '#dadDrop');

$("#dadDrop").change(function() {
  $('#sonDrop').html('');
  var selDad = $('#dadDrop option:selected').val();
  for (var i = 0; i < sonArray.length; i++) {
    if (sonArray[i][0] == selDad) {
      $('#sonDrop').html($('#sonDrop').html() + '<option value="' + sonArray[i][0] + '">' + sonArray[i][1] + '</option>');
    }
  }
});

<select id="dadDrop">
</select>

<select id="sonDrop">
</select>

I made it using jQuery, but it looks huge (Probably because I'm still a newbie to JS and its libraries with amazing features). Is there a different logic that requires fewer lines? of course there is, but may you share it with me?


texts: Read numbers between 1 and 5, then print the minimum and maximum

texts:
Just looking for some feedback regarding how to optimize my code.  It works, but just want some feedback on how to improve the solution.

Requirements:

Prompt for and read a number between 1 and 5. Repeat this step until the input is 1..5.
Repeat the following multiple times according to the number read in step 1.

a. Read in a list of integers ending with a 0. The 0 marks the end of
the input and is not considered part of the list
b. Print the largest and smallest integers in the list.
c. If only a    zero appears in the list, print an error message

CODE:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class SIMPLE_NUMBER_PROGRAM {

    public static void main(String[] args) {

        int input = prompt();
        ArrayList<Integer> inputList;
        inputList = new ArrayList();
        Integer min;
        Integer max;

        if (input == 0 && inputList.isEmpty()) {
            System.out.println("error: empty list!");
        } else {
            while (input < 1 && input != 0 || input > 5 && input != 0) {
                input = prompt();
            }
            while (input >= 1 && input <= 5) {
                inputList.add(input);
                input = prompt();
            }
            min = Collections.min(inputList);
            max = Collections.max(inputList);
            System.out.println("Min: " + min + "\n" + "Max: " + max);
        }

    }

    private static int prompt() {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number: ");
        return sc.nextInt();
    }

}


texts: FormArray total of each formgroup via RxJS

texts:
Stackblitz - https://stackblitz.com/edit/angular-plp4rb-formarray-total-prs9ay

I'm new to RxJS observables.

I've created a form array where the total for a line is quantity * rate. Via valueChanges for the line form group I set the total via the calcTotal method.

On form changes I emit all the lines up to parent to calculate the total.

Questions:

Do I have any memory leaks?
Why is it if I stick debounceTime(1) inside the lineItem valueChanges then this stops working where the calculation is out by the last change?

    lineItem.valueChanges.pipe(
      takeUntil(this.destroyed$),
      debounceTime(1)
    ).subscribe(value => this.calcTotal(lineItem))

Why is it if I remove the {emitEvent: false} and put in a debounceTime as above the total stops working altogether?
Should i be using some other way like combineLatest? If so how do I collect the valueChanges observables (I'll figure it out from here if this is required)?

import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup } from '@angular/forms'
import { Subject } from 'rxjs'
import { takeUntil, debounceTime} from 'rxjs/operators'
import { MatTable } from '@angular/material';

import { Line } from '../app.component';

@Component({
  selector: 'app-total-calculator',
  templateUrl: './total-calculator.component.html',
  styleUrls: ['./total-calculator.component.css']
})
export class TotalCalculatorComponent implements OnInit {
  displayedColumns = ['quantity', 'rate', 'total'];
  formGroup: FormGroup;

  @Input() lines: Line[];
  @Output() linesChange = new EventEmitter<Line[]>();
  @ViewChild(MatTable) private matTable: MatTable<any>;

  get linesArray(): FormArray {
   return this.formGroup.get('lines') as FormArray;
  }

  private destroyed$ = new Subject<void>();

  constructor(private fb: FormBuilder) {
   this.buildForm();
  }

  ngOnDestroy() {
   this.destroyed$.next();
   this.destroyed$.complete();
  }

  addLineClick() {
    this.addLineFormGroup();
  }

  addLineFormGroup() {
    this.linesArray.push(this
      .getLineFormGroup());
    this.matTable.renderRows();
  }

  private buildForm() {
     // formarray
     this.formGroup = this.fb.group({
       lines: this.fb.array([])
     });

     // subscribe to any changes and emit these
     this.formGroup.valueChanges.pipe(
       takeUntil(this.destroyed$),
       debounceTime(300)
     ).subscribe(value => {
        if (!this.formGroup.valid) {
          return;
        }
        this.linesChange.emit(value['lines']);
    });
  }

  getLineFormGroup(): FormGroup {
    let lineItem = this.fb.group({
      quantity: new FormControl(),
      rate: new FormControl(),
      total: new FormControl()
    });
    lineItem.valueChanges.pipe(
      takeUntil(this.destroyed$),
    ).subscribe(value => this.calcTotal(lineItem))
    return lineItem
  }

  calcTotal(line: FormGroup) {
    const quantity =  +line.controls['quantity'].value;
    const rate =      +line.controls['rate'].value;
    line.controls['total'].setValue((quantity * rate).toFixed(2), {emitEvent: false});
  }

  ngOnInit() {
  }

}
```


texts: Engineering a minimalist image interface without templates

texts:
I'm practicing different ways of class design, so I'd like feedback on the design characteristics. Of course code practice comments are also welcome.

It was a conscious decision to omit templates. My next version will use a class template to store image data, similar to CImg and boost::GIL. I intend to make more classes with increasing complexity (templates, abstract base class, variadic templates). Until I reach a detailed yet highly abstract image class.

Header:

#ifndef AIMG
#define AIMG

#include <vector>
#include <string>

class AImg
{
public:
  const std::vector<short> dimsizes; //or std::array of length 4?
  const int N;     //# of elements ( = product of dimension sizes)
  unsigned int Bytes {1}; //bytes per element
  std::string tag; //meta info like "rgb"
  std::string cast;//used for returning data of type cast
  void* data;      //pointer to some array/container/byte-blob

  AImg(const std::vector<short>&); //you have to specify image size when creating. But may be empty of data.
  void setdata(void*);
  void* getdata();

  //example of pseudo-template method:
  void plusone(std::string);
  int operator()(unsigned int); //variable args would allow better indexing

private:
  int getN();
  //checkcast() ?
};

//public fcns
AImg::AImg(const std::vector<short>& input): dimsizes(input), N(getN()), cast("") {}
int AImg::operator()(unsigned int idx){
   if (cast=="int")
    {return ((int*)data)[idx];} else return 0;
  }
void  AImg::setdata(void* input){data=(void*)input;}
void* AImg::getdata(){return data;}
void  AImg::plusone(std::string cast){
        if (cast=="int")
        {
          int* idata = (int*)data;
          for (int i = 0;i<N;i++){idata[i] += 1;}
        }
        else if (cast == "float")
        {
          float* fdata = (float*)data;
          for (int i = 0;i<N;i++){fdata[i] += 1.0;}
        }
        //...other types
        // careful: N is based on elements of some user-defined type. Not all types have the same precision (#bytes).
        // So you'd need to normalize N based on the type size ( sizeof() ) to properly iterate over the data, or forbid certain types
      }

//Private fcns
int AImg::getN(){ //doesn't STL have a std::prod() ?!?!
  int prod = 1;
  for(short n : dimsizes) prod *= n;
  return prod;
}

#endif // AIMG

Main:

#include <iostream>
#include "AImg.h"

using std::cout;  using std::cin;
using std::endl;  using std::vector;

int main()
{
  //create image object of size 2x2
AImg img(vector<short> {2,2});
  //create image data: simple int array
int d[4] {1,2,3,4};
img.setdata(d); //make sure length of d equals N, i.e. fill img up completely
img.plusone("int");
int* d2 = (int*)img.getdata(); //need to explicitly re-cast in c++
cout<<d2[0]<<d2[1]<<d2[2]<<d2[3]<<endl;
img.cast = "int";
cout<<img(0)<<img(1)<<img(2)<<img(3)<<endl;
}

Personally I think a class design like this is risky to use, so should I add more safety checks? It also seems harder to maintain and extend compared to a class using templates.

It also seems hard to extend the model to allow for inhomogenous (sub)pixels. For example, the value of a pixel at (1,1,1) could be an int but the value of the pixel at (1,1,2) could be an unsigned char.


texts: Implementation of lru_cache for daily "top categories" query

texts:
In my website, I want to show top categories by products' view / sell counts.

Since this is not something changes every hour, I want to fetch real results only once a day from database (may be once a week). Here is what I have done:

def global_context(request):
    ## ... some other queries

    today = datetime.datetime.now().day
    top_cats = top_categories(today)  # hit once a day
    return {'top_categories': top_cats}

@lru_cache(maxsize=2)
def top_categories(day):
    # fetch first 50 top-selling products
    top_products = Product.objects.all().order_by('-sell_count')[:50]

    # get first 10 unique categories
    categories = list(set([product.categori for product in top_products]))[:10]

    return categories

This code is working. (I have tested with per minute version). But I wonder,

Is this correct way to achieve my goal?
When currsize reached to maxsize nothing happened. Code kept working. Why?
Should I manually reset / clear cache with cache_clear?


texts:
I was trying to get my computer information and I came up with this code. It is working but I need opinions on how I am doing it. It is my first time to using std::string to return strings. Is it good or is there another way around?

struct USER
{
    std::string ID;
    std::string Username;
    std::string PCName;
    std::string OSVersion;
};

std::string GetOSVersion()
{
    OSVERSIONINFOEX osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
    GetVersionEx((LPOSVERSIONINFOA) &osvi);

    std::string Version = "Unknown Operating System";
    std::string ServicePack = osvi.szCSDVersion;

    if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion >= 1)
    {
        if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
            Version = "Windows XP Home Edition " + ServicePack;
        else
            Version = "Windows XP Professional " + ServicePack;

        return Version;
    }
    return Version;
}

void InitUser(User* u)
{
    char UsernameBuffer[UNLEN + 1];
    DWORD UsernameBufferSize = sizeof(UsernameBuffer);
    GetUserName(UsernameBuffer, &UsernameBufferSize);
    u->Username = UsernameBuffer;

    char ComputerNameBuffer[MAX_COMPUTERNAME_LENGTH + 1];
    DWORD ComputerNameBufferSize = sizeof(ComputerNameBuffer);
    GetComputerName(ComputerNameBuffer, &ComputerNameBufferSize);
    u->PCName = ComputerNameBuffer;

    u->OSVersion = GetOSVersion();

    return;
}


texts: Cube root in Python 3 using Bisection Search: Numbers in -1 to 0

texts:
Here is my code, which doesn't seem to work for numbers in between -1 and 0 (works perfectly fine otherwise)

I think the code enters an infinite loop, somehow, hence I get no result after entering the number. Please have a look and let me know what changes should be made. I am a beginner at programming and would appreciate any help!

    cube = float(input('Enter:'))
if abs(cube) > 1:
    num_guesses = 0
    epsilon = 0.0001
    low = 0
    high = cube
    guess = (high + low) / 2.0

    while abs(abs(guess) ** 3 - abs(cube)) >= epsilon:
        if cube > 0:
            if guess ** 3 < cube:
                low = guess
            else:
                high = guess
            guess = (low + high) / 2.0
            num_guesses += 1
        else:
            if guess ** 3 > cube:
                low = guess
            else:
                high = guess
            guess = (low + high) / 2.0
            num_guesses += 1

if abs(cube) < 1:
    num_guesses = 0
    epsilon = 0.0001
    low = cube
    high = 1
    guess = (high + low) / 2.0

    while abs(abs(guess) ** 3 - abs(cube)) >= epsilon:
        if cube > 0:
            if guess ** 3 < cube:
                low = guess
            else:
                high = guess
            guess = (low + high) / 2.0
            num_guesses += 1
        else:
            low = -1
            high = cube
            if guess ** 3 > cube:
                high = guess
            else:
                low = guess
            guess = (low + high) / 2.0
            num_guesses += 1

print(num_guesses)
print('The cube root of',cube,'is closest to',guess)

Thanks a lot!