texts: Toggle classes and aria attributes for panels, only one panel open at any time

texts:
I am scrapping the use of JavaScript libraries like jQuery for vanilla javascript. It would be good for any suggestions of improvement I could make for the following bit of code:

I have a collection of panels
Each panel contains a button and a content div

I require the ability to toggle on/off for each panel, but only one panel can be open or active at any one time.

I'm adding classes and removing classes
I'm adding ARIA properties and removing ARIA properties

My JavaScript works just fine, however, I am positive big improvements could be made and very interested for best approaches.

Example JavaScript:

function panel() {

    // Get elements
    var panel = document.getElementsByClassName('Panel');
    var button = document.getElementsByClassName('Panel-button');
    var content = document.getElementsByClassName('Panel-content');

    var i;

    // Init
    for (i = 0; i < panel.length; i++) {
        button[i].setAttribute('aria-expanded', false);
        content[i].setAttribute('aria-hidden', true);
    }

    // Reset
    var panelReset = function() {

        for (i = 0; i < panel.length; i++) {

            button[i].classList.remove('Panel-button--selected');
            button[i].setAttribute('aria-expanded', false);

            content[i].classList.add('JS-hidden');
            content[i].setAttribute('aria-hidden', true);

        }

    };

    // Click
    var panelClick = function() {

        if (this.classList.contains('Panel-button--selected')) {

            this.classList.remove('Panel-button--selected');
            this.setAttribute('aria-expanded', false);

            this.nextElementSibling.classList.add('JS-hidden');
            this.nextElementSibling.setAttribute('aria-hidden', true);

        } else {

            panelReset();

            this.classList.add('Panel-button--selected');
            this.setAttribute('aria-expanded', true);

            this.nextElementSibling.classList.remove('JS-hidden');
            this.nextElementSibling.setAttribute('aria-hidden', false);

        }

    };

    for (i = 0; i < button.length; i++) {
        button[i].onclick = panelClick;
    }

}

// Dom ready
document.addEventListener('DOMContentLoaded', function() {
  panel();
});

Example of some of the HTML:

  <button class="Panel-button" aria-controls="one">
    Button 1
  </button>

Content 1

  <button class="Panel-button" aria-controls="two">
    Button 2
  </button>

Content 2

  <button class="Panel-button" aria-controls="three">
    Button 3
  </button>

Content 3


texts: Conway's Game of Life Java Implementation

texts:
Keep state the same if it doesn't fall in the following conditions:

Change to 2 if there are exactly 2 ones in the neighbors
Change to 3 if there are more than 2 ones in the neighbors

It is also wrapping around so neighbors can be cyclic.

I wrote a basic structure and modularized it to individual functions. I wish to understand better coding techniques and how I can improve.

package code.Misc;
public class changeStateGame {
public static void main(String args[]){

    int current[][] = {
            {0,0,0,0,0,0,0},
            {0,0,0,0,1,0,0},
            {0,0,0,1,1,0,0},
            {0,0,1,1,0,0,0},
            {0,0,0,0,0,0,0}
    };
    int aux [][] = new int [current.length][current[0].length];

    for(int i=0;i<current.length;i++){
        for(int j=0;j<current[0].length;j++){
            aux[i][j]=0;
        }
    }

    System.out.println("Current State");
    printStateGame(current);
    System.out.println("Changed State");
    printStateGame(changeState(current,aux,0,aux[0].length));

}

public static void printStateGame(int a[][]){
    for(int i=0;i<a.length;i++){
        for(int j=0;j<a[0].length;j++){
            System.out.print(a[i][j]+" ");
        }
        System.out.println();
    }
}

public static int [][] changeState(int c[][],int a[][], int row, int col){

    for(int i=0;i<a.length;i++){
        for(int j=0;j<a[0].length;j++){
            a[i][j]=checkNeighbors(c,i,j);
        }
    }
    return a;
}

public static int checkNeighbors(int a[][],int row,int col){

        int neighborCount = 0;
        for(int i=row-1;i<row+1;i++){
            for(int j=col-1;j<col+1;j++){

                        if (i < 0)
                            i = a.length - 1;
                        if (j < 0)
                            j = a[0].length - 1;
                        if (i == a.length)
                            i = 0;
                        if (j == a[0].length)
                            j = 0;
                        if(i==row){
                            if(j==col){
                                continue;
                            }
                        }
                        if(j==col){
                            if(i==row){
                                continue;
                            }
                        }
                        neighborCount += checkElement(a[i][j]);

            }
        }
    return modifyElement(a[row][col],neighborCount);
}
public static int checkElement(int a){
    if(a==1)
        return 1;
    else
        return 0;
}

public static int modifyElement(int a, int count){
    if(count<2){
        return a;
    }
    else if (count == 2){
        return 2;
    }
    else {
        return 3;
    }
}
}


texts: Scroll to top and addClass onClick - then removeClass on .mouseout

texts:
The function is to click a button, the browser window then scrolls to the top of the page, then a class is added to a menu item (with CSS to make the sub menu appear). Then when the cursor leaves the sub menu, the class is removed to allow the sub menu to disappear.

Can I make the following code shorter or more efficient? I have written it to work with Joomla and jQuery with no conflict.

jQuery(document).ready(function(){
    jQuery("#instruct-us-readmore").click(function(){
        jQuery('html, body').animate({scrollTop:0}, 800);
        setTimeout(
        function() {
            jQuery("#iceMenu_144 ul.sub_level_1").addClass("instruct-button-click");
        },950);

     });
});

  jQuery(document).ready(function(){
        jQuery("#iceMenu_144 ul.sub_level_1").mouseleave(function(){
            jQuery("#iceMenu_144 ul.sub_level_1").removeClass("instruct-button-click");
    });
      });


texts: Common interface with different return types

texts:
I am creating a small app working on file system. The user can choose a directory and than, application get one of the possible result (examples):

return number of lines in all *.java files
return number of lines in all *.java files without comments
return number of all classes
return number of ifs etc...

Because I want to follow the single responsibility principle, and because all these functionalities have something in common, I want to create one class for each functionality (using commons.io DirectoryWalker) under a common interface. That's why I find such an interface useful:

**
 * Common interface for counting classes (lines, words, classes, etc...)
 */
public interface Counter {
    /**
     * count required things starting from startDirectory, recursively or not,
     * and consider only specified extensions
     */
    int count(File startDirectory, boolean recursive, List<String> fileExtensions);
    int count(File startDirectory, boolean recursive);
}

Now, the user can simply create some collection with counters, create and add new counter easily, iterate etc.

Questions:

Of course it is just a simplification, but do you think that the main idea of using an interface here is reasonable?
Maybe I will have some methods which will return something different than int - for example, Map with pairs, or a list of the ten longest files. In this case my interface is not correct. What should I do in such case? Maybe the interface's method should return Object like this:

Object count(File startDirectory, boolean recursive);

But this seems bad to me as it will lead to some unfriendly casting when parsing the returned value (Object). I can create some special DTO object like the below which will contain all possible "answers":

public class CounterDTO {
    public int numerOfLines; // used for counters counting lines
    public int numberOfIfs;  // used for counters counting if statements
    public Map<File, Integer> linesInFiles;  // ... File -> number of lines
    public List<File> longestFiles; // used for indicating files with maximal number of lines
    // and so on...
}

Then the interface method would look like:

CounterDTO count(File startDirectory, boolean recursive);

Is this OK or is there a better way?


texts:
I have moved all my web-server code dealing with user management into a single Node.js module that I pasted below. I have spent time polishing it, and churned it through JSHint. I am generally happy with the code, except for the error handling. I find it clunky at best.

How can I improve error handling in the following code? Are there design or API guidelines I have not followed?

// ???
// Deal with the case where an admin no longer has admin rights, but still has a session open

var server = require('./server.js').server;
var User = require('./database.js').User;

// Define the user API
var API = {
    list: [list, 'private'],
    login: [login, 'public'],
    logout: [logout, 'private'],
    add: [add, 'admin'],
    remove: [remove, 'admin'],
    edit: [edit, 'admin']
};

// Attach path handlers
for(var label in API) {
    var denied = 'Permission denied';

    var wrapper = (function (label) {
        return function (req, res) {
            var callback = API[label][0];
            var permission = API[label][1];

            if(!req.session) {
                if(permission !== 'public') {
                    res.send(denied);
                    return;
                }
            } else if((permission === 'admin') && (req.session.rights !== 'Administrator')) {
                res.send(denied);
                return;
            }

            callback(req, res);
        };
    }(label));

    server.post('/user/' + label, wrapper);
}

function list(req, res) {
    User.find({}, null, {sort: {username: 1}}, function (err, users) {
        res.send(users);
    });
}

function login(req, res) {
    var errorMessage = 'Invalid user/password combination';

    find(req.body.username, function(err, user) {
        if(printError(err)) {
            return;
        }

        // Check we have a user
        if(!user) {
            res.send(errorMessage);
            return;
        }

        // Check for a username/password match
        user.comparePassword(req.body.password, function(err, isMatch) {
            if(printError(err)) {
                return;
            }

            if(isMatch) {
                // Populate the session cookie
                req.session.username = user.username;
                req.session.rights = user.rights;

                res.send('OK');
            } else {
                res.send(errorMessage);
            }
        });
    });
}

function logout(req, res) {
    // Clear session
    req.session.username = undefined;
    req.session.rights = undefined;
    res.send('OK');
}

function add(req, res) {
    find(req.body.username, function (err, user) {
        if(user) {
            res.send('The user already exists');
        } else {
            new User(req.body).save(function (err) {
                if(printError(err)) {
                    return;
                }

                res.send('OK');
            });
        }
    });
}

function remove(req, res) {
    find(req.body.username, function (err, user) {
        user.remove(function (err) {
            if(printError(err)) {
                return;
            }

            res.send('OK');
        });
    });
}

function edit(req, res) {
    find(req.body.username, function (err, user) {
        if(printError(err)) {
            return;
        }

        // Populate username and rights
        user.username = req.body.user.username;
        user.rights = req.body.user.rights;

        // Only update nonempty passwords
        if(req.body.user.password !== '') {
            user.password = req.body.user.password;
        }

        user.save(function(err) {
            if(printError(err)) {
                return;
            }

            res.send('OK');
        });
    });
}

function find(username, callback) {
    User.findOne({
        username: username
    }, callback);
}

function printError(err) {
    if(err) {
        console.error('ERROR: ', err.message);
        // console.trace();
    }

    return err;
}


texts:
How can this algorithm be improved? I mean, a list with 3000 items takes about 5 seconds to sort, according to Sublime Text. Using Python's sorted function is immediate.

from random import randint

def bubble_sort(iterable):
    while True:
        corrected = False
        for item in range(0, len(iterable) - 1):
            if iterable[item] > iterable[item + 1]:
                iterable[item], iterable[item + 1] = iterable[item + 1], iterable[item]
                corrected = True
        if not corrected:
            return iterable

if __name__ == '__main__':
    random_list = [randint(0, 100) for _ in range(3000)]
    print(bubble_sort(random_list))


