texts: Creating a Navbar Menu from JSON data with Lodash

texts:
I am trying to create a navbar menu from JSON data. Actually I have achieved it but I am looking for feedback not to call getItems twice? How can I improve my code?
Thank you
var _ = require('lodash');

let menuConfig = [
    {
        ID: 1,
        TAG: "M:A",
        PARENT_TAG: "MAIN",
        TITLE: "A Title"
    },
    {
        ID: 2,
        TAG: "AS1",
        PARENT_TAG: "M:A",
        TITLE: "A Subtitle 1"
    },
    {
        ID: 3,
        TAG: "AS2",
        PARENT_TAG: "M:A",
        TITLE: "A Subtitle 2"
    },
    {
        ID: 4,
        TAG: "AS3",
        PARENT_TAG: "M:A",
        TITLE: "A Subtitle 3"
    },
    {
        ID: 5,
        TAG: "M:B",
        PARENT_TAG: "MAIN",
        TITLE: "B Title"
    },
    {
        ID: 6,
        TAG: "BS1",
        PARENT_TAG: "M:B",
        TITLE: "B Subtitle 1"
    },
    {
        ID: 7,
        TAG: "BS2",
        PARENT_TAG: "M:B",
        TITLE: "B Subtitle 2"
    },
    {
        ID: 8,
        TAG: "M:C",
        PARENT_TAG: "MAIN",
        TITLE: "C Title"
    },
    {
        ID: 8,
        TAG: "CS1",
        PARENT_TAG: "M:C",
        TITLE: "C Subtitle 1"
    }
]

function getMenu() {
    let grouped = _.groupBy(menuConfig, "PARENT_TAG");
    let menu = getItems(grouped.MAIN, grouped);
    console.log(JSON.stringify(menu, null, 3));
}

function getItems(items, grouped) {
    let subMenu = [];
    _.forEach(items, (item) => {
        let newItem = getItem(item, grouped)
        if (newItem) {
            subMenu.push(newItem);
        }
    });
    return subMenu;
}

function getItem(item, grouped) {
    if (grouped[item.TAG]) {
        let subMenu = getItems(grouped[item.TAG], grouped);
        if (subMenu && subMenu.length) {
            return {
                title: item.TITLE,
                subMenu: subMenu
            }
        }
    } else {
        let newItem = {
            title: item.TITLE
        }
        return newItem;
    }
}

getMenu();

Output needs to be like this;
[
  {
    "title": "A Title",
    "subMenu": [
      {
        "title": "A Subtitle 1"
      },
      {
        "title": "A Subtitle 2"
      },
      {
        "title": "A Subtitle 3"
      }
    ]
  },
  {
    "title": "B Title",
    "subMenu": [
      {
        "title": "B Subtitle 1"
      },
      {
        "title": "B Subtitle 2"
      }
    ]
  },
  {
    "title": "C Title",
    "subMenu": [
      {
        "title": "C Subtitle 1"
      }
    ]
  }
]


texts: Derived Class to keep track of "original strings" in std::regex and ease out their usage while coding

texts:
We all know that std::regex class doesn't allow access to the original string which was used as the source expression. (In fact, GCC even keeps the original string as _M_original_str, but won't allow external access. Still, I have not used this member because it is implementation detail.)

So I derived a lightweight class to so that the std::regex will seem to behave like the string it was created from, well... not exactly, but kind of close. It lets the std::regex do its thing, but also keeps a record of the current string associated with the regex expression as its own member. And uses this member to allow new behaviors.

It allows direct retrieval of the original string. It also allows direct comparison with a std::string to check for equality, which in turn allows two regex's to be checked for equality.

But there's a catch. To check for equality, it uses the tracked string inside both objects to check for equality, which is a little flawed because two distinct strings can lead to same regex. So in that case it fails.

Also, since a constructor called with no arguments must create a regex object which matches nothing, I've accounted for that by keeping track of it in the derived class by maintaining a bool.

I want to know if it is good enough?
Have I tied up all loose ends while deriving from std::regex?
Can using it carelessly create unexpected errors?

So here it is:

#include <iostream>
#include <regex>
#include <string>

using namespace std;

class Regex: public regex
{
public:
    Regex ();
    Regex ( const string& str, flag_type flag = regex::ECMAScript );
    Regex ( const Regex& rhs );

    Regex& Assign ( const string& str, flag_type flag = regex::ECMAScript );
    Regex& Assign ( const Regex& rhs );

    string GetSourceStr () const { return m_str; }

    Regex& operator= ( const string& str ) { return this->Assign( str, flags() ); }
    Regex& operator= ( const Regex& rhs ) { return this->Assign( rhs ); }

    bool operator== ( const Regex& rhs ) const
      { return  m_str == rhs.m_str && m_match_nothing == rhs.m_match_nothing; }

    bool operator== ( const string& rhs_str ) const
      { return  m_str == rhs_str && !m_match_nothing; }

private:
    string m_str;
    bool m_match_nothing;
};

Regex::Regex ()
: regex(), m_str( "" ), m_match_nothing( true )
{}

Regex::Regex ( const string& str, flag_type flag )
: regex( str, flag ), m_str( str ), m_match_nothing( false )
{}

Regex::Regex ( const Regex& rhs )
: regex( rhs ), m_str( rhs.m_str ), m_match_nothing( rhs.m_match_nothing )
{}

Regex& Regex::Assign( const string& str, flag_type flag )
{
    m_str = str;
    m_match_nothing = false;
    regex::assign( str, flag );

    return *this;
}

Regex& Regex::Assign( const Regex& rhs )
{
    if ( this == &rhs ) return *this;

    m_str = rhs.m_str;
    m_match_nothing = rhs.m_match_nothing;
    regex::assign( rhs );

    return *this;
}

int main()
{
    string text;
    string blank_str;

    Regex pattern; // default regex object: matches nothing
    Regex pattern2(""); // a regex object which only matches a blank string

    cout << (regex_match(blank_str, pattern) ? "1 match" : "1 no_match") << "\n"
         << (regex_match(blank_str, pattern2) ? "2 match" : "2 no_match") << "\n"
         << (pattern==pattern2 ? "1==2" : "1!=2") << "\n\n";

    pattern = "a*c+";
    cout << (pattern=="a*c+" ? "yeah" : "nah") << "\n"
         << (pattern=="abc+" ? "yeah" : "nah") << "\n";

    return 0;
}


texts:
I am hoping to make this method run a little faster. I typically need to run this on a list with more than 100000 entries. Note that at the start and end of the list, I wish to weight the average so that it is closer to the start or end value, hence the smaller framesize.

public PointPairList GetMovingAverage(int frameSize, PointPairList data)
{
    PointPairList movAvgPoints = new PointPairList();
    //Smooth each point in the list
    for (int i = 0; i < data.Count; i++)
    {
        //get the window range
        int actualFrameSize = frameSize;
        int start = i - (frameSize/2);
        int end = i + (frameSize/2);
        //ensure the window is the same size at the source list boundaries
        if (start < 0)
        {
            actualFrameSize = frameSize + start;
            start = 0;
        }
        if (end >= data.Count)
        {
            actualFrameSize = frameSize + (data.Count - 1 - end);
        }
        //Now get the sum of the window
        double sum = data.Skip(start).Take(actualFrameSize).Sum(p => p.Y);
        //add the average point to the result
        movAvgPoints.Add(new PointPair(data[i].X, sum/actualFrameSize));
    }
    return movAvgPoints;
}


texts: Type to represent multiple possible values

texts:
I created this type for use in a "Wizard"-style user interaction. In each step, the user chooses an option called a Modifier and each of those options contains subselections that must be made.

These Modifiers are stored with two parallel structures, one of the fixed values and a second of the selectable ones using this type. When the uses chooses a suboption, the chosen value is merged into the fixed values and when completed, the values are used to modify the wizard model.

/**
 *  A portion of a modifier that consists of a set of possible values and a number of them
 *  that will be selected. After selection, the selected values will be added to the set values
 *  of the modifier.
 */
export class SelectableModifier {

    constructor(numSelectionsNeeded:number, options:Array<any>, selectionTime:string) {
        this._numSelectionsNeeded = numSelectionsNeeded;
        this._options = options;
        this._selectionTime = selectionTime;
    }

    /**
     * The number of options that need to be selected.
     */
    private _numSelectionsNeeded:number;
    /**
     * The available options
     */
    private _options:Array<any>;

    private _selectionTime:string;

    /**
     * Choose from this selection, decomposing it into the selected options.
     *
     * @param chosenIndices
     */
    public makeSelection(chosenIndices:Array<Number>):Array<any> {
        if (chosenIndices.length != this._numSelectionsNeeded) {
            throw "The selection requires that " + this._numSelectionsNeeded + " selections be made but " + chosenIndices.length + " were instead."
        }
        return this._options.filter((element, index)=> {
            return chosenIndices.indexOf(index) !== -1;
        });
    }

    get numSelectionsNeeded():number {
        return this._numSelectionsNeeded;
    }

    get options():Array<any> {
        return this._options;
    }

    get selectionTime():string {
        return this._selectionTime;
    }
}


texts:
I often find myself writing LINQ queries like this.  I end up testing for Null and zero-counts pretty often, and the code sprawls out to be something like the following:

// GET: api/CustomBehaviours
public IEnumerable<CustomBehaviour> Get(int? orgID = null, long? userID = null)
{
    using (PAMDatabase db = new PAMDatabase(WebApiConfig.PAMConnectionString))
    {
        List<CustomBehaviour> output = new List<CustomBehaviour>();

        // Add all custom behaviours for the specified user
        if (userID != null) {
            var usr = db.context.users.AsNoTracking().Where(u => u.userID == userID).FirstOrDefault();
            if (usr != null)
            {
                var cbs = usr.customBehaviours.ToList();
                if ((cbs != null) && (cbs.Count > 0))
                    output.AddRange(Mapper.Map<List<CustomBehaviour>>(cbs));
            }
        }

        // Add all custom behaviours for the specified organisation
        if (orgID != null)
        {
            var org = db.context.orgs.AsNoTracking().Where(o => o.orgID == orgID).FirstOrDefault();
            if (org != null)
            {
                var cbs = org.customBehaviours.ToList();
                if ((cbs != null) && (cbs.Count > 0))
                    output.AddRange(Mapper.Map<List<CustomBehaviour>>(cbs));
            }
        }

        return output;
    }
}

Can this be made more concise?  I'm tempted to remove all the Null checks and wrap the whole thing in a big try { } catch {} but I believe that goes against the conventional use of exceptions.


texts:
I'm fairly new to JavaScript and Node and am wondering if I'm on the right track.

Module file:

'use strict';

var chalk = require('chalk');
var config = require('../config');
var moment = require('moment');
var rp = require('request-promise');

var todayDay = moment().format('dddd'); // ["Monday"]"
var todayDate = moment().format('DD').replace(/^0+/, ''); // "1"
var todayMonth = moment().format('MMMM'); // ["January"]

