texts: Calculating how long sales reps are idle

texts:
I wrote a procedure to calculate the number of months elapsed since a sales agent' last sale. It works but runs in over 10 minutes... for 20 rows.

Sub Latency()
' this sub-routine is used to calculate the no of recent idle months by an agent
Application.ScreenUpdating = False
For Each rng In Range("BL1:BL13000")
j = 1
Do Until ActiveCell.Offset(0, -23 - j) > 0    ' this reads the sales flag
j = j + 1
If j > 12 Then Exit Do
Loop
ActiveCell.Value = (j - 1)   ' inserts the value to the cell
ActiveCell.Offset(1, 0).Select
Next rng
End Sub


texts: Ruby Dynamic Struct - Pattern or AntiPattern?

texts:
There is a pattern that keeps coming up in my ruby code and I'm somewhat ambivalent about it. It's somewhere between a Hash and a Struct. Basically
I used method_missing to return/set values in the Hash unless I want to
override a specific value with some logic or flatten out the complex underlying structure in the JSON. It's very flexible and quickly
allows code changes, but it also hides much of the structure of the object.

In effect, the structure is in the data ( JSON file ) and not in the code.
Is this an effective Pattern or just asking for trouble down the road?

class AttributeKeeper

    def initialize
      @attributes = Hash.new
    end

    def import
       // Special import methods usually from JSON
    end

    def export
       // Export to JSON with maybe some data verification along the way.
    end

    def special_value= (value )
        // Perform data check on special value
        @attributes[special_value] = value
    end

    def checked_value
        // Return value if passes checks.
    end

    def method_missing(meth, *args, &block)
      smeth = meth.to_s
      trim = smeth.chomp('=') #Handle setter methods.
      unless ( smeth == trim )
        @attributes[trim] = args[0]
      else
        @attributes[smeth]
      end
    end

    def responds_to?(meth)
      smeth = meth.to_s
      if( @attributes[smeth] or smeth[-1,1] == '=')
        true
      else
        super
      end
    end

end


texts: Quaternion and Vector3 transfomation Math

texts:
hi I have made and AI for my enemies which works perfectly but a particular section of code is repetitive and I feel that it can be optimised

void ChangeDirection()
    {
        if (movement == Vector3.left)
            transformModel.rotation = Quaternion.Euler(0, 270, 0);
        else if (movement == Vector3.right)
            transformModel.rotation = Quaternion.Euler(0, 90, 0);
        else if (movement == Vector3.back)
            transformModel.rotation = Quaternion.Euler(0, 180, 0);
        else if (movement == Vector3.forward)
            transformModel.rotation = Quaternion.Euler(0, 0, 0);
    }

the enemy will be in a tight corridor where only the following movements are possible i.e enemy can only move the vector3. right, left, back and forward. thus the code works without any issues,
however, the code is repetitive and I want the enemy to move in whichever its movement vector will be.

