texts: Buttons that expand or collapse all the  within the document

texts:
I have <button>s that when pressed expand or collapse the contents of all the  within the document. The code works, but as a novice in JavaScript, I am not very confident in its performance and/or efficiency. Could you please review it.

expandDetBtn = document.getElementById("showBtn");
collapseDetBtn = document.getElementById("hideBtn");

expandDetBtn.addEventListener("click", function expandDetails(x) {
  var x = document.getElementsByTagName("details");
  var i;
  var len = x.length;
  for (i = 0; i < len; i++) {
    if (x[i].open == false) {
      x[i].setAttribute("open", "true");
    }
  }
});

collapseDetBtn.addEventListener("click", function expandDetails(x) {
  var x = document.getElementsByTagName("details");
  var i;
  var len = x.length;
  for (i = 0; i < len; i++) {
    if (x[i].open) {
      x[i].removeAttribute("open");
    }
  }
});
<button id="showBtn">Show details</button>
<button id="hideBtn">Hide details</button>

  Section 1

Text 1

  Section 2

Text 2

  Section 3

Text 3


texts: Interchange all occurrences of a character and its predecessor

texts:
Given a string like "abcdbcfbc" , I want all the occurrences of 'b' to be interchanged with their previous character.
The output should be: "bacbdcbfc"

I've come up with a temporary solution:

function punjabi_alternate($string) {
    $len = mb_strlen($string);
    $sploded = array();
    while($len-- > 0) {
        $sploded[$len] = mb_substr($string, $len, 1);
    }
    ksort($sploded);
    $len = mb_strlen($string);
    for ($i=0; $i < $len; $i++) {
        if( strcmp($sploded[$i], "b") == 0){
            $temp = $sploded[$i];
            $sploded[$i] = $sploded[$i-1];
            $sploded[$i-1] = $temp;
        }
    }
    return join('', $sploded);
}

Here I'm using mb_substr as my string contains unicode characters. The b is just an example.
In my production version I'm using this instead of "b"

html_entity_decode("&#x0A3F;")

It is working as expected.
I'd appreciate if there could be a cleaner way to do it.
Also the strings passed to the function can contain as many as 10,000 - 20,000 characters.
So, I'd prefer a preg_replace function with regex to do the same.


texts:
I am implementing a Tree in Java. It must be easy to add a new type of tree e.g. Binary tree and Tertiary tree. Each node can have at least one value. It must be easy to make a new type of node and make a tree of that node.

interface Node<T> {

    T getVal();

    boolean equals(Node<T> node);

    String toString();
}

interface Tree<T extends Node> {
    boolean addNode(T node);

    boolean removeNode(T node);

    String toString();
}

public class BinaryTreeNode<T> implements Node<T> {

    T value;
    BinaryTreeNode<T> firstChild, secondChild;

    BinaryTreeNode(T value) {
        this.value = value;
        firstChild = null;
        secondChild = null;
    }

    public T getVal() {
        return value;
    }

    public boolean equals(Node<T> node) {
        return this.value.equals(node.getVal());
    }

    public String toString() {
        return "" + value;
    }

    boolean setFirstChild(BinaryTreeNode<T> node) {
        firstChild = node;
        return true;
    }

    BinaryTreeNode<T> getFirstChild() {
        return firstChild;
    }

    boolean setSecondChild(BinaryTreeNode<T> node) {
        secondChild = node;
        return true;
    }

    BinaryTreeNode<T> getSecondChild() {
        return secondChild;
    }
}

import java.util.*;

public class BinaryTree<T extends BinaryTreeNode> implements Tree<T> {

BinaryTreeNode root;

    BinaryTree() {
        root = null;
    }

    public boolean addNode(T node) {

        if(root == null) {
            root = node;
        } else {
            addToLast(root, node);
        }

        return true;
    }

    boolean addToLast(BinaryTreeNode root, T node) {

        Deque<BinaryTreeNode> queue = new LinkedList<>();

        queue.addLast(root);
        while(!queue.isEmpty()) {
            BinaryTreeNode cur = queue.pollFirst();

            if(cur.getFirstChild() == null) {
                cur.setFirstChild(node);
                break;
            } else if(cur.getSecondChild() == null) {
                cur.setSecondChild(node);
                break;
            } else {
                queue.addLast(cur.getFirstChild());
                queue.addLast(cur.getSecondChild());
            }
        }

        return true;
    }

    public boolean removeNode(BinaryTreeNode node) {

        throw new UnsupportedOperationException();
    }

    public String toString() {

        Deque<BinaryTreeNode> queue = new LinkedList<>();

        if(root == null) {
            System.out.println("root is null");
            return "";
        }

        StringBuffer ans = new StringBuffer("");
        queue.addLast(root);
        while(!queue.isEmpty()) {
            BinaryTreeNode cur = queue.pollFirst();
            ans.append(" " + cur);

            if(cur.getFirstChild() != null)
                queue.addLast(cur.getFirstChild());

            if(cur.getSecondChild() != null)
                queue.addLast(cur.getSecondChild());

        }

        return ans.toString();
    }

    public static void main(String args[]) {

        BinaryTree<BinaryTreeNode> btree = new BinaryTree<>();

        BinaryTreeNode<Integer> node1 = new BinaryTreeNode<>(1);
        btree.addNode(node1);

        System.out.println(btree);
    }
}

Following this design pattern, I think it is easier to implement different types of binary trees like binary search tree, heap, red-black tree, etc. Also, one can easily add more information to a node while implementing own implementation of tree.

Is this a good design?


texts: Finding the most frequent words in Scala using Akka

texts:
I'm new to akka and would like to get some feedback on my first attempt.  The code takes text from stdin and finds the top 10 most frequently occurring words.

Specifically, I would like to know

Is passing the wordFrequencyAccumulator to the tokenizer a reasonable thing to do?  Are there better alternatives?
Is the use of postStop in the WordFrequencyAccumulator to send the final result to the parent a reasonable thing to do?  Are there better alternatives?
Anything else I might be doing that is weird or there is a better way?

import akka.actor._
import akka.routing._
import scala.io.Source
import scalaz._

import Scalaz._
import Utilities._

object WordCount {
  case class WordFrequencies(freq: Map[Token, Int])
}

class WordCount extends Actor {
  val wordFrequencyAccumulator = context.actorOf(Props[WordFrequencyAccumulator])

  val tokenizeProps = Props(new Tokenize(wordFrequencyAccumulator))
  val tokenizer = context.actorOf(RoundRobinPool(5).props(tokenizeProps))

  context.watch(tokenizer)

  Source.stdin.getLines.foreach(tokenizer ! _)
  tokenizer ! Broadcast(PoisonPill)

  def receive = {
    case WordCount.WordFrequencies(freq) =>
      freq.toList
        .sortWith(_._2 > _._2)
        .take(10)
        .foreach(println)
      context.stop(self)

    case Terminated(`tokenizer`) =>
      wordFrequencyAccumulator ! PoisonPill
  }
}

class Tokenize(wordFrequencyAccumulator: ActorRef) extends Actor {
  def receive = {
    case line: String =>
      val tokens = tokenize(line)
      val filteredTokens = tokens
        .filterNot(token => token.size < 3 || token.size > 45)
        .filterNot(stopWords)
      wordFrequencyAccumulator ! WordCount.WordFrequencies(frequencies(filteredTokens))
  }
}

class WordFrequencyAccumulator extends Actor {
  var frequencyAcc = Map[Token, Int]()

  def receive = {
    case WordCount.WordFrequencies(freq) => frequencyAcc = frequencyAcc |+| freq
  }

  override def postStop() = context.parent ! WordCount.WordFrequencies(frequencyAcc)
}


texts:
I am new to promises and although I am enjoying the simplicity after dealing with callback hell I am having some issues trying to chain them together as you can see by the mess below. So basically what I am trying to achieve is to run through the chain and if there are no duplicate people found then hit the catch and create the person. If not then go down the chain through the subsequent promises and it works but i feel like i am going about this in the wrong manner.
I think it is because in each promise i am resolve to true or false.

self.getPotentialPersonDuplicates()
    .then(function (result) {
        return result.length > 0
            ? self.promptUserToPickFromDuplicatePersons(result)
            : Promise.reject(new Error("There where no duplicates found"));
    })
    .then(function (result) { return result ? self.selectPersonFromDuplicatePersonLookup() : Promise.resolve(); })
    .then(function (result) { return result ? self.addAsParticipant(redirect) : Promise.resolve(); })
    .catch(function (e) {
        console.log(e.stack);
        return self.createOdsPerson()
        .then(self.addAsParticipant.bind(self, redirect));
    })
    .then($ui.stopWaiting());

The promise methods in there contain a lot of code and I don't think there are any code review related issues so I have not included them.


texts: Looking for a way to create a particular matrix in python in a less amount of time

texts:
I want to create a matrix like this in Python:
$$
\begin{pmatrix}
0 & 0 & 0 & 0 & 1 & 1 & 1 & 1 & 2 & 2 & 2 & 2 & 3 & 3 & 3 & 3\\
0 & 1 & 2 & 3 & 0 & 1 & 2 & 3 & 0 & 1 & 2 & 3 & 0 & 1 & 2 & 3\\
1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1 & 1
\end{pmatrix}
$$

I have written a code that works, but takes a long time to execute:

row = 3000
col = 4000

row_1 = np.asarray((col)*[0])
for i in range(1,row):
    row_1 = np.append(row_1, np.asarray((col)*[i]))
row_2 = np.asarray(row*[x for x in range(0,col)])
row_3 = np.asarray(col*(row)*[1])

output = np.vstack([row_1,row_2,row_3])

It takes between 55 to 65 seconds to run this code. Is it possible to create the same matrix in a way that is more efficient?


texts: Design/Architecture for MVC WinForms Dialog Control/Use

texts:
All I have built an MVC WinForms application where Views are blind and deaf of their controllers. To facilitate this I have used Ninject as my Dependency Injection (DI) Inversion of Control (IoC) container. I have a question regarding my design/architecture of the way I handle showing dialogs (remembering I want full testability for all components).

I have two "marker" interfaces for the controllers and views of dialogs. The controller interface is:

IDialogController.cs:

public interface IDialogController : IDisposable { }

Made disposable to enusure the view is cleaned up when we use using(saveDialogController){ ... }. The view interface is IDialogView.cs:

public interface IDialogView { }

I then have my ISaveDialogView.cs as:

public interface ISaveDialogView
{
    /// <summary>
    /// Load the items to be displayed in the ListView.
    /// </summary>
    /// <param name="items">The items to display.</param>
    void LoadItemList(IEnumerable<string> items);
}

and the actual view that uses this interface is SaveDialogView.cs:

public partial class SaveDialogView : Form, ISaveDialogView, IDialogView
{
    public SaveDialogView()
    {
        InitializeComponent();
    }

    private void buttonYes_Click(object sender, EventArgs e)
    {
        DialogResult = DialogResult.Yes;
        Close();
    }