rp({
  method: 'GET',
  uri: config.api.uri + '/tasks',
  qs: {
    access_token: config.api.accessToken,
    project_id: config.api.projectId,
    page_size: 5
  },
  json: true
})
  .then(function(res) {
    console.log(res);
    var data = res.data;

    data.forEach(function(val) {

      // day is today or date and month is today
      if (val.custom_fields.custom_353.indexOf(todayDay) > -1 ||
        val.custom_fields.custom_356.indexOf(todayMonth) > -1 && val.custom_fields.custom_358 == todayDate) {

        // post
        rp({
          method: 'POST',
          uri: config.api.uri + '/incidents',
          qs: {
            access_token: config.api.accessToken
          },
          body: {
            item: {
              name: val.name,
              description: val.description,
              due_date: moment().toISOString(),
              assigned_to: {
                type: val.assigned_to.type,
                id: val.assigned_to.id
              },
              project: {
                id: config.api.projectId
              },
              custom_fields: {
                custom_361: val.custom_fields.custom_384, // sequence
                custom_352: val.custom_fields.custom_270, // time
                custom_354: val.custom_fields.custom_269, // procedure
                custom_277: val.custom_fields.custom_183, // service group
                custom_278: val.custom_fields.custom_184 // service
              }
            }
          },
          json: true
        })
          .then(function(res) {
            console.log(chalk.green(val.name));
          })
          .catch(function(err) {
            console.log(chalk.red(err));
          });
      } else {
        console.log(chalk.grey(val.name));
      }
    });
  })
  .catch(function(err) {
    console.log(chalk.red(err));
  });

Config file:

'use strict';

var env = process.env.NODE_ENV || 'development';
var config = {};

switch (env) {
  case 'development':
    config = require('../env/development/config.json');
    break;
  case 'production':
    config = require('../env/production/config.json');
    break;
};

module.exports = config;


texts: Strongly connected components in a graph: Kosaraju's algorithm

texts:
I implemented Kosaraju's algorithm on a graph with 800k vertices and 5100k edges.
The time taken by various operations are:
  building graph took  11.84  seconds
  ordering took  2.54 seconds
  finding SCCs took  2.63  seconds
My computer has an i7 with 4GB RAM.
I would like to know if my code can be made more efficient.
How can I improve the way I've approached the problem?

def makeGraph(txtfile):
    '''Makes a graph(defaultdict) from given text file
        Input: txt, each line's first element gives tail, next is head of an edge
        Output: defaultdict, each vertex as a key with two values'''
    Graph = defaultdict(lambda:[[],[]])
    with open(txtfile) as graphRep:
        for line in graphRep:
            tail,head = line.split()
            tail,head = int(tail),int(head)
            Graph[tail][0].append(head) #edge from key(tail) to head
            Graph[head][1].append(tail) #above edge reversed
    return Graph

def dfs_Order_main(G):
    ''' outer loop for dfs call, iterates through each vertex
        calls dfs on it if has not been explored
        Input: Graph(defaultdict)
        Output: Order(dict)'''
    Order = {} #stores time taken to explore a vertex
    count =[1]
    toVisit = []
    visited = set()
    for vert in range(1,len(G.keys())+1):
        if vert not in visited:
            dfs_Order(G,vert,Order,visited,count)
    return Order

def dfs_Order(G,vert,Order,visited,count):
    toVisit = [vert]
    while len(toVisit)>0:
        nextNode = toVisit[-1] #LIFO
        if G[nextNode][1] == []: #no more edges to explore (terminating condition)
            visited.add(nextNode) # completed exploring
            v = toVisit.pop()
            Order[count[0]]=v #store time
            count[0] +=1
        else:
            visited.add(nextNode)
            for i in G[nextNode][1]:
                if i not in visited:
                    visited.add(i)
                    toVisit.append(i)
            G[nextNode][1] = [] #after adding a vertex's edges, set it to []
    return                                    #used as terminating condition

def dfs_scc_main(G,order):
    ''' outer loop for dfs call, iterates through each vertex
        calls dfs on it if has not been explored
        Input: Graph(defaultdict),order in which vertices are to be explored
        Output: scc(defaultdict), strongly connected components'''
    scc = defaultdict(int)
    toVisit = []
    visited = set()
    for i in range(len(order),0,-1): #traverse in decreasing order of time
        vert = order[i]                         #taken to explore a vertex
        if vert not in visited:
            dfs_scc(G,vert,scc,visited)
    return scc

def dfs_scc(G,lead,scc,visited):
    toVisit = [lead]
    scc[lead] +=1 #increments the value for a leader
    while len(toVisit)>0:
        nextNode = toVisit[-1]
        if G[nextNode][0] == []:
            visited.add(nextNode)
            toVisit.pop()
        else:
            visited.add(nextNode)
            for i in G[nextNode][0]:
                if i not in visited:
                    scc[lead] +=1
                    visited.add(i)
                    toVisit.append(i)
            G[nextNode][0] = []
    return


texts:
I have a code that works but is very badly written. The main is very verbose, it is just to test the class.
I want to make objects move on a chessboard (a coordinate grid). I've defined these object as Vehicles. They have a position (x,y) on the plane and a direction. Being forced to move only North-South-East-West possible directions could be

North: (0, 1)
South: (0, -1)
East: (1, 0)
West: (-1, 0)

Vehicles can proceed only step by step (x+1, y), (x, y+1), where x, y are integers. Two vehicles cannot stand in the same position. A vehicle maintains its direction while it is possible, that is while it encounters an occupied position.

So I have to create a void move function which has as arguments the positions of the nearby vehicles (North South East West). Such a function should:

Check if the vehicle can maintain its direction and, if it can, refresh the vehicle position with the new position;
If the cell is occupied, go for another direction, check if the cell in that direction is free...
If every cell surrounding the vehicle is occupied, stay still.

I wrote a code that accomplish point 1 but I have difficulties with point 2. In particular, I can't think about a smart way to change the Vehicle's direction. Here's my code so far, it works but surely this is not the best way to do what I want to do:

 #include <iostream>
#include <cmath>

using namespace std;

class Vehicle {
private:
    int x, y;
    int vx, vy;
public:
    int getx() { return x;}
    int gety() { return y;}
    int getvx() { return vx;}
    int getvy() { return vy;}
void sety(int a) { y = a;}
void setx(int a) { x = a;}
void setvx(int a) {
    if (a != 0) {
        vx = a / abs(a);
    }else { vx = a;}
}
void setvy(int a) {
    if (a != 0) {
        vy = a / abs(a);
    }else { vy = a;}
}

void move(Vehicle * v) {
    int big = 0;
    int per[8];
    per[0]=0;   // North
    per[1]=1;
    per[2]=0;   // South
    per[3]=-1;
    per[4]=1;   // West
    per[5]=0;
    per[6]=-1;  // East
    per[7]=0;

    while(big<8) {
        int cont=0;
        for(int i=0; i<4; i++) {
            if (x+vx != v[i].getx() or y+vy != v[i].gety()) {
                cont ++;
            }
        }
        if(cont==4) {
            x = x + vx;
            y = y + vy;
            break;
        } else {
            vx = per[big];
            vy = per[big+1];
            big = big + 2;
        }
    }
}

void print() {
    cout << "x: " << x << endl;
    cout << "y: " << y << endl;
    cout << "vx: " << vx << endl;
    cout << "vy: " << vy << endl;
    cout << endl;
}

};

int main() {
Vehicle x;
x.setx(0);
x.sety(0);
x.setvx(0);
x.setvy(1);
x.print();

Vehicle v[4];

v[0].setx(0);
v[0].sety(1);
v[1].setx(-1);
v[1].sety(0);
v[2].setx(0);
v[2].sety(-1);
v[3].setx(1);
v[3].sety(0);

for(int i = 0; i<4; i++) {
    v[i].setvx(0);
    v[i].setvy(1);
    v[i].print();
}

x.move(v);
x.print();

v[2].setx(0);
v[2].sety(-2);
v[2].print();

x.move(v);
x.print();

}


texts:
I asked a previous question of this same program. I would like more opinions before I submit this assignment since I edited the program after receiving feedback last time.

public class Room_Dimension
{
    //Data fields
    private double length;
    private double width;

    //Constructor
    public Room_Dimension(double length, double width)
    {
        super();
        this.length = length;
        this.width = width;
    }

    //Copy constructor
    public Room_Dimension(Room_Dimension rd)
    {
        this.length = rd.getLength();
        this.width  = rd.getWidth();
    }

    //Accessors
    public double getLength()
    {
        return length;
    }

    public double getWidth()
    {
        return width;
    }

    //Mutators
    public void setLength(double length)
    {
           this.length = length;
    }

    public void setWidth(double width)
    {
           this.width = width;
    }

    //Function to calculate the area
    public double getArea()
    {
        return length * width;
    }

    //Function to display information
    public String toString()
    {
        return "Dimensions of room: (length = " + length + ", width = " + width + ")";
    }

}

public class Room_Carpet
{
    //Data fields
    private Room_Dimension rd;
    private double carpetCost;

    //Constructor
    public Room_Carpet(Room_Dimension rd, double carpetCost)
    {
        super();
        this.rd = rd;
        this.carpetCost = carpetCost;
    }

    //Copy constructor
    public Room_Carpet(Room_Carpet rc)
    {
         this.rd             = rc.rd;
         this.carpetCost     = rc.getCarpetCost();
    }

    //Function to determine total cost of carpet that will fill area
    public double getTotalCost()
    {
        return carpetCost * rd.getArea();
    }

    //Function to get size
    public Room_Dimension getSize()
    {
        return rd;
    }

    //Function to get carpet cost
    public double getCarpetCost()
    {
        return carpetCost;
    }

    //Function to display information
    public String toString()
    {
        return "" + rd + ", Carpet cost per square feet = $" + carpetCost + ", " + "Total cost = $" + getTotalCost() + "";
    }

}

public class Carpet_Calculator
{
    public static void main(String[] args)
    {
        // Create a Scanner object for keyboard input.
        Scanner keyboard = new Scanner(System.in);

        // Display information about program.
        System.out.println("This program will display the carpet cost of a room.");
        System.out.println("Please enter the following information.");

        // Get the length of the room.
        System.out.print("Enter the length of room: ");
        double length = keyboard.nextDouble();

        // Get the width of the room.
        System.out.print("Enter the width of room: ");
        double width = keyboard.nextDouble();

        // Get the cost of price per square feet of the desired carpeting.
        System.out.print("Enter the price per square feet for the desired carpeting: ");
        double carpetCost = keyboard.nextDouble();

        //Close keyboard
        keyboard.close();

        // Create Room_Dimension and Room_Carpet objects.
        Room_Dimension dimension = new Room_Dimension(length, width);
        Room_Carpet roomCarpet = new Room_Carpet(dimension, carpetCost);

        // Print the object calling the toString
        System.out.println(roomCarpet);
    }
}


texts:
I have a Perl application that allows the user to choose between two different formats for data output (and there will likely be more in the near future). In the heart of the algorithm, the code makes a call to a print subroutine.

my $stats = analyze_model_vectors( $reference_vector, $prediction_vector );
print_result( $stats, $tolerance );

The print_result subroutine simply calls more specific methods.

sub print_result
{
  if($outformat eq "text")
  {
    print_result_text(@_);
  }
  elsif($outformat eq "xml")
  {
    print_result_xml(@_);
  }
  else
  {
    # Should not reach this far if input checking is done correctly
    printf(STDERR "Error: unsupported output format '%s'\n", $outformat);
  }
}

Is this good practice? What other alternatives are there and what are their pros/cons? I could think of the following alternatives.

