texts: jQuery templating with ES6/ES2015 template strings

texts:
I have been using a particular pattern over and over again when I want to keep my jQuery apps more safe from XSS. I do something like this. (It uses ES6 template strings)

function doSomething ($el, user) {
  var $html = $(`

`);
  $html.appendTo($el);
  $html.find('.username-text').append(document.createTextNode(user.name));
  $html.find('.description').append(document.createTextNode(user.description));

  return $html;
}

var user = {
  name: "John",
  description: "",
  img: 'http://placehold.it/100x100'
};

doSomething($('body'), user);

JS Bin

User defined fields become text nodes which means I need to create a jQuery element or some sort of DOM structure to hold them. I also use find which means at least in jQuery I have to append it to the actual DOM itself. So I was thinking it would be nice to have a more general way of nesting jQuery elements (I guess you could say "components") inside the template itself kind of like React's JSX but for jQuery.

This is what I came up with. (It uses a tagged template literal which returns a jQuery object).

var jQTemplate = (function ($) {

  var tempFiller = function (key) {
    return `<div id='jQT-jQTemplate-tempFiller-${key}'></div>`;
  };

  var jQTemplate = function (strings, ...values) {
      var $docFrag = $(document.createDocumentFragment());
      var nodeIndexes = [];
      var html = "";
    for(let i = 0; i < strings.length; ++i) {
      html += strings[i];

      var value = values[i];
      var allNodes = Array.isArray(value) && value.every(el=>el instanceof Node || el instanceof jQuery)
      if(value) {
        if(value instanceof Node || value instanceof jQuery || allNodes) {
          nodeIndexes.push(i);
          html += tempFiller(i);
        } else if(value) {
          html += value;// || '';
        }
      }
    }
    $docFrag.append(html);
    nodeIndexes.forEach(function (i) {
      var value = values[i];
      $($docFrag[0].getElementById(`jQT-jQTemplate-tempFiller-${i}`))
    .replaceWith(value);
    });

      return $docFrag;
    };

  return {
    template: jQTemplate,
    textNode: (text) => document.createTextNode(text)
  };

}($));

Here is some example usage: (not the best "app" but shows the different ways I intended it to be used)

/*
* Example usage
*
*/

var {template, textNode} =  jQTemplate;

console.log("started");

function bootstrapButton (type, text) {
  return $(`<a class="btn btn-${type || "default"} btn-lg" href="#" role="button">${text || ""}</a>`)
}

function jumbotron () {
  var $learnMore = bootstrapButton("primary", "Add Content");

  $learnMore.on('click', function (el) {
    $("body").append('
Lorem Ipsum.
');
  })

  return template`

Hello, world!

...

${$learnMore}

`;
}

$("body").on("click", '.js-deleteParent', function () {
  $(this).parent().remove();
});

var userInput = ['', "more user input"];

var trustedHtmlContent = [`<h1>Header</h1>`, `<h3>Sub Header</h3>`];

var extraClass ="container";

template`

      ${trustedHtmlContent.map(el=>$(el))}
      ${userInput.map(el=>textNode(el))}

     ${jumbotron()}

`.appendTo("body");

JS Bin

Any thoughts, suggestions, or comments? Is there any reason why this shouldn't be used in production?


texts:
This is my first time using Tkinter and really trying to get use to using classes in Python. I wonder if I'm using self entirely too much, but here is my code:

from Tkinter import *

class MainFrame(object):
    def __init__(self):
        self.display()
    #display all the labels for the main frame
    def labels(self):
        #adding x-cord label
        x_cord_label = Label(self.top, text = 'X-Coordinate').grid(row=0,column = 0)
    #calls the visible features
    def display(self):
        self.top = Tk()
        self.labels()
        self.entries()
        self.buttons()
        #must remain at bottom or wont be displayed
        self.top.mainloop()

    #display all the entry boxes for the main frame
    def entries(self):
        x_cord_entry = Entry(self.top,bd=5).grid(row=0,column = 1)

    def buttons(self):
        x_cord_button = Button(self.top, text = 'Enter').grid(row=0,column = 2)

I am planning on main just having the mainframe being generated.

main.py
from mainFrame import MainFrame
def main():
    window = MainFrame()

if __name__=="__main__":
    main()


texts: Simple proof-of-work (based on HashCash)

texts:
I'm trying to build a simple (yet effective) brute-force protection for my App-API.
The client requests an identity - the server supplies a random string (called seed, which it remembers via PHP  session) and a security level.
If the client wants to login it needs to supply a suffix for the seed which results in a SHA512 hash with leading zero-bytes (security level times).
Java (generation):
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashCash {
    private final static String HASH_ALGORITHM = "SHA-256";

    private final MessageDigest hashGenerator;

    /**
     * Creates a new HashCash generator using the SHA-256 algorithm
     * @throws NoSuchAlgorithmException If the "SHA-256" algorithm is not available
     */
    public HashCash() throws NoSuchAlgorithmException {
        hashGenerator = MessageDigest.getInstance(HASH_ALGORITHM);
    }

    /**
     * Generates a HashCash for the specified level
     * @param seed A seed for the HashCash
     * @param targetLevel The target level for the HashCash
     * @return The generated HashCash
     */
    public long generateHashCash(final String seed, final int targetLevel) {
        // Variation counter (and final result)
        long counter = 0;
        while(true) {
            // Check if the current hashCash reaches the desired security level
            if(getSecurityLevel(seed + counter) >= targetLevel)
                return counter;
            // Increase hash counter
            counter++;
        }
    }

    /**
     * Computes the security level of the given value
     * @param value The value to compute the level of
     * @return The security level of the value
     */
    private final int getSecurityLevel(final String value) {
        hashGenerator.update(value.getBytes());
        final byte[] hash = hashGenerator.digest();
        int level = 0;
        for(final byte b: hash) {
            if(b != 0)
                break;
            level++;
        }
        return level;
    }
}

PHP (verification):
const HASH_CASH_SEC_LEVEL = 8;

/**
 * Verifies a HashCash suffix (by checking it's security level)
 * @param string $seed The seed of the identity
 * @param string $suffix The HashCash suffix
 * @return bool Whether the given HashCash suffix is valid
 */
function verifyHashCash(string $seed, string $suffix): bool {
    $hash = hash('sha256', $seed.$suffix, true);
    $level = 0;
    $length = strlen($hash);
    for($b = 0; $b < $length; $b++) {
        if(ord($hash[$b]) !== 0)
            break;
        $level++;
    }
    return $level >= HASH_CASH_SEC_LEVEL;
}

Are there any security related issues?
Are there performance optimizations for the Java code?


texts: How to remove duplicated code? AOP and Generics are Ok

texts:
I have figures - TriangleItem and CircleItem:

public abstract class BaseItem
{
  protected int _id;
  protected string _description;
}

public sealed class TriangleItem : BaseItem
{
  public int TriangleId { get { return _id; } set { _id = value; } }
  public string TriangleDescription { get { return _description; } set { _description = value; } }
}

public sealed class CircleItem : BaseItem
{
  public int CircleId { get { return _id; } set { _id = value; } }
  public string CircleDescription { get { return _description; } set { _description = value; } }
}

And I have figure collections TriangleBox and CircleBox:

public abstract class BaseBox
{
  public string ItemsXml { get; set; }
  public string Descriptions { get; set; }
  public static abstract BaseBox Boxing( BaseItem[] items );
  public abstract void Unboxing();
}

public sealed class TriangleBox : BaseBox
{
  public static override BaseBox Boxing( BaseItem[] items )
  {
    string[] ids = items.ToList().Cast<TriangleItem>().Select( i => i.TriangleId.ToString() ).ToArray();
    string[] descriptions = items.ToList().Cast<TriangleItem>().Select( i => i.TriangleDescription ).ToArray();

    return new TriangleBox()
    {
      ItemsXml = Util.ToXml( ids ),
      Descriptions = descriptions.Aggregate( ( d, next ) => next + ", " + d )
    };
  }

  public TriangleItem[] Unboxing()
  {
    return Util.FromXml( ItemsXml ).Select( i => new TriangleItem { TriangleId = int.Parse( i ), TriangleDescription = i } ).ToArray();
  }
}

public sealed class CircleBox : BaseBox
{
  public static override BaseBox Boxing( BaseItem[] items )
  {
    string[] ids = items.ToList().Cast<CircleItem>().Select( i => i.CircleId.ToString() ).ToArray();
    string[] descriptions = items.ToList().Cast<CircleItem>().Select( i => i.CircleDescription ).ToArray();

    return new CircleBox()
    {
      ItemsXml = Util.ToXml( ids ),
      Descriptions = descriptions.Aggregate( ( d, next ) => next + ", " + d )
    };
  }

  public CircleItem[] Unboxing()
  {
    return Util.FromXml( ItemsXml ).Select( i => new CircleItem { CircleId = int.Parse( i ), CircleDescription = i } ).ToArray();
  }
}

As you can see, I have almost the same method implementations - Boxing and Unboxing.
I use these methods as follows:

  public BaseBox Do( BaseItem[] items )
  {
    BaseBox result = null;

    if( items is CircleItem[] )
      result = CircleBox.Boxing( items );
    else if( items is TriangleItem[] )
      result = TriangleBox.Boxing( items );

    return result;
  }

  public TriangleItem[] GetTriangles()
  {
    TriangleBox tb = DB.GetTriangleBox(); // From database
    return tb.Unboxing();
  }

  public CircleItem[] GetCircles()
  {
    CircleBox cb = DB.GetCircleBox(); // From database
    return cb.Unboxing();
  }

Can I changle something to have only one Boxing and Unboxing implementations?
What would you change in this code? What do you dislike (except catch null method's parameters)? AOP and Generics are OK if need.

In Do-method I have to know items's type. And I have to return empty TriangleBox or CircleBox if items.Length is 0. How I have to write my Do-method with this case?


texts: Find matching dictionary words given a Scrabble tray

texts:
This is a question I was asked in an interview, below is a cleaned-up copy of the answer I gave. Apparently this answer was not satisfactory. How can it be improved?

Question: Given a dictionary of words (a text file with 100000+ entries) and a list of n letters with possible repeats (i.e. a Scrabble tray), return the list of words which can be formed from some or all of the letters in the tray.

function scrabble(dictionary, tray) {
  return dictionary.filter(w => isWordInTray(tray, w));
}

function isWordInTray(tray, word) {
  // build multiset of letters in tray
  let counts = {};
  for (const letter of tray) {
    if (counts[letter] === undefined) {
      counts[letter] = 1;
    } else {
      counts[letter]++;
    }
  }

  // take letters from the word and decrement tray count
  for (const letter of word) {
    if (counts[letter] > 0) {
      counts[letter]--;
    } else {
      return false;
    }
  }
  return true;
}

//---------------

// dictionary (full dictionary contains 178691 entries)
const dict = ['AA', 'ABSORBABILITIES', 'AD', 'ADD', 'BAD', 'DAD', 'FOO']; // ...

// test case
const exampleTray = ['D', 'D', 'A'];
console.log(scrabble(dict, exampleTray));

// expected correct answer (in any order)
// [ 'AD', 'ADD', 'DAD' ]

Caveats

The interviewer said that the problem was "kind of like Scrabble", this was the only mention of Scrabble. The size of the tray was given simply as n (it was described as a list of letters, not a tray).
The full dictionary was given to me as a text file, it is sorted and has 178691 entries. I've included a minimal subset which works with the test case I was given in the interview.
counts is a hashtable but I could have used a 26-element array instead to get O(1) inserts and lookups which improves the worst case from O(n), but n = 26, so it's not a big deal.
I'm not looking for micro-optimizations for special cases: I'm only seeking to decrease the big-O worst case complexity.

Alternative Approaches

These are the other approaches which spring to mind:

Approach 2: Generate all words

The opposite approach is to generate all words from the tiles and look them up in the dictionary, but if we treat the tray as a multiset of letters then the number of words we will generate is a multiset permutation and that's just for the case where len(word) = len(tiles) without considering all the shorter words which can be formed.

The size of the tray was given as n, while in the game of Scrabble it's at most 7 (news to me as I don't play Scrabble), the interviewer never gave this restriction, so presumably max(n) = max(len(word) in dict) which is "ABSORBABILITIES" at 15 letters. That's going to be a huge search space. I asked what n was and he said "anything".

If my understanding is correct, the worst case for multiset permutations is when each letter in the tray is unique, because this is simply the number of permutations which is n!. Again, this doesn't account for the need to also find words shorter than the tray length.

7! = 5040, so for an actual Scrabble tray, generating all words is feasible, but at 9! we've generated more words than are in our dictionary and by 15! there's over a trillion.

Approach 3: Use a trie?

When I see words being looked up in a dictionary, I think of a trie (prefix tree). What I can't see is what it would offer in this case, especially w.r.t big-O worst case complexity.

Is there something I'm totally missing?

Big-O

Assuming that all words are of length w and the tray is also that length, the dictionary is of length n, and there are no anagrams; the complexity should be O(n*w).

(This also assumes that counts is replaced with an array as mentioned above.)


texts: LeetCode Count number of set bits solution

texts:
Question - Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).