texts: Finding the right structure for my application

texts:
I have three different types of XML files (structure) which I would like to import into a database.

Every hour a cronjob calls my import.php with a specific XML file type as a parameter.

The import script includes a bootstrap.php (AutoLoader, Setup Doctrine DB Connection) and puts all files matching the name convention of this type in an array and calls a static method for this class.

Simplified code (import.php):

<?php
require_once("bootstrap.php");

function getFiles($pattern)
{
    $fileList = NULL;
    foreach( glob('xml/*'.$pattern.'.xml') as $filename )
    {
        $fileList[] = $filename;
    }

    return $fileList;
}

switch($xmlType)
{
    case "TypeA":
    TypeA::importFeed(getFiles($xmlType));
    break;

case "TypeB":
    TypeB::importFeed(getFiles($xmlType));
    break;

case "TypeC":
    TypeC::importFeed(getFiles($xmlType));
    break;
}

Currently, the classes (TypeA, TypeB, TypeC) contain no other method except importFeed.

Inside importFeed, only 2 things are equal in each class:

Getting the entityManager (Doctrine) by calling $em = app::getEm();
Convert XML into SimpleXMLElement using my parser class $feedObj = Parser::xmlToObject($xmlFile);

Everything else in importFeed differs from class to class because of the different XML types. Only a few tasks repeating e.g. check if an entity already exists in the database.

My first thought was creating a Helper class for this and some other repeating tasks I also need outside the import-script in this application.

But I'm not sure if this helper class should be a normal, "static" or "singleton" class.

The helper-methods doesn't need a specific object instance so static-methods would a good choice. But in some methods I need access to the DB and I do not wont to call app::getEm(); in every method because I don't think this is a good/clean solution.

At this point I challenged my current application design and read a lot of articles about this. The point is the application is not large and it should not be so using a Framework like Symfony is completely exaggerated - nonetheless I want a good solution.

All three classes (TypeA/B/C) have the same function that looks like this:

public static function importFeed($xmlFiles)
{
   $em = \App::getEm();
   foreach($xmlFiles as $xmlFile)
   {
      try
      {
         $feedObj = Parser::xmlToObject($xmlFile);
         ...import xml data to database - differns ...
      }
      catch(\Exception $e)
      {
         ....
      }
   }
}

Only the "..." area differs a lot because of the different XML structure but this part isn't really important for the question. In short: A Doctrine entity is created and many setAttributeX methods are called and in the end $em->flush().

My feeling tells me that it is not right to have three classes with only static methods to import XML files, but I can't find a better solution.


texts: Merge two DataTables by adding corresponding entries

texts:
I've been looking over internet for a method of combining 2 datatables with exactly the same cells with numbers to add them together, Merge method never help because it just appended the second table. The task was later accomplished by my hand-written method:

static DataTable CombineDT34(DataTable dt3, DataTable dt4) {
        var combinedDT34 = dt3;
        for (var r3 = 0; r3 < dt3.Rows.Count; r3++) {

            for(var c3 = 1; c3 < dt3.Columns.Count; c3++) {

                dt3.Rows[r3][c3] =
                    (Convert.ToInt32(dt3.Rows[r3][c3]) +
                    Convert.ToInt32(dt4.Rows[r3][c3]));
            }
        }

        return dt3;
    }

Is there are a way to do this better?


texts: Format 2 Excel sheets then save both sheets as a new workbook

texts:
I'm trying to optimize some VBA that I put together. I know that using  Select a lot slows down performance quite a bit so I've been trying to cut that out where I can. Is there anything else in my code that I can change or do differently to improve performance? Thank you in advance!

Sub PP_Formatting_Saving()

Application.ScreenUpdating = False

'Ungroups sheets by selecting Wksht 2
Worksheets(2).Select

'Input 1 into Cell AK1 then Multiply columns to convert to number
Range("AK1").Value = "1"
Range("AK1").Copy

Range("N" & Rows.Count).End(xlUp).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply, _
SkipBlanks:=False, Transpose:=False

Range("AA" & Rows.Count).End(xlUp).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply, _
SkipBlanks:=False, Transpose:=False

Range("G" & Rows.Count).End(xlUp).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply, _
SkipBlanks:=False, Transpose:=False

Range("AK1").ClearContents

'Format Amount as Accounting
Range("J" & Rows.Count).End(xlUp).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.Style = "Comma"

'Format header color & bold
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
With Selection.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 12632256
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With
Selection.Font.Bold = True

'Autofit all columns
Cells.Select
Cells.EntireColumn.AutoFit
Columns("O:O").ColumnWidth = 40

'Filter all headers
Selection.AutoFilter

'Unwrap Text in sheet 1
Worksheets(1).Select
Cells.Select
With Selection
    .WrapText = False
End With

'Format Amount as Accounting
Range("C" & Rows.Count).End(xlUp).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.Style = "Comma"

'Input 1 into Cell AK then Multiply columns to convert to number
Range("AK1").Value = "1"
Range("AK1").Copy
Range("B" & Rows.Count).End(xlUp).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply, _
SkipBlanks:=False, Transpose:=False

'Autofit all columns
Cells.Select
Cells.EntireColumn.AutoFit

'Format header color & bold
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
With Selection.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 12632256
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With
Selection.Font.Bold = True

'Filter all headers
Selection.AutoFilter

Dim ws As Worksheet
Dim wbNew As Workbook

'Select PP sheet, filter all cells on Variable1 in Column 31.          Copy all of that then paste in new sheet, rename sheet as PP1.      UsedRange selects all cells with value in it
Sheets("PP").Select
ActiveSheet.UsedRange.AutoFilter Field:=31, Criteria1:= _
    "Variable1"
Cells.Select
Range("Y1005").Activate
Selection.Copy
Sheets.Add After:=ActiveSheet
ActiveSheet.Paste
ActiveSheet.Name = "PP1"

'Select BK sheet, filter all cells on Variable2 in Column 16.  Copy all of that then paste to new sheet, rename as BK1.  UsedRange selects all values in worksheet.
Sheets("Bk").Select
ActiveSheet.UsedRange.AutoFilter Field:=16, Criteria1:= _
    "Variable2"
Cells.Select
Range("O15").Activate
Application.CutCopyMode = False
Selection.Copy
Sheets.Add After:=ActiveSheet
ActiveSheet.Paste
ActiveSheet.Name = "BK1"

'Copy BK & PP in Array then save as new workbook
Worksheets(Array("BK", "PP")).Copy
Set wbNew = ActiveWorkbook

'Naming the workbook w/ date format
wbNam = "BK_PP_"
dt = Format(DateAdd("m", -1, Now), "yyyy_mm")

'Save location
ActiveWorkbook.SaveAs "\\user\location\" & wbNam & dt & ".xlsx"

'Close new workbook that just saved
ActiveWorkbook.Close

'Delete sheets created in original workbook
Sheets("PP1").Delete
Sheets("BK1").Delete

End sub


texts:
I have been programming a maths quiz that can be used for teachers and I have have been trying to make the code as short as possible so it is easier to understand.

If there is any way I could make it more concise, please tell me and explain the programming behind it.

import sys
import random

def get_bool_input(prompt=''):
    while True:
        val = input(prompt).lower()
        if val == 'yes':
            return True
        elif val == 'no':
            return False
        else:
            sys.exit("Not a valid input (yes/no is expected) please try again")

status = input("Are you a teacher or student? Press 1 if you are a student or 2 if you are a teacher")

if status == "1":
    score=0
    name=input("What is your name?")
    print ("Alright",name,"welcome to your maths quiz")

    level_of_difficulty = int(input(("What level of difficulty are you working at?\n"
                                 "Press 1 for low, 2 for intermediate "
                                    "or 3 for high\n")))
    if level_of_difficulty not in (1,2,3):
        sys.exit("That is not a valid level of difficulty, please try again")

    if level_of_difficulty == 3:
        ops = ['+', '-', '*', '/']
    else:
        ops = ['+', '-', '*']

    for question_num in range(1, 11):
        if level_of_difficulty == 1:
            number_1 = random.randrange(1, 10)
            number_2 = random.randrange(1, 10)
        else:
            number_1 = random.randrange(1, 20)
            number_2 = random.randrange(1, 20)

        operation = random.choice(ops)
        maths = round(eval(str(number_1) + operation + str(number_2)),5)
        print('\nQuestion number: {}'.format(question_num))
        print ("The question is",number_1,operation,number_2)

        answer = float(input("What is your answer: "))
        if answer == maths:
            print("Correct")
            score = score + 1
        else:
            print ("Incorrect. The actual answer is",maths)

    if score >5:
        print("Well done you scored",score,"out of 10")
    else:
        print("Unfortunately you only scored",score,"out of 10. Better luck next time")

    class_number = input("Before your score is saved ,are you in class 1, 2 or 3? Press the matching number")
    if class_number not in ("1","2","3"):
        sys.exit("That is not a valid class, unfortunately your score cannot be saved, please try again")
    else:
        filename = (class_number + "txt")

        with open(filename, 'a') as f:
            f.write("\n" + str(name) + " scored " + str(score) +  " on difficulty level " + str(level_of_difficulty))

        with open(filename, 'a') as f:
            f = open(filename, "r")
            lines = [line for line in f if line.strip()]
            f.close()
            lines.sort()

        if get_bool_input("Do you wish to view previous results for your class"):
            for line in lines:
                print (line)
        else:
            sys.exit("Thanks for taking part in the quiz, your teacher should discuss your score with you later")

if status == "2":
    class_number = input("Which classes scores would you like to see? Press 1 for class 1, 2 for class 2 or 3 for class 3")
    if class_number not in (1,2,3):
        sys.exit("That is not a valid class")
    filename = (class_number + "txt")
    with open(filename, 'a') as f:
        f = open(filename, "r")
        lines = [line for line in f if line.strip()]
        f.close()
        lines.sort()
        for line in lines:
            print (line)


texts: Improving multiple assignment using an iterator function

texts:
Often I need to perform multiple assignment from a sequence
(e.g. from the result of a split()) but with some semantics
that, AFAIK, are not available in the language:

Assign N first elements and silently ignore the rest (like Perl's
list assignment).

>>> a, b = 'foo bar is here'.split()
>>> a, b
('foo', 'bar')
>>>

Assign the remaning items to the last variable in the variable list:

>>> a, b, c = 'foo bar is here'.split()
>>> a, b, c
('foo', 'bar', ['is', 'here'])
>>>

If the sequence doesn't have enough values, set the variables to a
default value (None or any other, again similar to Perl):

>>> a, b, c, d, e = 'foo bar is here'.split()
>>> a, b, c, d, e
('foo', 'bar', 'is', 'here', None)
>>>

I have designed an iterator function to help me with this, but I'm
concerned about my solution to this problem from the point of view of
pythonic adherence:

Usefulness: Using an iterator for this kind of job is the right
option, or there is something more appropriate?  Or even worse: my
need to do this kind of assignment in Python is not favoring other
language features?
Clearness: The implementation is solid and clear enough?  Or is
there some other way to implement this that would be cleaner?