Test for output format in the heart of the algorithm, and call the appropriate printing subroutine there.
I've never used subroutine references before, but perhaps when I could store a reference to the correct subroutine in a scalar variable and call the print method with that scalar in the heart of the algorithm.
Place code for all output formats in a single subroutine, separated by if/elsif/else statements.

Keep in mind there may be more output formats required in the near future.


texts:
I'm using Microsoft's SqlDataConnection type provider. However, the only way I've seen to update a row in the database is to use something similar to this where it updates mutable values:

let updateProduct product =
  let currentProduct = query {
    for c in context.Product do
    where (c.Product_id = product.ProductId)
    select c }

let record = currentProduct |> Seq.head

record.Product_name <- product.ProductName
record.Product_count <- Nullable<int>(product.ProductCount)
record.Product_price <- product.ProductPrice

try
    context.DataContext.SubmitChanges()
with
    | ex -> printfn "Error when inserting - %s" ex.Message

In case it's needed, I'm using this Product type:

[<CLIMutable>]
type Product = {
  ProductId: int
  ProductName: string
  ProductCount: int
  ProductPrice: string
}

Is there a "more F# way" to handle the update instead of updating the record I find from the database?


texts:
I am new to Trees and BFS/DFS as well as programming and I decided to play around to learn how to traverse trees.

I did not want to use the shift() JavaScript function.

The constructors and code are below.  Since I am new, I would like to know how I may improve my code.  If the method implemented is inefficient, and if so, how may I make it more efficient.

I realize I could possibly combine the traverse() and secondTrav() function in to one, by including some conditionals, so I will be trying to fix this as well.

Node constructor:

function Node(data){
     this.data = data;
     this.left = null;
     this.right = null;
}

Tree constructor:

function Tree(){
      this.root = null;
}

Pushes Nodes in to Tree (Binary):

Tree.prototype.push = function(val){

     var root = this.root;

     if(root === null){
       this.root = new Node(val);
       return;
     }

     var currentNode = root;
     var newNode = new Node(val);

     while(currentNode !== null){
       if(val < currentNode.data){
         if(currentNode.left === null){
           currentNode.left = newNode;
           break;
         }else{
           currentNode = currentNode.left;

         }
       }else{
         if(currentNode.right === null){
           currentNode.right = newNode;
           break;
         }else{
           currentNode = currentNode.right;
         }
       }
     }
   }

Function to implement BFS, returns Node values as an Array:

Can traverse() and secondTrav() be combined?

function bfs(tr){

    var stackLeft=[];
    var stackRight=[];
    var order = [];
    var currentNode1 = tr.root;

    stackLeft.push(currentNode1);
    traverse(stackLeft);

    function traverse(stackLeft){
      stackRight=[];
      for(i=0; i<=stackLeft.length-1; i++){
        order.push(stackLeft[i].data)

        if(stackLeft[i].left !== null){
          stackRight.push(stackLeft[i].left);
        }
        if(stackLeft[i].right !== null){
          stackRight.push(stackLeft[i].right);
        }
      }
      if(stackRight.length === 0 && stackLeft.length === 0){
        return order
      }else{
      secondTrav(stackRight);
      }
    }

    function secondTrav(stackRight){
      stackLeft=[];
      for(i=0; i<=stackRight.length-1; i++){
        order.push(stackRight[i].data)
        if(stackRight[i].left !== null){
          stackLeft.push(stackRight[i].left);
        }
        if(stackRight[i].right !== null){
      stackLeft.push(stackRight[i].right);
        }
      }
      traverse(stackLeft);
    }
    console.log(order);
}

The above code works for the following implementation:

var newTree = new Tree();

newTree.push(100);
newTree.push(90);
newTree.push(110);
newTree.push(105);
newTree.push(95);
newTree.push(92);
newTree.push(97);
newTree.push(107);
newTree.push(102);

bfs(newTree);


texts:
I read time complexity of radix sort is O(wn) or O(n log n), if all n numbers are distinct. After implementation it look to me as if I have implemented radix sort which has time complexity of O(n ^2). Please take a look at my implementation and suggest, if there is some implementation problem or my observation about time complexity is wrong.

Please note: I have hard coded few values for simplicity to sort 3 digit numbers only.

private void LSBSort(int[] arr) {
    _LSBSort(arr, 1);
}

private void _LSBSort(int[] arr, int divisor) {
    Deque[] deques = new Deque[10];
    for(int i = 0 ; i < arr.length ; i++) {
        int mod = (arr[i] /divisor ) % 10;
        if (deques[mod] == null) {
            deques[mod] = new ArrayDeque<>();
        }
        deques[mod].add(arr[i]);
    }
    divisor *= 10;
    if (divisor > 1000) {
        return;
    }

    int cursor = 0;
    for (int i = 0 ; i < 10 ; i++) {
        if (deques[i] != null) {
            for (int j = 0 ; j <= deques[i].size() ; j++) {
                cursor = cursor + j;
                arr[cursor] = (int)deques[i].pollFirst();
            }
            cursor++;
        }
    }
    _LSBSort(arr, divisor);
}


texts: Copying data from a table into a two-dimensional array

texts:
Is it possible to remove the inner loop by assigning data.Data.Tables[0].Rows[i].ItemArray directly?

object[,] arr = new object[52784, 21];

for (int i = 0; i < data.Data.Tables[0].Rows.Count; i++)
{
    for (int j = 0; j < data.Data.Tables[0].Columns.Count; j++)
    {
        arr[i, j] = data.Data.Tables[0].Rows[i][j];
    }
}

The reason why I need this code is because, I want to write to data of this dataTable to Excel using Interop which requires a 2-D array as input.


texts:
I had an interview and was asked a problem. I provided a solution and wanted to make sure if this is correct.

There is a Tile class. It has a boolean variable isGoldenTile which is false for all but true for one tile.

There is a List<Tile> neighbors. These are list of its immediate neighbors which are tiles.

There is a method getNeighbors() which returns the list of neighbors.

Finally, there is a method findGoldenTile which returns a Tile object. This returns the golden tile.

In no way I could alter the class except for the method body for findGoldenTile.

Here is my solution:

public class Tile {

    private boolean isGoldenTile = false;
    private List<Tile> neighbors = null;

    public Tile(boolean isGoldenTile, List<Tile> neighbors) {
        this.isGoldenTile = isGoldenTile;
        this.neighbors = neighbors;
    }

    public boolean isGoldenTile() {
        return isGoldenTile;
    }

    public List<Tile> getNeighbors() {
        return neighbors;
    }

    public Tile findGoldenTile() {
        if(this.isGoldenTile == true){
            return this;
        } else if (this.getNeighbors().size() > 0){
            for(int i=0;i<this.getNeighbors().size();i++){
                if(this.getNeighbors().get(i).isGoldenTile == true){
                    return this.getNeighbors().get(i);
                }
            }
        } else {
            for(int i=0;i<this.getNeighbors().size();i++){
                return this.getNeighbors().get(i).findGoldenTile();
            }
        }
        return null;
    }
}


texts: Modifying __getattr__ to return a nested attribute instead of the named object

texts:
I'm writing an application with two basic class types:

DocumentObject
Property (of document object).

Property instances are attributes of the DocumentObject class and The Property class has several simple attributes of its own (value, unit, etc.) and some methods.
In trying to make the scripting as user friendly as possible, I would like
objectName.propertyName
to return the value attribute of the Property instance, not the Property instance itself. Of course, it is possible to write objectName.propertyName.value but most of the time, the user will be interacting with the value, not the Property instance.
It seems it should be possible to implement this behaviour using modified __getattr__ and __setattr__ methods in DocumentObject like in the following example:
Input
class Property():
    def __init__(self, name, value, unit='mm'):
        self._name = name
        self.value = value
        self._unit = unit
        self._isVisible = True

    @property
    def name(self):
        return self._name

    @property
    def unit(self):
        return self._unit

    @property
    def isVisible(self):
        return self._isVisible

    @isVisible.setter
    def isVisible(self, value):
        self._isVisible = bool(value)

class DocumentObject():
    def __init__(self, properties):
        object.__setattr__(self, 'properties', dict())
        self.properties = properties

    def __getattr__(self, name):
        if "properties" in vars(self):
            if name in self.properties:
                return self.properties[name].value
            else: raise AttributeError
        else: raise AttributeError

    def __setattr__(self, key, value):
        if key in self.properties:
            self.properties[key].value = value
        else:
            object.__setattr__(self, key, value)

brick = DocumentObject({'length': Property('length',10), 'width': Property('width',5)})
print(brick.properties["length"].name)
print(brick.length)

Output
length
10

Questions:

Is is good practice to do this?
Are there likely to be some negative consequences of this decision?
Is there a more elegant solution that I have missed?


texts:
I have the following table called info:

info_name   |   info_value

name        |   Susan

desc        |   Human

I'm trying to print Susan without knowing that the value is Susan.

The following code works, but I want to know if what I wrote is correct.

I'm open to any improvements.

Config Class:

class Config {

    private $hostname = 'localhost';
    private $username = 'blah';
    private $password = 'blah';
    private $database = 'blah';

    public function __construct()
    {
        $this->connection = new mysqli($this->hostname,$this->username,$this->password,$this->database);

        if($this->connection->connect_errno)
        {
            die('Error: ' . $this->database->error);
        }
    }

    public function query($query)
    {
        return $this->connection->query($query);
    }

    public function __destruct()
    {
        $this->connection->close();
    }

}

Name Class:

class Name {

    protected $name;

    public function __construct()
    {
        $this->db = new Config;

        $r = $this->db->query('SELECT info_value FROM info WHERE info_name="name"');

        while($row = $r->fetch_row())
        {
            $this->name = $row['0'];
        }

    }

    public function getName()
    {
        return $this->name;
    }

}

Print Results:

<?php $show_name = new Name(); echo $show_name->getName(); ?>

Thanks for any help!


texts: Is there a circular reference in a set of template substitutions?

texts:
I have a configuration engine that allows the user to specify a dictionary with text templates (read from a JSON file) where each placeholder like {x} can be substituted for a value found under a key with the same name e.g. x.

var constants = new Dictionary<string, object>
{
    { "x", "foo {y} baz" },
    { "y", "bar {x} qux" },
};

These are just two sample strings to show how it can look like. The real configuration contains connection strings, email lists, user names, sql etc.

They are resolved at runtime with this method

public static string FormatAll(this string text, Dictionary<string, object> values)
{
    while (text.ToString() != (text = text.Format(values))) ;
    return text;
}

where Format is a more advanced version of my question about string interpolation.

As you can probably see in the example, there is a danger that someone creates a circular template path and the formatting runs forever.

In order to prevent this from happening, I thought I validate the template dictionary before I let the formating method work with it. This is what I've come up with.

The ValidateIsNotCircular extension runs over the reference dictionary and checks each path for recursiveness and as soon as it finds one that is circular, it throws an exception that contains the path. I wanted it to work without recursion so I used a Stack.

Sidenote: This time I'm confined to C# < 6 so no fancy code here :-(