here is the rest my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyMovement2 : MonoBehaviour
{
    public float speed;
    public Vector3 movement;
    public Animator animator;
    private GameObject gameManager;

    void Start()
    {

        movement = Vector3.back;
        gameManager = GameObject.FindWithTag("GameController");

    }
    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Wall")
        {

            CorrectPosition(new Vector3(1, 1, 1));
            movement = Vector3.zero;

        }
    }

    public Transform transformModel;
    void ChangeDirection()
    {
        if (movement == Vector3.left)
            transformModel.rotation = Quaternion.Euler(0, 270, 0);
        else if (movement == Vector3.right)
            transformModel.rotation = Quaternion.Euler(0, 90, 0);
        else if (movement == Vector3.back)
            transformModel.rotation = Quaternion.Euler(0, 180, 0);
        else if (movement == Vector3.forward)
            transformModel.rotation = Quaternion.Euler(0, 0, 0);
    }
    void CorrectPosition(Vector3 CorrectPositionOF)
    {
        Vector3 posNow = transform.position;
        if (CorrectPositionOF.x == 1)
            posNow.x = Mathf.RoundToInt(gameObject.transform.position.x);
        if (CorrectPositionOF.y == 1)
            posNow.y = Mathf.RoundToInt(gameObject.transform.position.y);
        if (CorrectPositionOF.z == 1)
            posNow.z = Mathf.RoundToInt(gameObject.transform.position.z);
        transform.position = posNow;
    }
    public LayerMask whatIsWall;
    private Vector3[] direction = { Vector3.left, Vector3.forward, Vector3.back, Vector3.right };
    void FixedUpdate()
    {
        GetComponent<Rigidbody>().velocity = movement * speed;
        animator.SetFloat("runningSpeed", GetComponent<Rigidbody>().velocity.magnitude);
        for (int i = 0; i < direction.Length; i++)
        {
            RaycastHit hit;
            if (Physics.Raycast(transform.position, direction[i], out hit, 18, 0 << 11 | 1 << 8 | 1 << 9)
                && hit.collider.gameObject.tag == "Player"
                && movement == Vector3.zero)
            {
                movement = direction[i];
                ChangeDirection();
                return;
            }
        }

    }
}
```


texts: Looping Array object with conditions and comparison the performance with ECMA VS Vanilla JS

texts:
The Plain vanilla JS needs to converted in to advanced ECMA. The below 3 snippets shown yields the correct result. Need to identify which among them is performance oriented
this.allUserDetails.forEach((el, indx) => {
    if (type === 0 && flagResumeAll === false) {
        if (el.extensionTime === time && el.userProctorSignal === 0) {
            this.toggleButtonDisplayType = 0;
        } else {
            flagResumeAll = true;
        }
    } else if (type === 1 && flagPauseAll === false) {
        if (el.extensionTime === time && el.userProctorSignal === 1) {
            this.toggleButtonDisplayType = 1;
        } else {
            flagPauseAll = true;
        }
    }
});

The above code could be repaced with Code I and Code II
Code I
if (type === 0 && flagResumeAll === false) {
    this.allUserDetails.filter(el => {
        if(el.extensionTime === time && el.userProctorSignal === 0) {
        this.toggleButtonDisplayType = 0;
        } else {
        flagResumeAll = true;
        }
    })
} else if (type === 1 && flagPauseAll === false) {
    this.allUserDetails.filter(el => {
        if(el.extensionTime === time && el.userProctorSignal === 1) {
        this.toggleButtonDisplayType = 1;
        } else {
            flagPauseAll = true;
        }
})

Code II
this.allUserDetails.filter(el => {
    if(type === 0 && flagResumeAll === false && el.extensionTime === time && el.userProctorSignal === 0) {
        this.toggleButtonDisplayType = 0;
    } else if (type === 0 && flagResumeAll === false){
        flagResumeAll = true;
    } else if (type === 1 && flagPauseAll === false && el.extensionTime === time && el.userProctorSignal === 1) {
        this.toggleButtonDisplayType = 1;
    } else if(type === 1 && flagPauseAll === false) {
        flagPauseAll = true;
    }
})

Which among them is yields better in performance replacing from plain/vanilla JS to Code I/II.
Will this be further simplified..


texts: Fizz Buzz function that returns an array

texts:
I am a newbie to JS and I am working on a FizzBuzz challenge. Below is what I have tried. Essentially when the function takes a value then it would iterate from 1 up to the value and an array would result.
I am seeking advice on adding conditional checking such as:

If the value of n is less than 4, it will return the string: "Please insert a value greater than or equal to 4".
If the function is passed no value, it should return an empty array.

I am not sure where to add and should I be using if...else or simply if for each conditional checking.
var fizzBuzz = function(n, arr = []) {
  for (let i = 1; i < n; i++) {
  if (n === 1) {
    arr.push('1');
    return arr.reverse();
  } else {
    if (n % 4 === 0 && n % 5 === 0) {
      arr.push('FIZZBUZZ');
    } else if (n % 5 === 0) {
      arr.push('Buzz');
    } else if (n % 4 === 0) {
      arr.push('Fizz');
    } else {
      arr.push('' + n);
    }
    return fizzBuzz(n - 1, arr);
  }
  }
}


texts: Improving or replacing a long if statement

texts:
I have a an if statement that works just fine, however, it has become a bit long and I need help to figure out how I can reduce the lines of code and thereby the readability.
I have a defaultMonth and set of months and a corresponding price. I need to add or reduce the price depending on the defaultMonth and month selected by the user.
Here are some examples of the output I need (note the interval is the same):
If default month is 60 - set price accordingly:
Month    -     Price
60             0.0
48             0.1
36             0.2
24             0.35
12             0.5

If default month is 48 - set price accordingly:
Month    -     Price
60             -0.1
48             0.0
36             0.1
24             0.25
12             0.4

If default month is 36 - set price accordingly:
Month    -     Price
60             -0.2
48             -0.1
36             0.0
24             0.15
12             0.3

The way I've built it now is with an if statement for each default month and nested ifs for each month.
if (defaultMonth === 60) {
    if (month === 60) {
        this.price += 0.0
    }
    if (month === 48) {
        this.price += 0.1
    }
    if (month === 36) {
        this.price += 0.2
    }
    if (month === 24) {
        this.price += 0.35
    }
    if (month === 12) {
        this.price += 0.5
    }
}
if (defaultMonth === 48) {
    if (month === 60) {
        this.price -= 0.1
    }
    if (month === 48) {
        this.price += 0.0
    }
    if (month === 36) {
        this.price += 0.1
    }
    if (month === 24) {
        this.price += 0.25
    }
    if (month === 12) {
        this.price += 0.4
    }
}
if (defaultMonth === 36) {
    if (month === 60) {
        this.price -= 0.2
    }
    if (month === 48) {
        this.price -= 0.1
    }
    if (month === 36) {
        this.price += 0.0
    }
    if (month === 24) {
        this.price += 0.15
    }
    if (month === 12) {
        this.price += 0.3
    }
}
if (defaultMonth === 24) {
    if (month === 60) {
        this.price -= 0.35
    }
    if (month === 48) {
        this.price -= 0.25
    }
    if (month === 36) {
        this.price -= 0.15
    }
    if (month === 24) {
        this.price += 0.0
    }
    if (month === 12) {
        this.price += 0.15
    }
}
if (defaultMonth === 12) {
    if (month === 60) {
        this.price -= 0.5
    }
    if (month === 48) {
        this.price -= 0.4
    }
    if (month === 36) {
        this.price -= 0.3
    }
    if (month === 24) {
        this.price -= 0.15
    }
    if (month === 12) {
        this.price += 0.0
    }
}


texts: Finding the average of each row in a CSV file

texts:
I am getting back into python after a year of not doing it at all. I just wrote a bit of code to create a file that looks like this:

1,2
1,1,1,1
-1,0,1
42,17

Then I decided to take the average of each line and put it into a list. For this I wrote the following:

def line_averages():
    out_file = open("data.csv", "w") #create data file
    out_file.write("1,2\n1,1,1,1\n-1,0,1\n42,17") #write numbers into data file
    out_file.close()

    f = open("data.csv", "r") #read data file
    lines = f.readlines()
    avLines= [] #create a list to put averages into
    for line in lines:
        line2 = line.replace("\n", "") #remove /n from lines
        line2 = line2.split(",") #split the lines by commas
        Nlines = [] #create a list to put floats into
        for i in line2:
            i = float(i)
            Nlines.append(i) #put the floats into the list
        sums = sum(Nlines) #total up each line from the file
        avLines.append(sums/len(line2)) #put the averages of each line into a list
    return avLines

I'm pretty happy as this does exactly what I wanted but I can't help but wonder if it can't be shortened/simplified. It seems a bit inefficient to me to have lots of "placeholders" (like  Nlines or line2) which are used to do an operation rather than being able to do the operation directly on them. What would you guys do (if anything) to make this more compact? I'm sure it could be done more succinctly!


texts:
I am trying to implement a hash table in Objective-C.  I did some testing and the implementation seems to work.  I am using an NSMutableArray to store linked lists of entries.  It also resizes when it gets almost full.  I am using an NSString for a key and any object as a value.  I store NSNull objects in an NSMutableArray to be able initialize it to a certain size.

The hash function I copied from the Java HashTable implementation:

#import "YZHashTable.h"
#import "Entry.h"

@interface YZHashTable()

@property (nonatomic,strong) NSMutableArray *tableArray;
@property (nonatomic) NSInteger elementCount;
@end

@implementation YZHashTable

const int HASHTABLECAPACITY=10;
const double HASHTABLELOADFACTOR = 0.75;

-(instancetype)init
{
    self  = [super init];
    if(self){
        [self resizeTableArray];
        _elementCount = 0;
    }

    return self;
}

-(void)resizeTableArray
{
    for(int i = 0; i < HASHTABLECAPACITY; i++){
        [self.tableArray addObject:[NSNull null]];
    }
}

-(NSMutableArray *)tableArray
{
    if(!_tableArray){
        _tableArray = [[NSMutableArray alloc]initWithCapacity:HASHTABLECAPACITY];
    }
    return _tableArray;
}

-(void)setElementCount:(NSInteger)elementCount
{
    if(elementCount < 0) return;
    _elementCount = elementCount;
}

-(void)addObjectForKey:(NSString *)key andValue:(id) value
{
    if(self.elementCount > [self.tableArray count] * HASHTABLELOADFACTOR){
        [self resizeTableArray];
    }
    NSUInteger keyArrayIndex = [self indexForHash:[key hash]] % [self.tableArray count];
    if([[self.tableArray objectAtIndex:keyArrayIndex] isKindOfClass:[NSNull class]]){
        [self.tableArray setObject:[[Entry alloc]initWithKey:key andValue:value] atIndexedSubscript:keyArrayIndex];
    }else{
        Entry *root = [self.tableArray objectAtIndex:keyArrayIndex];
        while(root.next && ![root.key isEqualToString:key]){
            root = root.next;
        }
        if([root.key isEqualToString:key]){
            root.value = value;
        }else{
            root.next = [[Entry alloc]initWithKey:key andValue:value];
        }
    }
    self.elementCount++;
}

-(id)getObjectForKey:(NSString  *)key
{
    id value = nil;

    NSUInteger keyArrayIndex = [self indexForHash:[key hash]] % [self.tableArray count];
    Entry *root = [self.tableArray objectAtIndex:keyArrayIndex];
    if(![root isKindOfClass:[NSNull class]]){
        while(![root.key isEqualToString:key] || root.next != nil){
            root = root.next;
        }
        if([root.key isEqualToString:key]) value = root.value;
    }

    return value;
}

-(id)removeObjectForKey:(NSString  *)key
{
    id value = nil;

    NSUInteger keyArrayIndex = [self indexForHash:[key hash]] % [self.tableArray count];
    Entry *root = [self.tableArray objectAtIndex:keyArrayIndex];
    if(![root isKindOfClass:[NSNull class]]){
        if([root.key isEqualToString:key]){
            if(!root.next){
                [self.tableArray setObject:[NSNull null] atIndexedSubscript:keyArrayIndex];
            }else{
                root = root.next;
            }
            self.elementCount--;
        }else{
            while(root.next && ![root.next.key isEqualToString:key]){
                root = root.next;
            }
            if([root.next.key isEqualToString:key]){
                root.next = root.next.next;
                self.elementCount--;
            }
        }

    }
    return value;
}

-(NSUInteger)count
{
    return self.elementCount;
}

-(NSUInteger)indexForHash:(NSUInteger)hash
{
    hash ^= (hash>>20)^(hash>>12);
    return hash ^ (hash >> 7) ^ (hash >> 4);
}

@end


texts: Functional implementation of the Maybe Monad in JS

texts:
A while ago, I really wanted to have the Maybe Monad in my JS projects. I ended up trying to use Promises as a stand-in solution (using Promise.resolve as my unit, then chaining from there), but using resolve and reject for nullable types made it unwieldy and difficult to parse.

I've seen some cool implementations of the Maybe Monad in JS online, but many use classes and seem to mutate state. I wanted to make an immutable and purely functional version (if not only as a proof of concept).

You will see that I also added a last formal parameter to Maybe and Just. This is so that, when a chain falls through, debugging can be made easier by seeing the last value that was valid.

I'm looking for more ways to make this usable and perhaps more abstract. I originally created a symbol for Nothing, but found that null works pretty well too. What are your thoughts and criticisms?

const MType = Symbol("Maybe");
const isMaybe = x => (x instanceof Object && MType in x);
const isNone = x => x === null || x === undefined;

const Just = (x, last) => ({
  valueOr : alternative => isNone(x) ? alternative : x,
  then : f => Maybe(isNone(x) ? x : f(x), x),
  catch : f => Maybe(isNone(x) ? f(last) : x, x),
  type : MType
});

const Maybe = (x, last = null) => isMaybe(x, last) ? x : Just(x, last);

const nested = {
  a : {
    b : {
      c : {
        e : 6
      }
    }
  }
}

console.log(
  Maybe(nested)
    .then(({ a }) => a)
    .then(({ b }) => b)
    .then(({ c }) => c)
    .then(({ d }) => d)
    .catch(last => `Last value: ${JSON.stringify(last)}`)
    .valueOr()
);

// Output: Last value: {"e":6}


texts: Drawing colored circles using Ruby and Tk

texts:
I am a high-school freshman who is kinda new to Ruby, and I am doing a small project on Ruby.  One of the big things that I want to get out of this project is how to follow the "Ruby standards" that programmers should follow.  Being as new as I am, I have no clue what I should/shouldn't do with this program.  Can anybody tell me what I could do to improve it to fit the community's standards?

require 'tk'

$point_A = [0,0]
$point_B = [750,750]
$rate = 1.5
$i=0
circs=Array.new

def before_drawing()
    $point_A = []
    temp_a = $point_B[0]**1/$rate
    temp_b = $point_B[1]**1/$rate
    $point_A << temp_a
    $point_A << temp_b
end

def after_drawing()
   $point_B = []
   $point_B = $point_A
end

canvas = TkCanvas.new(:width=>800, :height=>800).pack('fill' => 'both', 'expand'=>true)

while $i<10 do
    before_drawing()
    circs[$i] = TkcOval.new(canvas, $point_A, $point_B)
    if $i%2==0 then
        circs[$i][:fill] = 'blue'
    else
        circs[$i][:fill] = 'red'
    end
    after_drawing()
    $i+=1
end

Tk.mainloop


texts: Copying data from various sources into a master list

texts:
I am working on a Master List, where I am copying data from various sources for each month into the columns Z, AC, AF, AI etc. (always separated by 2 columns). Then I copy that cell all the way down to update the values for each row. As you can see in the code below, the only difference from one section of the code to the next is:

Change column (here Z to AC)
Change paths which are stored in different cells (e.g. fromPath changed to fromPath2.

How can I make it more efficient?

' Update Jan 2018

fromPath = Sheets("Filepaths for P25 2017").Range("G2")
vbaPath = Sheets("Filepaths for P25 2017").Range("F2")
vbaFile = Sheets("Filepaths for P25 2017").Range("H2")
Orderlist2017 = Sheets("Filepaths for P25 2017").Range("I2")

With ThisWorkbook.Sheets("Orderlist P25 2017")
Range("Z10").Formula = "=VLookup(C10,  '" & vbaPath & vbaFile & Orderlist2017 & "'!C14:Z90, 8, False)"
Range("Z10").Select
    Selection.Copy
    Range("Y10").Select
    Selection.End(xlDown).Select
    Range("Z85").Select
    Range(Selection, Selection.End(xlUp)).Select
    ActiveSheet.Paste
    Application.CutCopyMode = False

End With

' Update Feb 2018

fromPath2 = Sheets("Filepaths for P25 2017").Range("G3")
vbaPath2 = Sheets("Filepaths for P25 2017").Range("F3")
vbaFile2 = Sheets("Filepaths for P25 2017").Range("H3")
Orderlist2017 = Sheets("Filepaths for P25 2017").Range("I3")

With ThisWorkbook.Sheets("Orderlist P25 2017")
Range("AC10").Formula = "=VLookup(C10,  '" & vbaPath2 & vbaFile2 & Orderlist2017 & "'!C14:Z90, 8, False)"
Range("AC10").Select
    Selection.Copy
    Range("Y10").Select
    Selection.End(xlDown).Select
    Range("AC85").Select
    Range(Selection, Selection.End(xlUp)).Select
    ActiveSheet.Paste
    Application.CutCopyMode = False

End With


texts: Removing nodes with a given value from a linked list

texts:
Is this a good way of removing all the nodes that contains a value x?
This function takes as input the head of a list and has to delete all the nodes that contain a given value taken.  If there is any better way of doing this can you please show them to me?

node_t *funzione(node_t *head){

    int x;
    node_t *temp = head;
    node_t *curr = head;

    temp = (node_t *)malloc(sizeof(node_t));
    curr = (node_t *)malloc(sizeof(node_t));

    printf("Inserisci il valore che vuoi eliminare: \n");
    scanf("%d", &x);

    if (head == NULL)
        exit(0);

    while(head->val == x){
        head = head->next;
        free(temp);
        temp = head;
    }

    curr = head;
    temp = curr->next;

    while (temp != NULL){
        if (temp->val == x){
            if(temp->next != NULL){
                curr->next = temp->next;
                free (temp);
                temp = curr->next;
            }
            else {
                curr->next = NULL;
            }
        }
        else {
            curr = temp;
            temp = temp->next;
        }
    }

    return head;
}


texts: create generic method for two different anonymous types

texts:
Function 1:

 public HttpResponseMessage Get340BValidations()
        {
            int partitionId = GetPartitionId();
            //int partitionId = 10054;
            this.db.Database.CommandTimeout = 180;
            List<Validation340B> result = this.db.VW_Validation_340B.Where(x => x.partition_id == partitionId).ToList();

var duplicateClaims = result.GroupBy(a => a.claim_id).Where(g => g.Count() > 1).Select(y => new { claimID = y.Key, records = y.ToList() });

            var newResult = result.GroupBy(a => a.claim_id).Select(g => g.First()).ToList();

            foreach (var claim in duplicateClaims)
            {
                List<byte?> testIds = new List<byte?>();
                foreach (var record in claim.records)
                {
                    testIds.Add(record.claim_validation_test_id[0]);
                }
                newResult.Where(x => x.claim_id == claim.claimID).ToList().ForEach(y => y.claim_validation_test_id = testIds);

            }

}

Function 2:

public HttpResponseMessage GetQuantityValidations()
        {
            int partitionId = GetPartitionId();
            List<ValidationQuantity> = this.db.VW_Validation_Quantity.Where(x => x.partition_id == partitionId).ToList();
var duplicateClaims = result.GroupBy(a => a.claim_id).Where(g => g.Count() > 1).Select(y => new { claimID = y.Key, records = y.ToList() });

            var newResult = result.GroupBy(a => a.claim_id).Select(g => g.First()).ToList();

            foreach (var claim in duplicateClaims)
            {
                List<byte?> testIds = new List<byte?>();
                List<string> testNames = new List<string>();
                List<string> resultValues = new List<string>();
                foreach (var record in claim.records)
                {
                    testIds.Add(record.claim_validation_test_id[0]);
                    testNames.Add(record.Test[0]);
                    resultValues.Add(record.Result[0]);
                }

                newResult.Where(x => x.claim_id == claim.claimID).ToList().ForEach(y => { y.claim_validation_test_id = testIds; y.Test = testNames; y.Result = resultValues; });
}
            }

Two functions contains same set of code for finding the duplicate records and modification below part

var duplicateClaims = result.GroupBy(a => a.claim_id).Where(g => g.Count() > 1).Select(y => new { claimID = y.Key, records = y.ToList() });

            var newResult = result.GroupBy(a => a.claim_id).Select(g => g.First()).ToList();

            foreach (var claim in duplicateClaims)
            {
                ........
}

how can i simplify above two functions which uses the same set of code for finding the duplicates. need one common function which should behave like generic method accept different model as parameter and implement the same functionalities.


texts: Retrieving remote pages and parsing html

texts:
This is my code:

    <?php
$begin = microtime(TRUE);
$result = get_web_page('WEB_PAGE');

$dom = new DOMDocument();
$dom->loadHTML($result['content']);
$xpath = new DOMXPath($dom);

// Get the links
$matches = $xpath->evaluate('//li[@class = "lasts"]/a[@class = "lnk"]/@href | //li[@class=""]/a[ @class = "lnk"]/@href');
if ($matches === FALSE) {
    echo 'error';
    exit();
}
foreach ($matches as $match) {
    $links[] = 'WEB_PAGE'.$match->value;
}

$index = 0;

// For each link
foreach ($links as $link) {
    echo (string)($index).' loop '.(string)(microtime(TRUE)-$begin).'<br>';
    $result = get_web_page($link);

    $dom = new DOMDocument();
    $dom->loadHTML($result['content']);
    $xpath = new DOMXPath($dom);

    $match = $xpath->evaluate('concat(//span[@id = "header"]/span[@id = "sub_header"]/text(), //span[@id = "header"]/span[@id = "sub_header"]/following-sibling::text()[1])');
    if ($matches === FALSE) {
        exit();
    }
    $data[$index]['name'] = $match;

    $matches = $xpath->evaluate('//li[starts-with(@class, "active")]/a/text()');
    if ($matches === FALSE) {
        exit();
    }
    foreach ($matches as $match) {
        $data[$index]['types'][] = $match->data;
    }

    $matches = $xpath->evaluate('//span[@title = "this is a title" and @class = "info"]/text()');
    if ($matches === FALSE) {
        exit();
    }
    foreach ($matches as $match) {
        $data[$index]['info'][] = $match->data;
    }

    $matches = $xpath->evaluate('//span[@title = "this is another title" and @class = "name"]/text()');
    if ($matches === FALSE) {
        exit();
    }
    foreach ($matches as $match) {
        $data[$index]['names'][] = $match->data;
    }

    ++$index;
}

?>

This is what is being printed:

0 loop 1.66981506348
1 loop 2.49688410759
2 loop 3.00950098038
3 loop 3.5253970623
4 loop 4.01076102257
5 loop 4.67162799835
6 loop 5.2378718853
7 loop 5.74008488655
8 loop 6.26041197777
9 loop 6.78747105598
10 loop 7.47332000732
11 loop 8.03243994713
12 loop 8.50538802147
13 loop 9.37472701073
14 loop 11.5049209595
15 loop 12.2112920284
16 loop 12.6640410423
17 loop 13.1369791031
18 loop 13.8875179291
19 loop 14.4746370316
20 loop 14.9760200977
21 loop 15.5332159996
22 loop 16.1946868896
23 loop 17.0584990978
24 loop 17.840462923
25 loop 18.6889989376
26 loop 19.6185629368
27 loop 20.8282380104
28 loop 22.0119960308
29 loop 22.9078469276
30 loop 24.0000309944
31 loop 24.6960549355
32 loop 25.1580710411
33 loop 25.5702528954
34 loop 26.2709059715
35 loop 26.7621939182
36 loop 27.2691950798
37 loop 27.88843894
38 loop 28.6984479427
39 loop 29.4622280598
40 loop 30.2815680504
41 loop 31.1307020187

What it does is basically connects to a remote page, retrieves it and parses links from that page.
Then for each link, it retrieves it and parses it, creates a new data structure and then uses it (the part of using the structure is not included here).
The output that I added is the time that has passed since the beginning of the runtime of the script.
It takes about 30 seconds for this code to run, which is insane.
How can I improve it?


texts:
The process:

I read the lookup and create a list aa.
I traverse through the glob.glob("C:\\project resource\\dump\\*.html") and find matching.
If a match is found, I create a file if not available, but if available, I just append it to the file.

import glob,re
from bs4 import BeautifulSoup
import unidecode
lis=[]
aa=open("C:\project resource\lookup.txt","r")
aa=aa.readlines()
aa=[b.split("\t") for b in aa ]
print "started"
for sa in aa:
    for a in glob.glob("C:\\project resource\\dump\\*.html"):

        if sa[0] =="".join(re.findall("_(\d+).",a)):
            try:
                fi= open(sa[1].strip()+".txt","a")
                html=" ".join(open(a,"r").readlines()[1:])
                soup = BeautifulSoup(html)
                # kill all script and style elements
                for script in soup(["script", "style"]):
                    script.extract()    # rip it out
                # get text
                text = soup.get_text()
                # break into lines and remove leading and trailing space on each
                lines = (line.strip() for line in text.splitlines())
                # break multi-headlines into a line each
                chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
                # drop blank lines
                text = ' '.join(chunk for chunk in chunks if chunk)
                text=re.sub("\s+"," ",text)

                fi.write(unidecode.unidecode(text)+"\n")
            except:
                print a
            fi.close()
            break
    else:
        print sa,"no match"

lookup.txt sample:

123\tapple
124\tdad
125\tdude

Sample file names in dump:

12_123.html
12_124.html
123234_125.html

Time:

File count :1,65,000
Time: 2 days

Is there a change which can increase the speed of this process?


texts:
My code takes an input, uses the input to take a number of letters from the start of the alphabet and put them at the end. I intend to use this to create a Caesar style cipher.

Is there a way to do this more elegantly?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    class Program
    {
        static void Main()
        {
            GettingInput gi = new GettingInput();
            var input = gi.GetInput();
            Console.WriteLine("Your input:\n{0}", input);
            List<char> alphabet = new List<char>();

            for (char c = 'a'; c <= 'z'; c++)
            {
                alphabet.Add(c);
            }
            for (int i = 0; i < input; i++)
            {
                alphabet.Add(alphabet[i]);
            }

            for (int i = input ; i > 0; i--)
            {
                alphabet.Remove(alphabet[i-1]);
            }

            for (int i = 0; i < 26; i++)
            {
                Console.WriteLine(alphabet[i]);
            }

            Console.ReadLine();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    public class GettingInput
    {
        public int GetInput()
        {
            Console.WriteLine("Please input an int:");
            while (true)
            {
                try
                {
                    int input = Convert.ToInt32(Console.ReadLine());
                    return input;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    Console.WriteLine("Please input a valid int:");
                }

            }

        }

    }
}

All feedback welcome!


texts: Extracting first name, last name, phone number, and address from a form

texts:
I have this:

public void InfoAssignment()
{
    //MessageBox.Show(firstName = firstNameBox.Text);
    firstName = firstNameBox.Text;
    lastName = lastNameBox.Text;
    phoneNumber = phoneBox.Text;
    address = addressBox.Text;

    //Check for text in firstNameBox
    if (!String.IsNullOrWhiteSpace(firstName))
    {
        firstName = firstNameBox.Text;
    }
    else
    {
        MessageBox.Show("Please enter a first name");
        return;
    }

    if (!String.IsNullOrWhiteSpace(lastName))
    {
        lastName = lastNameBox.Text;
    }
    else
    {
        MessageBox.Show("Please enter a last name");
        return;
    }

    if(!String.IsNullOrWhiteSpace(phoneNumber))
    {
        phoneNumber = phoneBox.Text;
    }
    else
    {
        MessageBox.Show("Please enter a phone number");
        return;
    }

    if (!String.IsNullOrWhiteSpace(address))
    {
        address = addressBox.Text;
    }
    else
    {
        MessageBox.Show("Please enter a phone number");
        return;
    }
    //firstName = firstNameBox.Text;
    //lastName = lastNameBox.Text;
}

It does what I need it to do but obviously this is basically repeating the same thing with only minor variations. I'm thinking there has to be a better way of which I'm unaware. Is there?


texts: Custom backend app with require.js approach

texts:
I'm working on a small custom backend app in PHP for personal use (and practice MVC) and I thought it was a nice opportunity to try (and learn) requirejs to 'organize' my scripts and load just what the page needs.

I wrote some lines just to test its functionality, and works pretty well... but I've been wondering if this is a correct approach. Keep in mind I'm completely new to it.

Step by step, this is what I've done so far...

main.js: just basic settings

requirejs.config({
    'baseUrl': url + 'js',
    'paths': {
        'custom': 'custom/back',
        'jquery': 'libs/jquery-2.1.3.min',
        'jquery-ui': 'libs/jquery-ui.min'
    }
});

require(['custom/app'], function(app) {
    app.start();
});

app.js: the app 'starts' and checks if there're forms in the page. If so, it requires form related scripts

define(['jquery'], function() {
    var start = function(){
        //check if there're forms and if so, requires form related scripts
        if($("form").length>0){
            require(['custom/forms/forms'], function() {});
        }

        //do something else...
    };
    return {
        start: start
    };
});

forms.js: Here, I load common scripts for all forms (for example, inline validation) and specific scripts for certain fields...

define([], function() {
    //it requires a script that contains regex and validation stuff
    require(['custom/forms/validations'], function() {validations});
    //if there's a 'special input' field (just an example) it requires some script to bind stuff
    if($(".special-input").length>0){
        require(['custom/forms/special-input'], function(specialInput) {
            specialInput.bind();
        });
    }
});

special-input.js: This file bind actions for those 'special' fields and loads jquery UI to use, in this case, the draggable features... I also wrote some internal methods that doesn't export

define(['jquery-ui'], function() {
    var inputs= $(".special-input");
    //bind function: binds interactive elements
    var bind = function(){
        inputs.draggable();
        someFunctionOne(input);
    };

    var someFunctionOne= function(elem){
        //do something...
    };

    var someFunctionTwo= function(elem){
        //do something...
    };

    return {
        bind: bind
    };
});

This works OK so far, but is this approach (module separation) a good idea? I can see this helps to keep my js scripts small and well organized, but maybe I'm missing something, or not taking full advantage of requirejs' features.


texts: An overloaded random number function template using modern C++

texts:
I don't mess around a lot with templates (or with GTK), but today I wrote something and would like to know how it can be improved, and hopefully clarify a few things in the process.

So, Randolfi() is a function template which returns a random number. A range can be specified as arguments.

It uses features new to C++11, based on these:

How to generate a random number in C++?
Random number generation in C++11 , how to generate , how do they work?

(The name "Randolfi" is a joke made by a few colleagues regarding my last name, Ranolfi.)

randolfi.hpp

#ifndef RANDOLFI_HPP
#define RANDOLFI_HPP

#include <random>

template <typename T>
T Randolfi()
{
    std::mt19937 rng;
    rng.seed( std::random_device()() );
    std::uniform_int_distribution<T> dist;
    return dist(rng);
}

template <typename T>
T Randolfi(T range_start, T range_end)
{
    std::mt19937 rng;
    rng.seed( std::random_device()() );
    std::uniform_int_distribution<T> dist(range_start, range_end);
    return dist(rng);
}

#endif //RANDOLFI_HPP

randolfi-test.cpp

#include <iostream>
#include <string>
#include <gtkmm.h>
#include "randolfi.hpp"

using namespace std;

int main()
{
    auto app = Gtk::Application::create();

    uint a_random_number = Randolfi<uint>();

    Gtk::MessageDialog dialog( to_string(a_random_number) );
    dialog.run();

    return 0;
}

Notes:

Somehow it doesn't feel right to have such a large proportion of redundant lines across the function overloads. I think there might be a template-related trick to help here, but searching for it proved useless since all the results I found (like this one) are concerned about type parameter overloading, which is not my case.
I though about declaring it as Randolfi(T range_start = NULL, T range_end = NULL) and then checking if (range_start != NULL && range_end != NULL), but that does not save me any lines, and also appears to be frowned upon.
As it is, the function can be called without type argument for the second overload, but not for the first one:

Randolfi(0, 100);  // type parameter ommited for template
Randolfi();  // Fails - compiler has no clue on know how to instantiate template

I have a feeling this inconsistency is bad practice.
I'm mostly concerned about the template header, but I did include my testing code (randolfi-test.cpp) to this question so maybe someone can let me know if I did something terribly wrong. From my part, I'd like to avoid calling Gtk::Application::create() but that doesn't seem to be possible.

Thanks!


texts: Looping through table rows and replacing key terms in a word template

texts:
Here is my code for a sub which does the following:

read header of a table into an array
reads first row of said table into a 2nd array
loops through the first array and replaces the marked keywords <keyword> in a word template file (.dotx) with the data row cell (includes header and body)

This sub is then called by another sub specifying both table rows and the template file.

Now since I am not a programmer by profession I am pretty sure that this is far from the best way to do it efficiently, so any comments or improvements are much appreciated.

Sub ReplacefromRange(header As Range, DataRow As Range, TemplateFile)

    Dim heading() As String
    Dim data() As String
    Dim i As Integer
    Dim x As Variant

    ' Creates a first array that takes "header" as argument
    i = -1
    For Each x In header.Cells
        i = i + 1
        ReDim Preserve heading(i) As String
        heading(i) = x.Value
    Next x

    ' Creates second array that takes "DataRow" as argument
    i = -1
    For Each x In DataRow.Cells
        i = i + 1
        ReDim Preserve data(i) As String
        data(i) = x.Value
    Next x

    ' Uses a for each loop through heading() to find and replace individual entries in the "TemplateFile" argument

    i = 0
    For Each x In heading()
        With TemplateFile                        'looks at the word document body
            .Application.Selection.Find.Text = "<" & heading(i) & ">"
            .Application.Selection.Find.Execute
            .Application.Selection = data(i)
            .Application.Selection.EndOf
            ' the part below looks at the header content
            .Sections(1).headers(wdHeaderFooterPrimary).Range.Find.Execute _
        FindText:="<" & heading(i) & ">", Format:=False, ReplaceWith:=data(i), Replace:=wdReplaceAll, Wrap:=wdFindContinue
            i = i + 1
        End With
    Next x

End Sub


texts:
I have a function that extracts basic parts-of-speech words (NN,NNP,JJ,VBS etc.) from about 2000 sentences. I want to understand if there is a way to optimize so I can bring down the execution time (from about 12 secs right now to single digits) if possible.

import re, nltk, html

def extract_entities(text_list):

    entities=set()

    for sentence in text_list:
        try:

            tokens = nltk.word_tokenize(sentence)
            tagged = nltk.pos_tag(tokens)
            [entities.add(word.lower()) for word,pos in tagged
                 if pos in ['NN','NNP','NNS','NNPS','JJ','VBS','VBN','VBG','VBD']]

        except Exception as e:
            print('stage 1',e)

    return entities


texts:
I lately spend a lot of time at Project Euler programming challenges. I have following problem which I should solve:

  Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the Fibonacci sequence whose values do not
  exceed four million, find the sum of the even-valued terms.

I wrote Java code and I submitted it.

Implementation

First, I wrote helper method fibonacci(int n) which calculates a n-th word of fibonacci sequence and returns it. In main method I created a list of numbers and a n variable, that would be incremented in a loop. In the loop I was looking for all numbers that are even-valued that are added to the list. Next, I created result variable and I sum all numbers in the list and then, finally I printed it out to console.

Main.java:

package pl.hubot.projecteuler.problem2;

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

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        int n = 0;
        while (fibonacci(n) < 4_000_000) {
            if (fibonacci(n) % 2 == 0) numbers.add(fibonacci(n));
            n++;
        }
        int result = 0;
        for (Integer number : numbers) {
            result += number;
        }
        System.out.print(result);
    }

    private static int fibonacci(int n) {
        if (n == 0) return 0;
        else if (n == 1) return 1;
        else return fibonacci(n - 1) + fibonacci(n - 2);
    }
}


texts: Add values to a multidimensional array of unknown depth

texts:
I have the following class:

class MultiArray
{
    private $array = array();

    public function add()
    {
        $keys = func_get_args();
        $value = array_pop($keys);

        $array =& $this->array;
        foreach ($keys as $key) {
            if (!isset($array[$key])) {
                $array[$key] = array();
            }
            $array =& $array[$key];
        }
        if (!in_array($value, $array)) {
            $array[] = $value;
        }
    }

    public function getData()
    {
        return $this->array;
    }
}

Here's an example on how to use it:

$words = new MultiArray();
$words->add('A');
$words->add('A', 'airplane');
$words->add('C', 'car', 'Nissan');
$words->add('R', 'road', '16th avenue', 'Richmond');

print_r($words);

This will output:

Array
(
    [0] => A
    [A] => Array
        (
            [0] => airplane
        )

[C] => Array
    (
        [car] => Array
            (
                [0] => Nissan
            )
    )
[R] => Array
    (
        [road] => Array
            (
                [16th avenue] => Array
                    (
                        [0] => Richmond
                    )
            )
    )
)

It does the job but I feel like this is bad code. Is there a way to improve this code?


texts: discord.js/node : filter().map() best method

texts:
I'm learning javascript with discord.js and node and I'm always looking for the "best" code.

Is this the "best code" for my map() ? ([role] required, (role) optional)

// Get [role] (@role) args
let roles = msg.mentions.roles.filter(role => (args[2] === `<@&${role.id}>` || args[3] === `<@&${role.id}>`)).map(role => {
  nbArgs++;
  return role.id;
});

// Get text
let txtContent = msg.content.split(/ +/g).splice(nbArgs).join(' ');


texts: Listing YouTube videos using API with RxJava

texts:
I am new to RxJava and have the following code which I use to search YouTube videos via the API and ultimately display them in a list.

private fun showYouTubeSearchView() {
    val youtubeSearchView = viewFactory.getYouTubeSearchView(null)
    val contentView = youtubeSearchView.rootView

    youtubeSearchView.subscribeSearchEvent()
        .subscribeOn(Schedulers.io())
        .observeOn(Schedulers.io())
        .switchMap { searchTerm ->
            searchYouTubeUseCase.searchYouTube(searchTerm)
                .flatMapIterable { youTubeSearchResults ->
                    youTubeSearchResults.items
                }
                .flatMap { item ->
                    getVideoStatisticsUseCase.getViewCount(item.id.videoId)
                        .flatMap { viewCount ->
                            Observable.just(
                                YouTubeListItemModel(
                                    item,
                                    viewCount
                                )
                            )
                        }
                }
                .toList()
                .toObservable()
        }
        .observeOn(AndroidSchedulers.mainThread())
        .flatMap { youTubeListItemModels ->
            youtubeSearchView.showSearchItems(youTubeListItemModels)
            youtubeSearchView.subscribeItemClicked()
        }
        .subscribe(
            { youTubeListItemModel ->
                showCreateVideoClipView(youTubeListItemModel)
            },
            { t ->
                Snackbar.make(contentView, "Error", Snackbar.LENGTH_LONG).show()
                Log.e(TAG, "error", t)
            }
        )

    setContentView(contentView)
}

You will notice a second API call is required to get the view count for each item in the list.

I hope the code is relatively understandable as-is. I feel as though the doubly nested switchMap/flatMap/flatMap is probably indicative of poor design. Is there a better way of accomplishing the same thing?


texts:
I know this question has been asked before now but in Python. Recently, I set out to write an anagram in C#. For instance, orchestra can be rearranged into carthorse and the anagram should not have more repeated than the original. The function is meant to check if the two words are the same and return true in this case. I started with putting the two words in two separate dictionaries with the letters as a key and the count as value.

The idea is using a dictionary ensures the keys can not be repeated. Then I looped through the second dictionary (secondString) and checked if each letter existed as a key in the first dictionary (firstString). Additionally, if the letter existed, the code checks if they have the same count. The rest of the code is self-explanatory.

using System;
using System.Collections.Generic;

public class AreAnagrams
{
    public static bool AreStringsAnagrams(string a, string b)
    {
        Dictionary<char,int> firstString = new Dictionary<char,int>();
        Dictionary<char,int> secondString = new Dictionary<char,int>();

        foreach(char character in a)
        {
            if(firstString.ContainsKey(character)== true)
            {
                firstString[character]+=1;
            }
            else
                firstString[character]=1;
        }
        foreach(char character2 in b)
        {
            if(secondString.ContainsKey(character2)== true)
            {
                secondString[character2]+=1;
            }
            else
                secondString[character2]=1;
        }

        foreach(KeyValuePair<char,int> letterValue in secondString)
        {
            if(firstString.ContainsKey(letterValue.Key))
            {
                if(firstString[letterValue.Key] != secondString[letterValue.Key]){

                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        //throw new NotImplementedException("Waiting to be implemented.");
        return  true;
    }

    public static void Main(string[] args)
    {
        Console.WriteLine(AreStringsAnagrams("momdad", "dadmom"));
    }
}

But I scored 75% and I feel this can be improved on. Also, is there any easy conversion from string to dictionary?


texts: Finding number of times each string in an Array of strings occurs in a large stream of characters (i.e large string)

texts:
Interview problem:

  Given a stream of characters (e.g. acacabcatghhellomvnsdb) and a list of words (e.g. ["aca","cat","hello","world"] ) find and display count of each and every word once the stream ends.(Like : "aca" : 2 , "cat" : 1 , "hello" : 1 , "world" : 0 ).

This solution works functionally.  Please let me know if there is a faster more optimized algorithm or if there are some corner scenarios I did not take care of.

#define VALUE_KEY 1
#define COUNT_KEY 2

NSMutableArray *stringsToSearchFor = [@[[@{@VALUE_KEY: @"cat", @COUNT_KEY: @0} mutableCopy],[@{@VALUE_KEY: @"aca", @COUNT_KEY: @0} mutableCopy], [@{@VALUE_KEY: @"hello", @COUNT_KEY: @0} mutableCopy],[@{@VALUE_KEY: @"world", @COUNT_KEY: @0} mutableCopy]] mutableCopy];

NSString *stringStream = @"acacabcatghhellomvnsdb" ;

    for(NSMutableDictionary *nextDict in stringsToSearchFor)
    {
        NSUInteger currRangeStart = 0 ;
        NSUInteger currRangeLength = [nextDict[@VALUE_KEY] length] ;
         NSUInteger currentStringNumFound = 0 ;

        while(currRangeStart <= [stringStream length]-currRangeLength)
        {
            NSRange foundRange = [stringStream rangeOfString:nextDict[@VALUE_KEY]
                                                     options:0
                                                       range:NSMakeRange(currRangeStart, [stringStream length]-currRangeStart)] ;
            if(foundRange.location != NSNotFound)
            {
                 currRangeStart = foundRange.location+1 ;
                 currentStringNumFound++;
            }
            else
            {
                break ;
            }
        }

        if(currentStringNumFound)
        {
            nextDict[@COUNT_KEY] = @(currentStringNumFound) ;
        }
    }

    NSLog(@"Num occurrences dict is %@",stringsToSearchFor) ;


texts: Unit test for a function that adds users

texts:
I'm new to unit testing and I'm curious if anyone can see any problems with my approach below.  Basically I want to test the Add function.  To do this I am creating a new Account object, passing that to the Add function, retrieving that account and finally comparing the retrieved objects values to hard coded values.

I'm wondering if anyone can see any thing that would not be considered best practice for unit tests?  Specifically, should I be using the testUser object in my asserts rather than the hard coded values?  Anything else I should consider?

[TestMethod]
public void TestAddUser()
{
    AccountAccess accountActions = new AccountAccess();
    Account testUser = new Account("abe",1000m);
    accountActions.Add(testUser);
    Account retrievedUser = accountActions.GetAccount("abe");
    Assert.AreEqual("abe", retrievedUser.name, "Added user does not have corret name: 'abe' - '" + retrievedUser.name + "'");
    Assert.AreEqual(1000m, retrievedUser.limit, "Added user does not have corret limit: '1000' - '" + retrievedUser.limit + "'");
}


texts:
In my project I need to do an automatic sliding vertical slider:

var number = 0;
var count = $(".home-header-boxes .col-6").children().length;
window.setInterval(
    function() {
        number = number + 104; // 104px div height
        $(".home-header-boxes .col-6 .home-header-boxes-profile-wrapper").each(function(i) {
            $(this).css({
                "transform": "translateY(-" + number + "px)",
            })
        })

        if (number == count * 104) {
            number = 0;
            $(".home-header-boxes .col-6 .home-header-boxes-profile-wrapper").each(function() {
                $(this).css({
                    "transform": "translateY(0px)",
                })
            })
        }
    }, 3000);

I wonder if there is a simpler way to do this vertical slider, because sometimes the transformY is not going up fluently. It is disappearing and showing.

Example jsfiddle


texts: Day elapsed since today from a given date

texts:
My function calculates days elapsed from the current date.  Input is fixed.  I will get vector.

Please comment on this.

static bool daysElapsed(const std::vector<char>& vec,int& val)
{
    std::string str(vec.begin(),vec.end());
    char *pos;// whose value is set by the function to the next character in str after the numerical value.
    int l = strtol(str.c_str(),&pos,10); // Its intention we don’t check till which length strtol converted
    if ((errno == ERANGE && l == LONG_MAX) || l > INT_MAX)      return false;
    if ((errno == ERANGE && l == LONG_MIN) || l < INT_MIN)      return false;

    int year = l/10000;
    int month = (l%10000)/100;
    int date = l%100;

    struct std::tm a = {0,0,0,date,
        month-1,   //Month (0 – 11; January = 0).
        year-1900  //Year (current year minus 1900).
    };
    struct std::tm b;

    time_t rawtime;
    time (&rawtime);                // Get the current calendar time UTC !-> Do not rely on this time, Convert to local time first
    localtime_s (&b,&rawtime);
    time_t x = std::mktime(&a);
    time_t y = std::mktime(&b);
    if ( x != (std::time_t)(-1) && y != (std::time_t)(-1) ) // Ensure both time are valid
    {
        double difference = std::difftime(y, x) / (60 * 60 * 24);
        std::cout << "difference = " << difference << " days" << std::endl;
    }
    else
        return false;

    return true;

}


texts:
Motivation: I have a large number of large read-only dicts with large string keys mapped to tuples of two floats. They are taking up a large amount of heap space.

Proposed solution: a 3xn NumPy array, with the first column being the hash value of the key, and sorted by that column. Only contains and getitem ops are required for my needs.

I realize that this solution is \$O(log(n))\$ rather than \$O(c)\$ but I assume that this isn't that big a problem for my application as there aren't that many lookups per request and my primary problem is memory constraints.

I'm not sure how well searchsorted performs here though, or if I should try to change the stride somehow so that the first column is contiguous or something like that. I should also probably be using a record array.

import numpy

class FCD(object):

  def __init__(self, d):
    data = []
    for key, value in d.iteritems():
      data.append((hash(key), value[0], value[1]))
    data.sort()
    self.data = numpy.array(data)

  def __getitem__(self, key):
    hkey = hash(key)
    ix = numpy.searchsorted(self.data[:, 0], hkey)
    if ix < len(self.data) and self.data[ix][0] == hkey:
      return self.data[ix][1:]
    else:
      raise KeyError

  def __contains__(self, key):
    hkey = hash(key)
    ix = numpy.searchsorted(self.data[:, 0], hkey)
    return ix < len(self.data) and self.data[ix][0] == hkey


texts: Is there a better way of defining generic entity classes?

texts:
I have some entities in use in my project, and to make things easier, I would like to have the type of the key for that entity defined via a generic. E.g.:

public abstract class Entity<T>
{
    public virtual T Id { get; set; }
}

This way, I can pull the Id field into the base entity and not have to define it every time (There's a few other fields on Entity in the real system, so there is other utility to doing this)

Then, since I'm using Fluent NHibernate, I make a generic mapping class to go along with this generic entity:

internal abstract class EntityMapping<T,TK> : ClassMap<T> where T : Entity<TK>
{
    protected EntityMapping()
    {
        Id(m => m.Id);
    }
}

And starting here is when I wonder if there's a better way of handling this. C# doesn't seem to infer the TK type parameter from the Entity definition, and having to add to all of my mapping classes the key parameter for the entity they map seems redundant, all the more so since it also extends to some of the higher  generic data access classes, e.g.:

public abstract class EntityRepository<T,TK> where T : Entity<TK> { }

Is there a tidier way of handling this, or is this what I have to do if I want to have the key type of my entities passed in?


texts:
I am new to JavaScript programming and would like to get your comments/input or corrections on this chunk of code. I have tried to emulate patterns from recognized GitHub projects but I still don't have good feel for what "good" NodeJS code looks like.

I have written a very simple HTTP routing framework that works differently than ones currently available (it's a personal project / learning experience).

GitHub

var req, meth, url;
/**
 * Fork -> Synchronous process
 * @param  {Function} callback
 */
var _sync = function(callback) {
    _assembleTask(null, workFlow[meth][url].sync, function(err, tasks) {
        if (err) return callback(true, 'Invalide Workflow : ' + tasks);
        async.series(tasks, function(err, results) {
            return callback(err, results);
        });
    });
};

/**
 * Fork -> Parallel process
 * @param  {Function} callback
 */
var _async = function(callback) {
    _assembleTask(null, workFlow[meth][url].async, function(err, tasks) {
        if (err) return callback(true, 'Invalide Workflow : ' + task);
        async.parallel(tasks, function(err, results) {
            return callback(err, results);
        });

    });
};

/**
 * Merg - Parallel process
 * @param  {Object}   data - return values of sync and async
 * @param  {Function} callback
 */
var _merg = function(data, callback) {
    _assembleTask(data, workFlow[meth][url].merg, function(err, tasks) {
        if (err) return callback(true, 'Invalide Workflow : ' + tasks);
        async.series(tasks, function(err, results) {

            return callback(err, {
                'sync': data.sync,
                'async': data.async,
                'merg': results
            });
        });
    });
};

/**
 * URL Matcher
 * @param {String}   needle - incoming url
 * @param {Object}   haystack - JSON object for
 * @param {Function} callback
 */
var _urlMatch = function(needle, haystack, callback) {
    var match = null;
    for (var i in haystack) {
        if (urlglob(i, req.url)) {
            match = i;
            break;
        }
    }
    return callback(match);
};

/**
 * Assemble tasks
 * @param {data}     data - data to be passed into instantiated object
 * @param {taskList} taskList - list of tasks to instantiate
 * @param {Function} callback
 */
var _assembleTask = function(data, taskList, callback) {
    var tasks = {};
    var err = false;
    for (var key in taskList) {
        var module = taskList[key].split('.');
        if (!procsObj[module[0]]) return callback(true, module);
        var procsInst = new procsObj[module[0]](req, data);
        if (!procsInst[module[1]]) return callback(true, module);
        tasks[module[0] + '_' + module[1]] = procsInst[module[1]];
    }
    return callback(err, tasks);
};

/**
 * Main Method
 * @param  {Object}   request - request object passed from HTTP
 * @param  {Function} callback
 */
this.run = function(request, callback) {
    req = request;
    if (!(req.method in workFlow) && !('*' in workFlow)) {
        callback(405, 'Method Not Allowed');
    } else {
        meth = (req.method in workFlow) ? req.method : '*';
        _urlMatch(req.url, workFlow[meth], function(match) {
            if (match === null) {
                callback(404, 'Not Found');
            } else {
                var a = {};
                url = match;
                typeof workFlow[meth][url].sync != 'undefined' && (a.sync = _sync);
                typeof workFlow[meth][url].async != 'undefined' && (a.async = _async);
                async.parallel(a, function(err, results) {

                    typeof workFlow[meth][url].merg != 'undefined' && _merg(results, callback);
                    typeof workFlow[meth][url].merg == 'undefined' && callback(err, results);

                });
            }
        });
    }
};
};


texts: Converting an integer to a 3 character String (base62)

texts:
I wrote a code to convert an Integer between 1 and 238328 to a unique String, formed from base62 characters (A-Za-z0-9) and of length 3. The String generated can be reconverted to get back the initial Integer.

For example, if the number was 238328 I can convert it to "zzz". I want to be able to use that String "zzz" and get back the number 238328. I have written 2 methods to perform these operations and based on my testing it is working fine.

I am looking for some inputs on making it more readable and possibly more efficient. The conversion consists of 3 nested loops which really does not look right, though I can't get my head around a better way to do this.

class Permutation {

    private final String[] DICTIONARY = new String[]{
            "0","1","2","3","4","5","6","7","8","9",
            "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
            "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

    private Map<String, Integer> codes = new HashMap<>();
    private Map<Integer, String> numbers = new HashMap<>();

    String generateCode(int num){

        int maxNumber = 238328;
        if(num > maxNumber || num < 1) return null;

        if(numbers.containsKey(num)){
            return numbers.get(num);
        }

        int counter = 0;

        for (int i = 0; i < DICTIONARY.length; i++) {
            for (int j = 0; j < DICTIONARY.length; j++) {
                for (int k = 0; k < DICTIONARY.length; k++) {
                    String code = DICTIONARY[i] + DICTIONARY[j] + DICTIONARY[k];
                    counter++;
                    numbers.put(counter, code);
                    codes.put(code, counter);
                    if(counter == num) return code;
                }
            }
        }

        return null;
    }

    int decode(String code){
        if(codes.containsKey(code)){
            return codes.get(code);
        }

        return 0;
    }
}


texts: Check if two nodes are cousins in a Binary Tree

texts:
Given the binary Tree and the two nodes say ‘a’ and ‘b’, determine whether the two nodes are cousins of each other or not.

Two nodes are cousins of each other if they are at same level and have different parents.

Looking for code review, optimizations and best practices.

public final class CheckCousins {

    private TreeNode root;

    public CheckCousins(List<Integer> items) {
        create(items);
    }

    private void create (List<Integer> items) {
         if (items.size() == 0) {
            throw new IllegalArgumentException("There should atlease be single item in the tree");
        }
        root = new TreeNode(items.get(0));

        final Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        final int half = items.size() / 2;

        for (int i = 0; i < half; i++) {
            if (items.get(i) != null) {
                final TreeNode current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (items.get(left) != null) {
                    current.left = new TreeNode(items.get(left));
                    queue.add(current.left);
                }
                if (right < items.size() && items.get(right) != null) {
                    current.right = new TreeNode(items.get(right));
                    queue.add(current.right);
                }
            }
        }
    }

    private static class TreeNode {
        private TreeNode left;
        private int item;
        private TreeNode right;

        TreeNode(int item) {
            this.item = item;
        }
    }

    public boolean isCousin(int x, int y) {
        List<NodeData> nodeDatas = new ArrayList<>();
        isCousins(null, root, x, y, 0, nodeDatas);
        if (nodeDatas.size() < 2) return false;
        NodeData nd1 = nodeDatas.get(0);
        NodeData nd2 = nodeDatas.get(1);

        return nd1.depth == nd2.depth && nd1.parent != nd2.parent;
    }

    private static class NodeData {
        private TreeNode parent;
        private int depth;

        public NodeData(TreeNode parent, int depth) {
            this.parent = parent;
            this.depth = depth;
        }
    }

    private void isCousins(TreeNode parent, TreeNode node, int x, int y, int level, List<NodeData> nodeDatas) {
        if (nodeDatas.size() == 2) return;

        if (node == null) {
            return;
        }
        if (node.item == x || node.item == y) {
            nodeDatas.add(new NodeData(parent, level));
            return;
        }

        isCousins(node, node.left,  x, y, level + 1, nodeDatas);
        isCousins(node, node.right, x, y, level + 1, nodeDatas);
    }
}

public class CheckCousinsTest {

    @Test
    public void testIncompleteTree() {
        CheckCousins cs1 = new CheckCousins(Arrays.asList(1, 2, 3, 4, null, null, 7));
        assertTrue(cs1.isCousin(4, 7));
    }

    @Test
    public void testCompleteBinaryTreeSuccess() {
        CheckCousins cs2 = new CheckCousins(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
        assertTrue(cs2.isCousin(4, 7));
        assertTrue(cs2.isCousin(4, 6));
        assertTrue(cs2.isCousin(5, 6));
        assertTrue(cs2.isCousin(5, 7));
    }

    @Test
    public void testCompleteBinaryTreeFailure() {
        CheckCousins cs2 = new CheckCousins(Arrays.asList(1, 2, 3, 4, 5, 6, 7));
        assertFalse(cs2.isCousin(4, 4));
        assertFalse(cs2.isCousin(4, 5));
        assertFalse(cs2.isCousin(6, 7));
        assertFalse(cs2.isCousin(2, 3));
        assertFalse(cs2.isCousin(2, 1));
    }

}


texts: Java class that generates a short URL string for an input string

texts:
Help me find out if the approach I took to generate random strings here is correct to be able to return the appropriate short URLs.

      import java.util.HashMap;
      import java.util.Map;
      import java.util.Map.Entry;
      import java.util.Random;
        /**
         *
         * Given a input string create a random
         * string
         *
         * @author
         * @creation Mar 23, 2015
         *
         */
        public class URLTinyMe {

    /*Map stores 1:1 mapping of input url and tinyurl*/
    private Map<String,String> urlMap = new HashMap<String,String>();

    private static URLTinyMe urlTinyMeObj = null;

    /**
     * return static instance of URLTinyMe
     * @return
     */
    public static URLTinyMe getInstance(){
      if(null == urlTinyMeObj){
        synchronized (URLTinyMe.class){
          if(null == urlTinyMeObj){
            urlTinyMeObj =  new URLTinyMe();

          }
      }
      }
      return urlTinyMeObj;
    }

    /*
     * Private constructor, restrict instance creation
     */
    private URLTinyMe() {

    }

    /**
     * TinyMefy a URL
     * @return String
     */
    public String getTinyMeUrl(String inputUrl){

        String tinyUrl = inputUrl;

        if(urlMap.containsKey(inputUrl)){//Check if url already exists
            tinyUrl =  urlMap.get(inputUrl);
        }else{
            StringBuilder charList = new StringBuilder();
            do{
                int random = getRandonNumber(48,122);//Accept only characters and numericals A-Z,0-9,a-z
                charList.append((char)random);
            }while(urlMap.containsValue(charList.toString()));

            urlMap.put(inputUrl, charList.toString());
            tinyUrl =  charList.toString();
        }
        return tinyUrl;
    }

    /**
     * From the tinyUrl return the original input url
     * @param tinyUrl
     * @return
     */
    public String getOriginalUrl(String tinyUrl){
      String inputUrl = null;
      if(urlMap.containsValue(tinyUrl)){
       for(Entry<String,String> entry:urlMap.entrySet()){
         if(entry.getValue().equals(tinyUrl)){
           inputUrl = entry.getKey();
         }
       }
      }
      return inputUrl;
    }
    /*
     * Return random number for the limit
     * */
    private int getRandonNumber(int lowLimit, int highLimit){
        int random = 0;
        Random randomObj = new Random();
        do{
            random = randomObj.nextInt(highLimit);

        }while(!(random >= lowLimit && random <= highLimit) ||
                (random > 57 && random < 65) ||
                (random > 90 && random <97));

        return random;
    }

}


texts:
This is sort of a follow up to a previous question (Do I have any SQL leaks?).

I have changed some things around and am working on a solution where I use Active Directory to gather information about the user rather than use the user table from the application that is run on these App Servers (the thing I am trying to keep track of).

I think that this method might be better utilized if it were written differently:

public bool isValid(string url)
{
    HttpWebRequest urlReq;
    HttpWebResponse urlRes;
    try
    {
        urlReq = (HttpWebRequest)WebRequest.Create(url);
        urlReq.Method = "HEAD";
        urlReq.Timeout = 200000;
        urlRes = (HttpWebResponse)urlReq.GetResponse();
        urlRes.Close();
        return true;
    }
    catch (Exception ex)
    {
        //Url not valid
        strErrorMSG = "Exception From isValid Method. Exception to follow: " + ex.ToString();
        return false;
    }
}

And this is how I am currently using it:

if (isValid(strInput))
{
    try
    {
        XmlReader xmlReader = XmlReader.Create(strInput);
        using (xmlReader)
        {
            while (xmlReader.Read())
            {
                if (xmlReader.NodeType == XmlNodeType.Text)
                {
                    strServer = xmlReader.Value.ToString();
                    strServer = strServer.Replace("\r", "");
                    strServer = strServer.Replace("\n", "");
                    strServer = strServer.Replace(" ", "");
                }
            }
            xmlReader.Close();
        }
    }
    catch (Exception e)
    {
        strServer = "Error";
        strErrorMSG = "Error with the xmlReader Exception as follows: " + e.ToString();
    }
}
else
{
    strServer = "XML-Missing";
}

I take this information and then I store it in an SQL table where I pull the information from it to populate a data grid on a website so I can see how many users are on each app server (using the App Server indirectly by running the application).

The variables strServer and strErrorMSG (are horrible names I know, I may refactor that as well while I am working on the version) get inserted into an SQL table so that I can see that there is an error with the Windows Service and have an error message that I can grab.

One of the things on my to-do list is to add a function that will email me with errors should the SQL Server not be accessible from the client machine.

I only use 1 SQL table at the moment for all the information that is gathered with this Windows service, another reason why I am working on the e-mail functionality.

Note: This is code from a Windows service that runs on almost 1000 computers.

How does my boolean method look, and can I tweak this somehow to make it work with the XmlReader more efficiently (or even at all)?

I created this Windows service to track which AppServer a user's application is connected to via a load balancer.

I install an XML on each AppServer with their own unique "server" node(which is pretty much the only thing there), the windows service needs to query that XML and return the value in that node giving it the server that the application is connected to. After that the Windows service sends the information to a SQL table so that it can be viewed via a website.

The reason for the weird logging is because this service is running on somewhere around 1000 computers in the state, and I am already sending information to the SQL Table, where the information is being displayed on the website(what we monitor frequently) so this is the fastest way at the moment for seeing the error messages.  I am looking into a way where I can have the exceptions E-mailed to me instead of only sending to the Table so that I don't have to stare at the site all the time.

I agree that I don't like the isValid method and that it creates an extra request.  What I am looking for is a way to merge it with the XmlReader and some of you have given me really good ideas how to accomplish this and I appreciate it greatly.


texts: Concurrent LRU cache using sychronizedMap() or ReadWriteLock

texts:
Trying to implement a simple, thread-safe LRU cache that's meant for "read mostly" use.

Collections.sychronizedMap()

Clean, simple, not much else to say.

public class LRUConcurrentCache<K,V> {
   private final Map<K,V> cache;
   private final int maxEntries;

   public LRUConcurrentCache(
         int maxEntries
   ){
      this.maxEntries = maxEntries;
      this.cache = Collections.synchronizedMap(
         new LinkedHashMap<K,V>(this.maxEntries, 0.75F, true){
               private static final long serialVersionUID = -1236481390177598762L;
               @Override
               protected boolean removeEldestEntry(Map.Entry<K,V> eldest){
                  return size() > maxEntries;
               }
            });
   }
   public void put(K key, V value){
      cache.put(key, value);
   }
   public V get(K key){
      return cache.get(key);
   }

ReadWriteLock

Seems like overkill, and frankly, I believe get() should use writeLock(), not readLock() since LinkedHashMap.get() records access by manipulating entries.

public class LRUConcurrentCache<K,V> {
   private final Map<K,V> cache;
   private final int maxEntries;
   private final ReadWriteLock readWriteLock;
   private final Lock readLock;
   private final Lock writeLock;

   public LRUConcurrentCache(
         int maxEntries
   ){
      this.maxEntries = maxEntries;
      this.cache =
         new LinkedHashMap<K,V>(this.maxEntries, 0.75F, true){
               @Override
               protected boolean removeEldestEntry(Map.Entry<K,V> eldest){
                  return size() > maxEntries;
               }
            };
      this.readWriteLock = new ReentrantReadWriteLock(true);
      this.readLock = readWriteLock.readLock();
      this.writeLock = readWriteLock.writeLock();
   }
   public void put(K key, V value){
      writeLock.lock();
      try{
         cache.put(key, value);
      }finally{
         writeLock.unlock();
      }
   }
   public V get(K key){
      //should use writeLock.lock()
      readLock.lock();
      try{
         return cache.get(key);
      }finally{
         //should be writeLock()
         readLock.unlock();
      }
   }

Thoughts?


texts:
Challenged by Sandy Metz's newsletter, I've tried to implement this kata from exercism. However, my solution, which passes the tests, is quite a lot simpler than Sandy's solution. Ok, so she's using refinements and also supports the inverse, but still... As she's probably smarter than me, do I miss something?

class Fixnum
  ROMAN = {
    1000 => "M",
    900 => "CM",
    500 => "D",
    400 => "CD",
    100 => "C",
    90 => "XC",
    50 => "L",
    40 => "XL",
    10 => "X",
    9 => "IX",
    5 => "V",
    4 => "IV",
    1 => "I"
  }

  def to_roman
    result = ""
    ROMAN.reduce(self) { |number, (divider, letter)|
      letter_multiplier, remainder = number.divmod(divider)
      result << (letter * letter_multiplier)
      remainder
    }
    result
  end
end


texts: Making an accordion from a multi-level HTML list

texts:
I am writing some code to turn a multi level UL into an accordion:

$(document).ready(function () {

$('.s4-ql li ul').each(function (index) {
    $(this).hide();
});

$('.s4-ql ul li ul').each(function (index) {
    var length = 0;
    length = $(this).children().length;
    var CurrentItem = $(this).parent().find('a:first');
    CurrentItem.find('.menu-item-text').append('(' + length + ')');
});
$('.s4-ql ul li').hover(
  function () {
      $(this).find('a:first').next().slideToggle('normal');
  },
  function () {
      $(this).find('a:first').next().slideToggle('normal');
  }
);
});

Can anyone tell me whether I am being relatively efficient or whether there is anywhere that I can "trim the fat", so to speak? The code also counts the number of children and displays that number on the main parent.


texts: Public function that traverses through a tree

texts:
So I have this function that lets one traverse through a tree without having to get the root node of the tree. The user basically sends a parameter that is either Movement.LEFT or Movement.RIGHT that specifies where to move to. It then returns the current node it is on. If the current node is a leaf, the tree traversal starts back in the root.

public HuffmanNode traverseNode(Movement direction)
{
    currentNode = (currentNode.isALeaf()) ? root : currentNode;
    currentNode = (direction == Movement.LEFT) ? currentNode.getLeftChild() : currentNode.getRightChild();
    HuffmanNode retrievedNode = currentNode;

    if (currentNode == null) currentNode = root;

    return retrievedNode;
}

Here's the code for the Huffman node.

package app.utils.ds;

public class HuffmanNode
{
    private HuffmanNode leftChild;
    private HuffmanNode rightChild;
    private HuffmanNode parent;
    private int colorValue;
    private int frequency;

    public HuffmanNode(int colorValue, int frequency)
    {
        this.colorValue = colorValue;
        this.frequency = frequency;
    }

    public void setParent(HuffmanNode parent)
    {
        this.parent = parent;
    }

    public void setLeftChild(HuffmanNode child)
    {
        leftChild = child;
        if (leftChild != null) {
            frequency += leftChild.getFrequency();
            child.setParent(this);
        }
    }

    public void setRightChild(HuffmanNode child)
    {
        rightChild = child;
        if (rightChild != null) {
            frequency += rightChild.getFrequency();
            child.setParent(this);
        }
    }

    public HuffmanNode getParent()
    {
        return parent;
    }

    public HuffmanNode getLeftChild()
    {
        return leftChild;
    }

    public HuffmanNode getRightChild()
    {
        return rightChild;
    }

    public int getColorValue()
    {
        return colorValue;
    }

    public boolean isALeaf()
    {
        return (leftChild == null) && (rightChild == null);
    }

    public int getFrequency()
    {
        return frequency;
    }
}

The code seems fine but I have a gut feeling that this might have code smells and can still be improved. How else can I improve this?


texts: Alternative for VLOOKUP/Index-Match in VBA

texts:
I am sharing this function I wrote with the community to provide an alternative to slow VLOOKUP and/or Index-Match functions. Also, if you have any feedback/suggestions to make this better please let me know. I tested this function using a lookup of just under 160,000 rows and it returned results in 2 seconds. This surpasses the native VLOOKUP and or Index-Match by a very large margin.

Usage:

Can be used in a worksheet as an array formula (i.e. must be entered using Ctrl+Shift+Enter).
Can be used in VBA as well.

Original Post:

 Public Function FastLookUp(ByRef rngLookUpVals As Range, ByRef rngLookUpTable As Range, _
                               ByVal lngLookUpValCol As Long, ByVal lngSearchCol As Long, _
                               ByVal lngReturnCol As Long, _
                               Optional ByVal boolBinaryCompare As Boolean = True) As Variant

  Dim i As Long
  Dim dictLooUpTblData As Object
  Dim varKey As Variant
  Dim arryLookUpVals() As Variant, arryLookUpTable() As Variant, _
         arryOut() As Variant

        arryLookUpVals() = rngLookUpVals.Value2
        arryLookUpTable() = rngLookUpTable.Value2

        Set dictLooUpTblData = CreateObject("Scripting.Dictionary")
        If boolBinaryCompare Then
            dictLooUpTblData.CompareMode = vbBinaryCompare
        Else
            dictLooUpTblData.CompareMode = vbTextCompare
        End If

        'add lookup table's lookup column to
        'dictionary
        For i = LBound(arryLookUpTable, 1) To UBound(arryLookUpTable, 1)

            varKey = Trim(arryLookUpTable(i, lngSearchCol))

            If Not dictLooUpTblData.Exists(varKey) Then
                'this is called a silent add with is faster
                'than the standard dictionary.Add Key,Item
                'method
                dictLooUpTblData(varKey) = arryLookUpTable(i, lngReturnCol)
            End If

            varKey = Empty
        Next i

        i = 0: varKey = Empty

        ReDim arryOut(1 To UBound(arryLookUpVals, 1), 1 To 1)

        For i = LBound(arryLookUpVals, 1) To UBound(arryLookUpVals, 1)
            varKey = Trim(arryLookUpVals(i, lngLookUpValCol))

            'if the lookup value exists in the dictionary
            'at this index of the array, then return
            'its correspoding item
            If dictLooUpTblData.Exists(varKey) Then
                arryOut(i, 1) = dictLooUpTblData.Item(varKey)
            End If

            varKey = Empty
        Next i

    FastLookUp = arryOut

End Function

Note: You could change the parameters to arrays instead of ranges and use this function to execute lookups on arrays in memory as well. You could also use Early-Binding for another increase in speed.


texts:
This is a header file for my bezier curve utility and several of BezierCurve2D's methods return newly created arrays of Point2D objects.

Should I create (using new) and delete objects in the same scopes? Should I have these methods receive a pre-allocated space of Point2Ds?

#ifndef BEZIER_UTILITY_H
#define BEZIER_UTILITY_H

class Point2D {
public:
    double X;
    double Y;
    Point2D();
    Point2D(double X, double Y);
    void set(double X_p, double Y_p);
    void set(Point2D* point_p);
};

class BezierBase {
protected:
    int values_length;
    double* temp_space;
    int temp_space_bytes;
    double* interp (double t, double* values);
public:
    BezierBase(int values_length);
    ~BezierBase();
};

class BezierCurve2D: public BezierBase {
private:
    double* Xs;
    double* Ys;
    double calc_dist (double x1, double x2, double y1, double y2);
    Point2D* linear_raster (double* values, int max_results, double goal_dist, double tolerance);
public:
    BezierCurve2D(double* x_values, double* y_values, int values_length);
    Point2D* rasterize (int max_results, double goal_dist, double tolerance);
    Point2D* rasterizeToX (int max_results, double goal_dist, double tolerance);
    Point2D* rasterizeToY (int max_results, double goal_dist, double tolerance);
    Point2D* getT (double t);
    double measure (double segment_dist, double tolerance);
};

#endif


texts:
I have a json file which needs to be restructured.
The following is the code.

while IFS='' read -r line || [[ -n "$line" ]]; do
    COUNT=$(( $COUNT + 1 ))
    #echo "[$COUNT]"
    [ $COUNT -lt 5 ] && continue
    sj=`echo $line | jq ._source`
    index=`echo $line | jq ._index | tr -d '"'`
    itype=`echo $line | jq ._type| tr -d '"'`
    echo '{ "index" : { "_index" :"'$index'","_type":"'$itype'"}}' >> bulk_result.bulk
    echo $sj >> bulk_result.bulk
#echo "$COUNT lines processed from file $1"
done < "$1"
echo "$COUNT lines processed from file $1"

Basically, the program is reading  a json record for example,

{"_index":"index1","_type":"rm","_id":"AVPkyS9w","_score":1,"_source":{"timestamp":"2016-04-05T05:00:00","token":"8eb38d14","tag":"logs.rm","message":"CouchbaseConnectSuccess,bucket=srmobjects","logsource":"rm.log","RM_pw":"","component":"rm-01-NFR","RM_un":"","timeEpochMs":1459832400.248,"RM_bucket":"srmobjects","RM_eventName":"CouchbaseConnectSuccess"}}

and converting it to the following

{ "index" : { "_index" :"index1","_type":"rm"}}
{ "RM_eventName": "FcgiClose", "timeEpochMs": 1459832435.293, "component": "rm-04-NFR", "logsource": "rm.log", "message": "FcgiClose,requestIndex=0", "tag": "logs.rm", "timestamp": "2016-04-05T05:00:35" }

The file size is about 4Gb . The code is taking a lot of time (in hours) in processing it.  Is there an efficient way to make this faster ?


texts: Printing the month name for the month number

texts:
This program asks a user to input any number equal to or between 1-12. It then converts the number to a message that will be printed (Copy the program to see it yourself). Is there a way to make the code shorter by still using the switch statement?

This is homework, so using a switch is a requirement.

import javax.swing.JOptionPane;

public class NumOfMonth {

   public static void main(String[] args) {

    int num = Integer.parseInt (JOptionPane.showInputDialog ("Enter any number equal to or between 1-12 to display the month"));

    switch (num)
    {
    case 1:
        System.out.println ("The name of month number 1 is January");
        break;
    case 2:
        System.out.println ("The name of month number 2 is February");
        break;
    case 3:
        System.out.println ("The name of month number 3 is March");
        break;
    case 4:
        System.out.println ("The name of month number 4 is April");
        break;
    case 5:
        System.out.println ("The name of month number 5 is May");
        break;
    case 6:
        System.out.println ("The name of month number 6 is June");
        break;
    case 7:
        System.out.println ("The name of month number 7 is July");
        break;
    case 8:
        System.out.println ("The name of month number 8 is August");
        break;
    case 9:
        System.out.println ("The name of month number 9 is September");
        break;
    case 10:
        System.out.println ("The name of month number 10 is October");
        break;
    case 11:
        System.out.println ("The name of month number 11 is November");
        break;
    case 12:
        System.out.println ("The name of month number 12 is December");
        break;
        default:
            System.out.println ("You have entered an invalid number");
        }
    } // main method
}


texts: C++ smart pointers and the Service Locator (anti-?)pattern

texts:
So I'm working on a game framework and one of the things I need are access to stateful "services" that can be accessed from all over. I was initially going to use the Singleton pattern but decided to try and come up with alternatives to avoid the short comings of that pattern.

So here is what I've got so far.

Main.cpp

#include "Engine.h"
#include "Logger.h"

int main(int argc, char* argv[]) {
    Engine engine;

    // old
    {
        auto logger = new Logger();

        engine.provide(logger);
        engine.getLoggerOld().log("old TEST");

        engine.provide(nullptr);
        delete logger;
    }
    engine.getLoggerOld().log("old TEST");//wont print, just calls empty funcs
    // old

    // new
    {
        auto splogger = std::make_shared<Logger>();

        engine.provide(splogger);
        engine.getLoggerNew()->log("new TEST");
    }
    engine.getLoggerNew()->log("new TEST");//wont print, just calls empty funcs
    // new

    return 0;
}

Engine.h

#pragma once

#include <memory>

#include "ILogger.h"
#include "NullLogger.h"

class Engine {
public:
    Engine() {
        //old
        serviceLogger = &nullLogger;

        //new
        spLoggerService = std::make_shared<NullLogger>();
    }

///////// old
public:
    void provide(ILogger* service) {
        if (service) {
            serviceLogger = service;
        } else {
            serviceLogger = &nullLogger;
        }
    }

    ILogger& getLoggerOld() const {
        return *serviceLogger;
    }
private:
    ILogger* serviceLogger;
    NullLogger nullLogger;

///////// old

///////// new
public:
    void provide(std::shared_ptr<ILogger> loggerService) {
        wpLoggerService = loggerService;
    }

    std::shared_ptr<ILogger> getLoggerNew() {
        if (wpLoggerService.expired()) {
            wpLoggerService = spLoggerService;
        }
        return wpLoggerService.lock();
    }
private:
    std::shared_ptr<ILogger> spLoggerService;
    std::weak_ptr<ILogger> wpLoggerService;

///////// new
};

I'm a bit unsure on how I should implement the services, in the above example(s) "Engine"(The Service Locator) essentially is designed to never really "own" the services, and instead it only holds a reference to the services, it's then the externally determined if/how/when the services become invalid.

In the example sections labeled "old", these are basically how I saw this pattern implemented elsewhere. I don't like that its left up to how its used to determine if the pointers will be valid or not.

In the example sections labeled "new" I tried to implement the more modern smart pointers, I like the automatic cleanup of the expired references, etc. But I'm still not sure if I like the way the references are handled.

So I guess my questions are:

Does it make sense to give total ownership of the service to the Engine(locator) and allow its life cycle to manage cleanup?
Should I stay with the raw pointer "old" way I found in online examples?
Should I keep going with the "new" smart pointer way?(one thing I'm not a fan of here is needing the if (wpLoggerService.expired()) check as well as the .lock() when accessing a service.(maybe there is a better smart pointer way to avoide this?)

Also if it makes sense for the Engine(Locator) to manage the life-cycle of the services, I was thinking of maybe making the "provide" function similar to that of the std::vector's emplace_back where you would do something like: engine.provide<Logger>(/*ctor args*/) and the .provide<T>() function would instantiate the object internally to prevent any ownership/access to it externally. (This just seems like a more reasonable way to let the Engine control its life-cycle, or is this dumb?)

Disclaimer: New to C++, first time using smart pointers, please be gentle :3


texts: Rock, Paper, Scissors game made in python

texts:
I added Rock, Paper, Scissors to one of my programs. I'm new to python and PEP 8, so I want to see how to improve my work.

def rock_paper_scissors(name):
    play_rps = True
    while play_rps:
        rps = ["rock", 'paper', 'scissors']
        player_rps = input("Rock, Paper, or Scissors: ").lower()
        com_rps = rps[random.randint(0,3)]
        print(com_rps)

        if com_rps == player_rps:
            print('Tie')

        if com_rps == 'rock' and player_rps == "scissors":
            print("Chatter Bot Wins!")

        if com_rps == 'scissors' and player_rps == "paper":
            print("Chatter Bot Wins!")

        if com_rps == 'paper' and player_rps == "rock":
            print("Chatter Bot Wins!")

        if player_rps == 'rock' and com_rps == "scissors":
            print(f"{name} Wins!")

        if player_rps == 'sicssors' and com_rps == "paper":
            print(f"{name} Wins!")

        if player_rps == 'paper' and com_rps == "rock":
            print(f"{name} Wins!")

        yn = input("Do you want to play again. Y/N: ").lower()

        if yn == 'n' or yn == 'no':
            play_rps = False


texts: Memoizing a tree's parent pointers in Python

texts:
I have a simple binary tree that has no parent pointers.
class Node:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Tree:
    def __init__(self, root=None):
        self.root = root

I need to traverse the tree from bottom up and cannot modify the Node class, so I'd like to memoize the parents.  I can modify the Tree class as such:
class Tree:
    def __init__(self, root=None):
        self.root = root
        self.memo = {}

    def memoize(self, node, parent_node):
        if node is None:
            return False
        self.memo[id(node)] = parent_node
        self.memoize(node.left, node)
        self.memoize(node.right, node)

    def get_parent(self, child):
        return self.memo[id(child)]

If I create a tree, memoize it, and run get_parent() I see what I expect:
a = Node(1)
tree = Tree(a)
b = Node(2)
c = Node(3)
a.left = b
a.right = c

tree.memoize(a, None)   # Tree root is instantiated with no parent
parent = tree.get_parent(b)

print(tree.memo)
>>> {4405793712: None, 4405793856: <__main__.Node instance at 0x1069b13b0>, 4405793928: <__main__.Node instance at 0x1069b13b0>}

print(parent.val)
>>> 1

This seems to work nicely.  However, I am a Python beginner, and want to know: is there a more Pythonic way to do this?


texts:
Yesterday morning I decided to stop procrastinating and start learning me some Haskell.

So far I've made this, which is a simple cli 'dice rolling' utility that can be used like:

$ ./dice 3d20
You rolled: 17

The code looks like this:

import Data.List.Split
import Data.Char
import Control.Monad
import Control.Monad.Random
import System.Environment

type Dice = (Int, Int)

diceCode :: String -> Dice
diceCode die = (parts!!0, parts!!1)
  where
    parts = [read x :: Int | x <- take 2 (splitOn "D" (map toUpper die))]

rollDie :: (RandomGen g) => Int -> Rand g Int
rollDie sides = getRandomR (1, sides)

rollDice :: (RandomGen g) => Dice -> Rand g Int
rollDice dice = liftM sum (sequence(replicate rolls (rollDie sides)))
  where
    rolls = fst dice
    sides = snd dice

main = do
  args <- getArgs
  roll <- evalRandIO (rollDice (diceCode (args!!0)))
  putStrLn ("You rolled: " ++ show roll)

I was able to get the diceCode 'parsing' function by myself without too much trouble.

The rollDie function is almost straight from an example in the Control.Monad.Random docs, which helped a lot.

I struggled for quite a while to find a recipe for summing the rolls in rollDice... it seemed to me I ought to use msum but I couldn't find a way to make it work. liftM sum seems to do exactly what I wanted though.

I also found the use of tuples quite cumbersome. In Python I could just do:
    rolls, sides = dice
but I seem to have to use the horribly-named fst and snd functions to access the members in Haskell (?)

I guess the next part of my adventure is to try and incorporate this into a larger program, eg a simple game.  It seems like the monadically-wrapped random int values are going to force the rest of the code to be 'monad-aware' (i.e. lots of use of liftM) and I wonder if there is a way to avoid this?


texts: Can someone review my implementation of a KeyValuePair?

texts:
public class KeyValuePair implements Comparable {

    private Comparable key;
    private Object value;

    public KeyValuePair(Comparable key, Object value) {
    this.key = key;
    this.value = value;
    }

    @Override
    public int compareTo(Object item) throws ClassCastException {
    if (!(item instanceof KeyValuePair)) {
        throw new ClassCastException("A KeyValuePair object was expected");
    }
    return this.key.compareTo(((KeyValuePair) item).key);
    }

    public Comparable getKey() {
    return this.key;
    }

    public Object getValue() {
    return this.value;
    }
}


texts: Converting from Celsius to Fahrenheit and vice versa

texts:
My code asks the user for the type of conversion, the degrees and spits the result back. It will prompt the user to ask for the type of conversion again if it's invalid. It will also prompt the user to see if he wants to quit or rerun the program again.

I was wondering if there is a more efficient way of doing this. I feel like I have a lot of redundant code on here.

public class Problem4 {

public static double celsiusToFahrenheit(double degree_C)
{
    double fahrenheitResult =  (9*(degree_C) / 5) + 32;
    return fahrenheitResult;
}

public static double fahrenheitToCelsius(double degree_F)
{
    double celsiusResult = 5*(degree_F - 32)/9;
    return celsiusResult;
}

public static void init(){
    Scanner scan = new Scanner(System.in);
    double result;
    char cont= 'y';
    char type;

    while (cont!='q' && cont!='Q')
    {
     System.out.println("Please enter the degree:");
     double degree = scan.nextDouble();

     System.out.println("Now enter the type of conversion (For Celsius, type 'C'. For Fahrenheit, type 'F')");
     type = scan.next().charAt(0);

     if(type!='c' && type!='C' && type!='f' && type!='F')
        {
             System.out.println("Error! You've entered an invalid conversion type!");
             System.out.println("Please enter a valid selection (Type C for celsius and F for fahrenheit");
             type = scan.next().charAt(0);
        }
     if (type == 'F' || type =='f')
        {
             result = fahrenheitToCelsius(degree);
             System.out.println("The conversion of "+ degree+"°F "+ "to Celsius is: " + result + "°C");

        }
     if (type == 'C' || type =='c')
        {
             result = celsiusToFahrenheit(degree);
             System.out.println("The conversion of "+ degree+"°C "+ "to Fahrenheit is: " + result + "°F");
        }

        System.out.println("Would you like to quit? Type 'q' to quit or type any other letter to continue:");
        cont = scan.next().charAt(0);
    }
    scan.close();
}

public static void main(String[] args)
{
    init();
}
}