In other words, this solution is better discarded or can it be
improved?

from itertools import *

def iterassign(iterable, *, count, use_default=False, default=None, tail=False):
    """Iterattor for multiple assignment.

    :param iterable: The iterable.
    :param int count: The maximum count of iterations.
    :param bool use_default: If set, and iterable ends before max_count,
        continue iteration using :param:`default`.
    :param default: Default value to use when :param:`use_default` is
        set to ``True``.
    """
    it = iter(iterable)
    for idx, element in enumerate(chain(islice(it, 0, count), repeat(default))):
        if idx >= count: break
        yield element
    else:
        raise StopIteration()
    if tail:
        yield list(it)

Usage examples:

>>> ret = 'foo bar is here'.split()
>>> a, b = iterassign(ret, count=2)
>>> a, b
('foo', 'bar')
>>> a, b, c = iterassign(ret, count=2, tail=True)
>>> a, b, c
('foo', 'bar', ['is', 'here'])
>>> a, b, c, d, e = iterassign(ret, count=5, use_default=True)
('foo', 'bar', 'is', 'here', None)
>>>


texts:
I'm writing a node.js application that involves handling clients based on their ID without any real way of confirming that the ID a client says it has is its actual ID. That is, it's possible for a client to tell the server it has an ID of foo even though it was assigned an ID of bar, thus being able to send and receive information from the server as though it was the existing client foo. This is obviously a significant security risk, so I want to ensure it's more or less effectively impossible to guess another client's ID.

I have a clients object, with keys corresponding to the ID of each client. I'm using the crypto library for PRNG and hashing; hashFct returns a SHA256 digest of the input. The following code is run when a client sends its initial creation request.

//Generate random string, hash, and truncate to 8 characters
rand = crypto.randomBytes(32).toString("base64");
id = hashFct(rand).substr(0, 8);

//Loop until unique
for(var i = 0; !!clients[id]; i++) {
    rand = crypto.randomBytes(32).toString("base64");
    id = hashFct(rand).substr(0, 8);
}

...

clients[id] = {
    id: id,
    ...
}

The idea behind the "loop until unique" section is to check if the clients object already has a value in it with the pseudo-random id as a key, and to regenerate the ID and try again until it's unique. Then the ID is put into the clients object as a new client, and the code moves on.

Is there anything glaringly stupid about this approach that I'm overlooking? Is there a better way to ensure an ID is unique, or perhaps a better way of generating the IDs?


texts: Find paths whose sum equals a target value in a binary tree

texts:
You are given a binary tree in which each node contains an integer value (which might be positive or negative). Design an algorithm to count the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The question asks for count only but I went one step ahead and found the paths too.

The following is my attempt at this code. Please let me know how I can improve it. Also I think the time complexity of the code is \$O(n^2)\$ because of the following reasoning:

findPathsWithSumHelper is called n times for each node in the tree.
This function goes through all the nodes below the root to find paths.
The total work done is \$n + 2 * \frac{n}{2} + 4 * \frac{n}{4} + \dots n * \frac{n}{n}\$ which equals \$O(n^2)\$.
The work done in copying the arrays using emplace_back is \$O(n)\$ at each node in the tree and adds a constant to \$O(n^2)\$.

#include <iostream>
#include <vector>
using namespace std;

struct Tree{
    struct Tree * left, *right;
    int data;
    Tree(int val): data(val), left(NULL), right(NULL){};
};

//insert nodes randomly in a BT
void insertNodeBT(Tree * &root, int val){

    Tree * newNode = new Tree(val);

    if(root==NULL){
        root = newNode;
        return;
    }

    int r = rand()%2;

    if(r)
        insertNodeBT(root->left, val);
    else
        insertNodeBT(root->right, val);
}

vector<vector<int>> findPathsWithSumHelper(Tree * root, int target, int prev, vector<int> path){

    vector<vector<int>> res;

    if(root == NULL){
        return res;
    }

    path.push_back(root->data);

    if(prev + root->data == target){
        res.push_back(path);
    }

    vector<vector<int>> temp;
    temp = findPathsWithSumHelper(root->left, target, prev+root->data, path);

    for(auto i : temp){
        res.emplace_back(move(i));
    }

    temp = findPathsWithSumHelper(root->right, target, prev+root->data, path);

    for(auto i : temp){
        res.emplace_back(move(i));
    }

    return res;

}

vector<vector<int>> findPathsWithSum(Tree * root, int target){

    vector<vector<int>> res;

    if(root == NULL){

        return res;
    }

    vector<int> path;
    res = findPathsWithSumHelper(root, target, 0, path);
    vector<vector<int>> temp;
    temp = findPathsWithSum(root->left, target);

    for(auto i : temp){
        res.emplace_back(move(i));
    }

    temp = findPathsWithSum(root->right, target);

    for(auto i : temp){
        res.emplace_back(move(i));
    }

    return res;

}

int main() {

    Tree *root = NULL;
    insertNodeBT(root, 4);
    insertNodeBT(root, 6);
    insertNodeBT(root, 2);
    insertNodeBT(root, 7);
    insertNodeBT(root, 5);
    insertNodeBT(root, 1);
    insertNodeBT(root, 3);
    insertNodeBT(root, -1);
    vector<vector<int>> res = findPathsWithSum(root, 6);

    for (auto i : res){
        for (auto j : i) {
            cout << j << " ";
        }
        cout<<endl;
    }
    return 0;
}

Following is a better solution but it only returns the count and not the actual paths. I feel it is \$O(nlogn)\$ but not sure.

int findPathsWithSum(Tree * root, int target, unordered_map<int, int> m){

    if(root==NULL)
        return 0;

    int res=0;

    for(auto &it : m){
        if(it.first+root->data == target)
            res++;
        m[it.first+root->data]++;
        m.erase(it.first);

    }

    if(root->data == target)
        res++;

    m[root->data]++;
    res += findPathsWithSum(root->left, target, m);
    res += findPathsWithSum(root->right, target, m);

    return res;

}


texts: Rust shortest way to find the maximum product of a fixed length substring

texts:
I'm trying to code in a Rust a function, that gives the maximum product of adjacent digits.
So given the string 123456789, with 3 adjacent digits, the maximum is 7 * 8 * 9 = 504.
I've tried to come up with this current functional solution (see previous edit for longer solutions). Could it be shortened? Comments are welcome.
The log is here, and desired, so the code runs quickly.
use std::iter::Map;
use std::str::Chars;

fn iter_log_digits(str: &str) -> Map<Chars<'_>, fn(char) -> f64> {
  str.chars().map(|c: char| (c.to_digit(10).unwrap() as f64).ln())
}

/// Returns the maximum log sum of adjacent digit characters.
/// # Arguments
/// - `str`: Assumes there are no 0s.
/// - `adj_count`: The number of adjacent digit characters.
fn max_adj_log_sum_no_zeros(str: &str, adj_count: usize) -> f64 {
  if str.len() < adj_count {
    return 0.;
  }
  let log_first: f64 = iter_log_digits(&str[..adj_count]).sum();
  iter_log_digits(&str).zip(iter_log_digits(&str[adj_count..])).fold(
    (log_first, log_first), // `(log_cur, log_max)`
    |(log_cur, log_max), (x_left, x_right)| {
      let log_next = log_cur - x_left + x_right;
      (log_next, log_max.max(log_next))
    }
  ).1
}

fn max_product_no_zeros(str: &str, adj_count: usize) -> u64 {
  max_adj_log_sum_no_zeros(str, adj_count).exp().round() as u64
}

max_product_no_zeros("123456789", 3) should return 504.


texts:
Write an improved code to identify a valid straight of eight cards, e.g. 4H,5S,AC,7C,8H,AH,0S,JC. Note that the card combination may include Wilds (as we see in our example, with the Ace of Clubs standing in for a Six and the Ace of Hearts standing in for a Nine), but must include at least two "natural" cards (i.e. non-Wild cards). Note also that the sequence of the cards is significant for this group type, and that 4H,5S,AC,8C,7H,AH,AS,AC, e.g., is not a valid straight of eight, as it is not in sequence. Aces are the only wild cards and must represent another card. Duplicate cards are allowed.
Card inputs are in a list of 2 value strings with the value:

2 to 9 - for 2 to 9
0 - for 10
J - for Jack
Q - for Queen
K - for King
A - for Ace

The suits are shown with values S(spade), C(club), H(heart), D(diamond)

Example input to be checked: 4H,5S,AC,7C,8H,AH,0S,JC
Output: True
Example input to be checked: AH,5S,AC,7C,AH,AH,AS,AC
Output: True
Example input to be checked: 4H,5S,AC,8C,7H,AH,AS,AC
Output: False

Here is my code:
group = input().split(",")
if len(group) == 8:
    #check for ace
    ace = [0 for card in group if card[0] == 'A']
    run_vals = {"0": 10, "J": 11, "Q": 12, "K":13}
    if len(ace) < 6:
        miss_count = 0
        for index in range(len(group)-1):
            if group[index][0]  == "A":
                miss_count += 1
                if group[index+1][0]  == "A" and index == len(group)-2:
                    miss_count += 1
                    continue
                else:
                    continue

            if group[index+1][0]  == "A" and index == len(group)-2:
               miss_count += 1
               continue
            if group[index+1][0]  == "A" and index <len(group)-2:
               continue

            if group[index+1][0] in run_vals:
                num1 = run_vals[group[index+1][0]]
            else:
                num1 = int(group[index+1][0])

            if group[index][0] in run_vals:
                num2 = run_vals[group[index][0]]
            else:
                num2 = int(group[index][0])

            if (num1 - num2) != 1:
                miss_count += 1

        if miss_count == len(ace):
            print(True)
        else:
            print(False)

    elif len(ace) == 6:
        ace_in_between = 0
        range_limits = [card for card in group if card[0] != "A"]
        for index in range(len(group)):
            if index > group.index(range_limits[0]) and index< group.index(range_limits[1]):
                ace_in_between += 1
        range_limits = [run_vals[val[0]] if val[0] in run_vals else val[0] for val in range_limits]
        if ace_in_between + 1 == (int(range_limits[1]) - int(range_limits[0]) ):
            print(True)
        else:
            print(False)
    else:
        print(False)
else:
    print(False)


texts:
Recently I submitted some string formatting and printing code (found here) that I wrote as an small exercise. It was implemented naively using string replacement. This time around I wanted to actually parse the format string. This is the first time I've ever attempted to write code which does any type of parsing. I'm not 100% sure that this code does not contain any critical flaws. In addition to pointing out any such oversights, I would appreciate advice on how this could be modified to make it either faster or more readable.

The functionality is supposed to be similar to the Console.WriteLine or String.Format functions of C#.

#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
#include <exception>
#include <utility>
#include <cctype>

template <typename T>
std::string to_string(T&& item)
{
    return boost::lexical_cast<std::string>(std::forward<T>(item));
}