public static void ValidateIsNotCircular(this Dictionary<string, IEnumerable<string>> values)
{
    var visitedKeys = new HashSet<string>();

    var stack = new Stack<Tuple<string, IEnumerator<string>>>();

    var currentRef = new Func<string>(() => stack.Peek().Item2.Current);
    var currentRefs = new Func<IEnumerator<string>>(() => stack.Peek().Item2);

    foreach (var item in values)
    {
        if (!visitedKeys.Add(item.Key)) continue;

        stack.Push(Tuple.Create(item.Key, item.Value.GetEnumerator()));
        do
        {
            while (currentRefs().MoveNext())
            {
                if (stack.Any(x => currentRef() == x.Item1))
                {
                    throw new CircularPathException(stack.Select(x => x.Item1));
                }

                var next = values[currentRef()];
                visitedKeys.Add(currentRef());
                stack.Push(Tuple.Create(currentRef(), next.GetEnumerator()));
            }
            stack.Pop();
        } while (stack.Any());
    }
}

class CircularPathException : Exception
{
    public CircularPathException(IEnumerable<string> path)
        : base(string.Format("Circular path [{0}]!", string.Join(", ", path.Reverse().Select(x => string.Format("'{0}'", x)))))
    { }
}

There is one more method that extracts the placeholders {x} from the templates and builds another dictionary with references (not part of the question), that looks like this:

var values = new Dictionary<string, IEnumerable<string>>
{
    { "c", new string[] {  } },
    { "x", new string[] { "y" } },
    { "y", new string[] { "c", "z" } },
    //{ "y", new string[] { "c", } },
    { "z", new string[] { "x" } },
};

I use this new dictionary to validate the paths:

values.ValidateIsNotCircular();

and this throws (by design):

  CircularPathException: "Circular path ['x', 'y', 'z']!"


texts:
I have done #1 of Project Euler's in Ruby. Using two different approaches. One uses set, another uses reduce.

require 'set'

start = Time.now

s1 = Set.new (1..1000/3.floor).map { |x| 3 * x }
s2 = Set.new (1..1000/5.floor).map { |x| 5 * x }
sum = s1.merge(s2).to_a.inject(:+)

duration = Time.now - start

puts "Sum: #{sum}, time elapsed #{duration} s"

Second method

start = Time.now
sum = (1..1000).select{ |x| x % 3 == 0 || x % 5 == 0 }.reduce(:+)
duration = Time.now - start

The second method consistently performs better than first method:

method 1: time elapsed 0.000364 s

method 2: time elapsed 0.000198 s

I wonder if it is a correct way to time how long the process takes. And whether it is considered to be performant. Also curious how other languages performs compares to this two algo. Any advice are welcomed~


texts: Construct list from a dataframe and a formula

texts:
A dataframe and a right-sided formula are given:
dat <- data.frame(
  A = c("a", "b", "c"),
  B = c("x", "y", "z"),
  NotUsed = c(1, 2, 3)
)

frml <- ~ A + B + A:B

From them, I want to get this list:
# [[1]]
# [1] a b c
# Levels: a b c
#
# [[2]]
# [1] x y z
# Levels: x y z
#
# [[3]]
# [1] a:x b:y c:z
# Levels: a:x b:y c:z

Here is how I get this list:
library(lazyeval) # to use 'as.lazy' and 'lazy_eval'
tf <- terms.formula(frml)
factors <- rownames(attr(tf, "factors"))
tvars <- attr(tf, "variables")
tlabs <- attr(tf, "term.labels")
used <- lapply(eval(tvars, envir = dat), as.factor)
names(used) <- factors
lapply(tlabs, function(tlab){
  droplevels(lazy_eval(as.lazy(tlab), data = used))
})

Do you have a better way to propose?


texts:
How can I optimize the following PHP/JS code?

It works like a charm but I think it is too long and I'm sure it could be optimized. If I have another form, I'll need to copy paste some lines from my PHP code and it'll be quickly overkill.

JavaScript:

<script>
$(document).ready(function() {
    $('#createAccount').on('submit', function() {
        var Email = $('#Email').val();
        var Password = $('#Password').val();
        var PasswordRepeat = $('#PasswordRepeat').val();

        $.ajax({
            url: $(this).attr('action'),
            type: $(this).attr('method'),
            data: $(this).serialize(),
            dataType: 'json',
            success: function(json) {
                $('.alert-message').text(json.reponse).show();
            }
    });
    return false;
    });
});
</script>

PHP:

<?php
$reponse="";
if(isset($_POST['Email']) && isset($_POST['Password']) && isset($_POST['PasswordRepeat'])) {

    // Si tous les champs ne sont pas renseignés
    if($_POST['Email'] == '' || $_POST['Password'] == '' || $_POST['PasswordRepeat'] == '') {
            $reponse = "Tous les champs doivent être remplis.";
    }

    // Si les mots de passe ne sont pas similaires
    if($_POST['Password'] != $_POST['PasswordRepeat']) {
            $reponse = "Les mots de passe ne sont pas similaires.";
    }

    // Si ce n'est pas une adresse de courriel
    if(!preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['Email'])) {
            $reponse = "L'adresse de courriel ne semble pas conforme.";
    }

    // Si le mot de passe est trop court
    if(strlen($_POST['Password']) <= 5) {
            $reponse = "Le mot de passe être top court.";
    }

    // Si tout est ok
    if(($_POST['Password'] == $_POST['PasswordRepeat']) && ($_POST['Email'] != '' && $_POST['Password'] != '' && $_POST['PasswordRepeat'] != '') && (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['Email'])) && (strlen($_POST['Password']) >= 6)) {
            $reponse = "Nice";
    }

}
else {
    $reponse = "Une erreur s'est produite.";
}

$array['reponse'] = $reponse;
echo json_encode($array);
?>


texts:
I am messing around with the sklearn ML library to see if i can "predict" stocks with it, currently when it takes all the datapoints i have, it "predicts" it but i am trying to get it to predict into like the future.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import AdaBoostRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
from sklearn.svm import SVR
from numpy import loadtxt
from matplotlib.dates import datestr2num
from datetime import datetime, date
from sklearn.ensemble import AdaBoostRegressor
import csv
print("imported libraries")

amt = 2516
forecast = 230

#converters = {0: datestr2num}
X = np.loadtxt(fname="dates.csv", dtype="float", delimiter=",")
y = np.loadtxt(fname="PredictionEngineTestDatabase.csv", dtype='float', delimiter=",")
print("imported y and X")

from sklearn.model_selection import train_test_split
validation_size = 0.15
seed = 7
X_train, X_validation, Y_train, Y_validation = train_test_split(X, y, test_size=validation_size, random_state=seed)
print("Test Train Split Created")

#import csv
#with open('dates2.csv', newline='') as datesfile:
#  datereader = csv.reader(datesfile, delimiter=',', quotechar='|')
#  for dt in datereader:
#    datetime_object = datetime.strptime(dt, "%Y-%m-%d")
#    timestamp = datetime.timestamp(datetime_object)
#    np.append(y, int(timestamp))
#    print("DateTime Stored")

svm = SVR(kernel='rbf', C=1e3, gamma=0.2, cache_size=6000)
print("created SVR with 6GB cache")

from sklearn.metrics import mean_squared_error

print("fitting svr")
svm.fit(X, y)
print("fitted svr")
svmconf = svm.score(X, y)
print("SVM Prediction Confidence", svmconf, '%')
y_1=svm.predict(X)
print("prediction complete")
print(y_1)

print(mean_squared_error(y, y_1))

fig=plt.figure(figsize=(24,12))
plt.plot(X, c="k", label="X")
plt.plot(y, c="r", label="Y")
plt.plot(y_1, c="b", label="SVR")
plt.xlabel("time")
plt.ylabel("price")
plt.title("test")
plt.legend()
plt.show()


texts:
I'm trying to clean up my JQuery code for my tabs. I have 3 different styles. How do I make the following shorter?

$(document).ready(function () {
    $('.tabs-style1 li').click(function () {
        var tab_id = $(this).attr('data-tab');
        $('.tabs-style1 li').removeClass('current');
        $('.tab-content-style1').removeClass('current');
        $(this).addClass('current');
        $("#" + tab_id).addClass('current');
    })
})

$(document).ready(function () {
    $('.tabs-style2 li').click(function () {
        var tab_id = $(this).attr('data-tab');
        $('.tabs-style2 li').removeClass('current');
        $('.tab-content-style2').removeClass('current');
        $(this).addClass('current');
        $("#" + tab_id).addClass('current');
    })
})

$(document).ready(function () {
    $('.tabs-style3 li').click(function () {
        var tab_id = $(this).attr('data-tab');
        $('.tabs-style3 li').removeClass('current');
        $('.tab-content-style3').removeClass('current');
        $(this).addClass('current');
        $("#" + tab_id).addClass('current');
    })
})

Your help will be appreciated!
http://michellecantin.ca/test/features/tabs/


texts:
I have WP Query like this:
      $map_args = array(
        'post_type'       => 'spots',
        'post_status'     => 'publish',
        'posts_per_page'  => -1
      );
      $markers_query = new WP_Query($map_args); ?>
      <?php if ($markers_query->have_posts()) : ?>
        <?php while ($markers_query->have_posts()) : $markers_query->the_post();
          $terms = get_the_terms( $post->ID , 'spots_categories' );
          $map_marker = get_field( 'map_marker', $terms[0]->taxonomy . '_' . $terms[0]->term_id );
          $tooltip_photo = get_the_post_thumbnail($post->ID, 'thumbnail', array('class' => 'marker-pop__photo'));
          $marker_url = esc_url(get_the_permalink());
          if ( $spot_location = get_field( 'spot_location' ) ) :
            $markersArray[] = array($spot_location['lat'], $spot_location['lng'], get_the_title(), 'http://localhost/icamp/app/wp-content/themes/iCamp/images/logo-black.svg', $tooltip_photo, $marker_url );
          endif; ?>
        <?php endwhile; ?>
      <?php endif; ?>
      <?php wp_reset_query(); ?>
      <?php wp_reset_postdata(); ?>

'spots' is my custom post type, and 'spots_categories' is my custom taxonomy. I have over 10.000 CPT in spots right now, so that query is really slow. I need all my posts (can't use pagination here), because I need to list that locations on leaflet map (pins with title, thumbnail and custom marker). Is there any better and faster way to list my custom pins with location to leaflet map? That Query is really slow.


texts: Access object in an custom attribute efficiently

texts:
Im trying to access the attribute directly in the parent component, that why Im using the ref method.
here an example of why Im trying to achieve: https://stackblitz.com/edit/react-lupsr2
Im accessing it using some for in loop currently, so far it works, although I think there is probably more efficient way to do the job. to me, using a for in loop is probably very expensive, and there is probably other way, more ecologic to achieve the end.

Here my react snippet:

class App extends Component {

  constructor(prop) {
    super(prop);
    this.children=React.createRef()
    this.state = {
      name: 'React'
    };
  }

  componentDidMount(){
    for (var key in this.children.current) {
      if(key.includes("__reactEventHandlers"))
        // ACCESS OBJECT HERE
        return console.log("in componentdidmount for in:", this.children.current[key].test)
    }
  }

  render() {
     console.log("this.children in render: ", this.children)
    return (

        <Hello name={this.state.name} />
        <button  onClick= {()=> console.log("children: ", this.children)} >   click to display children</button>

          Start editing to see some magic happen :)

    );
  }
}

any hint would be great,
thanks


texts: Client side authorization when retrieving from server

texts:
I have an endpoint to retrieve the user's authorization based on Joseph Silber's Bouncer.
I have a global can() function. It creates a unique key based on the authorization request and sets an object's property based on that key.
can (ability, model = null, id = null) {
  const key = `${ability}_${model}_${id}`
  const params = {
    ability, model, id
  }

  axios.get(this.route('authorize', params))
    .then(res => {
      Vue.set(this.userAuthorizations, key, res.data.allowed)
    })
    .catch(err => this.showError(err.message))

  return key
}