    private void buttonNo_Click(object sender, EventArgs e)
    {
        DialogResult = DialogResult.No;
        Close();
    }

    private void buttonCancel_Click(object sender, EventArgs e)
    {
        DialogResult = DialogResult.Cancel;
        Close();
    }

    public void LoadItemList(IEnumerable<string> items)
    {
        listBoxItems.DataSource = items;
    }
}

and the SaveDialogController.cs is:

public class SaveDialogController : IDialogController
{
    private ISaveDialogView view = null;

    public SaveDialogController(ISaveDialogView view)
    {
        if (view == null)
            throw new ArgumentNullException("view");

        this.view = view;
        Log.Trace("SaveDialogController.Ctor(): Initialized successfully");
    }

    public DialogResult ShowDialog(IWin32Window owner, IEnumerable<string> items)
    {
        view.LoadItemList(items);
        using ((Form)view)
        {
            var result = ((Form)view).ShowDialog();
            Log.Trace($"SaveDialogController.ShowDialog(): " +
                "DialogResult.{result.ToString()} returned from view");
            return result;
        }
    }

    #region IDisposable Members.
    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                if (view != null)
                {
                    ((Form)view).Dispose();
                    view = null;
                    Log.Trace("SaveDialogController.Dispose(): View disposed");
                }
            }
            disposed = true;
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    #endregion // IDisposable Members.
}

I can then call the dialog from another controller as follows:

using (SaveDialogController c = DialogControllerFactory.GetController<SaveDialogController>())
{
    DialogResult result = c.ShowDialog((Form)View, new List<string>() { "A", "B", "C" });
    // Do stuff...
}

My questions on this are as follows:

Is this design/architecture okay, could it be made better, if so, how?
Are there any problems with the way I am disposing the view/Form here?
Any other comments?

Thanks very much for your time.


texts: Puzzle game - converting binary numbers to decimal

texts:
I've been learning Python for a few weeks and I created a simple game where you convert binary numbers to decimal. It shows you n binary numbers and you are supposed to enter the numbers in decimal system in sequence as a password. After failing three times you lose. I'd like to implement it into a bigger game later.

Here's the code:

import random

# Conver decimal to binary.
def toBin(i):
    bin = "{0:b}".format(i)
    return bin

# Generate random password and it's binary version.
def generatePassword(n):
    password = []
    passwordBin = []
    for i in range(n):
        a = random.randint(0, 9)
        password.append(a)
        passwordBin.append(toBin(a))
    return password, passwordBin

# Prints the binary password and a frame.
def printPassword(password):
    print(12 * '#')
    for i in range(len(password[1]) + 4):
        if i <= 1:
            print(2 * '#' + 8 * ' ' + 2 * '#')
        elif i <= 5:
            print(2 * '#' + password[1][i - 2].rjust(4, '0').center(8) + 2 * '#')
        else:
            print(2 * '#' + 8 * ' ' + 2 * '#')
    print(12 * '#')

# The game loop.
def puzzle(n):
    password = generatePassword(n)
    win = False
    endLoop = False
    attempts = 3
    while endLoop is False:
        # Check remaining attempts.
        if attempts > 0:
            printPassword(password)
            print('Attempts remaining: ' + str(attempts) + '\n')
            # Looping through password numbers.
            for i in range(n):
                print('Number ' + str(i + 1), '\t\t', end='')
                # Input and check for ValueError.
                try:
                    inp = int(input())
                except ValueError:
                    print('You can only enter numbers.')
                    break
                # Is input correct?
                if inp == password[0][i]:
                    print('CORRECT')
                else:
                    attempts -= 1
                    print('WRONG\n')
                    break
            # End loop and win.
            else:
                endLoop = True
                win = True
        # End loop.
        else:
            endLoop = True
    # Check win condition.
    if win is True:
        print('ACCESS GRANTED')
    else:
        print('ACCESS DENIED')

# Run the game.
puzzle(4)

Are there any ways to improve my code, expecially the puzzle(n) function? The conditions and loops took me some time to get working and still kinda confuse me. I hope there aren't any bugs.


texts:
I threw this together and would love any suggestions on how to improve on this simple DataTable to given Type T mapper. Anything from coding conventions to speed optimizations or "you're doing something stupid".

public class test {

  static ISXLog log = new XLog();

  public void runTest() {
    var data = RetrieveDataSet(/*parameters not important*/);
    AddressType[] addr = mapObjects<AddressType>(data.Tables[0]);
  }

  // overload for optional function parameter
  public static T[] mapObjects<T>(DataTable dt ) where T : new(){
    return mapObjects<T>(dt, (p => p.IsCollection()));
  }

  // mapObjects from DataTable to Type T
  public static T[] mapObjects<T>(DataTable dt, Func<PropertyInfo,bool>propRestriction) where T : new() {
  T[] newobjs;
  var Rows = dt.Rows;
  newobjs = new T[Rows.Count];
  var MField = typeof(DataRowExtensions)
    .GetMethod(@"Field", new[] { typeof(DataRow), typeof(string) });

  for (int i = 0; i < Rows.Count; i++) {
    DataRow dbobj = Rows[i];
    var obj = newobjs[i] = new T();
    var objProps = obj.GetType().GetProperties();

    foreach (var prop in objProps) {
      try {
        if (!dbobj.Table.Columns.Contains(prop.Name) || propRestriction(prop)) {
          log.Debug("Nothing to set for property: {0}", prop.Name);
        }else{
          MField = MField.GetGenericMethodDefinition()
            .MakeGenericMethod(prop.PropertyType);

          var objval = MField.Invoke(null, new object[] { dbobj, prop.Name });
          prop.SetValue(obj, objval, null);
          log.Debug("Set property '{0}' to value '{1}'", prop.Name, objval);

        }
      }
      catch (Exception e) {
        log.DebugException("Error occured while trying to set prop: " + prop.Name, e);
      }
    }
  }
  return newobjs;
}

  public static class PropertyInfoExtensions
  {
    public static bool IsCollection(this PropertyInfo property) {
      return (!typeof(String).Equals(property.PropertyType) &&
        typeof(IEnumerable).IsAssignableFrom(property.PropertyType));
  }
}


texts:
This is a Perl program intended for my chemistry class. Since I am just learning to write in Perl, which is my first language, can you tell me if you think that this is well written? If not, could you tell me what is wrong with it or what could be improved?

## Name:Titration
## Beginning of Program

#Input Variables
system "clear";     # Clear the Screen

print "Milliliters Solute: ";
chomp ($milliliters_solute=<>);

print "Milliliters Solvent: ";
chomp ($milliliters_solvent=<>);

print "Molarity of Solvent: ";
chomp ($molarity_solvent=<>);

print "Moles of Solute: ";
chomp ($moles_solute=<>);

print "Moles of Solvent: ";
chomp ($moles_solvent=<>);

system "clear";     # Clear the Screen

#Calculate Answer
$liters_solute=$milliliters_solute/1000;
$liters_solvent=$milliliters_solvent/1000;
$molarity=($liters_solute/$liters_solvent)*($molarity_solvent/1)*($moles_solvent/$moles_solute);

#Print Answer
system "clear";     # Clear the Screen
print "Molarity is $molarity \n";

## End of Program


texts: Converting the first and last name to pig latin

texts:
The following question was taken from Absolute Java 5th ed. by Walter Savitch:

  Write a program that starts with the string variable first set to your first name and the string variable last  set to your last name. Both names should be all lower- case. Your program should then create a new string that contains your full name in pig latin with the first letter capitalized for the first and last name. Use only the pig latin rule of moving the first letter to the end of the word and adding “ay.” Output the pig latin name to the screen. Use the substring  and  toUpperCase  methods to construct the new name.
  For example, given
  first = "walt";
  last = "savitch";
  the program should create a new string with the text “Altway Avitchsay” and print it.

This is the code that I have written:

    public class Question3 {

    private static String first;
    private static String last;
    private static String newName;

    public static void main(String[] args) {

        Question3 name = new Question3("walt", "savitch");

        System.out.println(name.convertName(first) + " "
                + name.convertName(last));

    }

    public Question3(String lowerCaseFirstName, String lowerCaseLastName) {
        first = lowerCaseFirstName;
        last = lowerCaseLastName;
    }

    private String convertName(String originalName) {
        String firstLetter = originalName.substring(0, 1);
        newName = nameWithoutFirstLetter(originalName) + firstLetter; // move first letter to the end
        newName = capitalizeFirstLetter() + nameWithoutFirstLetter(newName) // capitalize first letter and add "ay" to the end
                + "ay";
        return newName;
    }

    private String capitalizeFirstLetter() {
        String capitalFirstLetter = newName.substring(0, 1).toUpperCase();
        return capitalFirstLetter;
    }

    private String nameWithoutFirstLetter(String name) {
        String restOfName = name.substring(1);
        return restOfName;
    }
}


texts:
I want to save my users tokens id into my database using POST request in Swift (here PHP code here). I am a bit confused about synchronous and asynchronous request.

Is this code the right way to do it?
would the app crash if there is a connection problem while it is sending the synchronous request
shall I use an api key (not sure is the correct word) to "identify" the user

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

    var userId = "001" //I just use it as USER number 1

    // prepare the tolen to be saved from <xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx> to xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    var token = NSString(format: "%@", deviceToken)
    token = token.stringByReplacingOccurrencesOfString(
        "<",
        withString: "")
    token = token.stringByReplacingOccurrencesOfString(
        ">",
        withString: "")
    token = token.stringByReplacingOccurrencesOfString(" ", withString: "")

    dispatch_async(dispatch_get_main_queue(), { () -> Void in

        var postBody = NSString(format: "user=%@&token=%@", userId, token)
        var endBody = NSURL(string: "http://www.myServer.com/api/v1.0/saveToken.php")
        var request = NSMutableURLRequest(URL: endBody!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30.0)

        request.HTTPMethod = "POST";
        request.HTTPBody = postBody.dataUsingEncoding(NSUTF8StringEncoding)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

        var response: NSURLResponse?
        var error: NSError?

        NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)

        println(response)
        println(error)

    })

    }


texts: Algorithm for comparing two lists of objects, to insert added items, and delete removed items

texts:
I use two lists of objects invoices, original list and a new modified list. I would insert in db invoices presents in the new modified list but not presents in the original list.

For delete, I would remove from db invoices presents in the original list but absent in the new modified list.

This is what I did and that works, but I am not satisfied with the algorithm used, someone would have a way to do this more simply and clearly?