int hammingWeight(uint32_t n) {
        int count = 0;
        while(n>0){
            count+=n&1;
            n>>=1;
        }
        return count;
    }

Can you come up with a better method?

One gentleman came up with this

int hammingWeight(uint32_t n) {
    int count = 0;

    while (n) {
        n &= (n - 1);
        count++;
    }

    return count;
}

How does one come up with such creative solutions?

And do you have a better one or any improvements I can make to my solution?


texts:
I want to have a caching class to cache different types.  I want each type to be cached in a different MemoryCache but in a generic way.

Am I doing it right?

internal static class RecordsCache
{
    private static Dictionary<string, ObjectCache> cacheStore;
    static private CacheItemPolicy policy = null;

    static RecordsCache()
    {
        cacheStore = new Dictionary<string, ObjectCache>();

        ObjectCache activitiesCache = new MemoryCache(typeof(Activity).ToString());
        ObjectCache lettersCache = new MemoryCache(typeof(Letter).ToString());
        ObjectCache contactssCache = new MemoryCache(typeof(Contact).ToString());

        cacheStore.Add(typeof(Activity).ToString(), activitiesCache);
        cacheStore.Add(typeof(Letter).ToString(), lettersCache );
        cacheStore.Add(typeof(Contact).ToString(), contactssCache );

        policy = new CacheItemPolicy();
        policy.Priority = CacheItemPriority.Default;
        policy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(12);
    }

    public static void Set<T>(string userID, int year, List<T> records)
    {
        var cache = cacheStore[typeof(T).ToString()];
        string key = userID + "-" + year.ToString();
        cache.Set(key, records, policy);
    }

    public static bool TryGet<T>(string userID, int year, out List<T> records)
    {
        var cache = cacheStore[typeof(T).ToString()];
        string key = userID + "-" + year.ToString();

        records = cache[key] as List<T>;
        return records != null;
    }

    public static void Remove<T>(string userID, int year)
    {
        var cache = cacheStore[typeof(T).ToString()];
        string key = userID + "-" + year.ToString();
        cache.Remove(key);
    }
}


texts: Deserialize JSON Strings Directly into Models?

texts:
I have Ruby models which are populated from the responses of API calls in the following way:

JSON.parse converts the response to a Hash
the Hash is passed into the initialize method of a class
the initialize method converts camelCase hash keys and assigns underscore_case instance variables
controller code works with these instances and converts back to json to send to the browser

This works fine, but some of these response objects are large.  Others are arrays of large objects.

Profiling shows that this process consumes a lot of CPU (and memory, but that is less of a concern) -- which makes sense given that I create hashes in order to create objects, and the back and forth between camelCase and underscore_case happens A LOT -- so what libraries or techniques have you come across which solve this problem?

Here is an oversimplified example:

JSON response from a third party API (unlikely to change):

"{\"abcDef\": 123, \"ghiJkl\": 456, \"mnoPqr\": 789}"

Class definition (attributes unlikely to change):

class Data
  attr_accessor :abc_def, :ghi_jkl, :mno_pqr

  def initialize(attributes = {})
    attributes.each do |key, val|
      send "#{key.underscore}=".to_sym, val
    end
  end

  def as_json
    instance_variables.reduce({}) do |hash, iv|
      iv_name = iv.to_s[1..-1]
      v = send(iv_name) if self.respond_to?(iv_name)
      hash[iv_name.camelize(:lower)] = (v.as_json(options) if v.respond_to?(:as_json)) || v
      hash
    end
  end
end

Controller:

get '/' do
  d = Data.new JSON.parse(api.get)
  # ... do some work ...
  content_type 'application/json'
  d.to_json
end


texts: Mass and length calculator using Perl 6 custom operator

texts:
I am studying chemistry in the university, and then I try to write all the things in the textbook with Perl6 or Perl, like balancing the chemical formula or other process!

Then I encountered the problem is on perl6 custom operator.
I feel I have been repeating my code and myself when i use the feature.
It is hard to read and write, and what is the way to deal with such problems?

#!/usr/bin/env perl6
use v6;
#basic SI(International System of Units) type

role MetricPrefix {
    method baseOn ( Str $base , Numeric $input ) {
        given $base {
            when 'pico' { return $input * 10**-12 }
            when 'namo' { return $input * 10**-9 }
            when 'micro' { return $input * 10**-6}
            when 'milli' { return $input * 10**-3 }
            when 'centi' { return $input * 10**-2 }
            when 'hecto' { return $input * 10**2 }
            when 'kilo' { return $input * 10**3 }
            when 'mega' { return $input * 10**6 }
            when 'giga' { return $input * 10**9 }
            when 'tera' { return $input * 10**12 }
            default { fail "you must input a metric prefix which allow pico to tera" }
        }
    }
}

class Mass does MetricPrefix {
    #basic Mass is g is different form si statda
    has $.g;

    submethod BUILD ( :$!g  ) {
    }

}

class Length does MetricPrefix {
    has $.Length ;

    submethod BUILD ( :$!Length  ) {
    }
}

multi postfix:<(kg)>( $input ) {
    return Mass.new( g => Mass.baseOn("kilo",$input) ) or fail "you Must input a number";
}

multi postfix:<(g)>( $input ) {
    return Mass.new( g => $input ) or fail "you Must input a number";
}

multi infix:<+>( Mass $inputOne , Mass $inputTwo ) is assoc<right> {
    return Mass.new( g => $inputOne.g + $inputTwo.g) or fail "error in there ";
}

multi infix:<->( Mass $inputOne , Mass $inputTwo ) is assoc<right> {
    return Mass.new( g => $inputOne.g - $inputTwo.g) or fail "error in there ";
}

multi infix:<*>( Mass $inputOne , Mass $inputTwo ) is assoc<right> is tighter( &infix:<+> ) is tighter( &infix:<-> ) is tighter( &infix:</>) {
    return Mass.new( g => $inputOne.g * $inputTwo.g) or fail "error in there ";
}

multi infix:</>( Mass $inputOne , Mass $inputTwo ) is assoc<right> is tighter( &infix:<+> ) is tighter( &infix:<-> )  {
    return Mass.new( g => $inputOne.g / $inputTwo.g) or fail "error in there ";
}

#the meterLeng
multi postfix:<(km)>( $input ) {
    return Length.new( Length => Length.baseOn("kilo",$input) ) or fail "you Must input a number";
}

multi postfix:<(m)>( $input ) {
    return Length.new( Length => $input ) or fail "you Must input a number";
}

multi infix:<+>( Length $inputOne , Length $inputTwo ) is assoc<right> {
    return Length.new( Length => $inputOne.Length + $inputTwo.Length) or fail "error in there ";
}

multi infix:<->( Length $inputOne , Length $inputTwo ) is assoc<right> {
    return Length.new( Length => $inputOne.Length - $inputTwo.Length) or fail "error in there ";
}

multi infix:<*>( Length $inputOne , Length $inputTwo ) is assoc<right> is tighter( &infix:<+> ) is tighter( &infix:<-> ) is tighter( &infix:</>) {
    return Length.new( Length => $inputOne.Length * $inputTwo.Length) or fail "error in there ";
}

multi infix:</>( Length $inputOne , Length $inputTwo ) is assoc<right> is tighter( &infix:<+> ) is tighter( &infix:<-> )  {
    return Length.new( Length => $inputOne.Length / $inputTwo.Length) or fail "error in there ";
}

#just a test
say 10(kg) + 1(g);
say 10(m) + 1(m);


texts:
In my data I have few hierarchy values - example address

Name -> Street -> City -> County -> State -> Country

The validation I need is: if a value in the above hierarchy is present, then all the previous/higher order values should be present.
Below is a valid case

Name -> Street -> City -> State
This is valid even though there is no country - as it is last in the order

and below is an invalid case

Name -> Street -> State -> Country
This is invalid as there is no City Which is of higher order than state and country.

The below code helped me in doing the checks. Can this be simplified further? I want to get rid of the last dummy return statement. (To the best of my knowledge, it is difficult to get rid of it. But there are more people far more knowledgeable than me.)
 package com.example.demo;

public class SimplyfyHierarchyCheck {

    public static void main(String[] args) {

        String a="a", b="b", c="c", d="d";

        SimplyfyHierarchyCheck shc = new SimplyfyHierarchyCheck();
        System.out.println(shc.isGapLessHierarchy("a", b, "", "") );
    }

    //can this method be made even more concise.
    private boolean isGapLessHierarchy(String... args) { //Hierarchy
        boolean isGapLess=true;

        for(int i=args.length-1; i>=0; i--) {
            if(args[i].isBlank() )  //nothing to check
            {
                continue;
            }
            for(int j=i-1; j>=0; j--) {
                if(args[j].isBlank() )  //gap found i.e false
                {
                    return false;
                }
            }
        }
        return isGapLess; //dummy return // am required to return true or false // can i get rid of this
    }

}


texts:
I am doing a college exercise and would like to know how to improve the execution of the idea. The idea is to create a program that converts temperature measurements.

Main.java

package app.cnv;