data () {
  return {
    userAuthorizations: {}
  }
}

So in a template, I do something like...
<button v-if="userAuthorizations[can('create', 'users')]">
  Create User
</button>

There will be a delay while it's retrieving the result, but since the key doesn't exist it won't show a restricted thing.
It looks ugly to me, but it's the most sustainable and reusable way I could think to do it on the front-end. Thoughts? What's a better way?


texts: Switch statements in Rock-Paper-Scissors game

texts:
I am very much new to design pattern. I'm trying to modify the Rock, paper, scissor game from an example book where I try to add more various design pattern. But I am encountering two similar switch statement which I think have duplicates and I don't have any idea on removing those duplicates.

A abstract class:

abstract class UserVsComp {
    protected static Item item;
    abstract protected Item getItem() throws WrongMove;
}

Here are the two switch statement:(First Class is for user movement)

class UserMove extends UserVsComp {
    private String move;
    public UserMove(String move) { this.move = move; }
    public Item getItem() throws WrongMove {
        switch (choiceValue(this.move)) {
            case 0 :  item = new Paper(); break;
            case 1 :  item = new Scissors(); break;
            case 2 :  item = new Rock(); break;
            default:  throw new WrongMove("Wrong move. Game end");
        }
    return item;
}

Second class is for Computer movement:

class ItemGenerator extends UserVsComp {
    public Item getItem() throws WrongMove {
        switch((int) (Math.random() * 2)) {
            case 0: item = new Paper(); break;
            case 1: item = new Scissors(); break;
            case 2: item = new Rock(); break;
            default:  throw new WrongMove("Wrong move. Game end");
        }
    return item;
    }
}

The two switch statement have same case (I guess duplicacy). I'd like to know if there is any way to remove this duplicacy.


texts:
This is my first Powershell script ever so bear with me.

I'm trying to replace values in a sharepoint list from a CSV file:

Param(
    [Parameter(Mandatory=$true)][string] $csvFileName = $null,
    [Parameter(Mandatory=$true)][string] $sharePointWebUrl = $null
)

$isError = $false

cls

$csvFileName = $csvFileName.Trim()
$sharePointWebUrl = $sharePointWebUrl.Trim()

if ([string]::IsNullOrEmpty($csvFileName))
{
    Throw "Please enter parameter values for CSVFileName"
}

if ([string]::IsNullOrEmpty($sharePointWebUrl))
{
    Throw "Please enter parameter values for sharePointWebUrl"
}

Add-PSSnapin Microsoft.Sharepoint.Powershell

try
{
    $csv = Import-Csv $csvFileName
    $subWeb = get-spweb -identity "$sharePointWebUrl"
    $mylistitems = $subWeb.Lists["MyList"].Items | sort Title

    $csvCollection = New-Object System.Collections.ArrayList
    $csv | ForEach-Object {
            $temp = "" | select "Topics", "Column1"
            $temp.Topics = $_.Topic
            $temp.Column1 = $_.NewTopic
            $csvCollection.Add($temp) | Out-Null
    }

    try
    {
            foreach ($li in $mylistitems) {
                    $loopcount=0
                    :loop foreach ($si in $csvCollection)
                    {
                        $loopcount =$loopcount + 1
                        if ($li["Topics"] -eq $si.Topics)
                        {
                            $li["Topics"] = $si.Column1
                            $isFound =$true
                            $li.Update()
                            break loop
                        }
                    }
            }
    }

    catch
    {
            $isError = $true
            $time = Get-Date
            $ErrorMessage = $_.Exception.Message
            "Error Occurred ($time) with error message: $ErrorMessage"| out-file ".\error.log" -append
    }
}

catch
{
    $isError = $true
    $time = Get-Date
    $ErrorMessage = $_.Exception.Message
    "Error Occurred ($time) with error message: $ErrorMessage"| out-file ".\error.log" -append
}

finally
{
    if ($web) {
        $web.dispose();
    }

    if ($isError) {
        write-host "script completed with error(s), please look into error.log file" -ForegroundColor Red
    } else {
        write-host "script completed successfully without error(s)" -ForegroundColor Green
    }
}

Remove-PsSnapin Microsoft.SharePoint.PowerShell

Basically I am looping through a sharepointlist with a nested loop for the CSV file and comparing values. Is this the most efficient/correct way to do this?

Here are some sample lines from the CSV:

Topic,NewTopic,Comments
Building,Appliance,
Your workplace,My Workplace


texts: Calculate total width of a range of numbers

texts:
I'm mostly curious if there's a faster or more efficient algorithm I could use. I created this for a unique side project, as well as for an issue at work, so what the function does (e.g., return a negative int) isn't what I'm focused on.

In short, can I make this faster or more efficient?

// GetBufferLength returns the minimum length of a buffer that can hold the
// string representation of all the numbers with in the given range of
// integers, N.
// ADD will add additional space for extra characters. E.g., if one
// wanted "$1,$2,$3...", ADD should be 2 in order to gain the additional
// space for the comma and the dollar sign.
// Will return a negative value if N is negative.
func GetBufferLength(n, add int) int {

    // Handle some edge cases
    if n < 10 {
        return n + (n * add)
    }

    if n <= 100 {
        return (n*(2+add) - 9) + 1
    }

    // Gather the largest width of all our numbers.
    if 0 < n {

        // Account for 0
        n++

        // Find the greatest power of 10.
        i, x := 1, 0
        for i < n {
            i *= 10

            // Go doesn't fully support C-style for/while loops,
            // so occasionally we have to do some janky stuff.
            if i > n {
                i /= 10
                break
            }

            // Number of powers.
            x++
        }

        // Count width of numbers.
        l := 10
        for 1 < x {
            // Algorithm is X = W*N, where W is the current width of the
            // number and N is the number of numbers (i.e., the number
            // itself).
            l *= ((x + add) * 10)
            x--

            // Since we start with X being the largest power, we need to
            // subtract the previous power, otherwise we'd double up.
            //
            // E.g., given 1000 we'd end up with (4*1000) = 4000, and
            // that would imply that _all_ numbers from 1-1000 are
            // 4 digits wide. Since 0-9 are one digit, 10-99 are two.
            // and 100-999 are three, we need to compute _their_ widths
            // and subtract their difference from the largest power.
            l -= ((x + add) * 10)
        }

        // Include single digit numbers
        return (n-i)*(2+add) + l
    }

    return n
}


texts:
I'm really new to coding so I'm looking for a bit of feedback on this twin prime finder. She works pretty decent but I know it could be better.

import math
primes = []
def get_primes(lower, upper):
  for num in range(lower, upper):
    for i in range(2, num):
      if num % i == 0:
        break
    else:
      primes.append(num)
print get_primes(int(raw_input("Enter lower boundary")), int(raw_input("Enter upper boundary")))
print primes

for i in range(0, len(primes) - 1):
  if primes[i+1] - primes[i] == 2:
    print str(primes[i]), str(primes[i+1])


texts:
Class Student
{
   Int studentId,
   List<ClassB> Books,
  Bool IsPassed
}
Class Book
{
 Int bookId,
 List<int> pages
 }

I am creating a list of students the way below

    static void Main(string[] args)
     {

    var  students = GetStudents();
    var result = students.GroupBy(r => new { r.StudentId, r.IsPassed })
.Select(c =>
new Student()
{
IsPassed = c.Key.IsPassed,
StudentId = c.Key.StudentId,
Books = c.SelectMany(t=>t.Books).ToList()
}).ToList();

    }

private static List<Student> GetStudents() {

string connStr = ConfigurationManager.AppSettings["Conn"];

List<Student> students = new List<Student>(); SqlConnection conn = new SqlConnection(connStr); conn.Open();
SqlCommand command = new SqlCommand("Select * from Students", conn);

using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
 {
 var StudentId =             Convert.ToInt32(reader["StudentId"]); var BookId = Convert.ToInt32(reader["BookId"]); var IsPassed = Convert.ToBoolean(reader["IsPassed"]); var PageNUmbers = reader["PageNumber"].ToString().Split(',').Select(t => Convert.ToInt32(t)).ToList(); List<Book> books = new List<Book>(); books.Add(new Book() { BookId = BookId, PageNumber = PageNUmbers });
students.Add(new Student()
{
StudentId = StudentId,
Books = books,
 IsPassed = IsPassed
 });

 } }
return students;

}

Is there any better way to doo this?


texts: Simple Async Google Maps initializer with AngularJS

texts:
Here is a simple reusable AngularJS factory I came up with to initialize Google Maps Asynchronously, which somehow does not seem to be supported by major libraries (see below):

Following Google's guidelines I am using global callback function (which seems to be unavoidable harm), that resolves a dummy promise, which is the only API returned.

Then maps can be loaded anywhere by simply calling

Initializer.mapsInitialized.
    .then(function(){
        map = new google.maps.Map(element, options);
    });

Below is the code. Any critics, potential flaws, drawbacks, violation of best practices is welcome!

// Google async initializer needs global function, so we use $window
angular.module('GoogleMapsInitializer')
    .factory('Initializer', function($window, $q){

        // maps loader deferred object
        var mapsDefer = $q.defer();

        // Google's url for async maps initialization accepting callback function
        var asyncUrl = 'https://maps.googleapis.com/maps/api/js?callback=';

        // async loader
        var asyncLoad = function(asyncUrl, callbackName) {
          var script = document.createElement('script');
          //script.type = 'text/javascript';
          script.src = asyncUrl + callbackName;
          document.body.appendChild(script);
        };

        // callback function - resolving promise after maps successfully loaded
        $window.googleMapsInitialized = function () {
            mapsDefer.resolve();
        };

        // loading google maps
        asyncLoad(asyncUrl, 'googleMapsInitialized');

        return {

            // usage: Initializer.mapsInitialized.then(callback)
            mapsInitialized : mapsDefer.promise
        };
    })

Most major libraries built for Google Maps seem to use the standard script tag

<script src='//maps.googleapis.com/maps/api/js'></script>

which is, however, blocking, may result in delays, and makes the page unsuitable for offline testing.

On another note, library such as script.js async loader, does not seem to work with this particular script.


texts:
How does the following program look to print a list of strings? What places can I improve? Are there easier ways to print something like a linebreak after each string rather than hardcoding the \n into the string itself?
# Program, print out a list of strings, one per line
.data

SYS_EXIT   = 60
SYS_WRITE  = 1
SYS_STDOUT = 1

# Empty string means end of strings
strings:    .asciz  "Once\n", "upon\n", "a\n", "time\n", "...\n", ""

.text
.globl _start

get_string_length:
    mov $0, %eax
  .L1_loop:
    movzbl (%edi, %eax), %ecx
    cmp $0, %cl
    je .L1_exit
    inc %eax
    jmp .L1_loop
  .L1_exit:
    ret

_start:

    mov $strings,   %rbx
  print_loop:
    mov %rbx,       %rdi
    call get_string_length # (rdi=file_descriptor, rsi=starting_address, rdx=size)
    cmp $0, %eax
    jz exit
    mov $SYS_STDOUT,%edi
    mov %rbx,       %rsi
    mov %eax,       %edx
    mov $SYS_WRITE, %eax
    syscall
    lea 1(%eax, %ebx,), %ebx
    jmp print_loop

  exit:
    mov $0,        %edi
    mov $SYS_EXIT, %eax
    syscall