template <class... Args>
std::string format(const std::string& fmt, Args&&... args)
{
    std::string output;
    output.reserve(fmt.length() * 2);

    std::string arg_strings[] = { to_string(std::forward<Args>(args))... };

    bool placeholder_mode = false;
    std::string index_string;

    for (auto it = fmt.begin(); it != fmt.end(); ++it) {
        //check for end of brace enclosed placeholder
        if ((*it == '}') && (placeholder_mode == true)) {
            if ((index_string.length() == 0)) {
                throw std::invalid_argument("Invalid format string.");
            }
            //check if index_string contains a leading zero
            if ((index_string.length() > 1) && (index_string[0] == '0')) {
                throw std::invalid_argument("Invalid format string.");
            }
            int index = std::stoi(index_string);
            if (index > (sizeof...(args) - 1)) {
                throw std::out_of_range(
                    "Index (zero based) must be greater than or equal "
                    "to zero and less than the size of the argument list."
                );
            }
            output += arg_strings[index];
            index_string.clear();
            placeholder_mode = false;
            continue;
        }

        //escape double closing brace as single
        if ((*it == '}') && (*(it+1) == '}')) {
            it++;
            output.push_back('}');
            continue;
        }

        //check for unescaped closing brace
        //which doesn't close a placeholder
        if ((*it == '}') && (placeholder_mode == false)) {
            throw std::invalid_argument("Invalid format string.");
        }

        //escape double opening brace as single
        if ((*it == '{') && (*(it+1) == '{')) {
            it++;
            output.push_back('{');
            continue;
        }

        //check for begining of brace enclosed placeholder
        if ((*it == '{') && (placeholder_mode == false)) {
            placeholder_mode = true;
            continue;
        }

        if(placeholder_mode == true) {
            //check for non-digit characters
            if (isdigit(*it) == false) {
                throw std::invalid_argument("Invalid format string.");
            }
            index_string.push_back(*it);
        }
        else {
            output.push_back(*it);
        }
    }

    if (placeholder_mode == true) {
        //catch any other placeholders that were left open
        throw std::invalid_argument("Invalid format string.");
    }

    return output;
}

template <class... Args>
void print(const std::string& fmt, Args&&... args)
{
    std::cout << format(fmt, std::forward<Args>(args)...);
}

int main()
{
    print("Hello, {0}! The answer is {1}.\n", "World", 42);
}

Update: Version 2


texts:
I just want to return the first word in the image name (before the dash, dog in my example). Now I use it like this but believe it can be done in a simpler way (like one line of code):

$live_site_image = "http://example.net/wp-content/themes/example/images/dog-in-park.jpg";
$live_site_image = substr( strrchr( $live_site_image, '/' ), 1);
$live_site_image = strtok($live_site_image,"-");


texts: Compare and find duplicates in 2 corresponding columns in 2 sheets

texts:
I want to compare (500) and find duplicate daily records within 2 sheets, and copy the unmatched row to another sheet, copy the match from another to 3rd sheet, and delete the matched records from original sheet.

I have 3 worksheets (results, Master List, Follow Ups) " results" update daily with 500 records, and added to "master list", duplicate row added to "follow ups"

All have similar columns heading A to O.

I want to compare Column B (unique) and column A of worksheet "results" to " Master List".

The flow would be:

  Match a first cell value in column B of "results" to Column B cell values of " Master List"

  If match found - compare column A of "results" to Column A cell values of " Master List"

  If match found

  Copy the row of match from "Master List" for Column A to O to next available row of "Follow Ups"
  Mark the match row in "results" to be deleted in the end when search loop finished

  Else if match not found

  check next value in column B of " result" until last record

  When whole search ends, delete marked records for match found in "results" and copy all the left out records to Next available table row in "Master List".

I am kind of stuck and don't want to run in long loop, looking for expert help with shortest and fastest possible code. Here is some code already written and working, but not working well.

If possible optional approach (can both column value jointly compared with another sheet):

Set sht1 = xlwb.Worksheets("results")
    Set sht4 = xlwb.Worksheets("Master List")
    Set sht5 = xlwb.Worksheets("Follow Ups")

    For i = 2 To sht1.Range("A1").SpecialCells(xlCellTypeLastCell).Row
            For j = 2 To sht4.Range("A1").SpecialCells(xlCellTypeLastCell).Row
                    If sht1.Cells(i, 2) = sht4.Cells(j, 2) And sht1.Cells(i, 1) = sht4.Cells(j, 1) Then

                    'sht4.Rows(j).Copy
                   ' sht5.Activate

                    'sht5.Cells(1, sht5.Range("A1").SpecialCells(xlCellTypeLastCell).Row).Select

                    sht4.Rows(j).Copy _
                    Destination:=sht5.Cells(sht5.Range("A1").SpecialCells(xlCellTypeLastCell).Row + 1, 1)

                        'sht1.Rows(i).Delete

                        'i = i - 1
                     End If

            Next
    Next

sht1.Range("A2:O" & sht1.Range("A1").SpecialCells(xlCellTypeLastCell).Row).Copy Destination:=sht4.Cells(sht4.Range("A1").SpecialCells(xlCellTypeLastCell).Row, 1)


texts: improve performance of recursive function in c# method

texts:
I'm trying to write a function which will cache objects in memory.

The function below works, but performance is unbearable. What would you recommend to improve performance?

 public void SerializeInsertCache(object item)
        {
            //Get type of item object item
            Type type = item.GetType();

            //Get all of attributes type of item object
            TypeAttributes attributesType = type.Attributes;

            //Get object type full name for cach key
            string rootName = type.Name;

            string name = type.Name;
            PropertyInfo[] properties = type.GetProperties();
            PropertyInfo idRoot = properties.Where(p => p.Name == "Id").SingleOrDefault();

            int rootId = (int)idRoot.GetValue(item);

            string rootKey = "";

            foreach (var property in properties)
            {

                string propertyName = property.Name;
                var propertyValue = property.GetValue(item);
                Type propertyType = property.PropertyType;
                string propertyTypeName = propertyType.Name;
                bool cacheStatus = true;
                SerializeInsertCache(property);//recursive function

            }

           SaveInCache(item);
         }


texts: Getting TLE for SPOJ Bitplay challenge program

texts:
I have tried a naive way to solve this problem:

  Given a even number N (N  ≤ 109) and an integer K, you have to find the greatest odd number M less than N such that the sum of digits in binary representation of M is at most K.

I ended up with TLE, could not be able to think of optimized solution, need help to make a breakthrough.

#include <bits/stdc++.h>
using namespace std;
int k;
int ones(int n){
    return __builtin_popcount(n);
}
void value(int m,int &flag){
    while(m>0){
        if(k == 0){
            return;
        }
        if(k == 1){
            flag = 1;
            cout << "1" <<'\n';
            return;
        }
        if(ones(m) <= k){
            flag = 1;
            cout << m << '\n';
            return;
        }
       m-=2;
    }
}
int main(){
    int t;
    cin >> t;
    while(t-->0){
        int n,flag = 0;
        cin >> n >> k;
        (n&1)? value(n,flag): value((n-1),flag);
        if(flag == 0){
            cout << "-1" << '\n';
        }
    }
    return 0;
}


texts: Replace each element in ArrayList with pair of Ints which sum to existing element

texts:
Looking for general feedback and considerations to make for the next time :).

Write a method stretch that doubles the size of an ArrayList of integers by replacing every integer in the list with a pair of integers, each half the original. If a number in the original list is odd, then the first number in the replacement pair should be one higher than the second so that the sum equals the original number. For example, if a variable called list stores this sequence of values:

[18, 7, 4, 24, 11]

and you make the following call:

stretch(list);

Then the number 18 is stretched into the pair (9, 9), the number 7 is stretched into (4, 3), the number 4 is stretched into (2, 2), the number 24 is stretched into (12, 12) and the number 11 is stretched into (6, 5) yielding the following overall list which is twice the length of the original list:

[9, 9, 4, 3, 2, 2, 12, 12, 6, 5]

public void stretch(ArrayList<Integer> list) {
    for (int i = 0; i < list.size(); i+=2) {
        int value = list.get(i);
        int right = value / 2;
        int left = right;
        if (value % 2 != 0) {
            left++;
        }
        list.add(i, left);
        list.set(i + 1, right);
    }

}


texts:
This is the code for a calculator function. It takes the first and second number, combines them and asks for an input whether the calculation was correct. If the input is "Yes", a statement is printed. If the input is "No", a different statement is printed.

def calculator(number1,number2):
    answer = ['Yes', 'yes']
    print("The first number is %d." % number1,
          "The second number is %d." % number2)
    print("The sum is %d." % (number1 + number2))
    if input("Am I right? \nANSWER : ") in answer:
        print("Knew it!")
    else:
        print("Oh, well. Blame my programmer!")

Is there anything I can do to optimize the code and make it shorter and / or simpler?


texts:
I am just learning swift and tried to make a queue class with enqueue and dequeue.

The node holds the data for each element
The enqueue adds an element to the "queue"
The dequeue deletes the first element in the queue and returns the data
Head and Tail are references to node elements, which also tells if the queue is empty when they are nil (null)

Now I am wondering, have I done this correctly, both the theory and can the code be improved in Swift (used to code in Java)?

class Queue {

    class Node {
        // variables
        var data: String
        var prev: Node?

        init(data: String){
            self.data = data
        }
    }

    // variables
    var head: Node?
    var tail: Node?

    func enqueue(e: String){
        if head == nil && tail == nil {
            head = Node(data: e)
            head?.prev = nil
            tail = head
        } else {
            let temp = Node(data: e)
            tail?.prev = temp
            tail = temp

        }
    }

    func dequeue() -> String{
        let result = head?.data

        if head === tail {
            head = nil
            tail = nil
        } else {
            head = head?.prev
        }
        if (result == nil){
            return "empty"
        }
        return result!
    }

}

Testing the program:

var q: Queue
q = Queue()

q.enqueue("One")
q.enqueue("Two")
q.enqueue("Three")

print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())

Output:

One
Two
Three
empty


texts: Extreme use of pointers in adjacency list graph construction?

texts:
Playing around with pointers in C++, implemented an adjacency list graph.
Am I going too far/extreme trying to place data onto the heap?
graph.h
#include <memory>
#include <unordered_map>
#include <forward_list>
#include <utility>

template <typename TKey, typename TWeight>
class Graph{

    struct Adjacent {
        TKey key;
        TWeight weight;
        Adjacent(const TKey key, const TWeight weight): key(key), weight(weight) {};
    };

    struct Vertex {
        TKey value;
        std::unique_ptr<std::forward_list<Adjacent>> adjVertexList;
        explicit Vertex(const TKey value){
            this->value = value;
            adjVertexList = std::make_unique<std::forward_list<Adjacent>>();
        }
    };

private:
    // Since keys can be non-numeric,
    // use a hashmap to index into individual adj lists
    std::unordered_map<TKey, std::unique_ptr<Vertex>> vertices;

public:
    void addVertex(TKey value);