public class Main {
  public static void main(String[] args) {
    Celsius celsius = new Celsius(37);

    System.out.println(celsius.convert(new Fahrenheit()));

    Fahrenheit fahrenheit = new Fahrenheit(98.6);

    try {
      System.out.println(fahrenheit.convert(new Celsius()));
    } catch (AbsoluteZeroException e) {
      System.out.println(e.getMessage());
    }
  }
}

Temperature.java

package app.cnv;

public abstract class Temperature {
  public abstract double convert(Temperature to) throws AbsoluteZeroException;
}

Celsius.java

package app.cnv;

public class Celsius extends Temperature {
  double celsius;

  Celsius() {
  }

  Celsius(double celsius) {
    this.celsius = celsius;
  }

  @Override
  public double convert(Temperature to) {
    if (to instanceof Fahrenheit) {
      return (celsius * 9) / 5 + 32;
    }
    return celsius;
  }
}

Fahrenheit.java

package app.cnv;

public class Fahrenheit extends Temperature {
  double fahrenheit;

  Fahrenheit() {
  }

  Fahrenheit(double fahrenheit) {
    this.fahrenheit = fahrenheit;
  }

  @Override
  public double convert(Temperature to) throws AbsoluteZeroException {
    if (to instanceof Celsius) {
      if (fahrenheit < -459.67) {
        throw new AbsoluteZeroException("The temperature cannot be less than absolute zero.");
      } else {
        return ((fahrenheit - 32) * 5) / 9;
      }
    }
    return fahrenheit;
  }
}

AbsoluteZeroException.java

package app.cnv;

public class AbsoluteZeroException extends Exception {
  public AbsoluteZeroException(String err) {
    super(err);
  }
}


texts: Job execution on records supplied by database

texts:
I have a requirement to check all records in a table which is big (Around 1.5-2 million records). What I am doing is very simple, just get all the records and loop through one by one, and do things. I have a quartz job which will run every 2 minutes to check things.

ApplicationDetailCheckingJob.java

public class ApplicationDetailCheckingJob implements Job {

@Autowired
private DatabaseService databaseService;

@Value("${EnableJob}")
private boolean enableJob;

@Override
public void execute(JobExecutionContext jobExecutionContext) {
    if (enableJob) {
        try {
            LogService.info(this.getClass().getName(), "Started Checking...");
            //Get All Records
            List<Applications> allApplicationDetails = databaseService.getAllAppDetails();
                //Perform Check For Each Application
                allApplicationDetails.stream().forEachOrdered((app) -> {
                    //Check For Columns Values
                    //If SendTweet = 1, Send tweet to the Application's User
                    //If SendEmail = 1, Send Email to User
                    //If Send SMS = 1, Send SMS to User
                    //Rest is also similar procedures
                });
            LogService.info(this.getClass().getName(), "Finished checking.");
        } catch (Exception e) {
            LogService.error(this.getClass().getName(), e);
        }
    } else {
        LogService.info(this.getClass().getName(), "ApplicationDetailChecking Job is Disabled");
    }
 }
}

DatabaseService.java

public List<Applications> getAllAppDetails() {

    String sqlQuery = "SELECT * FROM Applications";
    List<Applications> appDetails = defaultJdbcTemplate.query(sqlQuery, BeanPropertyRowMapper.newInstance(Applications.class));

    LogService.info(this.getClass().getName(), "Number of records found = " + appDetails.size());

    return appDetails;
}

Can I improve these methods? Is there a better way?

If I use it in the live DB, I doubt the job can be finished before it's started again after 2 mins.


texts: Printing alternating characters of a string using Java 8 streams

texts:
Given a string, S, of length N that is indexed from 0 to N−1, I want to print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line:

  Hacker -> Hce akr

My code works, but I feel it could have been done more elegantly and maybe in a single stream instead of in two... Any ideas how to improve this?

private static String reindex(String input) {
    StringBuilder result = new StringBuilder();

    IntStream.range(0, input.length())
             .filter(index -> index % 2 == 0)
             .forEach(index -> result.append(input.charAt(index)));

    result.append(" ");

    IntStream.range(0, input.length())
             .filter(index -> index % 2 == 1)
             .forEach(index -> result.append(input.charAt(index)));

    return result.toString();
}


texts:
As practice I wanted to write a Socket in Java:

/* User: koray@tugay.biz Date: 21/02/15 Time: 13:30 */

import java.io.IOException;
import java.net.ServerSocket;

public class MyServer {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(8888);

        while (true) {
            new Thread(new ServerSocketThread(serverSocket.accept())).start();
        }
    }

}

and the rest of it:

/* User: koray@tugay.biz Date: 21/02/15 Time: 18:14 */

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ServerSocketThread implements Runnable {

    Socket socket;

    public ServerSocketThread(Socket accept) {
        this.socket = accept;
    }

    @Override
    public void run() {
        try {

            Scanner s = new Scanner(socket.getInputStream());
            String readLine;

            while (!(readLine = s.nextLine()).equals("bye")) {
                System.out.println(readLine);
            }

            new PrintWriter(socket.getOutputStream()).write("Bye then..");
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

I wanted to write it as clean as possible. Any improvements, suggestions?

I can use it like this:

Korays-MacBook-Pro:~ koraytugay$ telnet localhost 8888
Trying ::1...
Connected to localhost.
Escape character is '^]'.
koray
tugay
asdfako
bye
Connection closed by foreign host.


texts: Association count in single query for ActiveRecord

texts:
This is a small gem that gives the possibility to include counts of reflections when fetching active record objects. What do you think of the code? Any improvements or other (similar) use cases where it might be useful?

require 'active_record'

ActiveRecord::Base.extend AssociationCount
module AssociationCount
  def association_count(counted_model, distinct)
    table_name    = self.table_name
    counted_table = counted_model.table_name
    counted_name  = counted_table.singularize
    distinct_sql  = distinct ? 'DISTINCT' : ''

    joins(counted_table.to_sym)
      .select("#{table_name}.*, COUNT(#{distinct_sql} #{counted_table}.id) as #{counted_name}_count_raw")
      .group("#{table_name}.id")
  end

  def can_count(model_name, opts = {})
    model_name = model_name.to_s
    reflection = reflections[model_name]
    fail "No such reflection: '#{model_name}'" unless reflection

    options       = { distinct: true }.merge!(opts)
    singular_name = model_name.singularize

    define_association_count_method(model_name, singular_name)
    define_count_scope(singular_name, reflection, options[:distinct])
  end

  def define_association_count_method(model_name, singular_name)
    define_method "#{singular_name}_count" do
      raw_count_name = "#{singular_name}_count_raw"
      return send(raw_count_name) if self.respond_to?(raw_count_name)
      send(model_name).count
    end
  end

  def define_count_scope(singular_name, reflection, distinct)
    scope_name = "include_#{singular_name}_count"
    class_eval do
      scope scope_name, -> { association_count(reflection.klass, distinct) }
    end
  end
end


texts:
I'm working on a simple star rating system, and before I move on to actually "tallying" the votes, which I figure I'll just do with $.ajax, I wanted to make sure what I've done so far has been done as well as it can be.

JavaScript

//max number of stars
var max_stars = 5;

//add images to the ratings div
function fill_ratings() {
    var $rating = $("#rating");
    if($rating.length) {
        for(i = 1; i <= max_stars; i++) {
            $rating.append('');
            }
        }
    }

//variables...
var hovered = 0;
var has_clicked = false;
var star_clicked = 0;

function handle_ratings() {

    if(has_clicked == true) {
        for(i = 1; i <= star_clicked; i++) {
            $('#rating img#' + i).attr('src', 'star.png');
        }
    }

    $('#rating img').hover(function() {
        hovered = Number($(this).attr('id'));
        for(i = 1; i <= max_stars; i++) {
            if(i <= hovered) {
                $('#rating img#' + i).attr('src', 'star.png');
                } else {
                    $('#rating img#' + i).attr('src', 'star_default.png');
                }
            }
        }).click(function() {
                //if they click a star, only set the stars to grey that are after it.
                star_clicked = Number($(this).attr('id'));
                has_clicked = true;
                    for(i = 1; i <= star_clicked; i++) {
                        $('#rating img#' + i).attr('src', 'star.png');
                        //handle the vote here. eventually.
                    }
                }).mouseout(function() {
                    //if they haven't clicked a star, set all stars to grey.
                    if(has_clicked !== true) {
                            $('#rating img').attr('src', 'star_default.png');
                        } else {
                            //show their rating
                            for(i = 1; i <= max_stars; i++) {
                                if(i <= star_clicked) {
                                    $('#rating img#' + i).attr('src', 'star.png');
                                } else {
                                    $('#rating img#' + i).attr('src', 'star_default.png');
                                }
                            }
                        }
                    });
                }

$(function() {
    fill_ratings();
    handle_ratings();
    });

HTML

The code works, but I was wondering if anyone notices any code that I can improve. Also, is there anything wrong with the way it...looks? Should I be commenting more, indenting differently, or any other "formatting" type things?


texts:
I wrote code that takes csv and export it to sql table. It looks like this:

  def import_to_temp_table(table_name, filepath)
    headers_with_type = headers_for_temp_table.map { |x| x + ' text' }.join(', ')
    full_table_name = "csv_temp_#{table_name}"

    conn = ActiveRecord::Base.connection_pool.checkout
    raw = conn.raw_connection
    conn_string = "COPY #{full_table_name} FROM STDIN WITH DELIMITER ',' csv header;"

    conn.execute("DROP TABLE IF EXISTS #{full_table_name};")
    create_table_string = "CREATE TABLE #{full_table_name} (" "id serial NOT NULL, CONSTRAINT #{full_table_name}_pk PRIMARY KEY (id), " + headers_with_type + ");"
    conn.execute(create_table_string)

    raw.copy_data conn_string do
      File.open(filepath, 'r').each do |line|
        raw.put_copy_data "#{$INPUT_LINE_NUMBER - 1}," + line
      end
    end

    conn.select_value("select count(*) from #{full_table_name}").to_i
  end

This method will create table based on tablename variable, iterate thorugh csv headers and create columns with text type, and then will insert data to those columns. What do you think about this solution?


texts: Providing unchecked exception "wrapper" interfaces for an API with checked exceptions

texts:
I recently had a discussion in the forum of an API, because they changed an exception from checked to unchecked. I believed it needs to be checked, because it is recoverable. The arguments of "the other side" were verbosity and tediousness of try/catch or throws.

If it were purely theoretical question, I'd be right, but I agree that in practice it is sometimes tedious to write all these try/catches just for the sake of rethrowing unchecked exceptions, or logging.

So, an idea came to my mind, and I wonder whether it's viable. I'll illustrate with simple code:

public interface Foo {
    String foo() throws Exception;
}

public interface EasyFoo extends Foo {
    String foo();
}

These are two interfaces that define the same method (and this is enforced by inheritance), but the "easy" version does not define throwing checked exceptions. Then come 2 default implementations:

public class FooImpl implements Foo {

    @Override
    public String foo() throws Exception {
        return "foo";
    }
}

public class EasyFooImpl implements EasyFoo {

    Foo foo;

    public EasyFooImpl(Foo foo) {
        this.foo = foo;
    }

    @Override
    public String foo() {
        try {
            return foo.foo();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}

The latter delegates to the former, wrapping all exceptions in runtime exceptions.

And finally a factory:

public class FooFactory {
    public static Foo createFoo() {
        return new FooImpl();
    }

    public static EasyFoo createEasyFoo() {
        return new EasyFooImpl(new FooImpl());
    }
}

The benefits:

the user of the API can choose how he likes to use the implementation. If he doesn't intend to do anything with the checked exceptions, he can use the "easy" version
you support only one interface. The 2nd is the same, and you'll just have to add the methods that you have in the main one.
the user can use the EasyFoo in places where Foo is required:

EasyFoo foo = FooFactory.createEasyFoo();
helper.doSomething(foo); // which is public void doSomething(Foo foo);

Enough foos - the question is, is this a viable solution that can reduce verbosity while retaining the good sides of checked exceptions?


texts: Macro for counting number of elements in an array

texts:
We all know the classic version of counting the number of elements in a C array: sizeof(a)/sizeof(*a)

But this is dangerous, because if used on a pointer it will return garbage values.

So I made this macro, utilizing gcc extensions. As far as I can tell, it works the way it is supposed to, which is causing compiler error when used on a pointer instead of array.

#define COUNT(a) (__builtin_choose_expr( \
                  __builtin_types_compatible_p(typeof(a), typeof(&a[0])), \
                  (void)0, \
                  (sizeof(a)/sizeof(a[0]))))

/* Only to demonstrate how to use the macro. It's not part of the code
   I want reviewed. */
int main(void)
{
    int arr[5];
    int *p;
    int x = COUNT(arr);

    // This line will yield the compiler error:
    //     error: void value not ignored as it ought to be
    int y = COUNT(p);
}

Any suggestions? Have I missed anything crucial?


texts: Printing an Alternating Pattern to the Console

texts:
For this assignment, you will create the pattern of a chess board that
  is 8 x 8.  Use X and O to represent the squares.

  Create the appropriate nested looping structure to output the characters in an 8 x 8 grid on the screen using Console.Write() or
  Console.WriteLine() as appropriate.
  Include a decision structure to ensure that alternate rows start with opposite characters as a real chess board alternates the colors
  among rows.

Simple enough, but my first version stuffed everything inside of Main, which I don't care for. So, I wrote a second version that nicely separated the concerns. The problem with that, in my eyes at least, is that it now does exactly twice the amount of work as my initial "naive" version. Does the benefit of separating concerns outweigh the performance hit on an already exponential algorithm?

Also, I don't like this snippet (that exists in both versions of the code).

if (row % 2 == 0)
{
  grid[row, col] = (col % 2 == 0) ? dark : light;
}
else
{
  grid[row, col] = (col % 2 == 0) ? light : dark;
}

This differs only in the order of the characters, but I'm too close to it at this point to see a better way to clean up the control logic. Advice on it would be appreciated.

Version 1:

public static void Main()
{
    const int gridSize = 8;
    const string dark = "x";
    const string light = "o";

    for (var row = 0; row < gridSize; row++)
    {
        for (var col = 0; col < gridSize; col++)
        {
            string output;
            if (row % 2 == 0)
            {
                output = (col % 2 == 0) ? dark : light;
            }
            else
            {
                output = (col % 2 == 0) ? light : dark;
            }

            Console.Write(output);
        }
        Console.WriteLine();
    }
}

Version 2: (ideone here)

public static void Main()
{
    var grid = CreateGrid(8, 'o', 'x');
    PrintGrid(grid);
}

private static void PrintGrid(char[,] grid)
{
    for (var row = 0; row < grid.GetLength(0); row++)
    {
        for (var col = 0; col < grid.GetLength(0); col++)
        {
            Console.Write(grid[row, col]);
        }
        Console.WriteLine();
    }
}

private static char[,] CreateGrid(int gridSize, char light, char dark)
{
    var grid = new char[gridSize, gridSize];

    for (var row = 0; row < gridSize; row++)
    {
        for (var col = 0; col < gridSize; col++)
        {
            if (row % 2 == 0)
            {
                grid[row, col] = (col % 2 == 0) ? dark : light;
            }
            else
            {
                grid[row, col] = (col % 2 == 0) ? light : dark;
            }
        }
    }

    return grid;
}


texts: Spring Boot should we always use interfaces even with one implementation

texts:
quick question. I'm using Spring Boot and I created e.g. this class
public interface ProductService {

    Page<Product> getPage(Pageable pageable);

}

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Override
    public Page<Product> getPage(String name, Pageable pageable) {
        return productRepository.findAll(pageable);
    }
}

And this interface has only one implementation. And what is better to use interface with one implementation and inject interface or just create a class without interface and inject class?


texts: OO design of Reverse Polish Notation Calculator

texts:
This solution focuses on the design of classes, not the actual push and pop stack part. I will include that part of the code as well. The current code has 2 operators (plus and minus).

  If we add another subclass under Token, is there a way that we don't need to check in processInput() what each operator is and perform the right calculation?

I didn't know how to answer that question. I looked into Java Reflection, but still don't know how reflection can help me in this case. Can anyone shed some light on how I can make this design better?

I want to allow people to add new operators, multiply and divide, and maybe make their own definition for special operators.

This application will take input string like "1 2 + 1 -" and output 2 because "1 2 + 1 -" is the reverse Polish notation for  (1+2)-1 = 2.

import java.util.*;
public class RPNCalculator {
    public static Stack<Integer> stack;
    //assume this string has integers and legal operators +,- and deliminated by space
    // an example would be "12 2 + 1 -"
    private static String input;
    static String operators ="+-";

    public RPNCalculator(String userInput){
        input = userInput;
        stack = new Stack<Integer>();
    }

    public void processInput(){
        StringTokenizer st = new StringTokenizer(input, " ");
        while (st.hasMoreTokens()){
            String str = st.nextToken();
            if(!operators.contains(str)){
                stack.push(Integer.parseInt(str));
            }
            else{
                if(str.equals("+")){
                    Plus obj = new Plus();
                    obj.calc();
                }
                else if(str.equals("-")){
                    Minus obj2 = new Minus();
                    obj2.calc();
                }
            }
        }
        System.out.println(stack.pop());
    }
}

public abstract class Token {
    abstract void calc();
}
public class Minus extends Token {

    @Override
    void calc() {
        int a = RPNCalculator.stack.pop();
        int b = RPNCalculator.stack.pop();
        RPNCalculator.stack.push(b-a);

    }

}

public class Plus extends Token {

    @Override
    void calc() {
        int a = RPNCalculator.stack.pop();
        int b = RPNCalculator.stack.pop();
        RPNCalculator.stack.push(a+b);
    }

}
public class RPNDriver {
       public static void main(String[] args) {
           System.out.println("starting calculator...");
           RPNCalculator rpn = new RPNCalculator("1 2 +");
           rpn.processInput();
       }
}


texts: performance test the code for finding time taken to fill the disk space

texts:
I have written this module that takes input of configuration of multiple lines with first item as available storage and remaining are the process at different rate using sys.stdin .

#! /usr/bin/python

""" this script calculates the time remaining for available storage to get filled up.
"""

import sys

def time_to_meltdown(proc_r, available_storage):
    """
    this functions caclulates the time it will take to full the available disk space
    by n number of proceses by the rate of 1 byte after every d(p_i) seconds.

    :param list proc_r: number of process with constant but different rate memmory consumption
    :param int available_storage: total amount of free storage available on the farm.

    :return: time in seconds taken by n process to fill up the storage
    :rtype: int
    """
    mem = 0 # Initial consumption
    timeTaken = 0
    while mem < available_storage:
        timeTaken += 1 # increament each second by 1
        mem = 0
        for v in proc_r:
            mem += timeTaken // v
    return timeTaken

def main():
    """ this function builds data from the input and pass it
        to function that calculate time it will take to for
        available storage to get filled.
    """
    input_data = sys.stdin.read()
    config_lines = input_data.split("\n")
    for line in config_lines:
        if line:
            data = [int(data) for data in line.split() if data]
            available_storage = data[0]
            pr_i = data[1:]
            print "{} processes will take {} seconds to fill storage".format(len(pr_i), time_to_meltdown(pr_i, available_storage))

if __name__ == "__main__":
    main()

Please review the code for optimal performance.

When I run this code:

        while mem < available_storage:
        timeTaken += 1 # increament each second by 1
        mem = 0
        for v in proc_r:
            mem += timeTaken // v
    return timeTaken

above lines take quite substantial amount of time for long list of processes.


texts: Query messages and 'bold' part of a message. Show one query at a time but get the next query in advance for better user experience

texts:
In this react component I'm trying to display one message on the screen at a time. This message has a 'bold' substring in it which should be accounted for. There's 2 endpoints here,

message to retrieve a message, and

bold which retrieves what is bold (with start and end keys to a substring) about the message passed in as a parameter

I tried to optimize for user experience by always having two messages available, so that when the user clicks 'next', there already is a message to display and no waiting time. These are currentMessage and nextMessage.
I used two useState hooks as I found looping inside of a useEffect hook while fetching to be somewhat complicated. Would still love to be able to do that.
Moreover, I have used two useEffects. The first is simply run once, to get the initial message, and the other is run when the page renders and then every time the user clicks 'next'. When a user clicks next, that's when the app swaps the current message for the one which was in the 'queue'
const MessageBox = () => {
  const [message, setCurrentMessage] = useState("");
  const [bold, setCurrentBold] = useState("");
  const [nextMessage, setNextMessage] = useState("");
  const [nextBold, setNextBold] = useState("");
  const [isGettingMessage, setIsGettingMessage] = useState(true);

  useEffect(() => {
    fetch(`https://myapi.com/message`)
      .then((res) => res.json())
      .then((res) => {
        if (res.data) {
          setCurrentMessage(res.data.message);
          getBold(res.data.message, setCurrentBold);
        } else {
          console.log("handle err");
        }
      });
  }, []);

  useEffect(() => {
    if (!isGettingMessage) return;
    fetch(`https://myapi.com/message`)
      .then((res) => res.json())
      .then((res) => {
        if (res.data) {
          setNextMessage(res.data.message);
          getBold(res.data.message, setNextBold);
        } else {
          console.log("handle err");
        }
      });
    setIsGettingMessage(false);
  }, [isGettingMessage]);

  const getBold = (message, boldSetter) => {
    if (!message) return;
    fetch(`https://myapi.com/bold`, {
      method: "POST",
      headers: { "Content-type": "application/json" },
      body: JSON.stringify({ content: message }),
    })
      .then((res) => res.json())
      .then((res) => {
        if (res?.data?.bold.length) {
          boldSetter(res.data.bold);
          return;
        } else if (res.error) {
          console.log("handle err");
        }
        boldSetter("");
      });
  };

  const formatMessageAndBold = () => {
    if (message && bold) {
      return boldMessage;
    } else if (message && !bold) {
      return {message};
    }
  };

  const boldMessage = useMemo(
    () => (

        {message.substring(0, bold.start)}
        {message.substring(bold.start, bold.end)}
        {message.substring(bold.end)}

    ),
    [message, bold.start, bold.end]
  );

  const messageAndBold = formatMessageAndBold();

  const onClick = () => {
    if (isGettingMessage) return;
    setIsGettingMessage(true);
    setCurrentMessage(nextMessage);
    setCurrentBold(nextBold);
  };

  return (

      {messageAndBold}
      <button isLoading={nextMessage === message || !message} onClick={onClick}>
        {message ? "Next Message" : "Loading..."}
      </button>

  );
};

export default MessageBox;
```


texts:
I had an exercise to create two methods for simple queue class, first to delete last element and second to delete element at k position. Particularly I'm not asking for better implementation. Is it good enough and elegant ? What I should change ? I'll post only mentioned methods, rest should be simple enough.

/**
 * Deletes node at position k.
 */
public void delete(int k) {
    if (k > N || isEmpty()) throw new NoSuchElementException("Cannot delete element at position: " + k);
    Node previous = first;
    int deleteIndex = 1;

    if(k == deleteIndex){               //special case for first element
        if(first.next == null)
            last = null;
        first = first.next;
        N--;
        return;
    }

    for (Node node = first; node != null; node = node.next, deleteIndex++) {
        if (k == deleteIndex) {
            previous.next = node.next;
            if (previous.next == null) last = previous; //if deleted element was the last one
            N--;
            return;
        }
        previous = node;
    }
}

/**
 * Deletes last node from the queue.
 */
public void removeLastNode() {
    if(isEmpty()) throw new NoSuchElementException("Cannot delete last element from queue");
    if (N == 1) {           //special case for only one element in queue
        first = null;
        last = null;
        N--;
        return;
    }

    Node previous = null;
    for (Node node = first; node != null; node = node.next) {
        if (node.next == null) {
            previous.next = null;
            last = previous;
            N--;
        }
        previous = node;
    }
}


texts:
I wrote HListSum, whose type parameter is an input HList. Its Out type member represents the sum of that HList.

trait HListSum[L <: HList] {
  type Out <: Nat
}
object HListSum {

  type Aux[L <: HList, O <: Nat] = HListSum[L] { type Out = O }

  def apply[L <: HList](implicit ev: HListSum[L]): Aux[L, ev.Out] = ev

  implicit def hListSumInductive[H <: Nat, L <: HList, T <: Nat](
    implicit rest: HListSum.Aux[L, T],
             all: Sum[H, T]): HListSum.Aux[H :: L, all.Out] = new HListSum[H :: L] {
    type Out = all.Out
  }

  implicit val hlistSumHNil: HListSum.Aux[HNil, _0] = new HListSum[HNil] {
    type Out = _0
  }
}

Testing Examples:

import net.HListSum
import shapeless._
import nat._

scala> HListSum[_1 :: _2 :: HNil]
res0: net.HListSum[shapeless.Succ[shapeless._0] :: shapeless.Succ[shapeless.Succ[shapeless._0]] :: shapeless.HNil]{type Out = shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless._0]]]} = net.HListSum$$anon$4@5c609308

scala> val three: res0.Out = _3
three: res0.Out = Succ()

scala> HListSum[_1 :: _2 :: _5 :: HNil]
res1: net.HListSum[shapeless.Succ[shapeless._0] :: shapeless.Succ[shapeless.Succ[shapeless._0]] :: shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless._0]]]]] :: shapeless.HNil]{type Out = shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless._0]]]]]]]]} = net.HListSum$$anon$4@79e8b4d0

scala> val eight: res1.Out = _8
eight: res1.Out = Succ()

scala> val error: res1.Out = _4
<console>:19: error: type mismatch;
 found   : shapeless.nat._4
    (which expands to)  shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless._0]]]]
 required: res1.Out
    (which expands to)  shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless.Succ[shapeless._0]]]]]]]]
       val error: res1.Out = _4
                             ^

I'm not sure if my approach is actually inductive since I'm referencing all: Sum[H, T].

Please critique my HListSum for being idiomatic shapeless.


texts: Uploading series of large files to API via Node

texts:
I wrote a node script to traverse a folder of hour-long mp3s and upload them to Mixcloud via their API. It works, but I suspect it's fairly inefficient - the computer it's going to run on at our radio station is an old white Macbook. Would appreciate any insight for how to improve it.

  const restler = require('restler');
  const fs = require('fs');
  const readDir = require('readdir');
  const powerOff = require('power-off');

  const options = {
    folder: 'files',
    completefolder: 'complete',
    accesstoken: 'xxxxxxxxx'
  }

  // shut down computer
  const shutDown = () => {powerOff((err, stderr, stdout) => {
        if(!err && !stderr) {
            console.log(stdout);
        }
    })
  };

  // uploadFile uploads file with restler to mixcloud, if api returns rate limiting object, try again in x seconds
  const uploadFile = (folder, filename) => {
    const filepath = `./${folder}/${filename}`
    fs.stat(`./${folder}/${filename}`, function(err, stats) {
        const size = stats.size;
        restler.post(`https://api.mixcloud.com/upload/?access_token=${options.accesstoken}`, {
            multipart: true,
            data: {
                "mp3": restler.file(`./${folder}/${filename}`, null, size, null, 'audio/mpeg'),
                "name": filename,
                // "unlisted": true

                // more data can be added here depending on changes in workflow, automate images etc
            }
        }).on("complete", function(data) {
            const returned = JSON.parse(data);
            if (returned.error) {
              if (returned.error.type == "RateLimitException") {
                // try again in x seconds
                console.log(`uploading too fast, retrying upload of ${filename}after ${returned.error.retry_after} seconds`);
                setTimeout(() => uploadFile(folder, filename), returned.error.retry_after*1000);
              }
              else {
                console.log('non-rate-limiting error');
                console.log(returned);
              }
            }
            else {
              console.log('Success!');
              console.log(returned);
              // move uploaded files into completed folder
              fs.rename(`./${folder}/${filename}`, `./${options.completefolder}/${filename}`, (err) => {
                if (err) {
                  console.log(err)
                }
                else {
                  counter += 1;
                  console.log(counter);
                  if (counter === files.length) {
                    console.log('done');
                    shutDown();
                  }
                }
              })
            }
        });
    });
  };

  // get all mp3s and upload all of them
  const files = readDir.readSync(`./${options.folder}`, ['**.mp3'] );
  let counter = 0;
  for (var i = 0; i < files.length; i++) {
    uploadFile(options.folder, files[i])
  };