public void updateCustomerInvoicesCouple(List<CustomerInvoicesDto> originalCouplesListDto, List<CustomerInvoicesDto> newCoupleListDto){

    // 1 - Insert
    Iterator<CustomerInvoicesDto> itFinal = newCoupleListDto.iterator();

    // Browse all couples (customer-invoice) from final list
    // Insert couples of final list not in original list
    while(itFinal.hasNext()){
        CustomerInvoicesDto finalCoupleDto = (CustomerInvoicesDto) itFinal.next();

        Integer idCustomerFinal = finalCoupleDto.getCustomer().getId();
        Integer idInvoiceFinal = finalCoupleDto.getInvoice().getId();

        boolean coupleFind = false;
        for(CustomerInvoicesDto itemInitialCouple : originalCouplesListDto)
        {
            if(idCustomerFinal == itemInitialCouple.getCustomer().getId()
                    && idInvoiceFinal == itemInitialCouple.getInvoice().getId())
            {
                coupleFind = true;
            }
        }

        if(!coupleFind){
            // dto -> entity
            CustomerInvoicesEntity finalCoupleEntity = new CustomerInvoicesEntity();
            finalCoupleEntity = mapper.map(finalCoupleDto, CustomerInvoicesEntity.class);

            // Save in db
            CustomerInvoicesDao.save(finalCoupleEntity);
        }
    }

    // 2 - Delete
    Iterator<CustomerInvoicesDto> itInit = originalCouplesListDto.iterator();

    // Browse all couples (customer-invoice) from original list
    // Insert couples of final list not in final list
    while(itInit.hasNext()){
        CustomerInvoicesDto initialCoupleDto = (CustomerInvoicesDto) itInit.next();

        Integer idCustomerInitial = initialCoupleDto.getCustomer().getId();
        Integer idInvoiceInitial = initialCoupleDto.getInvoice().getId();

        boolean coupleFind = false;
        for(CustomerInvoicesDto itemFinalCouple : newCoupleListDto)
        {
            if(idCustomerInitial == itemFinalCouple.getCustomer().getId()
                    && idInvoiceInitial == itemFinalCouple.getInvoice().getId())
            {
                coupleFind = true;
            }
        }

        if(!coupleFind){
            CustomerInvoicesDao.remove(initialCoupleDto.getId());
        }
    }
}


texts:
I am using "AndEngine" and I would like to know if I am following the best practice when I want to refresh the entity.

Let say, I have 2 sprites and I want change them into 2 another sprites.

I usually do it like this :

class MainClass {
    private Sprite sprite1;
    private Sprite sprite2;

    private void someMethod(){
        sprite1 = new Sprite(0,0,someRegion1,getVertexBufferObjectManager());
        sprite2 = new Sprite(10,10,someRegion2,getVertexBufferObjectManager());

        attachChild(sprite1);
        attachChild(sprite2);
    }

    private void refreshSprites(Sprite pSprite1, Sprite pSprite2){
        Sprite temp1 = sprite1;
        Sprite temp2 = sprite2;
        sprite1 = sprite2 = null;
        runOnUpdateThread(new Runnable() {
                            @Override
                            public void run() {
                                temp1.detachSelf();
                                temp2.detachSelf();
                            }
                        });
        sprite1 = pSprite1;
        sprite2 = pSprite2;

        attachChild(sprite1);
        attachChild(sprite2);
    }
}


texts:
I came up with a small optimization while practice coding insertion sort in Python. It's mostly about not accessing the input array too much and letting the hardware do element shifts instead of swapping manually. Could someone comment on my coding style as well as the optimization idea?

Original Version

# this version of insertion sort is half as fast as selection sort on my machine
def runslow(input):

    for i in range(1,len(input)):

        j = i

        # list being accessed twice in this comparison
        while j > 0 and input[j] < input[j-1]:

            # unnecessary writes creating slowdown
            input[j-1], input[j] = input[j], input[j-1]

            j -= 1

Improved Version

# the optimized insertion sort
def run(input):

    for i in range(1,len(input)):

        j = i

        # extract the value being compared
        saved = input[i]

        # now list isn't being accessed twice unnecessarily
        while(j > 0 and input[j-1] > saved):

            # don't actually perform the intermediate swaps,
            # just let the cursor settle into the final position
            # input[j - 1], input[j] = input[j], input[j - 1]
            j-=1

        # now insert it and let the hardware do the actual shifting of the values in the list
        input.insert(j,input.pop(i))

    return input


texts: Custom hook to handles async calls with loading and error state?

texts:
I have built this hook to handle async calls.

It should manage state for the loading and error status.
It should also not accept other calls while loading === true.
It should also works with synchronous functions without issues.

Note that I used useCallback because I don't want doAction to change between renders, since I'll be using it a lot inside useEffect() in my components that make async calls. So I had to pass the loading from the component as a parameter currentLoading.

QUESTION:

Did I miss something? Will this work as per my requirements? Can I improve it somehow?

Sandbox Link: https://codesandbox.io/s/nice-carson-vk0nq

useAsyncAction.js

import React, { useCallback, useState} from "react";
import ReactDOM from "react-dom";

function useAsyncAction(action) {
  console.log("Rendering useAsyncAction...");

  // STATE FOR LOADING AND ERROR STATUS

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // doAction AS AN useCallback SO IT WON'T CHANGE BETWEEN RENDERS

  const doAction = useCallback(async (action,currentLoading) => {

    if (currentLoading) {
      console.log("There is one call in progress...");
      return;
    }

    // TRY BLOCK

    try {
      setLoading(true);
      setError(null);

      await action();

      setLoading(false);
    // CATCH BLOCK

    } catch (err) {
      setError(err);
      setLoading(false);
    }
  },[]);

  return {
    loading,
    error,
    doAction
  };
}

How I'm using it:

App.js

function App() {
  console.log("Rendering App...");

  const [myState, setMyState] = useState(null);
  const { loading, error, doAction } = useAsyncAction();

  // SIMULATES AN API RESPONSE

  function mockAPI() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("Here is your data");
      }, 1500);
    });
  }

  // EXAMPLE OF AN API ASYNC CALL

  async function getNewData() {
    const newData = await mockAPI();
    setMyState(newData);
  }

  // EXAMPLE OF A SYNC CALL

  function getNewDataSync() {
    setMyState("SYNC DATA");
  }

  // THE BUTTONS ARE CALLING doAction(action,loading)

  return (
    <React.Fragment>

myState: {myState}

loading: {JSON.stringify(loading)}

error: {JSON.stringify(error)}

      <button onClick={() => doAction(getNewData,loading)}>Do Action</button>
      <button onClick={() => doAction(getNewDataSync,loading)}>Do Action Sync</button>
    </React.Fragment>
  );
}


texts:
I'm fairly new to MySQLi and PHP, but I've been working at it for a bit now, and reading up on how to make secure login forms, avoid SQL injection etc. I'm a mere amateur though.

I've created an index.html page (not including the code here, just a basic form though), a register.html page (not including the code here, again it's just a basic form), adduser.php (which gets its call from "action" on the registration form),login.php (obviously gets its "action" from the index.html login form), logout.php, and a restricted.php with a check if session is active.

Everything is working. I'm just looking for some expert eyes to take a gander at my code and let me know if I'm missing anything whether it be major or minor, any security flaws, etc. Currently I don't have any form validation as I'm thinking of doing it client side with jQuery.

adduser.php

<?php

error_reporting(E_ALL);
session_start();
$mysqli = new mysqli ('localhost', '***', '***', 'test');

if($mysqli->connect_errno > 0) {
    die('Unable to connect to database [' . $mysqli->connect_error . ']');
}