    // Everything other than addDirectedEdge is just for a nicer API
    void addDirectedEdge(TKey src, TKey dst, TWeight weight);
    void addUndirectedEdge(TKey src, TKey dst, TWeight weight);
    void addDirectedEdge(TKey src, TKey dst);
    void addUndirectedEdge(TKey src, TKey dst);

};

graph.cpp
#include <stdexcept>
#include "graph.h"

template <typename TKey, typename TWeight>
void Graph<TKey, TWeight>::addVertex(TKey value) {
    vertices.insert(std::make_pair(value, std::make_unique<Vertex>(value)));
}

template <typename TKey, typename TWeight>
void Graph<TKey, TWeight>::addDirectedEdge(TKey src, TKey dst, TWeight weight) {

    auto srcPtr = vertices.find(src);

    if(srcPtr == vertices.end())
        throw std::invalid_argument("Cannot find source");
    else if(vertices.find(dst) == vertices.end())
        throw std::invalid_argument("Cannot find destination");

    Vertex* vertex = srcPtr->second.get();
    vertex->adjVertexList->push_front(Adjacent(dst, weight));

}

template <typename TKey, typename TWeight>
void Graph<TKey, TWeight>::addUndirectedEdge(TKey src, TKey dst, TWeight weight) {
    addDirectedEdge(src, dst, weight);
    addDirectedEdge(dst, src, weight);
}

template <typename TKey, typename TWeight>
void Graph<TKey, TWeight>::addDirectedEdge(TKey src, TKey dst) {
    addDirectedEdge(src, dst, 0);
}