texts: Hello World Node application with error handling

texts:
I wrote this simple server in node. Actually my goal is to better understand exception handling best practices in Node.
So my question is more specific.
Is this code bullet proof to exceptions? Are all errors or exceptions propertly handled?
How would you make it more safe? Where would you put try/catch?
Is there a place where try/catch is missing?

var http = require('http');

// Register handler for incoming requests.
var server = http.createServer(function(request, response) {

    var body = "";

    request.setEncoding("utf8");

    request.on('error', function(err) {
        console.error(err.stack);
    });

    // Listen for incoming data in the request.
    request.on('data', function(chunk) {
        body += chunk
    });

    // Has all data arrived?
    request.on('end', function() {

        // We should send response only when the whole request has been received, isn't it?
        response.writeHead(200, {
            'Content-Type': 'text/html',
            'X-Powered-By': 'bacon'
        });

        response.on('error', function(err) {
            console.error(err);
        });

        response.write('');
        response.write('');
        response.write('
Hello, World!
');
        response.write('
');
        response.write(body);
        response.write('
');
        response.write('');
        response.write('');
        response.end();

    });

});

// Listen on some port
server.listen(8085);


texts: Algorithm to park cars with minimal moves (2nd version)

texts:
I'm working on a car move problem. Suppose we have origin parking position for each car, [-1,1,2,3,7,6,4,5] (which means first position is empty, car with ID 1 parked at 2nd position, car with ID 2 parked at 3rd position), we want to find the minimal move to re-park car as specific desired positions. For example specific desired position [4,6,5,1,7,3,2,-1] means car with ID 4 parked at first position, car with ID 6 parked as 2nd position, etc. -1 means empty parking lot to utilize.

My 2nd version of code is based on the great thought and implementation from Joe (Algorithm to park cars with minimal moves), since it is new code, I make a new post other than changing the original post.

Here is my code, my major idea for what I think Joe's code needs some change,

Each time we move car a from position x to position y, we just make a move, we are not swap, which is first point I change Joe's code. I change (move) position of car a to position y and then update position y to empty;
Based on logic of 1st item, I think we should check for output[index] != empty, other than check for output[index] != input[index] to end of internal while loop.

My code mainly based on Joe's code,

def car_move_v2(input, output, empty=0):
    # print move from position a to positive b
    def print_move(a, b):
        input[b] = input[a]
        input[a] = empty
        position[input[a]] = a
        position[input[b]] = b
        print('{0}, {1} -> {2}'.format(input[b], a, b))
    position = {
        pos: index
        for index, pos in enumerate(input)
    }
    for start in range(len(input)):
        if input[start] == output[start]:
            continue
        if input[start] != empty:
            print_move(start, position[empty])
        index = start
        while output[index] != empty:
            prev_index = index
            index = position[output[prev_index]]
            print_move(index, prev_index)
    return

if __name__ == "__main__":
    car_move_v2([-1,1,2,3,7,6,4,5], [4,6,5,1,7,3,2,-1],-1)

Output,

4, 6 -> 0
2, 2 -> 6
5, 7 -> 2
1, 1 -> 7
6, 5 -> 1
3, 3 -> 5
1, 7 -> 3


texts: Login system using bcrypt and MySQL, to be used for any future projects

texts:
Main function will ask what the user wants to do. LoginSystem class will handle the sign up and login process as well with the checking if password is right. passwordHashing will use bcrpyt to salt and hash the password.
import bcrypt
from loginDbMySQL import insert, logging_in

def main():

    login_instance = LoginSystem()
    check = True

    while check == True:
        value = input("1-Login, 2-Sign-up, 3-Exit\n")
        if value == "1":
            login_instance.login()
            check = True
        elif value == "2":
            login_instance.sign_up()
            check = True
        elif value == "3":
            check = False

class LoginSystem():

    def sign_up(self):
        username = input("Enter a username: ")
        password = input("Enter a password: ")

        password_hash = self.passwordHashing(password)
        insert(username, password_hash)

    def login(self):
        username = input("Enter a username: ")
        password = input("Enter a password: ")

        password_hash = logging_in(username)
        self.comparePassword(password, password_hash)

    def passwordHashing(self, password):

        password_bytes = password.encode('utf8')

        salt = bcrypt.gensalt(14)

        password_hash_byte = bcrypt.hashpw(password_bytes, salt)

        password_hash_str = password_hash_byte.decode()

        return password_hash_str

    def comparePassword(self,password,password_hash):

        if bcrypt.checkpw(password.encode('utf8'), password_hash.encode('utf8')):
            print("Welcome")
        else:
            print("Incorrect Information")

if __name__ == "__main__":
    main()

loginDbMySQL handles the database insertion, checking, and query's
import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="*******",
    database="*******"
)

mycursor = mydb.cursor()

def insert(username,password_hash):

    mycursor = mydb.cursor(buffered=True)
    select_query = "SELECT usernames FROM login_table WHERE usernames= %s"
    mycursor.execute(select_query, (username,))
    check = mycursor.fetchone()

    if check == None:
        mycursor.execute("INSERT INTO login_table (usernames, password_hashs) VALUES (%s,%s)", (username, password_hash))
        mydb.commit()
        print("Account created!")

    else:
        print("Account already exist.")

def logging_in(username):

    mycursor = mydb.cursor(buffered=True)
    select_query = "SELECT * FROM login_table WHERE usernames= %s"
    mycursor.execute(select_query, (username,))
    check = mycursor.fetchone()

    if check == None:
        print("Incorrect information.")
    else:
        return check[1]


texts: Convert MS SQL datetime to Oracle varchar(32) interval

texts:
I have a query against an MS SQL database that takes the resulting dataset and stores it in an Oracle database table which then gets joined to another Oracle table using the column LABEL_YYYY_MM_DD_HH24_MI varchar(32).  I have converted the MS SQL datetime column q.InTimeStart as per below.

Is there a more efficient way of writing this line which takes datetime and finds beginning of 15min interval and stores as varchar(32)?

left(convert(varchar(32),convert(smalldatetime,floor(cast(q.InTimeStart as float)\*(24/.25))/(24/.25)),120),
len(convert(varchar(32),convert(smalldatetime,floor(cast(q.InTimeStart as float)*(24/.25))/(24/.25)),120)) -3) as LABEL_YYYY_MM_DD_HH24_MI,


texts:
I have written this code which adds a querystring to a URL:

exports.addQueryString = function(url, queryString) {
  var isQuestionMarkPresent = url && url.indexOf('?') !== -1,
    separator = '';

  if (queryString) {
    separator = isQuestionMarkPresent ? '&' : '?';
    url += separator + queryString;
  }

  return url;
};

Is there any way I can write this better?

Usage:

addQueryString('http://example.com', 'q=1&val=3&user=me');


texts:
I'm creating an app where the login page doesn't have the header/footer bars that the pages, after being logged in, would have.  I've created an example that works, but I'm unsure if I am using the prop/component inheritance or patterns correctly.

I feel like there is a lot of nesting going on here, but I'm unsure if that's the proper thing to experience or if I'm creating a mess for myself.

Here's my main Router:

export default (
  <Router history={hashHistory}>
    <Route path="/" component={App}>

      <Route path="login" component={Login} />

      <Route path="*" component={NotFoundPage} />

    </Route>
  </Router>
);

Here's my main app trigger that initializes and renders everything:

class App extends React.Component {

  render() {
    return (

        {this.props.children}

    );
  }

}

export default App;

Then, I created a Layout component to serve either a version with or without the header and footer:

class Layout extends React.Component {

  constructor(props) {
    super(props);
  }

  renderPageLayout() {
    if(this.props.type == 'wrap') {
        return(

                {this.props.children}

          );
    } else {
        return(

            {this.props.children}

          );

    }
  }

  render() {
    return(

        { this.renderPageLayout() }

      );
  }

}

export default Layout;

And my login page should not have a header/footer on it, so it is as follows:

class Login extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <Layout type="no-wrap">

        Login

      </Layout>
    );
  }

}