if(isset($_POST['submit'])) {

    $errors = array();
    $data = array();
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $confpass = $_POST['confpass'];
    $password_hash = password_hash($password, PASSWORD_DEFAULT);

    if(!($stmt = $mysqli->prepare("INSERT INTO users (fname, lname, username, email, password)
        VALUES (?,?,?,?,?)"))){
        echo "Prepare failed: (" . $mysqli->errno . ")" . $mysqli->error;
    }

    if(!$stmt->bind_param('sssss', $fname, $lname, $username, $email, $password_hash)){
     echo "Binding paramaters failed:(" . $stmt->errno . ")" . $stmt->error;
    }

    if(!$stmt->execute()){
     echo "Execute failed: (" . $stmt->errno .")" . $stmt->error;
    }

    if($stmt) {
        header('Location: index.html#testform')

    }
    else{
        echo "Registration failed";
    }

}

$mysqli->close();

login.php

<?php
error_reporting(E_ALL);

$mysqli = new mysqli ('localhost', '***', '***', 'test');

if($mysqli->connect_errno > 0) {
    die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
ob_start();
session_start();

    $username = $_POST['username'];
    $password = $_POST['password'];
if(isset($_POST['submit'])) {

    if(!($stmt = $mysqli->prepare("SELECT username, password FROM users WHERE username = ?"))){
            echo "Prepare failed: (" . $mysqli->errno . ")" . $mysqli->error;
    }

    if(!$stmt->bind_param('s', $username)){
        echo "Bind failed: (" . $stmt->errno . ")" . $stmt->error;
    }

    if(!$stmt->execute()){
     echo "Execute failed: (" . $stmt->errno .")" . $stmt->error;
    }

    $userdata = $stmt->get_result();
    $row = $userdata->fetch_array(MYSQLI_ASSOC);

    $stmt->bind_result($username, $password);
    $stmt->store_result();

             if(password_verify($password, $row['password'])){

            $_SESSION['user'] = $_POST['username'];
            header('Location: restricted.php');
            exit();
        }

    else{
        echo "Login Failed: (" . $stmt->errno .")" . $stmt->error;
    }
$stmt->close();

}

$mysqli->close();

restricted.php (just the top session code, the rest of the page is useless for the sake of this post)

<?php
error_reporting(E_ALL);
ob_start();
session_start();
$db = new mysqli ('localhost', '***', '***', 'test');

if($db->connect_errno > 0) {
    die('Unable to connect to database [' . $db->connect_error . ']');
}
if (!isset($_SESSION['user'])) {
    header('Location: index.html');
}

?>

logout.php

<?php
session_start();
if(session_destroy()) // Destroying All Sessions
{
header("Location: index.html"); // Redirecting To Home Page
}
?>


texts: Terser way of generating deeply nested hash

texts:
I need to generate a Ruby hash that looks like this:

{ "children" => [
  { "children" => [
    { "children" => [
      { "children" => [] }
    ]}
  ]}
]}

... for an arbitrary level of nesting.  So far the best I've come up with is:

def nested_hash(levels)
  return {} if levels < 1
  root = { 'children' => [] }
  children = root['children']
  (levels - 1).times { children = (children << { 'children' => [] }).first['children'] }
  root
end

This doesn't seem particularly terse or elegant.  Can anyone offer suggestions on making this more terse or elegant?


texts:
I would like to find out if following usage of an AtomicBoolean as a flag variable is correct and good for a multi-threaded application. It is expected that data is going to be loaded only once and when the application is at very low load. It is also expected that the list of SomeObjects is going to be read quite frequently by multiple threads at peak load, probably thousands of time in an hour so that is why I want to avoid hitting the database. The list is not going to be very large so keeping it in memory is not going to be a problem.

public class HibernateDao extends SomeOtherClass implements Dao {

    //Need suggestions for correct usage of following variable
    private AtomicBoolean dataLoaded = new AtomicBoolean();
    private List<SomeObject> someObjects;

    @Override
    public List<SomeObject> getAllSomeObjects() {
        if (dataLoaded.getAndSet(false)) {
            //aim is to atomically load the list only once and avoid calling loadAll
            //every time list is used
            someObjects= (List<SomeObject>) getHibernateTemplate().loadAll(SomeObject.class);
        }
        return someObjects;
    }

    @Override
    public void updateAllSomeObjects(Collection<SomeObject> someObjects) {
            //replaceAll is part of parent class and it removed and reloads
            //data for the entity i.e. SomeObject
        replaceAll(SomeObject.class, someObjects);
            //set this flag atomically so that data is fetched from DB next time
        dataLoaded.getAndSet(true);
    }

}


texts: JavaScript class that generates HTML form with validation

texts:
I'm trying to create a complex application—Table generator. And the first part if it is form that lets user input data source. As I figure source should be an absolute http url, so I have to give user <input> with validation, and <button> which will reflect validation state.

Eventually I came up with this:

class Form {
  constructor () {
    this.button            = document.createElement('button')
    this.button.innerHTML  = 'Upload'
    // Initially it's empty so it's invalid
    this.button.disabled   = true

    this.input             = document.createElement('input')
    this.input.placeholder = 'Path to data'
    // Let's assign our custom validator
    // since validation props are read only
    this.input.oninput     = () => this.validate()
  }
  validate () {
    // Tribute @LukeP
    // https://stackoverflow.com/a/34695026/2626747
    // Let's use anchor superpowers
    // rather then google `url regex`
    const a = document.createElement('a')
    a.href  = this.input.value
    // If typed value couldn't be parsed as an absolute url,
    // it'd be considerd as a path on current host
    this.button.disabled = !(a.host && a.host != window.location.host)
  }
  render () {
    const form = document.createElement('form')
    form.appendChild(this.input)
    form.appendChild(this.button)
    return form
  }
}

const form = new Form()
document.getElementById('app').appendChild(form.render())

I'm not satisfied with this code, and I can not explain why. I don't have somewhat strong experience in JS, so I'm relying on your peer review.

Help me make Web better, starting with my app.


texts: JS Function warning before closing browser

texts:
I have a function that makes sure the user wants to actually leave the page. I am not a jQuery expert. Is the code below the most efficient way to do this function? Or can it be simplified much more to run smoother? Any advice is greatly appreciated.

$(document).ready(function() {
  formmodified=0;
    $('form *').change(function(){
        formmodified=1;
    });
  window.onbeforeunload = confirmExit;
    function confirmExit() {
      if (formmodified == 1) {
          return "Are you sure you want to leave this page? This will abandon any progress on changes to document preferences";
      }
  }
  $("input[name='ModifyRecord']").click(function() {
        formmodified = 0;
    });
    $("input[name='DeleteRecord']").click(function() {
        formmodified = 0;
    });
    $("input[name='DeleteChecked']").click(function() {
        formmodified = 0;
    });
});


texts:
dlfcn.h is a library of C functions to work with dynamic dependencies (shared objects). I've been experimenting with wrapping them in a C++ API, mostly as practice in making a C++ wrapper.
This is an excerpt of my process of wrapping the Dl_serinfo parts of dlinfo(...) in the C library. For reference:

typedef struct {
    size_t dls_size;           /* Size in bytes of
                                the whole buffer */
    unsigned int dls_cnt;      /* Number of elements
                                in 'dls_serpath' */
    Dl_serpath dls_serpath[1]; /* Actually longer,
                                'dls_cnt' elements */
} Dl_serinfo;

And Dl_serpath:

typedef struct {
    char *dls_name;            /* Name of library search
                                path directory */
    unsigned int dls_flags;    /* Indicates where this
                                directory came from */
} Dl_serpath;

Note that the dls_serpath member of Dl_serinfo is a "flexible array member" and the entire Dl_serinfo struct is supposed to be allocated with enough space for dls_cnt entries in the array.

My wrapper:
#include <dlfcn.h>

#include <cstddef>
#include <memory>
#include <stdexcept>
#include <string_view>

namespace dl {
class dl_error : public std::runtime_error {
public:
    using std::runtime_error::runtime_error;
};

class serinfo;
class serpath {
    friend class serinfo;

private:
    std::string_view name_;
    unsigned int flags_;

    explicit serpath(::Dl_serpath path)
        : name_(path.dls_name)
        , flags_(path.dls_flags)
    {}

public:
    std::string_view name() const { return name_; }
    unsigned int flags() const { return flags_; }
};

class serinfo {
private:
    std::unique_ptr<std::byte[]> bytes;

public:
    explicit serinfo(void* dlhandle) {
        ::Dl_serinfo size;

        if (::dlinfo(dlhandle, RTLD_DI_SERINFOSIZE, &size)) {
            throw dl_error(::dlerror());
        }

        bytes = std::make_unique<std::byte[]>(size.dls_size);
        if (::dlinfo(dlhandle, RTLD_DI_SERINFOSIZE, bytes.get())) {
            throw dl_error(::dlerror());
        }

        if (::dlinfo(dlhandle, RTLD_DI_SERINFO, bytes.get())) {
            throw dl_error(::dlerror());
        }
    }

    unsigned int cnt() const {
        return reinterpret_cast<::Dl_serinfo const*>(bytes.get())->dls_cnt;
    }

    dl::serpath serpath(unsigned int index) const {
        return dl::serpath(
            reinterpret_cast<::Dl_serinfo const*>(bytes.get())->dls_serpath[index]);
    }
};
}


texts:
Considering that:

the passed parameters are all numbers
the passed date is a valid date

It should return:

true if the date is 18 or more years old
false otherwise

function isDate18orMoreYearsOld(day, month, year) {
    var maxBirthDate = new Date();
    maxBirthDate = new Date(maxBirthDate.setYear(maxBirthDate.getYear() - 18));
    var maxYear = maxBirthDate.getYear();
    var maxMonthOnMaxYear = maxBirthDate.getMonth() + 1;
    var maxDayOnMaxMonthOnMaxYear = maxBirthDate.getDate();
    if (year > maxYear) {
        return true;
    }
    if (year == maxYear) {
        if (month > maxMonthOnMaxYear) {
            return true;
        }
        if (month == maxMonthOnMaxYear) {
            if (day >= maxDayOnMaxMonthOnMaxYear) {
                return true;
            }
        }
    }
    return false;
}

Despite I don't want to lose maintainability and readability, I feel it could possibly have a lesser number of conditional statements.

Is there any improvement you suggest?

Also, if you spot any cases that the function fails it's very welcome.


texts: Extract specific positions from a char array

texts:
I have two arrays:

char input[] = "ughIuytLikeretC";

and

bool mask[] = {
    false, false, false, true, false,
    false, false, true, true, true,
    true, false, false, false, true,
};

My function takes these two arrays and returns the characters in input whose positions are true in mask such that in this example, the result being ILikeC.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

char *filtArray(char input[], bool mask[], char *filtered) {
    int j = 0;
    int i;
    for (i = 0; input[i]; i++) {
        filtered[j] = input[i];
        j += mask[i];
        }

    filtered[j] = 0;
    return filtered;
}

filtArray will run on billions of "input" strings of constant length and "mask" will be the same for all "input"s.


texts: Querying connection string across solution

texts:
I have an app.config file that contains some connection strings, this is accessed on a project-by-project basis

In my solution, I have the following projects:

A
B
C
D

Project A contains the app.config file, and a class called ConnectionStringHelper

public class ConnectionStringHelper
{
    public string GetConnectionString(string index)
    {
        return ConfigurationManager.ConnectionStrings[index].ConnectionString;
    }
}

Here is an example of how this is used (in project B):

var connectionString = new ConnectionStringHelper().GetConnectionString("test");

Is there anything wrong with having a public method that returns the connection string?

This feels like a code smell, but I'm unsure how I would get around it?

EDIT: I do use dependency injection across the solution, however I had to write this method to be able to use it in some unit tests, as I can't use DI with them.


texts:
//parses the text path vector into the engine
void Level::PopulatePathVectors(string pathTable)
{
    // Read the file line by line.
    ifstream myFile(pathTable);

        for (unsigned int i = 0; i < nodes.size(); i++)
        {
            pathLookupVectors.push_back(vector<vector<int>>());

            for (unsigned int j = 0; j < nodes.size(); j++)
            {
                string line;

                if (getline(myFile, line)) //enter if a line is read successfully
                {
                    stringstream ss(line);
                    istream_iterator<int> begin(ss), end;
                    pathLookupVectors[i].push_back(vector<int>(begin, end));
                }
            }
        }
    myFile.close();
}

This function is taking about 5 minutes to pass in a text file which is 744 * 744 lines long. Each line is a list of integers like this:

1 4 6 24 7 4 8 n

they can be of varying length. I have no idea why it's taking so long, but it needs to run in a matter of seconds, not minutes! The odd thing is that the same function in C# (in fact a very unoptimised version) does in fact only take seconds to run.

Could the problem be a setting?

This is a link to the path table it is parsing http://dl.dropbox.com/u/13519335/WepTestLevelPathTable.txt


texts: Function for inserting data into database

texts:
I have this function to ease out the task of inserting data into databases.
I am not very sure if it is secure to use it this way.

Any suggestions on improving it?

function insert_into($query,$datatype) {

        //$i=0; num=1; $i=1; num=2; for(i=1;)
        $num=func_num_args()-1;
        global $CONN;//set the global connection variable on.
        for($i=2;$i<=$num;$i++) //assign the 'n' variables to an array
        {
            $values[$i]=mysqli_real_escape_string($CONN,func_get_arg($i));

            if(empty($values[$i])|| !isset($values[$i])|| $values[$i]=="")
            {
                die("
Fatal Error: One or more parameters have an uninitialized or empty variable. You can't use an empty variable as a parameter.
");
            }
        }

        $blanks=str_repeat("?,", count($values)); //get the parameterized values as "?".
        $blanks=trim($blanks,","); //remove the extra ","

         $sql="INSERT INTO  ".$query." VALUES (".$blanks.");"; //make the query

         //set the connection

        $stmt= $CONN->prepare($sql); //prepare the query

        $bind=array();
        foreach ($values as $key => $val) {

            $bind[$key]=&$values[$key];
        }

        array_unshift($bind,$datatype);
        call_user_func_array(array($stmt,'bind_param'),$bind); // bind the variables

        #Replaced with above line ^ $stmt->bind_param($datatype, $xid);

        if($stmt->execute())    // set parameters and execute
    {
            $stmt->close();
        return 1; //sucessful

        } else {
            echo mysqli_error($CONN);
            $stmt->close();
            return 0;
        }
            $stmt->close();
            //close anyway

    }

     //SAMPLE: set_conn(); insert_into("tablename (stuff1, stuff2, stuff3)","sss",$val1,$val2,$val3);
    // set_conn() is another function which sets the connection to the database.
    //The above function returns 1 on success.

Does this have some serious issues like SQL injection or any other vulnerabilities? Thanks!


texts:
I just want to confirm that my ISO8583 format is correct.

Example:

For the data field 35, the length of the data is 36, so I put 36 before the 4842. Then all the data is inserted in a string (dataISO). This dataISO variable is then sent to another function SendISO().

private void btnSend_Click(object sender, RoutedEventArgs e)
{
    string command = cboISOCommand.SelectionBoxItem.ToString();
    string dataISO = "";

    if (command == "Pre-Auth")
    {
        string dataLength = "019A";
        string TPDU = "6001010000";
        string MTI = "0100";
        string BITMAP = "3020078020C00204";
        string ProCode = "380000"; // 3
        string Amount = "000000010000"; // 4
        string STAN = "000031"; // 11
        string POSEM = "051"; // 22
        string PANSequence = "001"; // 23
        string FunctionCode = "101"; // 24
        string ConditionCode = "00"; // 25
        string Track2 = "36484200000000009=15000000000000000000"; //35
        string TerminalID = "00000000"; //41
        string IdentificationCode = "000000000000000"; //42
        string ReservedISO = "2725F2A02045882023C008407A0000000031010950500000080009A031407229C01009F0206000000000010";
        ReservedISO +="9F03060000000000009F0902008C9F100706010A03A0A0029F1A0204589F1E0831313731313534399F26";
        ReservedISO +="081344604C7E2C7B589F2701809F3303E0B0C89F34031E03009F3501229F360204379F3704746733F19F4";
        ReservedISO +="104000000079F530152"; //55
        string ReservedPrivate = "006000019"; //62

        string total = dataLength + TPDU + MTI + BITMAP + ProCode + Amount + STAN + POSEM + PANSequence + FunctionCode + ConditionCode + Track2 + TerminalID + IdentificationCode + ReservedISO + ReservedPrivate;
        dataISO = total;
    }

    _controller.SendISO(client2, dataISO);
}

//To Send ISO Data Over TCP Socket
public void SendISO(TcpClient client, string isoData)
{
    string ip =     ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
    int port = ((IPEndPoint)client.Client.RemoteEndPoint).Port;

    if (!client.Connected)
    {
        OnControllerErrorFunction(
            new ControllerErrorArguments(String.Format("02<> IP {0} Port {1} not Connected", ip, Convert.ToString(port)), "DISCONNECTED"));
        return;
    }
    try
    {
        NetworkStream stream = client.GetStream();

        byte[] byteArray = Encoding.Default.GetBytes(isoData);

        if (stream.CanWrite)
        {
            stream.Write(byteArray, 0, byteArray.Length);
            stream.Flush();

            onControllerRawDataFunction(
                    new ControllerRawArguments(
                        string.Format("Send Controller {0} : {1}", ip, isoData)));
        }
    }
    catch (Exception err)
    {
        OnControllerErrorFunction(
            new ControllerErrorArguments(string.Format("02<>Controller {0} Error on sending data : {1} ", ip, isoData), err.Message));
        WriteSystemLog(err.Message, "Send Data To Controller");
        return;
    }
}

And for the function to send ISO Data over a TCP socket, is it correct in terms of the encoding before sending it using stream.Write?


texts:
I'm using the repository pattern with a context and ninject as the IOC. I have a service which handles getting and setting page properties in the database.

public class MyContext : DbContext
{
    public MyContext() : base ("DefaultConnection")
    {
    }

    public DbSet<PageProperty> PageProperties { get; set; }
    public DbSet<Contact> Contacts { get; set; }
}

public class DefaultRepository : IRepository
{
    MyContext _context;
    public DefaultRepository(MyContext context)
    {
        _context = context;
    }

    public IQueryable<PageProperty> PageProperties { get { return _context.PageProperties; } }
    public IQueryable<Contact> Contacts { get { return _context.Contacts; } }
}

public class ModuleLoader : NinjectModule
{
    public ModuleLoader()
    {

    }

    public override void Load()
    {
        var context = new MyContext();
        context.Database.Initialize(false);
        Bind<MyContext>().ToConstant(context).InSingletonScope();
        Bind<IRepository>().To<DefaultRepository>();
        Bind<IPagePropertyProvider>().To<DefaultPagePropertyProvider>().InSingletonScope();
    }
}

public class DefaultPagePropertyProvider : IPagePropertyProvider
{
    IRepository _repository;
    object _syncLock = new object();

    public DefaultPagePropertyProvider (IRepository repository)
    {
        _repository = repository;
    }

    public string GetValue(string pageName, string propertyName
    {
        lock (_syncLock)
        {
            var prop = page.PageProperties.FirstOrDefault(x => x.Property.Equals(propertyName) && x.PageName.Equals(pageName)).Value;

            return prop;
        }
     }
     public void SetValue(string pageName, string propertyName, string value)
     {
         var pageProp = _repository.PageProperties.FirstOrDefault(x => x.Property.Equals(propertyName) && x.PageName.Equals(pageName));
         pageProp.Value = value;
         _repository.SaveSingleEntity(pageProp);
     }
}

In my view I am doing 3 ajax calls, one to get a list from contacts to fill out a table, one ajax call to determine how many pages i have depending on the page size I'm using, and one ajax call to set the page size that I want to use. so a select box changes the page size (How many contacts per page: [  30]) , a table that displays the contacts (generated from jquery which decifers json), and finally a div containing a list of page numbers to click. The workflow is, call GetContacts(), this function then queries the PageProperties to find out the page size to use, then call GetPages(), this function also queries PageProperties to find out what page size to use, SetPageSize() which sets the page size. So GetContacts() and GetPages() is used when a page is selected from the div, SetPageSize() then GetContacts() and GetPages() is called when the select box change event is fired. GetContacts() and GetPages() is only called when the first SetPageSize() $.ajax request is done() and there is a success from that function.

Now, before I added lock(syncLock) in the DefaultPageProperty service and before I added InSingletonScope to both that service and the context, I was getting two errors.

  The connection was not closed. The connection's current state is connecting.

  An EdmType cannot be mapped to CLR classes multiple times

I assumed because the connection was in a connecting state, that the context was being reused and reused and reused, so I thought putting that to SingletonScope() would mean that only one connection was made, then I thought the same about DefaultPageProperty and then because I was making async calls to that service, I should put a lock over the database querying.

It works, and the problems don't exist. But I don't know if what I have done is correct within the pattern I'm using, I'm wondering if I've missed something fundamental? My question is, is this a proper/viable solution which won't create any caveats later down the road? Have I actually solved the issue or just created more?


texts: Python class w/ Telnet interface to memcached

texts:
I haven't had anyone help me out with code review, etc, so I thought I'd post a Python class I put together for interfacing with Telnet to get information from a memcached server.

import re, telnetlib

class MemcachedStats:

    _client = None

    def __init__(self, host='localhost', port='11211'):
        self._host = host
        self._port = port

    @property
    def client(self):
        if self._client is None:
            self._client = telnetlib.Telnet(self._host, self._port)
        return self._client

    def key_details(self, sort=True):
        ' Return a list of tuples containing keys and details '
        keys = []
        slab_ids = self.slab_ids()
        for id in slab_ids:
            self.client.write("stats cachedump %s 100\n" % id)
            response = self.client.read_until('END')
            keys.extend(re.findall('ITEM (.*) \[(.*); (.*)\]', response))
        if sort:
            return sorted(keys)
        return keys

    def keys(self, sort=True):
        ' Return a list of keys in use '
        return [key[0] for key in self.key_details(sort=sort)]

    def slab_ids(self):
        ' Return a list of slab ids in use '
        self.client.write("stats items\n")
        response = self.client.read_until('END')
        return re.findall('STAT items:(.*):number', response)

    def stats(self):
        ' Return a dict containing memcached stats '
        self.client.write("stats\n")
        response = self.client.read_until('END')
        return dict(re.findall("STAT (.*) (.*)\r", response))

This is also up on GitHub.

I would love some feedback on:

Organization
Better ways of accomplishing the same result


texts: Create an alternative wait in javascript

texts:
Im creating an single page application with not reload or redirects so I display all my contents with partial view(since im using MVC4 and angularjs ) and modals.

But I came with a situation, and that is that in some cases when i request a view with ajax to the server I need to perform some action(javascript loads) on the view when load but as you know i have to way for the response(the view) to execute this since still not present in the DOM. So I came with this solution. I just develop a method that allows me to wait for a piece HTML with timeouts and recursions and then execute the code when the HTML is render in the view.

//this is actually a service in angular, im just giving an example
    function $WaitFor(selector,callback,timeout)
    {
    var execute = function()
    {
    if(document.Selector(selector) != null)
    callback();
    else
    startTimeout()
    }

    var startTimeout = function()
    {
    setTimeout(execute, 200 || timeout)
    }

    startTimeout();

    }

And indeed the code works, it waits and execute the code successfully when the response(the view) is display. But, is that code ok? is there any another alternative that? And what about performance? Any sugestions/help you can give me??


texts: C++ compile-time checked switch 'statement'

texts:
In the project I work on there are several places where a switch statement is used on a type enum. (I know, better to use virtual functions or a visitor pattern or something, but sometimes switching on type codes is unavoidable - e.g., deserializing XML.) All of our type enums are of the simple form enum { TypeA, TypeB, TypeC, NumTypes } so it is known at compile time that all type codes for a given type are in the half-open range [0, NumTypes).

I decided to see if I could make the compiler verify that all type codes were being checked, and this is what I came up with:

// Switch.h

template <int iIndex, int iCount, class Dispatcher>
struct Switcher
{
    typename Dispatcher::ResultType
    operator()( const Dispatcher& dispatcher, int iCase ) const
    {
        if ( iCase == iIndex )
        {
            return dispatcher.template Case<iIndex>();
        }
        else
        {
            return Switcher<iIndex + 1, iCount, Dispatcher>()( dispatcher, iCase );
        }
    }
};

template <int iCount, class Dispatcher>
struct Switcher<iCount, iCount, Dispatcher>
{
    typename Dispatcher::ResultType
    operator()( const Dispatcher& dispatcher, int iCase ) const
    {
        return dispatcher.Default( iCase );
    }
};

template <int iCount, class Dispatcher>
typename Dispatcher::ResultType
Switch( const Dispatcher& dispatcher, int iCase )
{
    return Switcher<0, iCount, Dispatcher>()( dispatcher, iCase );
}

Example use:

#include "Switch.h"

#include <iostream>
#include <cassert>
#include <string>

enum MyType { TypeA, TypeB, TypeC, NumTypes };

class MyDispatcher
{
public:
    typedef std::string ResultType;

    template <int iType>
    std::string Case() const;

    std::string Default( int iType ) const;
};

template <>
std::string
MyDispatcher::Case<TypeA>() const
{
    return "TypeA";
};

template <>
std::string
MyDispatcher::Case<TypeB>() const
{
    return "TypeB";
};

template <>
std::string
MyDispatcher::Case<TypeC>() const
{
    return "TypeC";
};

std::string
MyDispatcher::Default( int iType ) const
{
    std::cout<< "ERROR: Unexpected type " << iType << std::endl;
    assert( false );
    return std::string();
}

int main() {
    MyType iType = TypeB;

    std::string zTypeName = Switch<NumTypes>( MyDispatcher(), iType );

    std::cout << "Type name: " << zTypeName << std::endl;
}

The Switcher template class will recursively instantiate versions of itself with increasing type codes, starting with zero and terminating at the iCount template parameter to the Switch function. Each instantiation will check its iIndex template parameter against the runtime iCase variable and call the dispatcher's Case<iIndex> function if it matches. The Default function will only be called if the runtime iCase variable is outside the expected range.

The key is that if any specialization of Case is missing in the dispatcher class, a linker error will be given complaining about a missing function. I know that many (most?) compilers can be set to produce warnings if not all members of an enum are handled in a switch statement, but there are too many places in the codebase (and likely in external headers) where not all cases are handled by design.

Thoughts? Any potential pitfalls? The system could be pretty easily extended to a range of enum values not starting at zero, but non-contiguous enum values would be a no-go.


texts: Authentication via LDAP and authorization via JDBC

texts:
I have a custom AuthenticationProvider for getting authentication via LDAP and authorization via JDBC. It's running but I think it's not the best way.

My custom AuthenticationProvider:

public class ADAuthenticationJDBCAuthorizationProvider implements AuthenticationProvider {

    private final ActiveDirectoryLdapAuthenticationProvider adDelegate;

    @Autowired
    private UtilisateurService utilisateurService;

    public ADAuthenticationJDBCAuthorizationProvider(ActiveDirectoryLdapAuthenticationProvider adDelegate) {
        this.adDelegate = adDelegate;
    }

    @Override
    public Authentication authenticate(Authentication authentication) {
        final Authentication a = adDelegate.authenticate(authentication);
        final String name = a.getName().toLowerCase();

        // Load additional authorities and create an Authentication object
        final Collection<GrantedAuthority> authorities = utilisateurService.loadRolesFromDatabase(name);
        final boolean isActive = utilisateurService.isActive(name);

        return new AbstractAuthenticationToken(authorities) {
            @Override
            public Object getCredentials() {
                return a.getCredentials();
            }

            @Override
            public Object getPrincipal() {
                return a.getPrincipal();
            }

            @Override
            public boolean isAuthenticated() {
                return isActive && a.isAuthenticated();
            }

            @Override
            public String getName() {
                return name;
            }

        };
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return adDelegate.supports(authentication);
    }
}

My configuration file:

public class GlobalSecurityConfig extends GlobalAuthenticationConfigurerAdapter {

    @Value("${ldap.domain}")
    private String DOMAIN;

    @Value("${ldap.url}")
    private String URL;

    @Autowired
    private JDBCUserDetailsService userDetailsService;

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(activeDirectoryLdapAuthenticationProvider()).userDetailsService(userDetailsService);
    }

    @Bean
    public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
        ActiveDirectoryLdapAuthenticationProvider adAuthenticationProvider
                = new ActiveDirectoryLdapAuthenticationProvider(DOMAIN, URL);
        adAuthenticationProvider.setConvertSubErrorCodesToExceptions(true);
        adAuthenticationProvider.setUseAuthenticationRequestCredentials(true);

    ADAuthenticationJDBCAuthorizationProvider authenticationProvider = new ADAuthenticationJDBCAuthorizationProvider(adAuthenticationProvider);

        return authenticationProvider;
    }
}

The custom UserDetailsService:

public class JDBCUserDetailsService implements UserDetailsService {

    @Autowired
    private UtilisateurService utilisateurService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final String name = username.toLowerCase();
        Collection<GrantedAuthority> authorities = utilisateurService.loadRolesFromDatabase(name);
        final boolean isActive = utilisateurService.isActive(name);

        return new User(username, "", isActive, true, true, true, authorities);
    }
}

Do you have any suggestion for a better solution?


texts:
What I have is a grocery list. Once I select a grocery by ticking the checkbox, I can select an amount for that product and a unit (unit is referred to in my below code as group). Once I am done, I click save and the values are updated in the database. But for all checkboxes that are unchecked, the values should be updated to 0. Also, if I DO select a checkbox, but I DO NOT select an amount OR a group, the values should all still be updated to 0.

The code below works flawlessly, but I think it could be written much shorter / better. Any pointers?

public function post()
{
    $checkboxes         = Input::get('checkbox');
    $checkedAmounts         = Input::get('amount');
    $checkedGroups      = Input::get('group');

    /* The below code checks if a checkbox was checked, an amount was selected and a group was selected. If any of those values are true, update the database with the values selected. */

        foreach ($checkedAmounts as $key => $value)
        {
            if($value !== '0')
            {
                Product::where('id', '=', $key) ->update(['amount' => $value]);
            }
        }

        foreach ($checkedGroups as $key => $value)
        {
            if($value !== '0')
            {
                Product::where('id', '=', $key) ->update(['group' => $value]);
            }
        }

        foreach ($checkboxes as $key => $value)
        {
            if($value !== '0')
            {
                Product::where('id', '=', $key) ->update(['selected' => '1']);
            }
        }

    /* The below code checks if a checkbox was NOT checked, an amount was NOT selected or a group was NOT selected. If ANY of those are false, update the database and set everything to 0 for that row. */

        foreach ($checkboxes as $key => $value)
        {
            if($value === '0')
            {
                Product::where('id', '=', $key) ->update(['selected' => '0']);
                Product::where('id', '=', $key) ->update(['amount' => '0']);
                Product::where('id', '=', $key) ->update(['group' => '0']);
            }
        }

        foreach ($checkedAmounts as $key => $value)
        {
            if($value === '0')
            {
                Product::where('id', '=', $key) ->update(['selected' => '0']);
                Product::where('id', '=', $key) ->update(['amount' => '0']);
                Product::where('id', '=', $key) ->update(['group' => '0']);
            }
        }

        foreach ($checkedGroups as $key => $value)
        {
            if($value === '0')
            {
                Product::where('id', '=', $key) ->update(['selected' => '0']);
                Product::where('id', '=', $key) ->update(['amount' => '0']);
                Product::where('id', '=', $key) ->update(['group' => '0']);
            }
        }

        return Redirect::to('groceries')->with('categories', Category::with('products')->orderBy('name', 'asc')->get());
}


texts:
Here is working code to get N closest points to some reference point.

Please help to improve it, specifically by commenting on my use of std algorithms and vectors/iterators manipulations.

Nearest.h

#pragma once

#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>

namespace nearest {

struct Point {
  double x;
  double y;
  double z;

  bool operator==(const Point& rhp) {
    return x == rhp.x && y == rhp.y && z == rhp.z;
  }

};

// Return N closest points to first point in vector in order
std::vector<Point> nearestN(const std::vector<Point>& points,
                            int N);

// Return N closest points to a reference point, in order - all
// within maximum distance threshold
std::vector<Point> nearestN(const std::vector<Point>& points,
                            int N,
                            const Point& reference,
                            double distanceThreshold);

}

Nearest.cpp

#include "Nearest.h"

using namespace std;

namespace nearest {

    // to print Point to cout
    std::ostream& operator<<(std::ostream &o, const nearest::Point& p) {
        o << "(" << p.x << ", " << p.y << ", " << p.z << ")" << std::endl;
        return o;
    }

    // defines sorting order for points
    struct ByDistance {
        const Point& origin;

        bool operator()(const Point& lp, const Point& rp) {
            return dist(origin, lp) < dist(origin, rp);
        }

        static double dist(const Point& lp, const Point& rp){
            double xs = (lp.x - rp.x) * (lp.x - rp.x);
            double ys = (lp.y - rp.y) * (lp.y - rp.y);
            double zs = (lp.z - rp.z) * (lp.z - rp.z);
            return sqrt(xs + ys + zs);
        }
    };

    vector<Point> nearestN(const vector<Point>& points, int N) {
        if (points.size() == 0) {
            vector<Point> empty;
            return empty;
        }
        return nearestN(points, N, points[0], INFINITY);
    }

    vector<Point> nearestN(const vector<Point>& points,
                           int N,
                           const Point& reference,
                           double distanceThreshold) {

        vector<Point> temp;
        temp.insert(temp.begin(), points.begin(), points.end());

        // filtering vector to remove all points far then distance from reference
        temp.erase(remove_if(temp.begin(),
                             temp.end(),
                             [&reference, distanceThreshold](Point& p){ return ByDistance::dist(p, reference) > distanceThreshold; }),
                   temp.end());

        ByDistance distance = {reference};
        sort(temp.begin(), temp.end(), distance);

        auto sz = min(static_cast<int>(temp.size()), N);
        vector<Point> result(sz);
        copy_n(temp.begin(), sz, result.begin());
        return result;
    }
}


texts: Passing a string, around quotation marks into another string, all in a mutli line string

texts:
the title might sound confusing but i have a multi line string which is my source code to be compiled. Inside that string i have a messagebox that will display another string, inside that string i want to pass a string. It got very confusing with all the quotation marks but i finally got it working:

        string source = @"
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Threading.Tasks;
        using System.Windows.Forms;

        namespace Compiler
            {
                static class Program
                {
                    static void Main()
                    {
                        MessageBox.Show(""this is my message: "" + """ + txtMessage.Text + @"""" + @");
                    }
                }
            }";

This returns: MessageBox.Show("this is my message: " + "Hello"); providing the value in txtMessage = Hello

So this works but is very messy, also if i pass something like "hi, into txtMessage that will mess it up because of the quotation mark, kinda like a sql injection. Would there be a better way to do this?


texts:
I have a gridview with CheckBox inside it.  When the user selects a row and clicks
on a button, a message is sent for the specific user.

How can this be optimized?

protected void btnSendSMSForSpeceficUser_Click(object sender, EventArgs e)
    {
        using (NoavaranModel.NoavaranEntities1 dbContext=new NoavaranModel.NoavaranEntities1())
        {
            int userId = Int32.Parse(Session["UserId"].ToString());
            var query = (from p in dbContext.Users
                         where p.UserId == userId
                         select p.CountOfSMS).FirstOrDefault();
            var query2 = (from p in dbContext.Users
                          where p.UserId == userId
                          select p).FirstOrDefault();
            int j = 0,sendCount=0;
            for (int i = 0; i <= grdStudents.Rows.Count - 1; i++)
            {
                string MobileNumbers = grdStudents.Rows[i].Cells[2].Text;
                int stID = Int32.Parse(grdStudents.Rows[i].Cells[0].Text);
                var query3 = (from p in dbContext.Students
                              where p.Id == stID
                              where p.IsRecivedSMS==false
                              select p).FirstOrDefault();
                GridViewRow row = grdStudents.Rows[i];
                CheckBox Ckbox = (CheckBox)row.FindControl("chkSelectStudents");
                if (Ckbox.Checked)
                {
                    j++;
                    if (j <= query) {
                        sendCount++;
                        Utility.SendMessageForStudents(MobileNumbers, txtMessage.Text);
                        query3.IsRecivedSMS = true;
                    }
                }
            }
            query2.CountOfSMS = query.Value - sendCount;
            dbContext.SaveChanges();
            ListBox1.Items.Add(sendCount.ToString());
        }
    }


texts:
I'm trying to implement a really basic queue (as an array) in my computer science class and want some feedback on my logic/methodology.  the queue is not circular, it just includes the basic functions of enqueue/dequeue (along with the other obvious ones.) Please criticize and give feedback so I can educate myself on the best practices.

I was given this assignment as part of an entry level CS class. I was told not to make a circular queue. So this of course is not an efficient model by any means.. just a rough idea of what queues do.

what the code should do: users can add to the queue by moving forward the last element of the array, and "remove" items (they kinda still float around in memory though. remove isn't a great word) by moving the first element forward.

Class declaration:

class queueList
{
private:
    int *list;
    int queueFront;
    int queueRear;
    int maxSize;

public:
    void enqueue(const int &x);
    bool isEmpty();
    bool isFull();
    void dequeue();
    queueList(const int &x);
    int front();
    int back();
};

class implementation:

queueList::queueList(const int &x)
{
    list = new int[x];
    queueRear = 0;
    queueFront = 0;
    maxSize = x;
}
void queueList::enqueue(const int &x)
{
    if (!isFull())
    {
        list[queueRear] = x;
        //cout << list[queueRear] << endl;
        queueRear++;
    }
}
bool queueList::isEmpty()
{
    return (queueFront == queueRear);
}
bool queueList::isFull()
{
    return (queueRear == maxSize);
}

void queueList::dequeue()
{
    if (!isEmpty())
    {
        list[queueFront] = 0;
        cout << list[queueFront] << endl;
        queueFront++;
    }
}

int queueList::front()
{
    return list[queueFront];
}

int queueList::back()
{
    return list[queueRear];
}
```


texts:
I have a method in Scala that checks if a game board is full or not. To speed this method up, I return inside the nested for loop to break out of both of them and stop execution. How would I achieve this in Scala in an idiomatic way?

def isFull: Boolean = {
  for (x <- getGrid.indices) {
    for (y <- getGrid(x).indices) {
      if (getGrid(x)(y).getState.isInstanceOf[Undecided]) {
        return false
      }
    }
  }
  true
}


texts: Encapsulating simple license backup to a disk

texts:
I am enapsulating my license backup to disk, using an interface ILicenseProvider and the implementation is DiskLicenseProvider. Also i am throwing an unchecked exception LicenseProviderException which wraps the checked exceptions in order to enable a central point of exception handling. Kindly review my code. What changes should I make?

public class LicenseProviderException extends RuntimeException {
    public LicenseProviderException(String message) {
        super(message);
    }
}

public class DiskLicenseProvider implements ILicenseProvider {

    private static final String APP_DIRECTORY = "test";
    private static final String LICENSE_FILENAME = "license.txt";
    private static final String TAG = DiskLicenseProvider.class.getSimpleName();
    private File appDirectory = new File(Environment.getExternalStorageDirectory(), APP_DIRECTORY);
    private File licenseFile = new File(appDirectory, LICENSE_FILENAME);

    @Override
    public boolean licenseExists() {
        return (appDirectory.exists() && licenseFile.exists() && licenseFile.length() > 0);
    }

    @Override
    public String getLicense() throws LicenseProviderException {
        StringBuilder builder = new StringBuilder();
        if (licenseExists()) {
            BufferedReader bufferedReader;
            try {
                bufferedReader = new BufferedReader(new FileReader(licenseFile));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    builder.append(line);
                }
                bufferedReader.close();
            } catch (FileNotFoundException e) {
                Log.d(TAG, "getLicense() called");
                throw new LicenseProviderException("Unable to find license file");
            } catch (IOException e) {
                Log.d(TAG, "getLicense() called");
                throw new LicenseProviderException("Unable to read license file");
            }

        }
        return builder.toString();
    }

    @Override
    public void saveLicense(String license) throws LicenseProviderException{
        if (!appDirectory.exists()) {
            if (!appDirectory.mkdirs()) {
                throw new LicenseProviderException("Unable to create application directory");
            }
        }

        try {
            FileWriter fileWriter = new FileWriter(licenseFile);
            fileWriter.write(license);
            fileWriter.close();
        } catch (IOException e) {
            Log.d(TAG, "saveLicense() called with: license = [" + license + "]");
            throw new LicenseProviderException("Unable to save license");
        }

    }

}

public interface ILicenseProvider {
    boolean licenseExists();

    String getLicense();

    void saveLicense(String license);

}


texts: Improving the speed of loop in javascript for objects

texts:
So I have a loop that works great, but doing some testing I notice it is a bit slow. I get an average time within the loop of about 0.11 seconds. Include that with some arrays containing a length of over 100 and the time starts making a big difference. So I mainly want to improve the speed of the loop without compromising the functionality it already has (which is taking a JSON object/array and turning it into an html format). Below is the code along with the function that is called within the loop.

let replacements = '';
let ind = 0;
for (let w in obj[key]) {
    if (Array.isArray(obj[key])) {
        if (Array.isArray(obj[key][w])) {
            if (obj[key].length > 10) {
                replacements += "Array(" + obj[key].length + ")"
                break
            }
            replacements += ((ind == 0) ? "Array(" : ", Array(") + obj[key][w].length + ")";
        } else {
            if (typeof obj[key][w] === 'object') {
                replacements += ((ind == 0) ? "" : ", ") + "{...}";
            } else {
                replacements += ((ind == 0) ? "" : ", ") + ObjectString(obj[key][w], "preview");
            }
        }
    } else {
        if (Array.isArray(obj[key][w]) || typeof obj[key][w] === 'object') {
            replacements += ((ind == 0) ? "" : ", ") + w + ": " + ((Array.isArray(obj[key][w])) ? "[...]" : "{...}");
        } else {
            replacements += ((ind == 0) ? "" : ", ") + w + ": ";
            replacements += ObjectString(obj[key][w], "preview");
        }
    }
    ind++;
}

function ObjectString(obj, type) { //~0.001-0.003 seconds
    let objString = obj;
    if (typeof objString == "string" && !objString.match(/<.*?>/g))
        objString = "\"" + objString + "\"";
    else if (/<.*?>/g.test(objString))
        objString = ((type == "normal") ? "
" + process(objString).replace(/</g, '&lt;').replace(/>/g, '&gt;') + "
" + objString : "\"...\"");
    else if (typeof objString == "number" || typeof objString == "boolean")
        objString = "" + objString + "";

    return objString
}

function process(str) {//~0.001 seconds

    var div = document.createElement('div');
    div.innerHTML = str.trim();

    return format(div, 0).innerHTML;
}

Hopefully this can be optimized to increase its speed, but if it can't then I would at least like some help to clean it up as I am sure this isn't the most effective way to do it. Thanks!

Edit: added the process function that was previous missing. Also for clarification I am using regular JSON arrays and objects that usually exceed 100 objects in the array. If you want an example of what that data could look like https://en.wikipedia.org/wiki/GeoJSON#Example has a good structure of some of the data I am parsing (containing both objects and arrays).


texts: Sanitising user inputs and user inputted data outputs

texts:
I am creating a function for sanitising user inputs and user inputted data outputs.

Please offer advise on any improvements which could be made:

function cleanse($input) {

    $search = array(
        '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
        '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
        '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
        '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
    );

    $output = preg_replace($search, '', $input);
    return $output;
}

function sanitise($input) {
    if (is_array($input)) {
        foreach($input as $var=>$val) {
            $output[$var] = sanitize($val);
        }
    } else {
        $input  = cleanse($input);
        $output = htmlspecialchars($input, ENT_QUOTES,'UTF-8',false);
    }
    return $output;
}


texts: Write MD5 hashes to file for all files in a directory tree

texts:
I'm ultimately trying to compare the MD5 hashes for files in two disparate directory trees to see if files are missing from one directory or the other.

More broadly, I'm pushing photos from my DSLR camera to Google Drive, and need to know which files need to be synced up. Pictures from my phone are automatically being synced with Google Drive, and I'd also like to detect which ones I need to sync down. I have separate scripts for getting the MD5 hashes from Google Drive and for comparing the MD5 hashes to see which files need to be synced, up or down.

#!/usr/bin/python

import os
import sys
import hashlib
import csv

src_dir = '/Volumes/Archive/Pictures'

with open('checksums_archive.tsv', 'wb') as fout:
    writer = csv.writer(fout, delimiter='\t', quotechar='\"', quoting=csv.QUOTE_MINIMAL)

    for root, subdirs, files in os.walk(src_dir):
        for file in files:
            file_path = os.path.join(root, file)
            checksum = hashlib.md5(open(file_path, 'rb').read()).hexdigest()

            writer.writerow([root, file, checksum])


texts:
(See the next iteration.)

Given a positive \$N\$, the following class generates all possible non-empty sets \$A \in \mathcal{P}(\{0, 1, \dots, N - 1\})\$ in lexicographic order. Also, it provides a method that can be used to copy a combination to a list. I am seeking primarily guidance regarding the API design of the class.

CombinationGenerator.java:

package net.coderodde.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class CombinationGenerator<T> {

    /**
     * The array holding indices to elements considered to be in a combination.
     * Only the first {@code k} indices are considered actually to encode an
     * item in a combination.
     */
    private final int[] indexArray;

    /**
     * The current number of items in a combination.
     */
    private int k;

    public CombinationGenerator(int totalNumberOfItems) {
        checkTotalNumberOfItems(totalNumberOfItems);
        this.indexArray = new int[totalNumberOfItems];
    }

    public boolean generateNextCombination() {
        if (k == 0) {
            k = 1;
            return true;
        }

        if (indexArray[k - 1] < indexArray.length - 1) {
            indexArray[k - 1]++;
            return true;
        }

        for (int i = k - 2; i >= 0; --i) {
            if (indexArray[i] < indexArray[i + 1] - 1) {
                indexArray[i]++;

                for (int j = i + 1; j < k; ++j) {
                    indexArray[j] = indexArray[j - 1] + 1;
                }

                return true;
            }
        }

        ++k;

        if (k > indexArray.length) {
            return false;
        }

        for (int i = 0; i < k; ++i) {
            indexArray[i] = i;
        }

        return true;
    }

    public void loadCombination(List<T> all, List<T> target) {
        Objects.requireNonNull(all, "The list being sampled is null.");
        Objects.requireNonNull(target,
                               "The list to hold the combination is null.");

        target.clear();

        for (int i = 0; i < k; ++i) {
            target.add(all.get(indexArray[i]));
        }
    }

    private void checkTotalNumberOfItems(int totalNumberOfItems) {
        if (totalNumberOfItems < 1) {
            throw new IllegalArgumentException(
                    "Total number of items is illegal: " +
                    totalNumberOfItems + ".");
        }
    }

    public static void main(final String... args) {
        List<String> all = new ArrayList<>();

        all.add("A");
        all.add("B");
        all.add("C");
        all.add("D");
        all.add("E");

        int row = 1;
        List<String> combinationHolder = new ArrayList<>();
        CombinationGenerator generator = new CombinationGenerator(all.size());

        while (generator.generateNextCombination()) {
            generator.loadCombination(all, combinationHolder);
            System.out.printf("%2d: %s\n", row++, combinationHolder);
        }
    }
}

CombinationGeneratorTest.java:

package net.coderodde.util;

import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;

public class CombinationGeneratorTest {

    private CombinationGenerator generator;

    @Test
    public void test() {
        List<String> all = new ArrayList<>();
        List<String> target = new ArrayList<>();

        all.add("A");
        all.add("B");
        all.add("C");
        all.add("D");
        all.add("E");

        for (int i = 1; i <= all.size(); ++i) {
            int combinations = pow2(i) - 1;
            int count = 0;

            generator = new CombinationGenerator(i);

            while (generator.generateNextCombination()) {
                count++;
            }

            assertEquals(combinations, count);
        }
    }

    private static int pow2(int exp) {
        return 1 << exp;
    }
}


texts: Converting xy coordinates to theta without discontinutities

texts:
This one is, or rather, should be, fairly simple. I have a list of tuples of XY positions, and am trying to pull out angles relative to the origin from it. However, unlike atan2 / friends, I want it to be continuous, in other words not wrapping. I know (and am assuming) that the differences between successive XY coordinates are small, and that there is a minimum radius. (In other words, it should pick the multiple of \$2\pi\$ that makes the difference between the previous angle and the current angle the smallest.)

Currently, this is the relevant snippet:

thetas = [math.atan2(coords[0][1], coords[0][0])]
prev = thetas[0]
for index in range(1, len(coords)):
    coord = coords[index]
    theta = math.atan2(coord[1], coord[0]) + (prev // (2*math.pi)) * (2 * math.pi)
    while theta - prev > math.pi:
        theta -= 2*math.pi
    while prev - theta > math.pi:
        theta += 2*math.pi
    assert abs(theta - prev) < math.pi/2
    thetas.append(theta)
    prev = theta

However, it's slow, and I doubt it's Pythonic. It's also doing a lot of "magic", for lack of a better word. Any suggestions for improvement?

Line profiler results here.


texts:
I want to get distinct of two columns from an SQL table. Can I optimize this query?

create TABLE #Temporary_tbl
(
    ProductColour VARCHAR(50),
    ProductSize VARCHAR(20),
)

insert into #Temporary_tbl (ProductColour)
select distinct productcolour
from shoptransfer

insert into #Temporary_tbl (ProductSize)
select distinct ProductSize
from shoptransfer

select * from #Temporary_tbl


texts: Countdown module that hides an element when a specified date is reached

texts:
I have the following piece of code which hides an element when a specified date was reached. I would like to get some tips about do's and don'ts.

Specifically, I'm interested in:

improvements brought to this code
avoid bad practices

And whatever you guys consider I should be careful about.

var Timer = (function(){
    var $el = $('#element');

    function count() {
        setInterval(function() {
            check();
        }, 1000);
    }

    function hide() {
        $el.hide();
    }

    function check() {
        var currentDate = new Date();
        var endingDate = new Date("July 25, 2016 11:06:00");

        if (currentDate.getTime() >= endingDate.getTime()) {
            hide();
        }
    }

    return {
        count: count
    };
})();

Timer.count();


texts:
This is a hackerank easy question.

  You are given a list of N people who are attending ACM-ICPC World
  Finals. Each of them are either well versed in a topic or they are
  not. Find out the maximum number of topics a 2-person team can know.
  And also find out how many teams can know that maximum number of
  topics.

  Note Suppose a, b, and c are three different people,
  then (a,b) and (b,c) are counted as two different
  teams.

  Input Format

  The first line contains two integers, N and M, separated by a single
  space, where N represents the number of people, and M represents the
  number of topics. N lines follow. Each line contains a binary string
  of length M If the i'th line's j'th character is 1, then the i'th
  person knows the j'th topic; otherwise, he doesn't know the topic.

  Constraints

  2≤N≤500
   1≤M≤500

  Output Format

  On the first line, print the maximum number of topics a 2-person team
  can know. On the second line, print the number of 2-person teams that
  can know the maximum number of topics.

Here is what I wrote:

Scanner console = new Scanner(System.in);
int n = console.nextInt();
int m = console.nextInt();
console.nextLine();
String[] arr = new String[n];
for(int p=0; p<n; p++){
    String s = console.nextLine();
    arr[p] = s;
}

Map<Integer, List<List<Integer>>> counts = new HashMap<>();

for(int i = 0; i< n-1; i++){

    String str=arr[i];

    for(int j=i+1; j<n; j++){

        String secondStr = arr[j];

        int count = 0;
        for(int k=0; k<m; k++){

            if(str.charAt(k) == '1' || secondStr.charAt(k) == '1'){
                count ++;
            }

        }

        List<Integer> mapping = new ArrayList<>();
        mapping.add(i+1);
        mapping.add(j+1);

        if(counts.containsKey(count)){
            List<List<Integer>> existingMappings = counts.get(count);
            existingMappings.add(mapping);
            counts.put(count, existingMappings);
        }else{
            List<List<Integer>> newMappings = new ArrayList<>();
            newMappings.add(mapping);
            counts.put(count, newMappings);
        }

    }
}

int max = counts.keySet().stream().mapToInt(Integer::valueOf).max().orElse(0);

int occurences = counts.get(max).size();

System.out.println(max);
System.out.println(occurences);

This worked and passed the challenge. But it has a code smell: Too many loops and even inner loops. Any improvements?


texts: Creating a function with limited number of args in python

texts:
I am learning programming, and I am thinking how to improve this code in a more pythonic way.

I have a function with number of arguments. However, any caller of the function can specify the arguments, and depending on the arguments given, I will return the dictionary. The given arguments must be only from the listed arguments.

The code that I have below has so much duplication (I remove carPower, carTime and carLease however it will do the same if/else part)
How can I improve this?

def creating_result(my_struct,
                carColour=None,
                carPrice=None,
                carGas=None,
                carBrand=None,
                carSpeed=None,
                carOwner=None,
                carPower=None,
                carTime=None,
                carLease=None,
                carEngine=None,
                carType=None
                ):

     if carColour and isinstance(carColour, list):
        my_struct["carColour"] = { "thekey" : carColour}
     elif carColour:
        my_struct["carColour"] = carColour

     if carPrice and isinstance(carPrice, list):
        my_struct["carPrice"] = { "thekey" : carPrice}
     elif carPrice:
        my_struct["carPrice"] = carPrice

     if carGas and isinstance(carGas, list):
        my_struct["carGas"] = { "thekey" : carGas}
     elif carGas:
        my_struct["carGas"] = carGas

     if carBrand and isinstance(carBrand, list):
        my_struct["carBrand"] = { "thekey" : carBrand}
     elif carBrand:
        my_struct["carBrand"] = carBrand

     if carSpeed and isinstance(carSpeed, list):
        my_struct["carSpeed"] = { "thekey" : carSpeed}
     elif carSpeed:
        my_struct["carSpeed"] = carSpeed

     if carEngine:
        my_struct["carEngine"] = carEngine

     if carPrice:
        my_struct["carPrice"] = carPrice

     if carType:
        my_struct["carType"] = carType

     print "my_struct is ", my_struct

if __name__ == "__main__":
    # test 1st caller
    my_dict = {}
    creating_result(my_dict, carPrice=1, carColour="red")

    # test 2nd caller
    my_dict = {}
    creating_result(my_dict, carSpeed="200", carType="SUV", carPrice=300)

In case I can not change the list of arguments of the function above, how can I improve the (if/else) of the function above?


texts: Checking if a booking can be cancelled or not based on three conditions

texts:
I have 2 if-else statements that checks whether a booking(object mb) can be cancelled or not. If the current user is an admin or department admin, the booking can be cancelled. However, if the booking has been cancelled, of course, it absolutely cannot be cancelled by anyone.

What I am worried about if the if-else statements can be improved further. Any help would be useful.

foreach (var ub in usersBookings)
{
    MyBookingModel mb = new MyBookingModel();
    mb.bookId = ub.bookingId.ToString() + "+" + ub.startDateTime.ToString();
    mb.bookDate = ub.startDateTime.ToString("dd/MM/yyyy");
    mb.bookSlot = ub.startDateTime.ToString("HH:mm") + " - " + ub.endDateTime.ToString("HH:mm");
    mb.facilityName = ub.facilityName;
    mb.status = ub.bookingStatus.Trim();
    mb.startDateTime = ub.startDateTime.ToString("yyyy-MM-dd HH:mm:00");

    mb.canCancel = false;

    if (mb.status == "Cancelled")
    {
        //absolute. if mb.status == "Cancelled", mb.canCancel is "false"
        mb.canCancel = false;
        goto add_object;
    }

    if (deptAdmin == true || isAdmin == true)
    {
        mb.canCancel = true;
    }

add_object:
    myBookings.Add(mb);
}


texts:
The problem is to find all divisors of a given integer n.

(It may be better to implement a true prime generator, rather than a fixed set, as discussed with examples here, but that was not my immediate concern. Also, I am aware that there are much faster algorithms to generate fixed number of prime numbers—I am avoiding them until I fully understand the algorithm.)

import functools
import itertools
import operator

def prime_generator(n):
    """
    Sieve of Eratosthenes
    Create a candidate list within which non-primes will be
    marked as None.
    """
    cand = [i for i in range(3, n + 1, 2)]
    end = int(n ** 0.5) // 2

    # Loop over candidates (cand), marking out each multiple.
    for i in range(end):
        if cand[i]:
            cand[cand[i] + i::cand[i]] = [None] * (
                (n // cand[i]) - (n // (2 * cand[i])) - 1)

    # Filter out non-primes and return the list.
    return [2] + [i for i in cand if i]

primes_list = prime_generator(100000)

def factorize(n):
    prime_multiples = []
    for item in primes_list:
        if item > n:
            break
        else:
            while n > 1:
                if n % item == 0:
                    n //= item
                    prime_multiples.append(item)
                else:
                    break
    return prime_multiples

def calculate_divisors(n):
    prime_multiples_list = factorize(n)

    """
    construct unique combinations
    A, B, B, C --> A, B, C, AB, AC, BB, BC, ABC, ABB, BBC
    """
    unique_combinations = set()
    for i in range(1, len(prime_multiples_list)):
        unique_combinations.update(
            set(itertools.combinations(prime_multiples_list, i)))

    # multiply elements of each unique combination
    combination_product = list(functools.reduce(operator.mul, i)
                               for i in unique_combinations)
    combination_product.sort()

    return combination_product

print(calculate_divisors(12500))
>>> [2, 4, 5, 10, 20, 25, 50, 100, 125, 250, 500, 625, 1250, 2500, 3125, 6250]

In the context of the above algorithm:

Can I shorten factorize function? (For example, I couldn’t find a way to turn into a list comprehension. I suspect there should be a shorthand via functoolsor itertools.)
Is there a more Pythonic implementation of calculate_divisors function?