template <typename TKey, typename TWeight>
void Graph<TKey, TWeight>::addUndirectedEdge(TKey src, TKey dst){
    addUndirectedEdge(src, dst, 0);
}
```


texts: Validate whether a ransom note can be made from a dictionary of words

texts:
For simplicity, it is checking whether the characters in a string (that needs to be created) are present in a larger string (dictionary). Would a character array of the letters make sense here, or would it be better with a Map<Character, Integer>?

public class RansomNoteProblem {
public static void main (String args[]){

    String blob = "thisisanothwllowllqend";
    String note = "thisisanotex";

    System.out.println(validateLetterCreation(blob,note));
}

public static boolean validateLetterCreation(String dict, String note){
    int charArray[] = new int[256];
    for(int i=0;i<dict.length();i++){
        int charValue = (int)dict.charAt(i);
        charArray[charValue]++;
    }

    for(int i=0;i<note.length();i++){
        int charValue = note.charAt(i);
        if(charArray[charValue]<=0){
            return false;
        }
        else {
            charArray[charValue]--;
        }
    }
    return true;

}
}


texts:
A Helper class for Fragment Management.
The FragmentsManager class has methods to add and replace fragments.
The replace method checks if the given fragment is present in backstack or not and if the fragment is present it brings back the old fragment.
Need review for the following:

Code optimized.
Memory Efficiency
Overall code review
Can the replace method be improved in any way so as to avoid creation of additional fragments?
I've tried to use popbackstack() but couldn't how to use it. Can you help with that?

Thanks

import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

class FragmentsManager {

    private static final String TAG = "FragmentsManager";
    private static FragmentTransaction transaction;
//    Return Fragment Transaction
    private static FragmentTransaction getTransaction(Activity activity){
//        if (transaction == null) {
//            return transaction;
//        }
        return getFragmentManager(activity).beginTransaction();
    }
//    Return Fragment Manager
    private static FragmentManager getFragmentManager(Activity activity){
        return ((AppCompatActivity)activity).getSupportFragmentManager();
    }

    /**
     * Add Fragment to the given ID
     * @param activity
     * @param fragment
     * @param id
     * @param add_to_backstack
     */
    static void addFragment(Activity activity, Fragment fragment, int id, boolean add_to_backstack){
        transaction = getTransaction(activity);
        transaction.add(id,fragment,fragment.getClass().getName());
        if (add_to_backstack)
            transaction.addToBackStack(fragment.getClass().getName());
        transaction.commit();
    }

     static void replaceFragment(Activity activity, Fragment fragment, int id, boolean add_to_backstack) {
        Fragment check_Fragment = getFragmentManager(activity).findFragmentByTag(fragment.getClass().getName());
        if (check_Fragment == null) {
            transaction = getTransaction(activity)
                    .replace(id,fragment,fragment.getClass().getName());
            if (add_to_backstack)
                transaction.addToBackStack(fragment.getClass().getName());
            transaction.commit();
        }
        else{
            transaction = getTransaction(activity);
            transaction.replace(id,check_Fragment,check_Fragment.getClass().getName())
                    .addToBackStack(null)
                    .commit();
        }
    }
}


texts: Calculate and apply realistic velocities when animating sprites

texts:
I am brand new to Scratch (and animation in general) and have been playing around with various techniques I feel will probably come in handy. My project in question can be viewed here. It started as a basic, infinitely scrolling background and a sprite (in this case a dragon) with a fixed position. The scrolling of the background gives the illusion that it is the dragon that is moving. This proved to be relatively simple so I attempted to add in the complexity of increasing and decreasing (more accurately, reverting) the velocity of the dragon. This was done through adjusting the speed at which the background is scrolled as well as adjusting the dragon's position along the X axis.

My intent for both the background and the dragon itself was to control the "speed" with the number of units (pixels, I would imagine) while its position was adjusted by at a time.

I wanted to simulate an an exponential rate of acceleration and deceleration, as opposed speeding up and slowing down uniformly, so my goal was to start with a base number of units and increment or decrement accordingly. This is where I think I went wrong... or maybe I didn't.

The 2 image below (sorry, no way to convert to "code" that I'm aware of) represents my methods for controlling the velocity for the background scrolling as well as the dragon with the same technique used for each. I feel like there should be a cleaner set of numbers/calculations that can be used to determine and set the number of pixels to adjust each by, but I'm finding myself at a loss. Am I on the right track?


texts: Converting decimal integer to binary string

texts:
I'm wondering how I can make this function better, more compact, even faster.

char* DectoBin(int dec) {
    int counter = 0;
    int x =0;
    while (dec>=x) {
        counter++;
        x = pow(2, counter);
    }
    //counter is the # of bits in the converted binary number
    char* bin = new char[counter+1];
    //+1 for nul byte
    int y = counter;
    int remainder = 0;

    while (counter > 0) {
        //% the dec number with the base 2 each time and if remainder>0 then set the bit
        remainder = dec % 2;
        dec /= 2;
        if (counter == y) {
            bin[counter] = '\0';
        }

        if (remainder > 0) {
            bin[(counter - 1)] = '1';
        }
        else {
            bin[(counter - 1)] = '0';
        }
        counter--;
    }
    return bin;
}


texts: Parallel Miller-Rabin Prime Test in Haskell

texts:
I implemented a prime number finder using the Miller-Rabin prime test in Haskell and it seems to be working. You enter a number and it finds the next prime following that number.

I also tried to make it parallel and I'm looking for some advice for how I can speed up the parallel version. Right now it runs much slower than the not parallel version.

Compiled with ghc -threaded -O2 miller_rabin.hs -o miller_rabin

Run with ./miller_rabin startnumber npar +RTS -N4 (I have a 4-core processor). npar is the parameter for parBuffer. If npar is 1 then the program runs single-threaded, otherwise is runs with multiple threads.

module Main where

import System.Random (StdGen, getStdGen, randomRs)
import System.Environment (getArgs)
import Control.Parallel.Strategies

main :: IO ()
main = do
    g <- getStdGen
    args <- getArgs
    let number = read . head $ args :: Integer
        npar = read $ args !! 1 :: Int
    p <- case npar of
            1 -> do putStrLn "Run single thread"
                    return $ find_prime g 20 number
            _ -> do putStrLn "Run multi-threaded"
                    return $ head $ primeList npar g 20 number
    putStrLn . show $ p

miller_rabin :: StdGen -> Int -> Integer -> Bool
miller_rabin g k n = all (not . trial_composite n d r)
                   $ take k (randomRs (2, n-2) g)
    where
        (d, r) = decompose (n-1) 0

trial_composite :: Integer -> Integer -> Integer -> Integer -> Bool
trial_composite n d r a = let x = fastPow a d n in
    if (x == 1) || (x==n-1)
    then False
    else all ((/=) (n-1)) $ map (\i -> fastPow a (d*(2^i)) n) [0..r-1]

decompose :: Integer -> Integer -> (Integer, Integer)
decompose d r
    | d `mod` 2 == 0 = decompose (d `div` 2) (r+1)
    | otherwise = (d, r)

fastPow :: Integer -> Integer -> Integer -> Integer
fastPow base 1 m = mod base m
fastPow base pow m | even pow = mod ((fastPow base (div pow 2) m) ^ 2) m
                   | odd  pow = mod ((fastPow base (div (pow-1) 2) m) ^ 2 * base) m

primeList :: Int -> StdGen -> Int -> Integer -> [Integer]
primeList npar g k n =
    let primes = filter (miller_rabin g k) [m,m+2..]
        primesP = primes `using` parBuffer npar rdeepseq
        m = if even n then n+1 else n
    in primesP

find_prime :: StdGen -> Int -> Integer -> Integer
find_prime g k n
    | even n    = find_prime g k (n+1)
    | otherwise = case miller_rabin g k n of
                    True  -> n
                    False -> find_prime g k (n+2)


texts:
How can I test a class that Swizzles? In particular, I want to test the following:

let bundleName = "Bundle.bundle"

var downloadedBundlePath: String? = Bundle.main.path(forResource: bundleName, ofType: nil)

class Localizer: NSObject {
    class func swizzleMainBundle() {
        MethodSwizzleGivenClassName(cls: Bundle.self, originalSelector: #selector(Bundle.localizedString(forKey:value:table:)), overrideSelector: #selector(Bundle.specialLocalizedStringForKey(_:value:table:)))
    }
}

extension Bundle {
    @objc func specialLocalizedStringForKey(_ key: String, value: String?, table tableName: String?) -> String {
        if self == Bundle.main {
            if let path = downloadedBundlePath, let bundle = Bundle(path: path) {
                return (bundle.specialLocalizedStringForKey(key, value: value, table: tableName))
            }
            return (self.specialLocalizedStringForKey(key, value: value, table: tableName))
        } else {
            return (self.specialLocalizedStringForKey(key, value: value, table: tableName))
        }
    }
}

func MethodSwizzleGivenClassName(cls: AnyClass, originalSelector: Selector, overrideSelector: Selector) {
    if let origMethod: Method = class_getInstanceMethod(cls, originalSelector), let overrideMethod: Method = class_getInstanceMethod(cls, overrideSelector) {
        if (class_addMethod(cls, originalSelector, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) {
            class_replaceMethod(cls, overrideSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
        } else {
            method_exchangeImplementations(origMethod, overrideMethod);
        }
    }
}

Which changes the localisation bundle for a local bundle that I have created within the user directory (when used correctly).

Do I need to rewrite this class to make it testable? I really have no real idea how to make it easily testable.


texts: Find numbers between 1 and 10000 whose sum of digits are prime

texts:
I have the following C code that finds numbers between 1 and 10000 whose sum of digits are prime and save then to a file.

#include<stdio.h>
#include<conio.h>
int sum_of_digits(int);
int check_prime(int);
void save_to_file(int);

int main()
{
    int i, num, isPrime;
    for(i=2; i<=10000; i++)
    {
        num = sum_of_digits(i);
        isPrime = check_prime(num);
        if(isPrime)
        {
            printf("%d ", i);
            save_to_file(i);
        }
    }
    getch();
    return 0;
}

int sum_of_digits(int num)
{
    int sum = 0;
    while (num != 0)
    {
        sum += num % 10;
        num /= 10;
    }
    return sum;
}

int check_prime(int num)
{
    int i;
    for (i=2; i<=num-1; i++)
    {
        if (num%i == 0)
            return 0;
    }
    if (i == num)
        return 1;
}

void save_to_file(int num)
{
    FILE *fp;
    fp=fopen("prime.txt","a+");
    fprintf(fp, "%d ", num);
    fclose(fp);
}


texts:
In order to have a "unified" (I realize how ambitious this actually is) syntax when working on dataframes, I wrote the following functions that is a general purpose dataframe set of tools in R.

is.constant <- function(x) {return(length(unique(x))==1)}

is.binary <- function(x) {return(length(unique(x))==2)}

level.count <- function(x) {length(unique(x))}

any.na <- function(x) {any(is.na(x))}

dataframe.drop <- function(df,drops) { df[,!(names(df) %in% drops)] }

dataframe.keep <- function(df,keeps) { df[,(names(df) %in% keeps)] }

dataframe.constant_columns <- function(df) { names(which(apply(df, 2, is.constant))) }

daraframe.low_variance <- function(df, threshold = 0.001) { names(which(apply(df, 2, var)<threshold)) }

dataframe.binary_columns <- function(df) { names(which(apply(df, 2, is.binary))) }

dataframe.rename_column <- function(df,old_name,new_name)
{
  names(df)[names(df)==old_name]<- new_name
  return(df)
}

dataframe.summarize_in_file <- function(df, filename)
{
  require(readr)

  coltypes <- sapply(df, class)
  colnames <- names(df)
  collevels <- sapply(df, level_count)
  colnas <- sapply(df, any_na)
  colmin <- sapply(df, min)
  colmax <- sapply(df, max)

  result <- data.frame(Name = colnames, Type = coltypes, Level = collevels, NAs = colnas, Min = colmin, Max = colmax)

  result <- result[order(-result$Level),]
  result <- result[order(result$Type),]

  write_csv(x = result,path = filename)
}

dataframe.duplicated_columns <- function(df) {
  features_pair <- combn(names(df), 2, simplify = F)
  toRemove <- c()
  for(pair in features_pair) {
    f1 <- pair[1]
    f2 <- pair[2]
    if (!(f1 %in% toRemove) & !(f2 %in% toRemove)) {
      if (all(df[[f1]] == df[[f2]])) {
        toRemove <- c(toRemove, f2)
      }
    }
  }
  return(toRemove)
}

dataframe.highly_correlated_columns <- function(df,threshold=0.995) {
  features_pair <- combn(names(df), 2, simplify = F)
  toRemove <- c()
  for(pair in features_pair) {
    f1 <- pair[1]
    f2 <- pair[2]
    if (!(f1 %in% toRemove) & !(f2 %in% toRemove)) {
      if (cor(df[[f1]],df[[f2]])>threshold) {
        toRemove <- c(toRemove, f2)
      }
    }
  }
  return(toRemove)
}

dataframe.order_by <- function(df,column_name)
{
  df[with(df, order(df[,column_name])), ]
}

Is there anything I could have done better in terms of performance/readability ?


texts: Recursively merge objects with corresponding property names

texts:
I have such objects that I need to merge:

defaultConditions =
  where:
    enabled: true
    acc_id:
      ne: null

conditions =
  where:
    id: 2
    acc_id:
      ne: 5

This helper recipe, which replaces where from defaultConditions with where from conditions, is not quite right for this purpose. So I wrote this:

extend = (object, properties) ->
  for key, val of properties
    if val?.constructor is Object and object[key]?.constructor is Object
      object[key] = extend object[key], val
    else
      object[key] = val
  object

How can it be improved?


texts: Downloading stock information from Yahoo! Finance

texts:
The program downloads stock information from Yahoo! Finance and displays it in the spreadsheet.  On my Mac the program takes 10 minutes to get data for approximately 4000 stocks and on the PC it takes 45 minutes.  I wrote another version which copies and pastes the data instead of iterating through each price value, but every time I run that macro, the runtime increases.  That version takes about 15 minutes on a PC and 45 minutes on a Mac.

I don't know what is going on but I just want a program that runs in < 15 minutes on both operating systems and has a consistent runtime.

Option Explicit

Sub GetData()

Application.Calculation = xlCalculationManual

Dim numb_tickers As Integer
numb_tickers =        Application.WorksheetFunction.CountBlank(Worksheets("Sheet1").Range(Sheet1.Cells(2, 2), Sheet1.Cells(5000, 2)))
numb_tickers = 5000 - numb_tickers

Dim start_ticker As Integer
start_ticker = Sheet3.Cells(5, 2) + 1
Dim end_ticker As Integer
end_ticker = Sheet3.Cells(6, 2) + 1

Dim x As Integer
For x = start_ticker To end_ticker

    Dim DataSheet As Worksheet
    Dim EndDate As Date
    Dim StartDate As Date
    Dim Symbol As String
    Dim qurl As String
    Dim nQuery As Name
    Dim LastRow As Integer

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    Sheets("Data").Cells.Clear

    Set DataSheet = ActiveSheet

        StartDate = Sheet3.Cells(2, 2)
        EndDate = Sheet3.Cells(3, 2)
        Symbol = Sheet1.Cells(x, 2)
        Sheets("Data").Range("a1").CurrentRegion.ClearContents

        qurl = "http://ichart.finance.yahoo.com/table.csv?s=" & Symbol
        qurl = qurl & "&a=" & Month(StartDate) - 1 & "&b=" & Day(StartDate) & _
            "&c=" & Year(StartDate) & "&d=" & Month(EndDate) - 1 & "&e=" & _
            Day(EndDate) & "&f=" & Year(EndDate) & "&g=" & Sheets("Data").Range("a1") & "&q=q&y=0&z=" & _
            Symbol & "&x=.csv"

QueryQuote:
             With Sheets("Data").QueryTables.Add(Connection:="URL;" & qurl, Destination:=Sheets("Data").Range("a1"))
                .BackgroundQuery = True
                .TablesOnlyFromHTML = False
                On Error GoTo ErrorHandler
                .Refresh BackgroundQuery:=False
                .SaveData = True
            End With

            Sheets("Data").Range("a1").CurrentRegion.TextToColumns Destination:=Sheets("Data").Range("a1"), DataType:=xlDelimited, _
                TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
                Semicolon:=False, Comma:=True, Space:=False, other:=False

         Sheets("Data").Columns("A:G").ColumnWidth = 12

Dim numb_days As Integer
numb_days = Application.WorksheetFunction.CountBlank(Worksheets("Data").Range(Sheet2.Cells(2, 7), Sheet2.Cells(1000, 7)))
numb_days = 1000 - numb_days

Dim z As Integer
For z = 2 To numb_days + 1

    Worksheets("Sheet1").Cells(x, z + 5) = Worksheets("Data").Cells(z, 7)

Next z

ErrorHandler:  Resume Next

Next x

Dim xyz As Integer
For xyz = 2 To numb_days + 1
    Worksheets("Sheet1").Cells(1, xyz + 5) = Worksheets("Data").Cells(xyz, 1)
Next xyz

Application.Calculation = xlCalculationAutomatic

End Sub


texts: The importance of consistency in percentage returns when investing

texts:
It is said that

  Being consistent in percentage annual returns leads to larger amount over time.

That is for any given principal, getting 20% successively for 2 years is better than 30% for first year and 10% for second year even though both percentages add to 40. First case yields 44% while the later one yields 43%.

I have tried to simulate this for arbitrary number of years and arbitrary percentages using Python 3. The obvious added constraint is that sum of percentages is constant (otherwise, inconsistent arbitrarily high percentages will obviously beat consistent low percentages).

from operator import mul
from functools import reduce
import numpy as np
from collections import namedtuple
from typing import List, Tuple

def avg_cagr(percents: List[int]) -> float:
    '''Given (successive) % annual growth rates, returns average Compound Annual Growth Rate'''
    amount = reduce(mul, [1+p/100 for p in percents])
    return (amount**(1/len(percents)) - 1)*100

def dirichlet(n: int = 5, amount: float = 100) -> List[float]:
    '''Returns n random numbers which sum to "amount"'''
    random_returns = np.random.dirichlet(alpha=np.ones(n), size=1)[0]*amount
    return random_returns

def simulate_returns(n: int = 5, amount: float = 100, iterations: int = 40) -> List[Tuple[float, float]]:
    '''Generate bunch of random percentages that sum to a constant and compare average CAGR with their deviation'''
    net_returns = namedtuple('net_returns', 'deviation CAGR')
    results = []
    for _ in range(iterations):
        random_returns = dirichlet(n, amount)
        avg_returns = avg_cagr(random_returns)
        deviation = np.std(random_returns)
        results.append(net_returns(deviation, avg_returns))
    return sorted(results, key=lambda x: x.CAGR, reverse=True)

if __name__ == '__main__':
    results = simulate_returns()
    print('\n'.join(('dev=' + str(round(result.deviation, 2)) + ', ' + 'CAGR=' + str(round(result.CAGR, 2))) for result in results))

Key Ideas in the code:

Dirichlet distribution is used to generate bunch of random numbers that sum to a constant
Standard deviation is used to illustrate consistency

Result: Simulation agrees with maxim.


texts: Store the newest 100 numbers. (delete old ones)

texts:
The task is to store the newest ~100 numbers and calculate their sum.

I would like to optimize for time-performance.

Usage: In the context of sequence alignment, after creating a 2D scoring-matrix between 2 sequences, starting at the bottom right corner, I want to search for the optimal alignment path. Here I adapt previous alignment algorithms to search for the optimal alignment at a fixed alignment length. For this, the sum of the previous path isn't sufficient, but instead I want to save the values of the previous path into each cell.

storage = []
new_number = 1

def store_numbers(storage, new_number, storage_size = 100):
    storage.append(new_number)
    if len(storage)>storage_size:
        del storage[0]
    return storage, sum(storage)

#test
for x in range(100):
    print(store_numbers(storage, x, storage_size = 10)

Ideas: Avoid the function? Avoid append() - del() and instead overwrite? Instead of list use Numpy array or something else?


texts: Get properties from all children in a recursive SQL structure

texts:
In our product, Company is a model that can have many Companies belonging to it; so some Companies are parents, some are children, and many are both.

We have a helper method Company.root that has as its children all Companies that do not actually have a parent; in this way, accessing Company.root and recursively iterating over the children will touch every Company in the database.

For context, 'branches' are just Companies with a special flag set (namely that they cannot have children of their own).

We have a method Company#get_deep_props that makes one SQL call per Company below the queried Company. This has abysmal performance on some pages, and for instance when we need to do Company validation we need to check other companies in the chain for a few different values to ensure pseudo-uniqueness (can not make the column unique).

How can we improve this performance of this method? Can we cache the companies on the first call and use the ActiveRecord::Selection in subsequent calls? Not all properties of Companies are in the database (some are computed) so I don't think we can replace the code with a (sufficiently complex) SQL query in ALL cases, but we might be able to do it for some.

has_many :subdealers, class_name: "Company", foreign_key: "dealer_id"

def children
  root ? Company.where("dealer_id IS NULL") : subdealers
end

def get_deep_props(prop, options = {})
  prop            = prop.to_sym
  default_options = { :with_branches => true }
  options         = default_options.merge(options)
  child_props     = []

  children.each do |child|
    next if (child.branch? && !options[:with_branches])
    child_props.concat(child.get_deep_props(prop, options))
  end

  case prop
  when :dba_tags
    child_props.concat(read_attribute(prop).split)
  when :branches
    child_props.concat(branches)
  when :terminals
    child_props.concat(terminals)
  when :employees
    child_props.concat(employees)
  when :self
    child_props.push(self)
  else
    child_props.push(read_attribute(prop))
  end

  child_props
end

In the database, Company's dealer_id is the id of the parent Company, or null if the company has no parent.


texts:
I wrote a simple cython script to optimize the collections.Counter of a dictionary counter and the python zip implementation (the main input is a list of tuples). Is there a way to speed it up?

%%cython --annotate
cimport cython
import numpy as np
cimport numpy as np
from collections import defaultdict

@cython.boundscheck(False)
@cython.wraparound(False)
def uniqueCounterListCython(list x not None):

    cdef:
        Py_ssize_t i,n

    n = len(x)
    dx = defaultdict(int)
    for i from 0 <= i < n:
        dx[x[i]] += 1
    return dx

@cython.boundscheck(False)
@cython.wraparound(False)
def zipCython(np.ndarray[long,ndim=1] x1 not None, np.ndarray[long,ndim=1] x2 not None):

    cdef:
        Py_ssize_t i,n

    n = x1.shape[0]
    l=[]
    for i from 0 <= i < n:
        l.append(((x1[i],x2[i])))
    return l

Sample input -

uniqueCounterListCython(zipCython(np.random.randint(0,3,200000),np.random.randint(0,3,200000)))

EDIT:
Found a kind of trivial way to speed things up - just merge the two functions:

@cython.boundscheck(False)
@cython.wraparound(False)
def uniqueCounterListCythonWithZip(np.ndarray[long,ndim=1] x1 not None, np.ndarray[long,ndim=1] x2 not None):

    cdef:
        Py_ssize_t i,n

    n = x1.shape[0]
    dx = defaultdict(int)
    for i from 0 <= i < n:
        dx[((x1[i],x2[i]))] += 1
    return dx

Any more suggestions?


texts:
This code is a multi-threaded version of filter that uses pipes to communicate between the workers and the main thread. I am looking for any ways to make this code cleaner. I'm also interested in if there is anything I can do to make this play nicely with infinite iterators.

from multiprocessing import Process, Pipe
from itertools import cycle, count

def distributer(f, data):
    def worker(pipe):
        while True:
            piece = pipe.recv()
            if f(piece):
                pipe.send(piece)
            pipe.send(False)

    pipes = []
    for _ in range(8):
        parent_conn, child_conn = Pipe()
        p = Process(target=worker, args=(child_conn,))
        pipes.append(parent_conn)
        p.start()
        parent_conn.send(next(data))

    for pipe in cycle(pipes):
        if pipe.poll(.0001):
            ans = pipe.recv()
            if ans:
                yield ans
            pipe.send(next(data))

if __name__ == '__main__':
    def g(x):
        return x%1000==0
    data = count(1)
    for ans in distributer(g, data):
        print(ans)


texts: Codility Fish (queue) programming challenge

texts:
Today I have attempted a Codility exercise "Fish" (https://app.codility.com/programmers/lessons/7-stacks_and_queues/fish/), and I have to say I found it to be:
1) Not necessarily "easy" as implied by the page, AND
2) Quite satisfying to figure out in the end.
Below the text of the challenge:

  You are given two non-empty arrays A and B consisting of N integers.
  Arrays A and B represent N voracious fish in a river, ordered
  downstream along the flow of the river.

  The fish are numbered from 0 to N − 1. If P and Q are two fish and P <
  Q, then fish P is initially upstream of fish Q. Initially, each fish
  has a unique position.

  Fish number P is represented by A[P] and B[P]. Array A contains the
  sizes of the fish. All its elements are unique. Array B contains the
  directions of the fish. It contains only 0s and/or 1s, where:

  0 represents a fish flowing upstream,
  1 represents a fish flowing downstream.

  If two fish move in opposite directions and there are no other
  (living) fish between them, they will eventually meet each other. Then
  only one fish can stay alive − the larger fish eats the smaller one.
  More precisely, we say that two fish P and Q meet each other when P <
  Q, B[P] = 1 and B[Q] = 0, and there are no living fish between them.
  After they meet:

  If A[P] > A[Q] then P eats Q, and P will still be flowing downstream,
  If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream.

  We assume that all the fish are flowing at the same speed. That is,
  fish moving in the same direction never meet. The goal is to calculate
  the number of fish that will stay alive.

My solution is a bit playful, and I was wondering if anyone could have a look and let me know if this is a correct way of solving this problem. All comments will be appreciated.

import java.util.ArrayDeque;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public int solution(int[] A, int[] B) {

        ArrayDeque<Fish> safetyPool = new ArrayDeque<Fish>();
        ArrayDeque<Fish> activePool = new ArrayDeque<Fish>();

        for (int i = 0; i < A.length; i++) {
            activePool.offer(Fish.cFish(A[i], B[i]));
        }

        while(!activePool.isEmpty()) {
            // System.out.println(safetyPool + " " + activePool);
            Fish safeFish = safetyPool.peekLast();
            Fish swimmingFish = activePool.peekFirst();

            if (safeFish != null) {
                if (safeFish.dir == 1) {
                    if (safeFish.dir != swimmingFish.dir) {
                        if (safeFish.att > swimmingFish.att) {
                            activePool.removeFirst();
                        } else {
                            safetyPool.removeLast();
                        }
                    } else {
                        safetyPool.offer(activePool.pollFirst());
                    }
                } else {
                    safetyPool.offer(activePool.pollFirst());
                }
            } else {
                safetyPool.offer(activePool.pollFirst());
            }
        }
        return safetyPool.size();
    }
}

class Fish {
    public int att;
    public int dir;

    public Fish(int att, int dir) {
        this.att = att;
        this.dir = dir;
    }

    public static Fish cFish(int att, int dir) {
        return new Fish(att, dir);
    }

    @Override
    public String toString() {
        return String.format("Fish(att: %d, dir: %d)", att, dir);
    }
}
```