texts: Check non-continuous range for equal values

texts:
Background

I'm trying to check equality between cells in an irregular, non-continuous range of cells. For this purpose I would like to know if all cells are equal to the first Cell in the Range. The Range can be anything, but let's say it could be the following (don't mind the implicit reference for now):

Range("A1:C1,F1,K1,X1,AA1")

Sample Code:

Because the Range is non-continuous, there is no way to use the COUNTIF as a WorksheetFunction, nor can I implement some sort of INDIRECT within Evaluate. So I was looking for the easiest way to do this. I came up with the following:

'Get a 1D-array from columns of interest
Dim arr As Variant: arr = Application.Index(Range("A1:AA1").Value, 1, Array(1, 2, 3, 6, 11, 24, 27))

'Join the 1D-array and check against 7* the value of A1
If Join(arr, "") = Replace("???????", "?", Range("A1").Value) Then
    Debug.Print "All equal to first cell"
Else
    Debug.Print "Not all equal to first cell"
End If

Question:

I've spent quite some time trying to come up with some code that would avoid iteration over the Range object's Cells (or iteration of any type), for example like below:

'Get dictionary ready
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")

'Get range of cells
Dim rng As Range: Set rng = Range("A1:C1,F1,K1,X1,AA1")

'Iterate over cells
For Each cl In rng
    dict(cl.Value) = 1
Next cl

'Test for same values
If dict.Count = 1 Then
    Debug.Print "All equal to first cell"
Else
    Debug.Print "Not all equal to first cell"
End If

It has also become clear to me that there is no simple COUNTIF of an Array. And also something like Filter has proven to not be "error" proof.

While this is working code, I was hoping to find out the best way to know if all values in an irregular, non-continuous range of cells are the same. And therefor hope CR is the right place to ask.


texts:
This is a problem from "Automate the boring stuff".

  Write a function that uses regular expressions to make sure the password
  string it is passed is strong. A strong password is defined as one that is at
  least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You may need to test the string against multiple regex patterns to validate its strength.

How to improve this code?

#! /usr/bin/python3

import re

def uppercase_check(password):
    if re.search('[A-Z]', password): #atleast one uppercase character
        return True
    return False

def lowercase_check(password):
    if re.search('[a-z]', password): #atleast one lowercase character
        return True
    return False

def digit_check(password):
    if re.search('[0-9]', password): #atleast one digit
        return True
    return False

def user_input_password_check():
    password = input("Enter password : ")
        #atleast 8 character long
    if len(password) >= 8 and uppercase_check(password) and lowercase_check(password) and digit_check(password):
        print("Strong Password")
    else:
        print("Weak Password")

user_input_password_check()


texts: Bash script to manage multiple Java Development Kits installations

texts:
I'm writing a bash script to manage multiple JDKs, the script is very simple, you have to choose a directory when you store all the jdk's, and the  script maintain a symlink to the current jdk'. TheJAVA_HOMEis always pointing to thesymlink`.

In order to use the script you have to source the jdk-manager.bash in .bash_profile or .profile

The script is used by calling jdk function from the command line.

Questions:

is there any security issues in the script ?
is there any way to implement the same functionality without sourcing the shell file in a dotfile ?

#! /usr/bin/env bash

#set -u
#set -e

#to modify
JDK_ROOT="$HOME/local" # change it to the directory that contain the jdk's

JDK_PATTERN="[0-9]\.[0-9]\.+([0-9])?(_+([0-9]))"
CURRENT_JDK="$JDK_ROOT/.current_jdk"
SESSION=0;

# colors
textred=$(tput setaf 1)
texttyellow=$(tput setaf 3)
textreset=$(tput sgr0)
textgreen=$(tput setaf 2)

########################################################################""
# functions
########################################################################"

# ascii art
_print_java_ascii() {
printf ${texttyellow}"
   _     _ _
  (_) __| | | __     _ __ ___   __ _ _ __   __ _  __ _  ___ _ __
  | |/ _  | |/ /____|  _   _ \ / _  |  _ \ / _  |/ _  |/ _ \  __|
  | | (_| |   <_____| | | | | | (_| | | | | (_| | (_| |  __/ |
 _/ |\__ _|_|\_\    |_| |_| |_|\__ _|_| |_|\__ _|\__  |\___|_|
|__/                                             |___/

"${textreset}
}

_is_jdk() {
  return `[[ "$1" == jdk${JDK_PATTERN} ]]`
}

# init the current symlink
_init_current() {
  if [[ ! -L $CURRENT_JDK ]];
  then
    ln -s /dev/null $CURRENT_JDK
  fi
}

_get_current_jdk() {
  basename `readlink -f $CURRENT_JDK`
}
# list all available jdks in the JDK_ROOT directory
_ls_jdks() {
  for file in $(ls $JDK_ROOT)
  do
    if `_is_jdk "$file"`
     then
      if [[ $file == `_get_current_jdk` ]]
       then
    printf "${textgreen} > $file\n"
      else
    printf "${textreset}   $file\n"
      fi
    fi
  done
}

_set_current_jdk() {
  jdk="jdk$1"
  if `_is_jdk $jdk` && [[ -d "$JDK_ROOT/$jdk" ]]
  then
    rm "$CURRENT_JDK"
    ln -sf "$JDK_ROOT/$jdk" "$CURRENT_JDK"
    printf "${textgreen} INFO: ${textreset}Updating the \$JAVA_HOME to $JDK_ROOT/${textgreen}`_get_current_jdk`${textreset}  .\n\n";
    _ls_jdks;
  else
    printf "${textred} ERROR: ${textreset} there is no $jdk in $JDK_ROOT \n"
  fi
}

########################################################################""
# main
########################################################################"

export JAVA_HOME=$CURRENT_JDK;
export PATH="$JAVA_HOME/bin:$PATH"

jdk() {
 if [[ $SESSION -eq 0 ]]
  then
  _print_java_ascii;
  SESSION=1;
fi

_init_current;

if [[ $# -eq 0 ]]
then
  _ls_jdks;
else
  _set_current_jdk $1
fi
}


texts: can we use of $this in closure for jquery plugin

texts:
I tried creating a quick tooltip plugin using the jquery and jquery ui position. Is the way I have used the enclosure are right and is the use of position right since in ff it seem to have some memory problem..it remembers the previous position when I refresh the page after the first time. below is the code

This need the latest jquery & jquery ui

  $.fn.tooltip = function(options) {
            var defaults = {
                my : "left center",
                at : "right top",
                collision : "none",
                offset : "0 0"
            }

            var options = $.extend(defaults, options);

            return this.each(function() {
                var $this = $(this);
                var tip = $("" + $this.attr('tooltip') + "");
                tip.css({
                    width : options.width
                });
                $this.after(tip);
                tip.position({
                    my : options.my,
                    at : options.at,
                    of : $this,
                    collision : options.collision,
                    offset : options.offset
                });

                $this.add(tip).hover(function() {
                    var timeoutId = $this.data('timeoutId');
                    if(timeoutId) {
                        clearTimeout(timeoutId);
                    }
                    tip.fadeIn("slow");

                }, function() {
                    var timeoutId = setTimeout(function() {
                        tip.fadeOut("slow");
                    }, 650);
                    $this.data('timeoutId', timeoutId);
                });
            });
        };
        $(function() {
            $('#input1').tooltip();
            $('#input2').tooltip();
        });

css style

        .tooltip {
            display: none;
            position: absolute;
            background-color: #ffaa5e;/* #F5F5B5; */
            border: 1px solid #DECA7E;
            color: #303030;
            font-family: sans-serif;
            font-size: 12px;
            line-height: 18px;
            padding: 10px 13px;
            position: absolute;
            text-align: center;
            top: 0;
            left: 0;
            z-index: 3;
        }

html code to test this

http://jsfiddle.net/HE8QN/

thanks


texts:
Given a linked list and two positions m and n. The task is to rotate the sub-list from position m to n, to the right by k places. (link to GeeksforGeeks)
Examples
Input:
list 1->2->3->4->5->6, m = 2, n = 5, k = 2
Output: 1->4->5->2->3->6
Explanation: Rotate the sub-list 2 3 4 5 towards right 2 times
then the modified list is: 1 4 5 2 3 6
Input: list = 20->45->32->34->22->28, m = 3, n = 6, k = 3
Output: 20->45->34->22->28->32
Explanation: Rotate the sub-list 32 34 22 28 towards right 3 times
then the modified list is: 20 45 34 22 28 32
// Rotate the sub-list of a linked list from position M to N to the right by K places

#include <iostream>
using namespace std;

//  structure of the node in the linked list
struct Node {
    int data;
    Node* next;
};

// inserting at the beggining
void push( Node **head, int data ) {
    Node *newNode = new Node();
    newNode->data = data;

    if((*head) == NULL) {
        (*head) = newNode;
        return;
     }

    Node *temp = (*head);
    while(temp->next != NULL)
        temp = temp->next;
    temp->next = newNode;
    newNode->next = NULL;
  }

// display
void display(Node *head) {
    cout << "The list : \t";
    while (head != NULL) {
        cout << head->data << " ";
        head = head->next;
    }
}

// Rotate the linked list by k
void rotate(Node *head, int m, int n, int k) {
    Node *temp1 = head ;
    Node *temp3 = NULL, *ref = NULL, *last = NULL;

    for (int i = 0; i < m - 1 ; i++)
        temp1 = temp1->next;
    ref = temp1->next;
    temp3 = ref ;

    for (int i = 0; i < n - m; i++)
        temp3 = temp3->next;
    last = temp3->next;
    temp3->next = ref ;

    k = k%(n - m + 1);

    for(int i = 0; i < k; i++) {
        temp3 = ref;
        ref = ref->next;
    }
    temp3->next = last;

    // if the starting point is not 1st element
    if (m == 0)
        head = ref;
    else
        temp1->next = ref;

    display(head);
}

// Driver function
int main() {
    Node *head = NULL;

    push(&head, 1);
    push(&head, 2);
    push(&head, 3);
    push(&head, 4);
    push(&head, 5);
    push(&head, 6);
    push(&head, 7);

    display(head);

    cout << "\n\n";
    int m, n, k;
    cout << "m, n, k = \t";
    cin >> m >> n >> k ;

    rotate(head, m - 1, n - 1, k);
    return 0;
}


texts:
I need to generate random text for tests. I do that using alphanumeric characters and some special characters as well.

For some special cases, I cannot generate the random text with tags.
I have the concept of a tag as text surrounded in curly braces (e.g. {name}).

I have written a simple code to clean up the tags (e.g. removing one of the curly braces) and I'd like some feedback if looks ok for Scala.

val allCharacters = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890!@#%*()_+-=[]{x}|?.;:`"

def removeTags(text: String): String = {

    // A tag is any text between {}, like `{name}`
    def containsTag(text: String): Boolean = {
        val noTagsRegex: Pattern = Pattern.compile("^((?!(\\{.*\\})).)*$")
        !noTagsRegex.matcher(text).matches()
    }

    var newText = text
    if (containsTag(newText)) {
        val randomPosition = Random.nextInt(allCharacters.length - 1)
        newText = text.replace("}", allCharacters(randomPosition).toString)
    }
    newText
}

Below an idea of results running this method:

Text without tags

input: "dlfkhfks sldfjhsldf qiweo 93450934 %&%&%&^%"
output: "dlfkhfks sldfjhsldf qiweo 93450934 %&%&%&^%" (exactly the same)

Text with 1 tag

input: "dlfkhfks s{ldf}jhsldf qiweo 93450934 %&%&%&^%"
output: "dlfkhfks s4ldf}jhsldf qiweo 93450934 %&%&%&^%" (the { was replaced)

Text with more than 1 tag

input: "dlfkhfks s{ldf}jhsldf {{@}} qiweo 93450934 %&%&%&^%"
output: "dlfkhfks s4ldf}jhsldf 44@}} qiweo 93450934 %&%&%&^%"

There is room for improvements, like not doing replace to all occurrences by the same character, but this is something for another moment.


texts: Canonicalizing a large set of addresses using many regex substitutions

texts:
I have a script that is standardizing a large amount of data in the database. The standardization involves applying over 500 regular expressions to the data.

Here is some quick pseudocode:

Load the records from the database
for each record
   for each regular expression ##predefined list of 500 regular expressions
      apply regular expression to record
    end;
    write record to file
end;

Here is the relevant block of code in Perl:

while(my @row = $queryHandle->fetchrow_array())
{
    $accountKey = @row[0];
    $addressLine1 = @row[1];
    $addressLine2 = @row[2];

    #first remove all special characters leaving only numbers and alphabets
    $addressLine1 =~ s/[^A-Za-z0-9 ]//g;
    $addressLine2 =~ s/[^A-Za-z0-9 ]//g;

    for my $regexRef (@regexesList)
    {
        #now standardize the addresses
        $addressLine1 =~ s/$regexRef->{pattern}/$regexRef->{output}/ig;
        $addressLine2 =~ s/$regexRef->{pattern}/$regexRef->{output}/ig;
    }

    my $standardizedAddress = $addressLine1 . $addressLine2;
    $standardizedAddress =~ s/\s+//g; #remove all white space
    #Et_Run_Log("the normalized address is: $normalizedAddress");

    print $dataFileHandle "${standardizedAddress}\n";
    $rowCount++;
}

An excerpt of regexList:

my %regexHash;
$regexHash{pattern} = "\bstr\b";
$regexHash{output} = "street";

#add regex hash to list
push(@regexesList, {%regexHash});

$regexHash{pattern} = "\brd\b";
$regexHash{output} = "road";
push(@regexesList, {%regexHash});

This is working code but the performance is abysmal. Currently the script has been running for 2.5hours and has written out 3.13 million records to the output file with about 7million to go.

Is this the best it can get? Is there another faster, or less slower way? Maybe writing each row to a file first and then run each regular expression on the whole file?

I would like to know if there is better way to implement this before I try the above mentioned alternative.


texts:
I have a snippet of code here that uses C# and Linq. The ganttData variable I have has 12 warnings stating:

  possible multiple enumerations of IENumerable

Should I change it to a List or leave it the way it is?

private IEnumerable<ProductLineDto> FilterAtHighestLevel(IEnumerable<ProductLineDto> ganttData, GanttFilterDto ganttFilterDataModel)
        {
            if (ganttFilterDataModel.ProjectId == null)
                return ganttData;
            //Check if it's a productLine, project, or subproject that was selected from the project filter
            ProductLine productLine = UnitOfWork.ProductLineRepository.GetAll().SingleOrDefault(x => x.ProductLineID == ganttFilterDataModel.ProjectId.Value);
            Project project = UnitOfWork.ProjectRepository.GetAll().SingleOrDefault(x => x.ProjectID == ganttFilterDataModel.ProjectId.Value);
            SubProject subProject = UnitOfWork.SubProjectRepository.GetAll().SingleOrDefault(x => x.SubProjectID == ganttFilterDataModel.ProjectId.Value);

            if (productLine != null)
                ganttData = GetProuctLinesFromDto(ganttData, ganttFilterDataModel.ProjectId.Value);
            else if (project != null)
            {
                ganttData = GetProuctLinesFromDto(ganttData, project.ProductLineID);
                //its always the first one
                ganttData.ElementAt(0).Projects = ganttData.ElementAt(0).Projects.Where(x => x.ProjectId == ganttFilterDataModel.ProjectId.Value);
            }
            else if (subProject != null)
            {
                ganttData = GetProuctLinesFromDto(ganttData, subProject.Project.ProductLineID);

                /// Don't just filter for the subproject get the project and show the entire project tree
                /// What's the point of this filter then?

                var rootProject = SubProjectService.EntityRepo.GetAll().FirstOrDefault(x => x.SubProjectID == ganttFilterDataModel.ProjectId.Value);
                ganttData.ElementAt(0).Projects = ganttData.ElementAt(0).Projects = ganttData.ElementAt(0).Projects.Where(x => x.ProjectId == rootProject.ProjectID);

            }
            return ganttData;
        }

        private IEnumerable<ProductLineDto> GetProuctLinesFromDto(IEnumerable<ProductLineDto> ganttData, Guid id)
        {
            return ganttData.Where(x => x.ProductLineId == id);
        }


texts:
The following bash script was made to retrieve some local repository information in order to be used to display a condensed git status in terminal PS1 prompt.

It performs some simple greps over (git status) --short version text to display 6 repository status: Commits ahead, commits behind, added files, modifiled files, untracked files and deleted files

#!/bin/bash

if [[ $(find .git 2> /dev/null | wc -l) > 0 ]]; then

        local branch="$(git branch | grep '*' | cut -d ' ' -f 2)"
        local remote="$(git remote)/$branch"
        local status=""

        # Commits ahead
        local ahead=$(git rev-list --count $remote..$branch)
        [[ $ahead > 0 ]] && status="$status ⭑$ahead"
        # Commits behind
        local behind=$(git rev-list --count $branch..$remote)
        [[ $behind > 0 ]] && status="$status !$behind"
        # Added files
        A=$(git status -s | grep -Pc "^[RAM]..")
        [[ $A > 0 ]] && status="$status +$A"
        # Modifiled files
        M=$(git status -s | grep -Pc "^.M.")
        [[ $M > 0 ]] && status="$status ~$M"
        # Untracked files
        U=$(git status -s | grep -c "?? ")
        [[ $U > 0 ]] && status="$status ·$U"
        # Deleted files
        D=$(git status -s | grep -Pc "^.D.")
        [[ $D > 0 ]] && status="$status -$D"

        echo "$branch$status"
    fi

By now, I'm actually using this code inside a .bashrc function and, accordingly calling it through my PS1 variable:

It would be nice to receive some code review about grep and git usage, bash organization, syntax, readability and other improvements. I'm also interested in best practices over have function calls from PS1.


texts:
Due to some constraints I had to manually parse an HTTP response coming out of a stream.

I could not use buffered reader or scanner because the perform buffering and end up buffering bytes beyond the response header itself.

I'll be hitting my AWS S3 and only expect 200 or 206 status response.

This seems to work, but I'd appreciate some review.

final InputStream reader = socket.getInputStream();
stringBuilder.setLength(0);
//first fetch header
while (true) {

    final char read = (char) reader.read();
    if (read < 1) {
        //fail
        MiscUtils.closeAndIgnore(socket, reader);
        return false;
    }

    stringBuilder.append(read);
    if (read == '\n')
        break; //status header fetched
}

//check status
final String status = stringBuilder.toString();
Log.i("Downloader", status);
if (!(status.contains("200") || status.contains("206"))) {
    //fail
    MiscUtils.closeAndIgnore(socket, reader);
    return false;
}

//now consume the header
stringBuilder.setLength(0);
while (true) {

    final char read = (char) reader.read();
    if (read < 1) {
        MiscUtils.closeAndIgnore(socket, reader);
        return false;
    }

    stringBuilder.append(read);
    final int currentCount = stringBuilder.length();
    if (currentCount > 4 &&
            stringBuilder.charAt(currentCount - 1) == '\n' &&
            stringBuilder.charAt(currentCount - 2) == '\r' &&
            stringBuilder.charAt(currentCount - 3) == '\n' &&
            stringBuilder.charAt(currentCount - 4) == '\r') {
        break; //response consumed
    }
}

//print the header
final String completeResponse = stringBuilder.toString();
Log.i("Downloader", completeResponse);


texts:
I have created a jQuery slider for my personal website and I wanted to get some feedback on how it looks and if there are things I can do to make it better.

You can see the live demo here: http://www.nickmeagher.com

And here is the code:

        var sliderWidth = 0,
        marginLeft = 0,
        containerWidth = 1040,
        slideSpeed = 600,
        slideDuration = 6000,
        autoSlide = 0; // (0) = off (1) = on

function slide_right() {
        if ( (sliderWidth - Math.abs(marginLeft)) > containerWidth ) {
           $('.portfolio-inner-wrapper').stop().animate({
            'margin-left': '+=-' + containerWidth
           }, slideSpeed, function() {
            marginLeft += -containerWidth;
        });
     } else {
        $('.portfolio-inner-wrapper').stop().animate({
            'margin-left': '0px'
        }, slideSpeed, function() {
            marginLeft = 0;
        });
    }
}

function slide_left() {
    if ( (sliderWidth - Math.abs(marginLeft)) < containerWidth ) {
            $('.portfolio-inner-wrapper').animate({
                'margin-left': '+=+' + containerWidth
            }, slideSpeed, function() {
                marginLeft += containerWidth;
            });
    } else {
        $('.portfolio-inner-wrapper').animate({
                'margin-left': '0'
            }, slideSpeed, function() {
                marginLeft = 0;
            });
    }
}

// Iterate through each container to calculate width
$('.work-container').each(function() {
    sliderWidth += $(this).outerWidth( true );
});

// Set width of inner wrapper
$('.portfolio-inner-wrapper').css('width', sliderWidth);

$('a.next').click(function() {
    slide_right();
});

$('a.prev').click(function() {
    slide_left();
});

if (autoSlide == 1) {
    setInterval(function() {
        slide_right();
    }, slideDuration);
}


texts:
I wrote this web app that splits a URL graphically so that its parts can be customized to create a new URL. https://github.com/ibrahim-islam/urlpad. The app currently works as expected for usual URls but I am not so sure about the code structure.

module UrlPad {

    const map = (o: OmniboxFull): CustomOmniboxMap => {
        return {
            protocol: o.protocol,
            host: o.host,
            port: o.port,
            pathnames: o.pathname.split('/').filter(char => char),
            hash: o.hash,
            query: o.query
        };
    }

    class FormBuilder {

        private template: string[] = [];
        private for: string = '';

        constructor(forClass?: string) {
            this.for = forClass;
            this.template.push('
');
        }

        label(title: string) {
            this.template.push(`<label class="col-sm-2">${title}</label>`);
            return this;
        }

        input(value: string, id?: string, size: number = 10) {
            let id_att = id ? 'id="'+ id +'"' : '';
            this.template.push(`

            <input ${id_att} spellcheck="false" type="text" class="form-control ${this.for}" value="${value}">
`);
            return this;
        }

        build() {
            this.template.push('
')
            return this.template.join('');
        }
    }

    export function parse(url: string): string {
        let o = map(omnibox.parse(url));

        return Object.keys(o)
            .filter((key, index) => o[key])
            .map((key, index) => {
                let value = o[key];
                switch (key) {
                    case 'query':
                        return Object.keys(value)
                            .map((key, index) => new FormBuilder('query').label(`Querystring #${index}`).input(key, '',  5).input(value[key], '', 5).build())
                            .join('');

                    case 'pathnames':
                        return value
                            .map((value, index) => new FormBuilder('path').label(`Pathname #${index}`).input(value).build())
                            .join('');

                    default:
                        return new FormBuilder().label(key).input(value, key).build();
                }
            })
            .join('');
    }

    export function make(o: CustomOmniboxMap): string {
        let querystrings = Object.keys(o.query)
            .map((key, index) => `${key}=${o.query[key]}`)
            .join('&'),
            paths = o.pathnames.join('/');

        return `${o.protocol}://${o.host}${o.port ? ':' + o.port : ''}/${paths}${querystrings ? '?' + querystrings : ''}${o.hash ? o.hash : ''}`;
    }

}

window["UrlPad"] = UrlPad;

I made the app related functionality into a module, should it have been a class?
map function is only used inside parse function, should it have been a local function?
When testing this app should I test only the exported functions or any class or function I wrote as well?

Any other observations or suggestions to improve the code is also welcomed.


texts: Monte Carlo simulation to price an Option in Python

texts:
In what ways can I make this code more efficient?

I haven't put in comments and descriptions yet. I need to do that.
Ideally, I'd like to make the S, v, r, and K user entered as I did with T. I'm worried this is going to make the program cluttered though.
Is it possible to put this entire thing into a class to make it more streamlined? Ideally, I would like for someone to just open the program and it does everything at once instead of having to fiddle with the individual functions.
Since there are a lot of iterations to be done in the simulation, I want some sort of progress to be printed to the console so the user knows it is working and didn't "blow up" so to say. I've done this in a sort of rag-tag way, but is there a way to make it more clean and nicer?
I'd like to work on the readability of this program.

import datetime
import time as walltime
from random import gauss
from math import exp, sqrt

S = 863.00 # underlying price
v = 0.20 # vol of 20.00%
r = 0.0218 # 10 year rate of 2.18$

while True:
    t0 = raw_input("Enter a valid number of days (as an integer) until expiration: ")
    try:
        t0 = int(t0)
    except ValueError:
        continue
    if type(t0) == int:
        break
T = t0/ 365.0
K = 860.00
simulations = 100000000
payoffs = []
discount_factor = exp(-r * T)

def generate_asset_price(S,v,r,T):
    return S * exp((r - 0.5 * v**2) * T + v * sqrt(T) * gauss(0,1.0))

asset_price = generate_asset_price(S,v,r,T)

#print asset_price

def call_payoff(S_T, k):
    return max(S_T - k, 0.0)

#print call_payoff(S,K)

"""Use to price a put instead of call"""
#def put_payoff(S_T,k):
#   return max(k - S_T, 0.0)

print "\n"
print "Working, please wait..."
print "\n"

cl1 = walltime.clock()

count = 1
for i in xrange(simulations):
    S_T = generate_asset_price(S,v,r,T)
    payoffs.append(call_payoff(S_T, K))
    count += 1
    if count == 10000000:
        print "10 percent done"
    elif count == 25000000:
        print "25 percent done"
    elif count == 50000000:
        print "50 percent done"
    elif count == 75000000:
        print "75 percent done"

print "---------------------------"

cl2 = walltime.clock()
print "---------------------------"
print "End of computations, calculation time = ", (cl2-cl1), " sec"
print "---------------------------"
price = discount_factor * (sum(payoffs) / float(simulations))
print "Option Price: %.4f" % price
print "---------------------------"


texts: Simple CSS minifier for twig, with basic caching

texts:
On part of a project, I have some CSS being read using twig's source() function.
But sending a huge chunk of CSS is not optimal.
To reduce the size of the HTML, I've written this twig filter.

However, I've noticed that some big files would take a bit more to be minimified.
To reduce the time to re-minify the CSS, I've added a crude caching system.

Assuming that you have the following:

$twig = new Twig_Environment(new Twig_Loader_Filesystem( ... ), array( ... ));

You have the following code:

$twig->addFilter(new Twig_SimpleFilter('minify_css', function($css, $cache = true){
        $path = $_SERVER['DOCUMENT_ROOT'] . '/cache/minify_css/';
        $min_length = 1024;

        if(!is_dir($path))
        {
            mkdir($path, 0755, true);
        }
        $length = strlen($css);
        $result = '';

        if($cache && $length > $min_length && @is_file($file = $path . ($hash = md5($css)) . '.css' ))
        {
            $result = file_get_contents($file);
        }
        else if($length >= 9)
        {
            $result = preg_replace(
                array(
                    '@/\*[^*]*\*+([^/][^*]*\*+)*\/@', // /*abc*/ ->
                    '@([\-;\{]\w*)\s*:\s*@', //a : b -> a:b
                    '@\s*;\s*\}\s*@', //a:b ; } -> a:b}
                    '@\s*\{\s*@', // a { b:c} -> a{b:c}
                    '@\s*!important\s*@i', // a:b !important } -> a:b!important}
                    '@([,;}!:]|^)\s*0+\s*px@i', // a: 0px -> a:0
                    '@([,;:!.>~\+=\[\{\}\(]|^)[\s\r\n]+@', // a, b -> a,b
                    '@[\s\r\n]+([,;!>~\+=\]\{\}\)]|$)@', // a ,b -> a,b
                    '@([,:\( ])\s*#([\da-f])\2([\da-f])\3([\da-f])\4@i' // a: #FF00CC -> a:#F0C
                ),
                array(
                    '',
                    '$1:',
                    '}',
                    '{',
                    '!important',
                    '${1}0',
                    '$1',
                    '$1',
                    '$1#$2$3$4'
                ),
                str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $css)
            );

            if($cache && $length > $min_length)
            {
                file_put_contents($file, $result);
            }
        }
        return $result;
    }), array('is_safe' => array('html', 'css', 'js'))
);

This filter takes 1 parameter, to indicate if there's or not caching, and returns the minified CSS when applicable.

An example of it's usage:

{% for file in css_files %}
    <style>{{ source('assets/css/' ~ file ~ '.css') | minify_css }}</style>
{% endfor %}

This assumes that the template has access to the variable css_files, containing the name of those files.

What else can I improve here?
Any speed improvements or readability improvements?


texts: Shutdown method in queue implementations

texts:
I am trying to implement a shutdown method in queue implementation. I took the code from BlockingQueue source from Java and trying to check the shutdown method. Will the following code be thread safe and an acceptable implementation?

    import java.util.concurrent.atomic.*;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.ReentrantLock;

public class BlockingQueue<E> {

    /* Node encapsulating the object that needs to be stored */
    static class Node<E>{

        /* Make sure all the threads read / write are done on updated variable */
        volatile E element;
        Node<E> next;
        Node(E value) { element = value;}
    }

    private final int capacity;
    private final AtomicInteger count = new AtomicInteger(0);
    private final AtomicInteger shutdown = new AtomicInteger(0);

    /* Need lock to make the thread re-entrant */
    private final ReentrantLock putLock = new ReentrantLock(true);
    private final ReentrantLock getLock = new ReentrantLock();

    private final Condition queueNotEmpty = getLock.newCondition();
    private final Condition queueNotFull = putLock.newCondition();

    /* Make sure updates to head and tail variables are atomic
     *  May be redundant as I have already enclosed the updated to head and tail
     *  using locks.
     */
    private AtomicReference<Node<E>> head, tail;

    public BlockingQueue()
    {
        this.capacity = Integer.MAX_VALUE;
    }

    public BlockingQueue(int capacity){
        if (capacity <= 0)
            throw new IllegalArgumentException();

        this.capacity = capacity;
        head = tail = new AtomicReference<BlockingQueue.Node<E>>(null);
    }

    public void add(E e) throws InterruptedException, Exception{

        if (e == null) throw new NullPointerException();

        /* We need to wait if there is not enough space on the queue
         *
         */
        final ReentrantLock lock = this.putLock;
        final AtomicInteger count = this.count;
        int c =-1;

        lock.lockInterruptibly();
        try {

            try {
                while(count.get() == capacity)
                    queueNotFull.await();

                if(shutdown.get() == 1)
                    throw new Exception();

            } catch (InterruptedException exception) {
                queueNotFull.signal();
                throw exception;
            }

            // Add the element to the queue
            Node<E> elem = new Node<E>(e);
            Node<E> prevTail = tail.getAndSet(elem);
            prevTail.next = elem;

            c = count.incrementAndGet();
            if (c + 1 < capacity)
                queueNotFull.signal();
        } finally {
            lock.unlock();
        }

        if(c == 0)
            signalNotEmpty();
    }

     /**
     * Signals a waiting get. Called only from put/offer (which do not
     * otherwise ordinarily lock getLock.)
     */
    private void signalNotEmpty() {
        final ReentrantLock takeLock = this.getLock;
        takeLock.lock();
        try {
            queueNotEmpty.signal();
        } finally {
            takeLock.unlock();
        }
    }

     public void shutDown()
     {
         /* Get the locks */
         putLock.lock();
         getLock.lock();

         try{
             head.getAndSet(null);
             tail.getAndSet(null);

             shutdown.getAndSet(1);

             //Signal all put and get threads
             queueNotFull.signalAll();
             queueNotEmpty.signalAll();

         }finally {
             putLock.unlock();
             getLock.unlock();
         }
     }
}

Is there a better way to implement this method?


texts:
Is it good practice to keep the connection strings for websites in another folder outside of the site folder?
For example, here is the htdocs structure.  I am working on site3:
htdocs>
  site1>
  site2>
  site3>
     index.php
     include>
       database.php
  site4>

Using the above, here is the database.php connection file for site3:
<?php
  $host = 'xx.xxx.x.xx';
  $dbname = 'mydatabase';
  define ('DB_USER', 'dbusername');
  define ('DB_PASSWORD', 'dbpassword');

  try{
    $dbc = new PDO("mysql:dbname=$dbname;host=$host", DB_USER, DB_PASSWORD);
    $dbc->SetAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }
  catch(PDOException $e){
    echo "Conneciton failed: " . $e->getMessage() . "
";
  }
?>

So what I want to do is move the connection information into another folder, called 'connections'.  This is where I'll keep the actual connection info.
Here is the revised htdocs structure, with the connections directory:
htdocs>
  site1>
  site2>
  site3>
     index.php
     include>
       database.php
  site4>
  connections>
    site3conn.php

Within the connections directory, here is site3conn.php:
<?php
  $host = 'xx.xxx.x.xx';
  $dbname = 'mydatabase';
  define ('DB_USER', 'dbusername');
  define ('DB_PASSWORD', 'dbpassword');
?>

So now, the database.php connection file for site3 will pull in the connection string from the connections directory.  As follows:
<?php
  require("D:\htdocs\connections\site3conn.php");

  try{
    $dbc = new PDO("mysql:dbname=$dbname;host=$host", DB_USER, DB_PASSWORD);
    $dbc->SetAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }
  catch(PDOException $e){
    echo "Conneciton failed: " . $e->getMessage() . "
";
  }
?>

Please note, both examples allow me to successfully connect to the dB.  But I want to use the revised format.
I, of course, need to make sure users cannot navigate to the connections folder.  Unsure how I can do that.
With that said, is this good practice?  Is this more secure or less secure or neither?  Is there a better way?
Appreciate your thoughts.