export default Login;

I'm having trouble finding examples of similar things that are on a basic level and don't contain a bunch of ReactJS things that I haven't yet learned.


texts:
In order to convert a code such as:

Company company = new Company();
if(currentToken.equals("employee_list")) {
   company.setEmployees((ArrayList<Employee> parseEmployees(reader));
}
else if(currentToken.equals("contractor_list")) {
   company.setContractors((ArrayList<Contractor> parseContractors(reader));
}
else if(currentToken.equals("legal_name")) {
   company.setLegalName((String)reader.nextString());
}
else if(currentToken.equals("profit")) {
   company.setLegalName(Double.parseDouble((String)reader.nextString()));
} ...etc

I.e long list of if/else reading from a stream and populating the object I did the following:

public interface CustomSetter<T> {
  void setToObject(T o, Reader r);
}

HashMap<String, CustomSetter> setters = new HashMap<>();
setters.put("employee_list", new CustomSetter<Company>() {
     public void setObject(Company company, Reader reader) {
        company.setEmployees((ArrayList<Employee> parseEmployees(reader));
     }
 });

setters.put("contractor_list", new CustomSetter<Company>() {
     public void setObject(Company company, Reader reader) {
        company.setContractors((ArrayList<Contractor> parseContractors(reader));
     }
 });

etc.
Effectively doing:

setters.get(currentToken).setObject(company, reader);

So now I have all these initialized in my hashmap.
What do you think of this approach? Can it be improved?


texts: Updating only certain fields on a database row

texts:
I have data that I want to insert in a database.  Sometime a piece of data is already in the database, so I just want to update the fields that changed.

For example, if I insert these rows one after the other:

id | field1 | field2 | field3
1  | foo    | NULL   | bar
1  | baz    | hello  | NULL

I want to end up with:

id | field1 | field2 | field3
1  | baz    | hello  | bar

I use this query:

INSERT INTO `device` (`device_id`, `model`, `manufacturer`, `version`, `vendor_id`, `osd_name`)
VALUES (....)
ON DUPLICATE KEY UPDATE `version` = IFNULL(VALUES(`version`), `version`), `vendor_id` = IFNULL(VALUES(`vendor_id`), `vendor_id`), `osd_name` = IFNULL(VALUES(`osd_name`), `osd_name`)

Note that not all fields have to be updated. Is this the best way to do it?


texts:
I wrote this code to read from a CSV text file (containing data such as 12,3,568,48,3,8 with no more than 3 digits to each number). It stores the numbers as char arrays in the vector values. However, this does seem like a clumsy way of doing this with resizing the vector and copying the chars. Is there a neater/more succinct way of doing this?

#include <iostream>
#include <fstream>
#include <assert.h>
#include <vector>

int main() {
    using namespace std;
    ifstream in;
    in.open("Data.txt");
    assert(in.is_open());
    vector<char*> values;
    const int MAXSIZE = 4;
    char thisVal[MAXSIZE];
    while(in.getline(thisVal,MAXSIZE,',')) {
        values.resize(values.size() + 1);
        values.back() = new char[MAXSIZE];
        strcpy(values.back(), thisVal);
    }
    in.close();
    for (char* cp: values) cout<<*cp<<endl;
    return 0;
}


texts: Readability vs. maintainability: nested functions

texts:
What are the pros and cons of each option, considering long-term implications (increasing the number of functions / parameters, other developers taking over, etc.)?
Option 1: removes the need to pass foo and bar to each method, but will create nested functions that are hard to follow.
const myFunction = ({foo, bar}) => {
  const results = []

  const function1 = () => {
    return foo + bar;
  }

  const function2 = () => {
    return foo * bar;
  }

  const res1 = function1();
  const res2 = function2();

  results.push(res1, res2);
}

Option 2: you pass the parameters to each function, but remove the nesting, which in my opinion makes it more readable.
const function1 = ({foo, bar}) => {
  return foo + bar;
}

const function2 = ({foo, bar}) => {
  return foo * bar;
}

const myFunction = ({foo, bar}) => {
  const results = []

  const res1 = function1({foo, bar});
  const res2 = function2({foo, bar});

  results.push(res1, res2);
}

I would prefer to know how to improve my functional approaches here. Thank you!


texts:
I'm working on a parsing engine as part of a personal project, and I'd like to expose certain .NET APIs to the parsed environment. I put together a very simple tagged union that allowed me to nest types, and put together a few functions that built up a tree of namespaces. Before going further, I decided I needed to refine the types I was using, and came up with this:

type Node =
    | Namespace of string * Node list

    | Class of string * Node list * System.Type
    | Interface of string * Node list * System.Type
    | Structure of string * Node list * System.Type
    | Enumeration of string * (string * Base.AnyInteger) list * System.Type

    | Property of string * System.Reflection.PropertyInfo
    | Field of string * System.Reflection.FieldInfo
    | Event of string * System.Reflection.EventInfo

    | Constructor of System.Reflection.ConstructorInfo
    | Function of string * System.Reflection.MethodInfo
    | Subroutine of string * System.Reflection.MethodInfo

Base.AnyInteger is another tagged union elsewhere that has cases for every .NET integer type except bigint. My expectation with these "Nodes" is that each one (except constructors) will contain their name in the string, a Node list containing any child nodes, and a reference to their System.Type or System.Reflection.___Info to provide additional information when needed. Last, I added the extra empty lines to help mentally align each level of nodes.

After defining a list of constraints that would have to be managed "in logic", I remembered that I'm not working with VB or C#, and that F#'s type system is better than what I'm used to. After about a half hour I came up with this:

type Lvl1 = Namespace of string * (Choice<Lvl1, Lvl2>) list

and Lvl2 =
    | Class of string * Choice<Lvl2, Lvl3, Constructor> list * System.Type
    | Structure of string * Choice<Lvl2, Lvl3, Constructor> list * System.Type
    | Interface of string * Choice<Lvl2, Lvl3> list * System.Type
    | Enumeration of string * (string * Base.AnyInteger) list * System.Type

and Lvl3 =
    | Property of string * System.Reflection.PropertyInfo
    | Field of string * System.Reflection.FieldInfo
    | Event of string * System.Reflection.EventInfo
    | Function of string * System.Reflection.MethodInfo
    | Subroutine of string * System.Reflection.MethodInfo

and Constructor = System.Reflection.ConstructorInfo

This new set of types correctly describes what each node can contain, using the type system to enforce everything rather than just implying how the levels are arranged with empty lines. Now nodes from Lvl1 can contain children from Lvl1 or Lvl2, nodes from Lvl2 can contain children from Lvl2 or Lvl3 (Classes and Structures may also contain Constructors), and nodes at Lvl3 cannot contain any children.

Now that I've used the type system to make sure I can't accidentally add a Namespace node inside a Class node, are there any other obvious changes I should be making here? I'll also admit I was originally using list references for each list of child nodes, because it made it easier to reason about in an imperative way; I've since revisited my code and have removed ref and started making use of map/fold/etc.


texts:
I don't intend on implementing this into an application yet as I'm going to test it first.  As such, it doesn't do much beyond rolling.  It also overloads some "typical" operators such as == and !=.

Most of all, I'm still very unsure about my random number generator.  I've read about <random>'s std::uniform_int_distribution and that it has advantages over std::rand, but I'm also not sure if I've put it in a good place.  Client code will be forced to use my seed if my source file is used, but my header file is free from this.

What could be said about my RNG use?  Anything else that could be done?

Dice.h

#ifndef DICE_H
#define DICE_H

#include <ostream>

class Dice
{
private:
    int topValue; // same default type as std::uniform_int_distribution<>

public:
    void roll();
    int value() const { return topValue; }
};

// the C++ FAQ on SO suggests that these overloads are best as non-members

inline bool operator==(Dice const& lhs, Dice const& rhs) { return lhs.value() == rhs.value(); }
inline bool operator!=(Dice const& lhs, Dice const& rhs) { return !operator==(lhs, rhs); }
inline std::ostream& operator<<(std::ostream& out, Dice const& obj) { return out << obj.value(); }

#endif

Dice.cpp

#include "Dice.h"
#include <random>

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 6);

void Dice::roll()
{
    topValue = dis(gen);
}


texts: Prime factorization of a natural number greater than 1

texts:
I want to write a program in Java that return a prime factorization of any natural number greater than one.

After spending some time coding and debugging, the program runs fine. Since I am new to Java and programming in general, I don't know how bad my code style and class/method design are. Hence, I am here asking for some tips/advice on what I did wrong and what I could do to improve.

public class FTA_Prime_Factorization {

    /**
     * A method to ask for a integer input from user.
     *
     * @return num: int
     */
    protected static int user_input() {
        int num;
        Scanner inp;
        while (true) {
            inp = new Scanner(System.in);
            System.out.print("Please enter a greater-than-1 positive integer: #");
            if (inp.hasNextInt() && (num = inp.nextInt())>1)
                break;
            System.out.println("Please enter a integer greater than 1!!!");

        }
        return num;
    }

    /**
     * To check whether the parameter is a prime number.
     *
     * @param x: int
     * @return counts == 2: boolean
     */
    private static boolean checkPrime (int x) {
        int counts = 0;
        for (int i = x; i > 0; i--) {
            if (x % i == 0) {
                counts++;
            }
        }
        return counts == 2;
    }

    /**
     * To create an Arraylist of prime number that is less than 10000.
     *
     * @return primeList: Arraylist<Integer>
     */
    private static ArrayList<Integer> primes() {
        ArrayList<Integer> primeList = new ArrayList<>();
        for (int x = 1; x < 10000; x++){
            if (checkPrime(x))
                primeList.add(x);
        }
        return primeList;
    }

    /**
     * To create an Arraylist of prime factorization of the parameter.
     *
     * @param x: int
     * @return primeFactors: Arrarylist<Integer>
     */
    private static ArrayList<Integer> array(int x) {
        ArrayList<Integer> primeFactors = new ArrayList<>();
        ArrayList<Integer> listOfPrime = primes();
        for (int i : listOfPrime) {
            for (int j = x; j % i== 0; j /= i)
                primeFactors.add(i);
        }
        return primeFactors;
    }

    public static void main(String [] args) {
        ArrayList<Integer> temp = array(user_input());
        HashMap<Integer, Integer> counter = new HashMap<>();
        String primeFactors = "";
        for (int element : temp) {
            if (counter.get(element) != null){
                counter.put(element, counter.get(element)+1);
            }else{
                counter.put(element, 1);
            }
        }
        System.out.print("Canonical Form Prime factorization of x = ");
        for (int key : counter.keySet()) {
            primeFactors += counter.get(key) == 1 ? "(prime)"+key + " x " : "(prime)"+key+"^"+counter.get(key) + " x ";
        }
        System.out.println(primeFactors.substring(0, primeFactors.length() - 3));
    }
}

An example output (input = 3612):

Canonical Form Prime factorization of x = (prime)2^2 x (prime)3 x (prime)7 x (prime)43


texts:
I've been trying all night to get my fizzbuzz to use below 20 MB of RAM but I can't seem to get it much smaller than this.

# Sample code to read test cases
args <- commandArgs(trailingOnly=TRUE)
test.cases <- strsplit(readLines(args[[1]], warn=FALSE), '\n')
args <- NULL
for (test in test.cases) {
    if (length(test) > 0) {
        # ignore test if it is an empty line
        # 'test' represents the test case, do something with it
        test <- as.numeric(unlist(strsplit(test, " ")))
        x <- 0
        y <- 0
        for(i in 1: test[3]) {
            if(i != 1) cat(" ")
            flag <- TRUE
            out <- i
            x <- x + 1
            y <- y + 1
            if( x == test[1] ) {
                cat("F")
                x <- 0
                flag <- FALSE
            }
            if( y == test[2] ) {
                cat("B")
                y <- 0
                flag <- FALSE
            }
            if(flag) cat(out)
        }

        cat("\n")
    }
}


texts: Check database for item and create it if it doesn't exist

texts:
Is there a more efficient approach to this code?

// save associated tag
let saveTag question =

    if question.Tag = null then
        ()
        else
            let tagCount =
                query{
                    for row in db.Tags_Tags_Tags do
                    where (row.Tag = question.Tag)
                    select row
                    count
                }

            if tagCount > 0 then
                ()
                else
                    let tagToSave =
                        dbSchema.ServiceTypes.Tags_Tags_Tags(
                            Tag = question.Tag
                        )
                    insertRowIn db.Tags_Tags_Tags tagToSave
                    saveToDb()


texts: Return the amount of Quarters, Dimes, Nickels, and Pennies that you would get from the total amount of change

texts:
I made windows form in C# that takes the amount of change given, 1-99 and tells you the amount of quarters, dimes, nickels, and pennies you would get back. Can I improve the math in any way? It takes the total change and subtracts the value of the largest coin value that applies till the change becomes equal to zero.

        //set the variables
        int quarters = 0;
        int dimes = 0;
        int nickels = 0;
        int pennies = 0;
        int change = Convert.ToInt32(txtChange.Text);

        //logic
        do
        {
            if (change >= 25 && change <= 99)
            {
                change = change - 25;
                quarters++;
            }
            else if (change <= 24 && change > 9)
            {
                change = change - 10;
                dimes++;
            }
            else if (change == 5)
            {
                change = change - 5;
                nickels++;
            }
            else if (change <=4)
            {
                change = change - 1;
                pennies++;
            }

            txtQuarters.Text = quarters.ToString("n");
            txtDimes.Text = dimes.ToString("n");
            txtNickels.Text = nickels.ToString("n");
            txtPennies.Text = pennies.ToString("n");

        } while (change > 0);


texts:
Problem: convert this array of hashes:

cars = [
  { :model=>"Ferrari 458", :speed=>320 },
  { :model=>"Maserati MC12", :speed=>330 },
  { :model=>"Ferrari Enzo", :speed=>350 },
  { :model=>"Lamborghini Huracan", :speed=>325 }
]

to this data structure:

{
  above_320: [
    { :model=>"Maserati MC12", :speed=>330 },
    { :model=>"Lamborghini Huracan", :speed=>325 },
    { :model=>"Ferrari Enzo", :speed=>350 }
  ],
  the_rest: [
    { :model=>"Ferrari 458", :speed=>320 }
  ]
}

My solution:

cars.partition {|car| car[:speed] > 320}
.map.with_index {|cars,i| [ i == 0 ? :above_320 : :the_rest, cars ]}
.to_h

Any feedback would be greatly appreciated!


texts:
I have an implementation of Producer-Consumer multi-threaded interaction. It works, but I feel that during the execution wait states happen too often between Consumer thread and Producer.  In my case, Consumer accesses a queue at random intervals and takes data from it.  Now, the producer thread runs during the whole process life time.  The producer thread works as caching machine.  It checks in a loop if the size of queue is smaller than the maximum cache size allowed, and if that's the case, it keeps pushing new data into that cache.

My concern is that when the consumer tries to access the queue, the last is still locked by the producer thread and the consumer should wait.  I would like to get a feedback if what I am doing is optimal in terms of interaction flow between producer and consumer.

   //Called by consumer(main thead) to retrieve data from cache
 uint8_t* Worker::GetFrame() {

  boost::unique_lock<boost::mutex> lk(_frameCacheMutex);
  //If the cache is empty:
  while (0 == _frames_cache.size()) {
           //tell Producer to push data into cache
         _fill_cache_wait_cond.notify_one();
          //wait for the data to arrive(will be signaled by worker thread)
         _get_frame_wait_cond.wait(lk);

  }
  uint8_t * fr = _frames_cache.front();
  _frames_cache.pop();
  // notify worker thread to continue caching
  _fill_cache_wait_cond.notify_one();

  return fr;
}

Producer thread:

  void Worker::operator () () {
   //Some init here..
    while (isRunning) {
       boost::unique_lock<boost::mutex> lk(_frameCacheMutex);

       /// Here create the data for cache...

       _frames_cache.push(data);

       /// Notify waiting main thread to take data
       _get_frame_wait_cond.notify_one();

       /// If the cache is full ,wait
       while (_frames_cache.size() == cacheMaxSize ){

             _fill_cache_wait_cond.wait(lk);

       }

    }

}


texts: jQuery plugin authoring: Vertical Center example

texts:
I am fairly new at writing jQuery plugins. Moreover, I am a huge fan of best practice.

I have written a plugin which centers an element inside its parent. I would love some feedback on how I could have written it better.

(function( $ ){

  $.fn.verticalCenter = function(options) {

    var settings = $.extend({
      min: 0, // Minimum width of the viewport for the centering to take effect
      max: 10000 // Maximum width of the viewport
    }, options);

    var center_element = function(element, parent){
      var elementHeight = element.height();
      parent.css({
        position:'relative'
      });
      element.css({
        position: 'absolute',
        top: "50%",
        marginTop:-elementHeight/2
      });
    }

    var remove_style = function(element, parent){
      parent.css({ position:'' });
      element.css({ position: '', top: '', marginTop: '' });
    }

    var determine_action = function(element, parent){

      $(window).on('load resize orientationchange', function() {

        var windowWidth = window.innerWidth

        if (windowWidth > settings.min && windowWidth < settings.max) {
          center_element(element, parent);
        }
        else {
          remove_style(element, parent);
        }

      });

    }

    return this.each(function(){

      var $elementToCenter = $(this);
      var $parent = $elementToCenter.parent();

      determine_action($elementToCenter, $parent);

    });

  };

})( jQuery );

The plugin is supposed to be responsive, and it allows the user to pass in viewport min and max values. These values determine if the centering should occur.


texts:
I'm a .NET (C#/VB) developer who knows a little C and happens to need to write a native C++ Windows DLL.

Please have a look at the following code and tell me if the string operations are idiomatic C++:

int dpi;

void __stdcall FooEntryPoint(ENTRY_INFO* inEntryInfo)
{
    dpi = *reinterpret_cast<int *>(inEntryInfo->UserData);

    OutputDebugStringW((std::wstring(L"User Data supplied: ") + std::to_wstring(dpi)).c_str());

    FARPROC address = GetFooAddress();
    if (address == NULL)
    {
        OutputDebugStringW(L"Foo address not found.\n");
        return;
    }

    NTSTATUS result = FrobnicateFoo(address);
    if (FAILED(result))
    {
        OutputDebugStringW((std::wstring(L"Failed to frobnicate foo: ") + RtlGetLastErrorString() + L"\n").c_str());
    }
}

My thoughts on the matter:

As a .NET developer, I'm used to "Unicode is default unless there's a very good reason against it", and, thus, I just use L"..." string literals and ...W API methods without giving it further thought.
(std::wstring(...) + ... + ...).c_str() seems to be the simplest way in C++ to do string concatenations of wchar arrays (denoted as ...) without having to worry about memory allocations. I could use wostringstream, but it would just make the code more complicated.
I know that failing silently is bad practice, but the signature of FooEntryPoint is part of the interface contract I'm given, so this is "by design".

Does that make sense or am I violating any good C++ practices here?

Note: The code does not need to be portable.


texts:
These two methods do very similar things. Is it possible to condense these somehow?  This is using the Entity Framework.

public void ExportSiteData (FLEX_INV_EXP_SITE siteData)
{
    var uniqueSite = from e in _context.FLEX_INV_EXP_SITE
                     where e.SITE_ID == siteData.SITE_ID
                     select e;
    var count = uniqueSite.Count();

    if (count != 0) return;
    _context.FLEX_INV_EXP_SITE.AddObject(siteData);
    _context.SaveChanges();
}

public void ExportAddressData (FLEX_INV_EXP_ADDRESS addressData)
{
    var uniqueSite = from e in _context.FLEX_INV_EXP_ADDRESS
                     where e.SITE_ID == addressData.SITE_ID
                     select e;
    var count = uniqueSite.Count();

    if (count != 0) return;
    _context.FLEX_INV_EXP_ADDRESS.AddObject(addressData);
    _context.SaveChanges();
}


texts:
I reviewed this question that in my opinion uses a not so pretty batch-save so I tried improve it and this is what I came up with.

In this more generic solution that allows to reuse it I wanted to implement the using statement instead of manually disposing and recreating the context.

It is an extension that you can use on a collection of entities. It requires the size of the batch and a factory method for the context. The last parameter is for reporting progress.

Unlike the original solution this one works with double so it is able to report progress for collection that are smaller then 100 items.

Internally it uses two lambdas: one for checking if the batch should be saved and the other one for progress reporting. The context is wrapped with a using statement.

static class EnumerableExtensions
{
    public static void BatchSave<T, TContext>(
        this IList<T> items,
        int batchSize,
        Func<TContext> createContext,
        IProgress<double> progress
    )
        where T : class
        where TContext : DbContext
    {
        var count = 0;
        var lastPercentage = 0d;

        var nextBatch = new Func<bool>(() => ++count % batchSize == 0);

        var reportProgress = new Action(() =>
        {
            var percentage = Math.Round((double)count / (double)items.Count * 100d, 1);
            if (percentage > lastPercentage)
            {
                progress.Report(percentage);
                lastPercentage = percentage;
            }
        });

        var enumerator = items.GetEnumerator();
        while (enumerator.MoveNext())
        {
            using (var context = createContext())
            {
                context.Configuration.AutoDetectChangesEnabled = false;
                context.Configuration.ValidateOnSaveEnabled = false;

                do
                {
                    //context.Set<T>().Add(enumerator.Current);
                    Console.WriteLine("Add " + enumerator.Current);
                    reportProgress();
                } while (!nextBatch() && enumerator.MoveNext());
                //context.SaveChanges();
                Console.WriteLine("Save batch = " + count);
            }
        }
        reportProgress();
    }
}

class TestContext : DbContext { }

I needed to comment the two entity framework lines out so that it doesn't crash with the TestContext.

Example usage:

void Main()
{
    // convert items to string to satisfy the class constraint
    var items = Enumerable.Range(0, 23).Select(x => x.ToString()).ToArray();

    var batchSize = 10;

    var progress = new Progress<double>(percent => Console.WriteLine($"Progress {percent}"));
    items.BatchSave(batchSize, () => new TestContext(), progress);
}

Output:

Add 0
Add 1
Add 2
Add 3
Add 4
Add 5
Add 6
Add 7
Add 8
Add 9
Save batch = 10
Add 10
Progress 4,3
Add 11
Add 12
Add 13
Add 14
Add 15
Add 16
Add 17
Add 18
Add 19
Save batch = 20
Add 20
Add 21
Add 22
Save batch = 23
Progress 13
Progress 17,4
Progress 21,7
Progress 26,1
Progress 30,4
Progress 34,8
Progress 39,1
Progress 43,5
Progress 47,8
Progress 52,2
Progress 56,5
Progress 60,9
Progress 65,2
Progress 69,6
Progress 73,9
Progress 78,3
Progress 8,7
Progress 82,6
Progress 91,3
Progress 95,7
Progress 100
Progress 87


texts: JavaScript parameters - best practices for settings object/callback

texts:
I have the following function which runs as expected and is defined in the window object:

function myFunction(url, timeout, type, sc, ec) {
    return $.ajax({
        url: url,
        timeout: timeout,
        type: type,
        success: function (data) {
            if (typeof sc === 'function') {
                sc(data);
            }
        },
        error: function (jqXhr) {
            if (typeof ec === 'function') {
                ec(jqXhr);
            }
        }
    });
}

Which works as expected.

However, I am now expanding this function to be a whole lot more complex. As a result to this, I was wondering whether I could get some style guides (I'm a bit OCD when it comes to things like this in JS).

Additional features I am adding are as follows:

showLoader - the ability to show a modal loader
loaderMessage - the message displayed if showloader === true
storeAs - how to store the downloaded data

The new function now looks as follows:

(function (window, document, $, undefined) {
    function myFunction(settings, sc, ec) {
        var options = $.extend({
            showLoader: false,
            loaderMessage: 'Loading...',
            storeAs: null,
            timeout: 60000,
            url: 'http://www.google.co.uk',
            type: 'GET',
            success: function (data) {
                if (options.storeAs) {
                    localStorage.setItem(options.storeAs, JSON.stringify(data));
                }

                if (typeof sc === 'function') {
                    sc(data);
                }
            },
            error: function (jqXhr) {
                if (typeof ec === 'function') {
                    ec(jqXhr);
                }
            }
        }, settings);

        if (options.showLoader) {
            showLoader(options.loaderMessage); // external function to show loader
        }

        return $.ajax(settings);
    }

    window.app = {
        comms: {
            ajax: function (options, sc, ec) {
                return myFunction(options, sc, ec);
            }
        }
    };
}(this, this.document, jQuery));

Anonymous function

I like to now define all my code within anonymous functions since it frees up the global name space.

However, I have two questions:

Is it recommended/do I need to make use of the JavaScript new keyword? Is there any advantage to doing so?
If so, then how would I go about using it? I have got to grips with the majority of the language, just not the new constructor/keyword?

Parameters

My second change will be to address the parameters - five parameters in JavaScript is quite readable. However, any more isn't.

I am thinking of using a settings object as seen above:

Couple of questions surrounding this however:

Is it wise to use just one options object, as I am already doing here? $.ajax receives this settings object, but my settings object contains not just jQuery.ajax settings, but function settings - obviously jQuery will ignore these since it will use just the necessary options, but is there any reason to avoid this?
I could combine the success callback, and error callback into the options object but this looks quite messy. Is it better to provide the callbacks as separate parameters or move those into the options callback too?

What is the difference between:

var options = $.extend({}, {
    showLoader: false,
    loaderMessage: 'Loading...',
    storeAs: null
}, settings);

And:

var options = $.extend({
    showLoader: false,
    loaderMessage: 'Loading...',
    storeAs: null
}, settings);

Is there anything else I should be doing which I am missing, which is generally recommended in JavaScript?


texts: Last three values sfdc trigger functionalty

texts:
Please review the following salesforce trigger code

trigger BrandTrigger on Brand__c (before update) {
    for(Brand__c brand: Trigger.new){
        Brand__c oldBrand = Trigger.oldMap.get(brand.Id);
        if (oldBrand.Name != brand.Name) {

            if(String.isBlank(oldBrand.Old_Name__c)){
                brand.Old_Name__c = oldBrand.Name;
            }else{
                brand.Old_Name__c = split(oldBrand.Name + ', ' + brand.Old_Name__c );
            }
        }
    }

    private String split(String s) {
        Integer index = 0;
        for (Integer i = 0; i < 3; i++)
            index = s.indexOf(', ', index + 1);

        if(index > 2)
            return s.substring(0, index);
        else
            return s;
    }
}

Trigger sets at least three values in the "Old Value" field. These are the historical values of Brand_c.Name


texts:
I have a class Edge which looks something like this:

class Edge {

    Edge previous;
    Edge Next;

}

I have edges in an ArrayList. They have to form a loop, as in the last one is connected to the first one.

This is what I have:

    Edge previous, current, next;

    previous = edges.get(edges.size()-1);

    for (int i = 0; i < edges.size(); i++) {
        current = edges.get(i);
        next = i+1 == edges.size() ? edges.get(0) : edges.get(i+1);

        current.previousEdge = previous;
        current.nextEdge = next;

        previous = current;
    }

I only have the idea that this could be written clearer than it is now.


texts: Encapsulating Complex Calculation in JavaScript

texts:
This is code for performing a calculation that should be repeated with different levels and temperatures. I am concerned about the organization of this code as I feel it may contain too many helper functions and seems a little unnecessarily complicated. Only the getCharge() method needs to be exposed to the browser.

There is sample usage of this code after the initial definition.

var hprVessel = function (level, temp) {
/**
* @params {Number} level - Percentage load for HPR
* @params {Number} temp - temperature of fluid
*/
    var liquidCoefficients = [
        83.4485407734612,
        -0.111449280945489,
        0.000100022560084721,
        -0.00000206240663899928
    ];

    var vaporCoefficients = [
        0.895329190066827,
        0.016635773286873,
        -0.0000894924196507015,
        0.00000206296636296276
    ];

    var vessel = {
        // Vessel-specific Params
        diameter: 1.9583 * level,
        height: 0.2937 * level,
        length: 15.9583 * level,

        // Calculations
        getLiquidVol: function () {
            var r = this.diameter/2;
            var sectionArea = Math.pow(r, 2) * Math.acos((r - this.height) / r);
            var triangleArea = Math.sqrt(Math.pow(r, 2) - Math.pow((r-this.height), 2))*(r-this.height);

            return (this.length * sectionArea * triangleArea);
        },
        getVesselVol: function () {
            return (Math.PI * Math.pow(this.diameter, 2) * this.length);
        },
        getVaporVol: function () {
            return (vessel.getVesselVol() - vessel.getLiquidVol());
        },
        getLiquidCharge: function (temp) {
            return (vessel.getLiquidVol() * vessel.calcDensity(liquidCoefficients, temp));
        },
        getVaporCharge: function (temp) {
            return (vessel.getVaporVol() * vessel.calcDensity(vaporCoefficients, temp));
        },
        chargeHPR: function (temp) {
            return (1000 + vessel.getLiquidCharge(temp) + vessel.getVaporCharge(temp));
        },

        // Helper functions
        calcDensity: function (regressionCoefs, temp) {
            var liqDensityArray = regressionCoefs.map(function (coef) {
                return coef * Math.pow(temp, regressionCoefs.indexOf(coef));
            });

            return vessel.sum(liqDensityArray);
        },
        sum: function (arr) {
            return arr.reduce( function (prev, current) {
                return (prev + current);
            }
        }
    };

    return {
        getCharge: function() {
            return vessel.chargeHPR(temp);
        }
    };
}

var vessel = hprVessel(1, -30);
var result = vessel.getCharge();