texts: Find the number of K-Complementary pairs in an array

texts:
Below is the program to find k-complementary pairs: K = A[i] + A[j];.

package org.test;

import java.util.HashMap;
import java.util.Map;

public class ComplementaryPairs {

    public int noOfComplementaryPairs(int arr[],int k){
        int result = 0;
        for(int i=0;i<=arr.length;i++){
            for(int j=i;j<arr.length-1;j++){
                if(arr[i] + arr[j+1] == k){
                    result++;
                }
            }
        }
        return result * 2;
    }
    public static void main(String[] args) {
        int[] intArray = new int[] {4,5,6,3,1,8,-7,-6};
        int k = 1;
        System.out.println("No of k complementary pairs : "+new ComplementaryPairs().noOfComplementaryPairs(intArray, k));
    }

}

What is the time complexity of the above program? Is there a better way to optimize it further?


texts:
Please review my code.

public class CircularLinkedlistinsert {
    private Node first;

    private static class Node {
        int element;
        Node next;

        public Node(int element, Node next) {
            this.element = element;
            this.next = next;
        }
    }

    public void insertNodeInCircularLL(int element) {
        Node node = new Node(element, null);
        if (first == null) {
            first = node;
            first.next = first;
        } else {
            Node current = first;
            do {
                if (((current.element <= element)  && (current.next.element >= element)) || current.next == first)  {
                    node.next = current.next;
                    current.next = node;
                    if (element < first.element) {
                        first = node;
                    }
                    return;
                }
                current = current.next;
            } while (current != first);
        }
    }
}


texts: Product of all but one number in a sequence - Follow Up (2)

texts:
This code is a improved version of implementation which asked for a review: Product of all but one number in a sequence.
#include <stdio.h>
#include <stdlib.h>

//without division, with O(n) time, but extra space complexity as suggested
//return new array on the heap
int *derive_products(const int *nums, int count)
{
    int *retval = malloc(count * sizeof *retval);
    if (!retval && count)
        return 0;

    int mult=1; //product of prefix or suffix elements

    //swipe up
    for(int i=0; i<count; i++) {
        retval[i] = mult;
        mult *= nums[i];
    }

    //swipe down
    for(int j=count-1, mult=1; j>=0; j--) {
        retval[j] *= mult;
        mult *= nums[j];
    }

    return retval;
}

int main()
{
    /*Given an array of integers, return a new array such that each element at index i of the
    new array is the product of all the numbers in the original array except the one at i.
    For example, if our input was [1, 2, 3, 4, 5], the expected output would be
    [120, 60, 40, 30, 24] */
    int nums[] = {1, 2, 2, 4, 6};
    int size = sizeof(nums)/sizeof(nums[0]);

    int *products = derive_products(nums, size); //get a new array

    for (int i = 0; i < size; i++)
        printf("%d ", products[i] );

    free(products); //release heap memory

}


texts:
I've read so much arguing about "sort by value maps". Well, I wrote the following log(n) sort by value Map . And, by the way, a real Map , does not allow duplicate keys. Many of the maps I googled ignore that annoying problem. I assume this map is still log(n)...:

public static void sortByValue_logN() {

    class MyComp implements Comparator {
        Map<Object, Integer> sharedMap;

        public int compare(Object key1, Object key2) {
            if(key1.equals(key2)) { return 0; }

            Integer val1 = sharedMap.get(key1);
            Integer val2 = sharedMap.get(key2);

            if(val1 > val2) return -1;
            return 1;
        }

    }

    class TreeMapByValue<K> extends TreeMap<K, Integer> {
        Map<Object, Integer> sharedMap = new HashMap<Object, Integer>();
        TreeMapByValue(Comparator comp) {
            super(comp);
        }

        @Override
        public Integer put(K key, Integer val) {
            if(sharedMap.containsKey(key)) {
                super.remove(key);
                val += sharedMap.get(key);
            }
            sharedMap.put(key, val);

            super.put(key, val);

            return val;
        }
    }

    MyComp myComp = new MyComp();
    TreeMapByValue<Object> myMap = new TreeMapByValue(myComp);
    myComp.sharedMap = myMap.sharedMap;

    // all the rest is just testing the map
    Random rand = new Random();
    String[] story = { "The", "quick", "brown", "fox", "jumped" };

    for(int repeat = 0; repeat < 3; repeat++) {
        for(int i = 0; i < story.length; i++) {
            String key = story[i];
            int value = rand.nextInt(100);
            myMap.put(key, value);
            System.out.println(key + "-->" + value);
        }
    }

    for(Map.Entry<Object, Integer> entry : myMap.entrySet()) {
        System.out.println("key = " + entry.getKey() + "___value = " + entry.getValue());
    }
}

Surely (at least stylistically) something is bad about the above code.

I don't understand generics yet, so I am ok with ignoring that for now. I am also ignoring thread-safety issues as well.

My goal is to create a log(n) "sort by value" map that respects the property of not having duplicate keys. So, what is wrong with what I did?


texts:
The purpose of this PowerShell function is to make it simpler to output XML in a given format.  For my use case, that XML did not have a schema associated, so I've not implemented any namespace logic; though suspect that could be easily added.

Code

Add-Type -AssemblyName 'System.Xml.Linq'

function Create-XmlElement {
    [CmdletBinding(DefaultParameterSetName = 'ByXMLNodes')]
    param (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 0)]
        [string]$Name
        ,
        [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByXMLNodes', Position = 1)]
        [System.Xml.Linq.XObject[]]$ChildObjects
        ,
        [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true, ParameterSetName = 'ByValue', Position = 1)]
        [object]$Value
    )
    process {
        (New-Object -TypeName 'System.Xml.Linq.XElement' -ArgumentList ([System.Xml.Linq.XName]$Name), $Value, $ChildObjects)
    }
}

function Create-XmlAttribute { #just use a function for this as there's nothing clever required
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$Name
        ,
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$Value
    )
    process {
        (New-Object -type 'System.Xml.Linq.XAttribute' -ArgumentList ([System.Xml.Linq.XName]$Name), $Value)
    }
}

Example Usage

Set-Alias -Name 'X<>' -Value 'Create-XmlElement'   #added aliases to avoid over cluttering the below definitions
Set-Alias -Name 'X@' -Value 'Create-XmlAttribute'  #hopefully that makes the code a little easier to read
                                                   #I had gone with CXE and CXA, but then figured this notation may be clearer (though possibly risky / more confusing for some?)
(
    X<> 'Root' @(
        (X@ 'attribute1' 'attribute''s value'),
        (X<> 'hello' 'valuex'),
        (X<> 'hello2' (
            X<> 'aDate' (Get-Date)
        ))
    )
).ToString()

Output

The above example produces this XML:

<Root attribute1="attribute's value">
  <hello>valuex</hello>
  <hello2>
    <aDate>2017-06-09T16:09:27.0538147+01:00</aDate>
  </hello2>
</Root>


texts:
With help from the codereview community, I've written a function to flatten a generic nested array. I have it written several ways but want to focus on the following implementation:

func flatten (input: [Any]) -> [Any] {

    var outputArray = [Any] ()

    for i in 0..<input.count {
        let data = input[i];
        (data is [Any]) ? outputArray += flatten(input: data as! [Any]) : outputArray.append(data)

    }

    return outputArray

}

Is there a more "swifty" way to write this without using higher order functions?

Additionally, I've been reading about tail call optimization and wonder how I can make this tail call optimized?


texts:
I have a String with a double number. Unfortunately, the number is created on backends with different locals, so it could be both 101.02 and 101,02 (different delimiters). I need to get the position of this delimiter if it exists and get 0, if it is not.

I've come to two options:

int pos = amount.indexOf(',') == -1 ?
                (amount.indexOf('.') == -1 ? 0 : amount.indexOf('.'))
                : amount.indexOf(',');

Second option with the same logic but different style:

int pos = amount.indexOf(',');
if (pos == -1) pos = amount.indexOf('.');
if (pos == -1) pos = 0;

I do not need to have a double number from String, I just need the position of the delimiter to color the String (using the Android class Spannable).

Is there a cleaner way to achieve this goal? And which of these styles are better, in your opinion? Is there some way to use the DecimalFormat class to achieve the goal?


texts: Bubble sort a list of integers for a number of iterations

texts:
I wrote a program for this problem, but it stopped because it took too much time. Any tips?

The Problem:
Bubble sort is the simplest algorithm for elements sorting. At each iteration we sequentially compare values of subsequent elements and swap them if necessary.

Your job is to write a program which finds a state of a given list of positive integer numbers after applying a given count of bubble sort iterations

Input Sample:
Each line contains a space-separated list of positive integers and ends with a number of iterations, separated by vertical line ‘|’. Example:

48 51 5 61 18 | 2

Output Sample:

5 48 18 51 61

Explanation:

Iteration 1: 48 5 51 18 61

Iteration 2: 5 48 18 51 61

My code:

def bubsort(num, iters):
    itered = 1
    while itered != iters + 1:
        nums = sorting(num)
        itered += 1
    print ' '.join(num)

def sorting(num):
    for i in xrange(len(num) - 1):
        challenger = int(num[i])
        opponent = int(num[i + 1])
        if challenger > opponent:
            num[i], num[i + 1] = num[i + 1], num[i]
    return num

test = raw_input()
whole = test.strip().split(' | ')
num = whole[0].split()
iters = int(whole[1])
bubsort(num, iters)


texts:
How can I improve this code?

public class Address {
   public string house_no { get; set; }
   public string street { get; set; }
   public string zip { get; set; }
}
public class Contact {
   public string email { get; set; }
   public string ph_no { get; set; }
   public Address address { get; set; }
}

//Test program
class Program {
    static void GetContacts(string input)   {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        Dictionary<string, Contact> ContactList = serializer.Deserialize<Dictionary<string, Contact>>(input);
    }

    static void Main(string[] args)     {
        //jsonText is a string that I retrieve from a web service.
        string jsonText = ws.GetContactList();
        GetContacts(jsonText);
    }
}


texts: Project Euler problem 530 - GCD function is inefficient

texts:
Here is a description of Project Euler problem 530:

  Every divisor \$d\$ of a number \$n\$ has a complementary divisor \$n/d\$.

  Let \$f(n)\$ be the sum of the greatest common divisor of \$d\$ and \$n/d\$ over all positive divisors \$d\$ of \$n\$, that is \$\displaystyle f(n)=\sum_{d/n}\gcd\left(d, \frac{n}{d}\right)\$.

  Let \$F\$ be the summatory function of \$f\$, that is \$\displaystyle F(k) = \sum_{n=1}^{k}f(n)\$.

  You are given that \$F(10)=32\$ and \$F(1000)=12776\$.

  Find \$F(10^{15})\$.

Yesterday, I asked a question here: Project Euler Problem 530: sum of sum of greatest common divisors

I have improved my solution, which is now as follows:

import java.math.BigInteger;

public class problem530 {

public static void main(String[] args) {

    double start = System.nanoTime();

    BigInteger result = BigInteger.ZERO;
    long target = 100000;

    for (long i = 1; i*i <=  target; i++){
                for(long j = i; i*j <= target; j++) {
                    if (i != j) {
                    result = result.add(BigInteger.valueOf((GCD(i, j))*2));
                }
                    else {
                        result = result.add(BigInteger.valueOf(i));
                    }
                }
            }

    System.out.println(result);

    double duration = (System.nanoTime() - start)/1000000000;

    System.out.println("Your code took " + duration + " seconds to execute.");

}

public static long GCD (long p, long q) {
    if (p == 0) return q;
    else return GCD (q%p,p);
}

This solution uses a simplified version of the summation (it avoids factorisation).

However, the GCD function I'm using is computationally expensive and causes the code to be incapable of finding F(x) for large values of x.

Currently:

It ran F(10^1) = 32 in 0.0027 seconds.
It ran F(10^3) = 12766 in 0.0042 seconds.
It ran F(10^5) = 2907546 in 0.091 seconds.
It ran F(10^7) = 518387613 in 8.034 seconds.
It ran F(10^8) = 6563728768 in 97.368 seconds.

Clearly, to find F(10^15) would be practically impossible.

I think the solution might be to memoize the GCD function, or find some way to make it linearly more difficult, as opposed to exponentially, which is now happening.

Suggestions?

EDIT: I am not using the summation from the question. I'm using a simplified version of it.

This was suggested in another post on codereview, and it works, as long as I account for symmetry (the multiply by 2 part of the code), except when it's a perfect square.


texts: Counting Balanced numbers in a given array

texts:
I am trying a code challenge. Here is the problem description:

When an element is deleted from an array, the higher-indexed elements shift down one index to
fill the gap. A "balancing element" is defined as an element that, when deleted from the array,
results in the sum of the even-indexed elements being equal to the sum of the odd-indexed
elements. Determine how many balancing elements a given array contains.

Example
n=5 where n is the size, arr = [5, 5, 2, 5, 8]

When the first or second 5 is deleted, the array becomes [5, 2, 5, 8]. The
sumeven = 5 + 5 = 10
and sumodd = 2 + 8 = 10. No other elements of the original array have that
property.

There are 2 balancing elements that is arr[0] and arr[1].

And here is my solution:
public class Challenge {
  public static void main(String[] args) {
    countBalancingElements(new int[] {1, 1, 1});
  }
  static int countBalancingElements(int[] arr) {
    int count = 0;
    for (int i = 0; i < arr.length; i++) {
      if (evenIndexValEqualsOddIndexVal(removeElementInArr(arr, i))) {
        count++;
      }
    }
  }
  static int[] removeElementInArr(int[] arr, int index) {
    int[] result = new int[arr.length - 1];
    for (int i = 0, j = 0; i < arr.length && j < result.length; i++, j++) {
      if (i == index) {
        result[j] = arr[i + 1];
        i++;
      } else {
        result[j] = arr[i];
      }
    }
    return result;
  }
  static boolean evenIndexValEqualsOddIndexVal(int[] arr) {
    int evensum = 0;
    int oddsum = 0;
    for (int i = 0; i < arr.length; i++) {
      if (i % 2 == 0) {
        evensum += arr[i];
      } else {
        oddsum += arr[i];
      }
    }
    return evensum == oddsum && evensum != 0 && oddsum != 0;
  }
}

It looks like its runtime is \$O(n^2)\$.
evensum != 0 && oddsum != 0; is added to satisfy this input [0, 0], but it breaks for input {-5, 7, 0, 5 } whose evensum and oddsum is 0. So, cases like [0,0] are to be dealt with separately.


texts:
I want to have a continuous date sequence like ['2014-01-01','2014-01-02', ...]

Then I define a stream to do that.

def daySeq(start: Date): Stream[Date] = Stream.cons(start,  daySeq(plusDays(start, 1)))

I get the sequence within range [start, end) by calling

daySeq(from).takeWhile(_.getTime < to.getTime)

Any better/simple solution to do this ?