texts: Modifying list while iterating during Breadth-first search

texts:
I am writing a function for implementing breadth-first search over a no. of nodes in a directed graph. The nodes are all numbers from 1-100. This is my implementation:

def BFS(start= 1, adj_dict= None):
    level= {}
    current= [start]
    visible= []
    lno= 0
    step= 0
    for ele in current:
        if ele not in level:
            level[ele]= lno
            visible.extend(adj_dict[ele])
        current.remove(ele)
        if current==[]:
            current= visible[:]
            visible= []
            lno+=1
    return level

This did not work correctly and stored only the start key in adj_dict. I ran the debugger and saw that the code exited for loop after first iteration.

Upon searching a little about the cause of this, I found this question- https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating on SO. This was the cause of error. The answers to that question suggest that I create a new list somehow, either using list comprehension or using slicing but none of them will help in my case.

So, I thought of nesting the for loop inside a while loop to achieve the desired result. This is how it looks now:

while current:
    for ele in current:
        if ele not in level:
            level[ele]= lno
            visible.extend(adj_dict[ele])
        current.remove(ele)
        if current==[]:
            current= visible[:]
            visible= []
            lno+=1

This works now. What I want to ask is this a correct way to achieve the effect or am I just getting lucky and the code can break easily? Also is this the pythonic way?


texts:
I have a simple macro moving data from Teradata to Excel. The process normally takes me 10 minutes to perform manually, however the macro can run for hours sometimes. This is making the macro seems counterproductive. But I still want to give it a chance.
Manually, I would just simply paste the sql to teradata, and copy/paste the results to Excel. This takes about 10 mins including the teradata run time.
Can someone suggest any ways to improve the performance? I'm still quite new to macros, so using simple language would be very much appreciated.
Option Explicit
Global glbUN As String
Global glbPWD As String
Global cnEDW As ADODB.Connection

Sub RefreshData()

Call Open_EDWDatabase
DoEvents

 Call BuildCode
  DoEvents

End Sub

Public Sub Open_EDWDatabase()

Set cnEDW = New ADODB.Connection
If glbUN = "" Or glbPWD = "" Then
    'Open login screen and center the form for people with 2 monitors
    UserForm1.StartUpPosition = 0
    UserForm1.Left = Application.Left + (0.5 * Application.Width) - (0.5 * UserForm1.Width)
    UserForm1.Top = Application.Top + (0.5 * Application.Height) - (0.5 * UserForm1.Height)
    UserForm1.Show 1
End If

cnEDW.ConnectionString = "Driver={Teradata};Persist Security Info=False;User ID=" & glbUN & ";Pwd=" & glbPWD & ";Data Source=teradata_PRD"
cnEDW.Open

End Sub
Public Sub Close_EDWDatabase()

cnEDW.Close
Set cnEDW = Nothing

End Sub

Sub BuildCode()

 Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim LastLineofSQL As Long
Dim LastLineofSQL2 As Long
Dim strQry As String
Dim strQry2 As String
Dim x, y As Long
Dim OutputAddress As String
Dim iCol As Long

LastLineofSQL = 44

strQry = ""

Set cmd = New ADODB.Command
cmd.ActiveConnection = cnEDW
cmd.CommandTimeout = 20000000

For x = 1 To LastLineofSQL
        strQry = strQry + Sheets("Codes").Cells(x, 1).Value

    If InStr(strQry, ";") <> 0 Then
        cmd.CommandText = strQry
        Set rs = cmd.Execute

        If x = LastLineofSQL Then

            Sheets("Data").Range("B2").CopyFromRecordset rs
        End If
        strQry = ""
        DoEvents
    Else
        If Right$(strQry, 2) <> vbCrLf Then
            strQry = strQry + vbCrLf
        End If
    End If
Next x

End Sub


texts:
I tried a Yahtzee kata in Python the other day. I'm not particularly experienced in Python (C# is my main language) so I'd be interested in any feedback as to how I could have done things better. In particular, I wonder whether my Count and HighestRepeated methods could be a little more elegant.

import unittest

#helpers
def Count(dice, number):
    return len([y for y in dice if y == number])

def HighestRepeated(dice, minRepeats):
    unique = set(dice)
    repeats = [x for x in unique if Count(dice, x) >= minRepeats]
    return max(repeats) if repeats else 0

def OfAKind(dice, n):
    return HighestRepeated(dice,n) * n

def SumOfSingle(dice, selected):
    return sum([x for x in dice if x == selected])

#strategies
def Chance(dice):
    return sum(dice)

def Pair(dice):
    return OfAKind(dice, 2)

def ThreeOfAKind(dice):
    return OfAKind(dice, 3)

def FourOfAKind(dice):
    return OfAKind(dice, 4)

def SmallStraight(dice):
    return 15 if tuple(sorted(dice)) == (1,2,3,4,5) else 0

def LargeStraight(dice):
    return 20 if tuple(sorted(dice)) == (2,3,4,5,6) else 0

def Ones(dice):
    return SumOfSingle(dice,1)

def Twos(dice):
    return SumOfSingle(dice,2)

def Threes(dice):
    return SumOfSingle(dice,3)

def Fours(dice):
    return SumOfSingle(dice,4)

def Fives(dice):
    return SumOfSingle(dice,5)

def Sixes(dice):
    return SumOfSingle(dice,6)

def Yahtzee(dice):
    return 50 if len(dice) == 5 and len(set(dice)) == 1 else 0

class YahtzeeTest(unittest.TestCase):
    testCases = (
        ((1,2,3,4,5), 1, Ones),
        ((1,2,3,4,5), 2, Twos),
        ((3,2,3,4,3), 9, Threes),
        ((3,2,3,4,3), 0, Sixes),
        ((1,2,3,4,5), 0, Pair), # no pairs found
        ((1,5,3,4,5), 10, Pair), # one pair found
        ((2,2,6,6,4), 12, Pair), # picks highest
        ((2,3,1,3,3), 6, Pair), # only counts two
        ((2,2,6,6,6), 18, ThreeOfAKind),
        ((2,2,4,6,6), 0, ThreeOfAKind), # no threes found
        ((5,5,5,5,5), 15, ThreeOfAKind), # only counts three
        ((6,2,6,6,6), 24, FourOfAKind),
        ((2,6,4,6,6), 0, FourOfAKind), # no fours found
        ((5,5,5,5,5), 20, FourOfAKind), # only counts four
        ((1,2,5,4,3), 15, SmallStraight),
        ((1,2,5,1,3), 0, SmallStraight),
        ((6,2,5,4,3), 20, LargeStraight),
        ((1,2,5,1,3), 0, LargeStraight),
        ((5,5,5,5,5), 50, Yahtzee),
        ((1,5,5,5,5), 0, Yahtzee),
        ((1,2,3,4,5), 15, Chance),
        )

    def testRunAll(self):
        for (dice, expected, strategy) in self.testCases:
            score = strategy(dice)
            self.assertEquals(expected, score, "got {0} expected {1}, testing with {2} on {3}".format(score, expected, strategy.__name__, dice))
        print 'ran {0} test cases'.format(len(self.testCases))

if __name__ == '__main__':
    unittest.main()


texts: Is this HTML structure and CSS DRY enough in this country selection menu?

texts:
I have built this conceptual design of a localization menu on this CodePen

I am wondering if I should have structured my
s better or if this should be wrapped in a
 instead since
 could be reduced in the CSS with .international li.

HTML

      North America

      Europe

      Korea

CSS

.international {
  background-color: rgb(36, 30, 30);
  color: #fff;
  letter-spacing: 1px;
  padding: 12px 0;
  width: 100%;
}

.locale {
  display: inline-block;
  margin-left: 6px;
  vertical-align: middle;
}
.locale a { color: #fff; text-decoration: none; }

.americas, .europe, .korea {
  background-image: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/101702/flags-small.png');
  background-repeat: no-repeat;
  margin-top: 3px;
}
.americas {
  background-position: 0px 0px;
  height: 11px;
  width: 48px;
}

.europe {
  background-position: -48px 0px;
  height: 11px;
  width: 48px;
}
.korea {
  background-position: -96px 0px;
  height: 11px;
  width: 16px;
}

.intlButton {
  float: right;
  font-size: 24px;
  margin-right: 6px;
}

.intlButton a { color: #444; }
.intlButton i {
  background-color: rgba(225, 225, 225, .7);
  border-radius: 3px;
  padding: 4px;
}


texts: Game of Life generation procession algorithm

texts:
I've tried to make Game of Life in console and this is the algorithm I used to generate new generation:

void processGeneration() {
    population = 0;
    int neighbors;
    int tempGrid[ROWS][COLS];
    for(int i = 0; i < ROWS; i++) {
        for(int j = 0; j < COLS; j++) {
            if (grid[i][j] == -1) {
                continue;
            }
            neighbors = countNeighbors(i, j);
            if (grid[i][j] == 0) {
                if (neighbors == 3) {
                    tempGrid[i][j] = 1;
                } else {
                    tempGrid[i][j] = 0;
                }
            } else if (grid[i][j] == 1) {
                if (neighbors < 2 || neighbors > 3) {
                    tempGrid[i][j] = 0;
                } else {
                    tempGrid[i][j] = 1;
                }
            }
        }
    }
    for(int i = 0; i < ROWS; i++) {
        for(int j = 0; j < COLS; j++) {
            if (grid[i][j] == -1) {
                continue;
            }
            if (tempGrid[i][j] == 1) {
                population++;
            }
            grid[i][j] = tempGrid[i][j];
        }
    }
}

I'm a bit uncertain if what I did was right, so could you check the algorithm? Also, grid is the grid where I save the cells in and I just use tempGrid to change the values and then copy them to the grid.

int countNeighbors(int row, int col) {
    int neighbors = 0;
    for(int i = row - 1; i < row + 2; i++) {
        for(int j = col - 1; j < col + 2; j++) {
            if (i == row && j == col) {
                continue;
            }
            if (i > -1 && j > -1 && i < ROWS && j < COLS) {
                neighbors += grid[i][j];
            }
        }
    }
    return neighbors;
}


texts: A 'slow sort': repeatedly swap the first misordered pair

texts:
A 'slow sort' is probably the slowest practical sort. It compares each element with the elements after it, and swaps immediately if one is greater than the other, and goes back to the start of the array.

For example:

  CBAD -> BCAD -> ACBD -> ABCD

My code:

function go() {
   var arrLen=Math.floor(Math.random()*20)+30;
   var arr=Array.from({length:arrLen}).map(()=>Math.floor(Math.random()*20)); // make random array
   txtIn.textContent=arr; //display
   //txtOut1.textContent=arr.sort(function(a,b) {return -(aa-b); // native sort
   var srcPos=0,dstPos,tmp; // declare variables
   while (srcPos<arrLen-1) {
        dstPos=srcPos+1;
        while (dstPos<arrLen) { // three swap routines
             if (arr[srcPos]>arr[dstPos]) {tmp=arr[srcPos];arr[srcPos]=arr[dstPos];arr[dstPos]=tmp;srcPos=0;break}
             //if (arr[srcPos]>arr[dstPos]) {arr[srcPos]^=arr[dstPos];arr[dstPos]^=arr[srcPos];arr[srcPos]^=arr[dstPos];srcPos=0;break}
             //if (arr[srcPos]>arr[dstPos]) {arr[srcPos]+=arr[dstPos];arr[dstPos]=arr[srcPos]-arr[srcPos];arr[srcPos]+=arr[dstPos];srcPos=0;break}
             srcPos++;
             dstPos++;
             }
       }
   txtOut2.textContent=arr; //display
}
data

native sort

slowsort

<button onclick='go();'>go</button>

I have included three swap types, tmp, XOR and add, and commented out two of them. The native sort includes a EMCA2015 arrow function version.

It seems to work okay - admittedly I haven't tested it for other data types, but any feedback would be appreciated.


texts: BMI calculator in python using if statements

texts:
I am a beginner in the python language. I wrote a BMI calculator and I am wondering if there are any improvements I could make to the code. This is the code below:

print('Enter your weight in kilo:')
weightInKilo = float(input())

print('Enter your height in feet:')

heightInFeet = float(input())

heightInMeter = heightInFeet * 12 * 0.025

bodyMassIndex = weightInKilo / (heightInMeter ** 2)

if bodyMassIndex < 15:
    print('Your BMI = ' + str(bodyMassIndex)  + ' You are very severely underweight.')

elif bodyMassIndex >= 15 and bodyMassIndex <= 16 :
    print('Your BMI = ' + str(bodyMassIndex)     + ' You are severely underweight.')

elif bodyMassIndex > 16 and bodyMassIndex <= 18.5:
    print('Your BMI = ' + str(bodyMassIndex) + ' You are underweight.')

elif bodyMassIndex > 18.5 and bodyMassIndex <= 25:
    print('Your BMI = ' + str(bodyMassIndex) + ' You are Normal(healthy weight).')

elif bodyMassIndex > 25 and bodyMassIndex <= 30:
    print('Your BMI = ' + str(bodyMassIndex) + ' You are overweight.')

elif bodyMassIndex > 30 and bodyMassIndex <= 35:
    print('Your BMI = ' + str(bodyMassIndex) + ' You are moderately obese.')

elif bodyMassIndex > 35 and bodyMassIndex <= 40:
    print('Your BMI = ' + str(bodyMassIndex) + ' You are severely obese.')

elif bodyMassIndex > 40:
    print('Your BMI = ' + str(bodyMassIndex) + ' You are very severely obese.')

input('Please press Enter to exit')


texts:
I have files with over 100 million lines in each:

...
01-AUG-2012 02:29:44 important data
01-AUG-2012 02:29:44 important data
01-AUG-2012 02:36:02 important data
some unimportant data
blahblah (also unimportant data)
some unimportant data
01-AUG-2012 02:40:15 important data
some unimportant data
...

As you can see, there are important data (starting with date and time) and unimportant data.  Also in each second, there can be many lines of important data.

My goal is to count the number of "important data" in each second (or minute or hour...) and reformat date/time format. My script also lets me count data in each minute, hour etc using options.dlen:

options.dlen = 10 takes YYYY-MM-DDD
options.dlen = 13 takes YYYY-MM-DDD HH
options.dlen = 16 takes YYYY-MM-DDD HH:MM
options.dlen = 20 takes YYYY-MM-DDD HH:MM:SS

I have written the following script (this is the main part - I skip all the file openings, parameters etc).

DATA = {}

# search for DD-MMM-YYYY HH:MM:SS
# e.g. "01-JUL-2012 02:29:36 important data"
pattern = re.compile('^\d{2}-[A-Z]{3}-\d{4} \d{2}:\d{2}:\d{2} important data')

DATA = defaultdict(int)
i = 0
f = open(options.infilename, 'r')
for line in f:
    if re.match(pattern, line):
        if options.verbose:
            i += 1
            # print out every 1000 iterations
            if i % 1000 == 0:
                print str(i) + '\r',

        # converts data date/time format to YYYY-MM-DD HH:MM:SS format (but still keep it as datetime !)
        d = datetime.strptime( line [0:20], '%d-%b-%Y %H:%M:%S')
        # converts d, which is datetime to string again
        day_string = d.strftime('%Y-%m-%d %H:%M:%S')
        DATA [ str(day_string[0:int(options.dlen)]) ] += 1
f.close()
#L2 = sorted(DATA.iteritems(), key=operator.itemgetter(1), reverse=True)
#L2 = sorted(DATA.iteritems(), key=operator.itemgetter(1))
L2 = sorted(DATA.iteritems(), key=operator.itemgetter(0))

It takes about 3 hours to process over 100 million lines. Can you suggest performance improvements for this script?

Update: I have just used PyPy and the same task on the same server took 45 minutes.  I will try to add profile statistics.


texts:
I made this simple traceroute implementation using the libpnet library, which sends ICMP echo probes with an increasing time-to-live, and then outputs the IPs of the hosts replying.

I'm new to Rust, so any style/performance tips would be appreciated!

extern crate pnet;

use std::env;
use std::error;
use std::net;
use std::str::FromStr;

use pnet::packet::icmp::echo_request::MutableEchoRequestPacket;
use pnet::packet::icmp::IcmpTypes;
use pnet::packet::ip::IpNextHeaderProtocols;
use pnet::packet::ipv4::MutableIpv4Packet;
use pnet::packet::MutablePacket;
use pnet::transport::{icmp_packet_iter, transport_channel, TransportChannelType::Layer3};
use pnet::util;

type Result<T> = std::result::Result<T, Box<error::Error>>;

static IPV4_HEADER_LEN: usize = 21;
static ICMP_HEADER_LEN: usize = 8;
static ICMP_PAYLOAD_LEN: usize = 32;

fn main() {
    std::process::exit(match run_app() {
        Ok(_) => 0,
        Err(error) => {
            eprintln!("Error: {}", error);
            1
        }
    });
}

fn run_app() -> Result<()> {
    let args: Vec<String> = env::args().collect();
    match args.len() {
        2 => {
            let protocol = Layer3(IpNextHeaderProtocols::Icmp);
            let (mut tx, mut rx) = transport_channel(1024, protocol)
                .map_err(|err| format!("Error opening the channel: {}", err))?;

            let ip_addr = net::Ipv4Addr::from_str(&args[1]).map_err(|_| "Invalid address")?;
            let mut rx = icmp_packet_iter(&mut rx);
            let mut ttl = 4;
            let mut prev_addr = None;
            loop {
                let mut buffer_ip = [0u8; 40];
                let mut buffer_icmp = [0u8; 40];
                let mut icmp_packet =
                    create_icmp_packet(&mut buffer_ip, &mut buffer_icmp, ip_addr, ttl)?;
                tx.send_to(icmp_packet, net::IpAddr::V4(ip_addr))?;
                if let Ok((_, addr)) = rx.next() {
                    if Some(addr) == prev_addr {
                        return Ok(());
                    }
                    prev_addr = Some(addr);
                    // This is not quite ideal as replies may arrive in different order
                    // than they were sent in, but using the identification field
                    // would make this simple example more complex
                    println!("TTL: {} - {:?}", ttl, addr.to_string());
                }
                ttl += 1;
            }
        }
        _ => Err((format!("Usage: {} ip", args[0])).into()),
    }
}

fn create_icmp_packet<'a>(
    buffer_ip: &'a mut [u8],
    buffer_icmp: &'a mut [u8],
    dest: net::Ipv4Addr,
    ttl: u8,
) -> Result<MutableIpv4Packet<'a>> {
    let mut ipv4_packet = MutableIpv4Packet::new(buffer_ip).unwrap();
    ipv4_packet.set_version(4);
    ipv4_packet.set_header_length(IPV4_HEADER_LEN as u8);
    ipv4_packet.set_total_length((IPV4_HEADER_LEN + ICMP_HEADER_LEN + ICMP_PAYLOAD_LEN) as u16);
    ipv4_packet.set_ttl(ttl);
    ipv4_packet.set_next_level_protocol(IpNextHeaderProtocols::Icmp);
    ipv4_packet.set_destination(dest);

    let mut icmp_packet = MutableEchoRequestPacket::new(buffer_icmp).unwrap();
    icmp_packet.set_icmp_type(IcmpTypes::EchoRequest);
    let checksum = util::checksum(&icmp_packet.packet_mut(), 2);
    icmp_packet.set_checksum(checksum);
    ipv4_packet.set_payload(icmp_packet.packet_mut());
    Ok(ipv4_packet)
}


texts: Removing duplicates from a file containing IP addresses

texts:
I have a big txt file containing some specific IP addresses, and all of them appear more than once (the file has around 13 million lines). The file looks like this (the first octet is set to zero for anonimity):

0.169.252.233
0.140.165.113
0.112.0.44
0.89.149.36

What I want is to read all those addresses and print in an output file only the unique values of each IP, removing the duplicates. Below is the code I am using

int main(){
    FILE *in;
    FILE *out;

    in = fopen("in.csv", "r");
    out = fopen("out.csv", "w");
    char line[17];
    char IPdone[100000][17];   // IP addresses already in the output file
    int nIPs = 0;              // number of IPs in the output file
    int k = 0;
    int bol = 0;

    if(in == NULL) printf("ERROR");

    while (fgets(line, sizeof(line), in)) {    //reads input file line by line
        for (k=0; k<100000; k++){              // checks if the IP is already in the output file
            if(!strcmp(IPdone[k], line)){
                bol=1;
                break;
            }
            bol=0;
        }

        if(bol==0){      // if the IP is not in the output file, print and add to IPdone
            fprintf(out, line);
            strcpy(IPdone[nIPs], line);
            nIPs++;
        }else{          // if it is, continue
            continue;
        }
    }

    fclose(in);
    fclose(out);
}

I am not usually a programmer guy and, although I know this code is not efficient at all, I could not implement any other algorithm with success. This code does work, however, it takes really long to do its job (really really long), and I know there is a much better way of doing it. Also, this code limits the number of IP addresses to 100000 (size of IPdone), and I would rather have a code that can deal with limitless number of different addresses.

I tried the idea of sorting the in file but I had the problem: to sort the file, I need to store all the lines in a vector (right? not sure), but creating a vector[13000000][17] gave me memory problems.

As I said, I am not much into programming, so I would appreciate a help.


texts:
I am learning Python at present, from several books. I am new to programming and I need assistance with knowing when my code is written with good form and style - I want to ingrain the habit of writing good clean code, which would be accepted as thus by other programmers. This is a code example from the book Python Programming for the Absolute Beginner by Michael Dawson, which I have altered in several ways - a game which picks a random number and asks the player to guess that number:

# Alex Grattan
# 8/10/14

# Guess My Number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money

import random

print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")

# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1

# guessing loop
while guess != the_number:
    if guess > the_number:
        print("Lower...")
    else:
        print("Higher...")

    guess = int(input("Take a guess: "))
    tries += 1
    if tries == 5:
        print "You failed to guess in time!"
        break
    if guess == the_number:
        print("You guessed it! The number was", the_number)
        print("And it only took you", tries, "tries!\n")

raw_input("\n\nPress the enter key to exit.")

The code works, however, I feel it is slightly 'bloated' and messy. How would a more experienced programmer change my code?


texts: Test many sorting algorithms using Python and Nose

texts:
I'm trying to learn how to build a good test suite, using simple sorting as an example.
Particularly, I am using Nose to generate all the tests based on a simple list of lists, where each sublist is a unit-test for each sorting method, as seen below:

from nose.tools import assert_equal

def check_sort(s, arr):
    assert_equal( s(arr), sorted(arr) )

def selection_sort(arr):
    """Repeatedly find the smallest element in the unsorted part
    and swap it with the first element in the unsorted part"""
    for i in xrange(len(arr)):
        min_val = min(arr[i:])
        min_ind = i + arr[i:].index(min_val)
        arr[i], arr[min_ind] = arr[min_ind], arr[i]
    return arr

def test_sorts():
    sorts = [selection_sort]
    for s in sorts:
        examples = [ [],\
                 [1],\
                 [1,1],\
                 [1, 2, 3],\
                 [1, 3, 2],\
                 [2, 1, 3],\
                 [2, 3, 1],\
                 [3, 1, 2],\
                 [3, 2, 1],\
                 [-10, 35, 4, 99, 1003, 2],\
                 [-10, 2, 35, 4, 4, 99, 99, 1003, 2]]
        for arr in examples:
            yield check_sort, s, arr

It seems to me that there has to be a better way of doing this, by using classes and more advanced methods to set-up and tear-down on the go. The caveat is that I would like to be able to extend the sorts list, adding more functions that implement bubble sort, merge sort, quick sort, etc. without having to create more tests by hand.

Any advice is appreciated.


texts: Correct use of MVVM and MouseEvent Handling

texts:
My XAML looksl ike this:

<UserControl x:Class="Dexel.Editor.Views.UI_Sketches.UiSketchCanvas"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:cc="clr-namespace:Dexel.Editor.Views.CustomControls"
         xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
         xmlns:command="http://www.galasoft.ch/mvvmlight"
         mc:Ignorable="d"
    Background="{DynamicResource  BG}">
<Grid>
<ItemsControl ItemsSource="{Binding Rectangles}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="PreviewMouseLeftButtonDown">
                <command:EventToCommand Command="{Binding mouseTestCommand}" PassEventArgsToCommand="True"/>
        </i:EventTrigger >
    </i:Interaction.Triggers>
        <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas Background="Transparent"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Canvas.Left" Value="{Binding X}"></Setter>
            <Setter Property="Canvas.Top" Value="{Binding Y}"></Setter>
        </Style>
    </ItemsControl.ItemContainerStyle>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
                <Rectangle Width="{Binding Width}" Height="{Binding Height}" Fill="Transparent" Stroke="White">
                </Rectangle>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>

In my ViewModel I have this code to handle the command:

public ICommand MouseTestCommand
    {
        get
        {
            if (_mouseTestCommand == null)
            {
                _mouseTestCommand = new CommandBase(eventArgs => mouseTest(eventArgs), null);
            }
            return _mouseTestCommand;
        }
    }

which calls this function:

private void MouseTest(object eventArgs)
    {
        var test = (MouseButtonEventArgs)eventArgs;
        var source = (Rectangle)test.OriginalSource;
        var rectangle = source.DataContext as SketchRectangleViewModel;
        Selected = rectangle;

    }

Is the implementation I use right now even MVVM? If so is the code I use right now bad? I'm not sure if there is a better way but I somehow have to get the information where the user clicked and recieve the DataContext if it is an rectangle.

Problems I see already:

Somehow need to check that the recieved original source is actually a rectangle and not the canvas


texts: Two implementations of a PHP sign-up page

texts:
I want the most secure and well-written version for my sign-up page. I'm adding AJAX to it for validation, too. I'm still writing it.

If you have tips on AJAX or on how to improve this PHP code for AJAX, feel free to point out any mistake and make any modification you want, or if there are other security concerns I should worry about. I'm fairly new this is the most I know about how to fight SQL injection.

I wrote this version first after I learned about SQL injection:

if (isset($_POST['submit'])){
include_once 'dbh.inc.php';
  $username = mysqli_real_escape_string($conn, $_POST['username']);
  $pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
  $email = mysqli_real_escape_string($conn, $_POST['email']);
if(empty($username) || empty($pwd) || empty($email)){
  echo "Fill in all Fields!";
}else {
   if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
     echo "Email is invalid!";
   }else{
      $stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
      $stmt->bind_param("s", $uid);
      $uid = $username;
      $stmt->execute();
      $result = $stmt->get_result();
      $usernamecheck = mysqli_num_rows($result);
      $rowNum = $result->num_rows;
    if($rowNum > 0){
        echo "Username is taken!";
    }else{
        $stmt = $conn->prepare("SELECT * FROM users WHERE email=?");
        $stmt->bind_param("s", $uemail);
        $uemail = $email;
        $stmt->execute();
        $result = $stmt->get_result();
        $usernamecheck = mysqli_num_rows($result);
        $rowNum = $result->num_rows;
    if($rowNum > 0){
        echo "Email is taken";
    }else{
        $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
        $stmt = $conn->prepare("INSERT INTO users (username, pwd, email) VALUES (?, ?, ?)");
    $stmt->bind_param("sss",$uid, $password, $theemail);
    $uid = $username;
    $password = $hashedPwd;
    $theemail= $email;
    $stmt->execute();
    $result = $stmt->get_result();
    header("location: ../user-login.php");
        }
        }
     }
    }
 }else{
header("location: ../user-signup.php");
exit();
}

and this version, which I was told is a better version, but has no prepared statements, which i learned is the main thing to fight SQL injection:

include_once '../dbh.inc.php';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = $_POST['username'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];
if(empty($username) || empty($pwd) || empty($email)){
  echo "Fill in all Fields!";
  exit();
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
     echo "Email is invalid!";
     exit();
   }else{
$chk = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($conn, $chk);
while ($row = mysqli_fetch_array($result)) {
  if ($row['email'] == $email) {
    echo "Email Match";
  exit();
  } else {
   $chk = "SELECT * FROM user WHERE username='$username'";
   $result = mysqli_query($conn, $chk);
   while ($row = mysqli_fetch_array($result)) {
    if ($row['username'] == $username) {
    echo "Username Match";
    exit();
  } else {
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
$join = sprintf("INSERT INTO user(username, email, password) " .
    "VALUES ('%s', '%s', '%s', '%s'); ",
  mysqli_real_escape_string($conn, $username),
  mysqli_real_escape_string($conn, $email),
  mysqli_real_escape_string($conn, $hashedPwd),
  mysqli_insert_id($conn));
  if (mysqli_query($conn, $join)) {
    $i = "joined";
  } else {
    $i = "failed to join";
  }
  echo $i;
  }


texts: Implementing my own shared-ownership double-indirecting smart-pointer

texts:
I am implementing my own double-indirecting shared-ownership smart-pointer because I needed a way to replace the managed object a group of smart-pointers is pointing to with a new object (it's the method reset_all in the code below).

I tried to keep this as close as I could to the std::shared_ptr's interface, while avoiding things I don't understand / need like aliasing and conversion from other smart-pointer types.

//(it's all in an header file)
#pragma once

template <typename T>
class Manager {
    template <typename U>
    friend class SharedPtr;

    T* managed;
    unsigned int counter;

    Manager(T* new_ptr):
        managed(new_ptr), counter(1) {}
    ~Manager() = default;

    Manager<T>* own() {
        ++counter;
        return this;
    }
    void disown() {
        if (!(--counter)) {
            delete managed;
            delete this;
        }
    }
};

template <typename T>
class SharedPtr {
    public:
    SharedPtr() = default;
    SharedPtr(T* new_ptr) {
        if (new_ptr) {
            manager = new Manager<T>(new_ptr);
        }
    }
    SharedPtr(const SharedPtr &rhs):
        manager(rhs.manager->own()) {}
    SharedPtr(SharedPtr &&rhs):
        manager(rhs.manager) {
        rhs.manager = nullptr;
    }

    SharedPtr& operator=(const SharedPtr &rhs) {
        if (manager) {
            manager->disown();
        }
        manager = rhs.manager->own();
        return *this;
    }
    SharedPtr& operator=(SharedPtr &&rhs) {
        if (manager) {
            manager->disown();
        }
        manager = rhs.manager;
        rhs.manager = nullptr;
        return *this;
    }

    void swap(SharedPtr &rhs) {
        Manager<T>* tmp = manager;
        manager = rhs.manager;
        rhs.manager = tmp;
    }

    void reset() {
        if (manager) {
            manager->disown();
        }
        manager = nullptr;
    }
    void reset(T* new_ptr) {
        if (manager) {
            manager->disown();
        }
        manager = new Manager<T>(new_ptr);
    }

    T* get() {
        if (manager) {
            return manager->managed;
        }
        return nullptr;
    }

    T& operator*() {
        return *(manager->managed);
    }

    T* operator->() {
        return manager->managed;
    }

    unsigned int use_count() {
        if (manager) {
            return manager->counter;
        }
        return 0;
    }

    bool unique() {
        return use_count() == 1;
    }

    operator bool() {
        return (bool) manager;
    }

    void reset_all(T* new_ptr) {
        if (manager) {
            delete manager->managed;
            manager->managed = new_ptr;
            return;
        }
        manager = new Manager<T>(new_ptr);
    }

    ~SharedPtr() {
        if (manager) {
            manager->disown();
        }
    }

    private:
    Manager<T>* manager = nullptr;
};


texts: Speech Recognition Part 2: Classifying Data

texts:
Now that I have generated training data, I need to classify each example with a label to train a TensorFlow neural net (first building a suitable dataset).  To streamline the process, I wrote this little Python script to help me.  Any suggestions for improvement?

classify.py:

# Builtin modules
import glob
import sys
import os
import shutil
import wave
import time
import re
from threading import Thread

# 3rd party modules
import scipy.io.wavfile
import pyaudio

DATA_DIR = 'raw_data'
LABELED_DIR = 'labeled_data'
answer = None

def classify_files():
    global answer
    # instantiate PyAudio
    p = pyaudio.PyAudio()

    for filename in glob.glob('{}/*.wav'.format(DATA_DIR)):
        # define stream chunk
        chunk = 1024

        #open a wav format music
        wf = wave.open(filename, 'rb')
        #open stream
        stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                        channels=wf.getnchannels(),
                        rate=wf.getframerate(),
                        output=True)
        #read data
        data = wf.readframes(chunk)

        #play stream
        while answer is None:
            stream.write(data)
            data = wf.readframes(chunk)
            if data == b'': # if file is over then rewind
                wf.rewind()
                time.sleep(1)
                data = wf.readframes(chunk)

        # don't know how to classify, skip sample
        if answer == '.':
            answer = None
            continue

        # sort spectogram based on input
        spec_filename = 'spec{}.jpeg'.format(str(re.findall(r'\d+', filename)[0]))
        os.makedirs('{}/{}'.format(LABELED_DIR, answer), exist_ok=True)
        shutil.copyfile('{}/{}'.format(DATA_DIR, spec_filename), '{}/{}/{}'.format(LABELED_DIR, answer, spec_filename))

        # reset answer field
        answer = None

        #stop stream
        stream.stop_stream()
        stream.close()

    #close PyAudio
    p.terminate()

if __name__ == '__main__':
    try:
        # exclude file from glob
        os.remove('{}/ALL.wav'.format(DATA_DIR))

        num_files = len(glob.glob('{}/*.wav'.format(DATA_DIR)))
        Thread(target = classify_files).start()
        for i in range(0, num_files):
            answer = input("Enter letter of sound heard: ")
    except KeyboardInterrupt:
        sys.exit()


texts: IRepository Pattern - Interface Segregation Principle

texts:
I have an IRepository class that I use a lot.  But I noticed that for many of my repositories I do not implement most of the methods.  Also,  I usually don't have a TKey that I want to specify if I'm not using the GetById method but the current design forces me to specify it.  I was thinking of changing the interface or splitting up the interface into multiple smaller interfaces in order to make it cleaner and easier to use. Any ideas?

public interface IRepository<TEntity, in TKey>
{
    TEntity Insert(TEntity entity);

    TEntity Find(Expression<Func<TEntity, bool>> predicate);

    IQueryable<TEntity> FindAll(Expression<Func<TEntity, bool>> predicate);

    TEntity GetById(TKey key);

    TEntity Update(TEntity entity);

    IQueryable<TEntity> GetAll();

    void Delete(TEntity entity);
}

Here is an example implementation. Let me know if you need to see more than one method.  It is somewhat self explanatory.

/// <summary>
/// The invoices repository.
/// </summary>
public class InvoicesRepository : IRepository<Invoice, int>
{
    private readonly string connectionString;

    public InvoicesRepository(string connectionString)
    {
        this.connectionString = connectionString;
    }

    public Invoice Insert(Invoice entity)
    {
        using (SqlConnection connection = new SqlConnection(this.connectionString))
        using (SqlCommand command = new SqlCommand("INSERT INTO INVOICES VALUES (entity.SomeProp)", connection))
        {
            connection.Open();
            entity.Id = (int)command.ExecuteScalar();
            return entity;
        }
    }

    public Invoice Find(Expression<Func<Invoice, bool>> predicate)
    {
        throw new NotImplementedException();
    }

    public IQueryable<Invoice> FindAll(Expression<Func<Invoice, bool>> predicate)
    {
        throw new NotImplementedException();
    }

    public Invoice GetById(int key)
    {
        throw new NotImplementedException();
    }

    public Invoice Update(Invoice entity)
    {
        throw new NotImplementedException();
    }

    public IQueryable<Invoice> GetAll()
    {
        throw new NotImplementedException();
    }

    public void Delete(Invoice entity)
    {
        throw new NotImplementedException();
    }

    public Invoice GetById(int key)
    {
        throw new NotImplementedException();
    }
}


texts:
I'm new to TPL Dataflow and was looking for an action block to basically push an object on a timer - specifically to produce heartbeats on every interval.  I was unable to find anything out of the box so I decided to create a wrapper class on action block that would give me the desired functionality. I also wanted to include async/await pattern in the implementation.

Given the following heartbeat object:

public class Heartbeat
{
    public DateTime HearbeatTimeUtc { get; set; }
}

The wrapper class:

public class TimerActionBlock<TInput>
{
    private readonly ActionBlock<TInput> _actionBlock;

    public TimerActionBlock(Func<TInput, Task> func,
        Func<TInput, Exception, Task> excptionFunc)
    {
        _actionBlock = new ActionBlock<TInput>(async input =>
        {
            try
            {
                await func(input);
            }
            catch (Exception e)
            {
                await excptionFunc(input, e);
            }
        });
    }

    public void Start(Func<Task<TInput>> inputFunc,
        TaskScheduler scheduler,
        TimeSpan dueTime,
        TimeSpan period,
        CancellationToken cancellationToken,
        Action<Exception> onError)
    {
        Task
            .Factory
            .StartNew(async () =>
                {
                    await Task.Delay(dueTime);

                    while (true)
                    {
                        var input = await inputFunc();

                        await _actionBlock.SendAsync(input);

                        var task = Task.Delay(period,
                            cancellationToken);

                        try
                        {
                            await task;
                        }
                        catch (TaskCanceledException)
                        {
                            return;
                        }
                    }
                },
                cancellationToken,
                TaskCreationOptions.LongRunning,
                scheduler)
            .ContinueWith(task => { onError(task.Exception); }, TaskContinuationOptions.OnlyOnFaulted);
    }
}

Calling code would something like the following:

var timerActionBlock = new TimerActionBlock<Heartbeat>(heartbeat =>
    {
        Console.WriteLine(JsonConvert.SerializeObject(heartbeat));
        return Task.CompletedTask;
    },
    (heartbeat, exception) =>
    {
        Console.WriteLine(exception);
        return Task.CompletedTask;
    });

timerActionBlock
    .Start(() => Task.FromResult(new Heartbeat
        {
            HearbeatTimeUtc = DateTime.UtcNow
        }),
        TaskScheduler.Default,
        TimeSpan.FromSeconds(10),
        TimeSpan.FromMilliseconds(1000),
        CancellationToken.None,
        Console.WriteLine);


texts: Calculating some worst-case values for angles in an interval

texts:
Sadly enough I have a bit of code that is really slow and being a newbie in programmation, I don't have the faintest clue on how to optimize. Is there any way to make those calculations faster?

This code calculates the worst case of some parameters cycling through AktBeam and FileCounter (those cycles contain a LOT of other stuff, and I'm sorry to say that I cannot include the whole code) and inside a circumference (have a look at the select case block), and stores them in the BT and EC arrays.

AmplCo, AmplCr, PhaseCo and PhaseCr are arrays containing double variables.

I'm looking for all the possibilities here to make my processor perform the least amount of operations (e.g. if x^2 is worse than x * x, I'd use x * x).

Please notice that I cannot split the arrays in any way.

For PhiDrehung = 0 To 2*Sector-1 Step 3
    A = 0
    B = 0
    C = 0
    D = 0
    EC_Worst = 0
    BT_Worst = 0
    For k = 0 To FensterTheta
        For i = PhiDrehung-FensterPhi/2 To PhiDrehung+FensterPhi/2
            Select Case i
                Case Is < 0
                    l = 360+i
                Case Is > 359
                    l = i-360
                Case Else
                    l = i
            End Select
            A = A + AmplCo(FileCounter-1, AktBeam,l,k) * AmplCo(FileCounter, AktBeam,l,k) * Cos(PhaseCo(FileCounter-1, AktBeam,l,k) - PhaseCo(FileCounter, AktBeam,l,k)) + AmplCr(FileCounter-1, AktBeam,l,k) * AmplCr(FileCounter, AktBeam,l,k) * Cos(PhaseCr(FileCounter-1, AktBeam,l,k) - PhaseCr(FileCounter, AktBeam,l,k))
            B = B + AmplCo(FileCounter-1, AktBeam,l,k) * AmplCo(FileCounter, AktBeam,l,k) * Sin(PhaseCo(FileCounter-1, AktBeam,l,k) - PhaseCo(FileCounter, AktBeam,l,k)) + AmplCr(FileCounter-1, AktBeam,l,k) * AmplCr(FileCounter, AktBeam,l,k) * Sin(PhaseCr(FileCounter-1, AktBeam,l,k) - PhaseCr(FileCounter, AktBeam,l,k))
            C = C + (AmplCo(FileCounter-1, AktBeam,l,k)^2 + AmplCr(FileCounter-1, AktBeam,l,k)^2)
            D = D + (AmplCo(FileCounter, AktBeam,l,k)^2 + AmplCr(FileCounter, AktBeam,l,k)^2)
            BT_Worst = BT_Worst + (AmplCo(FileCounter-1, AktBeam,l,k)^2 + AmplCr(FileCounter-1, AktBeam,l,k)^2) / (AmplCo(FileCounter, AktBeam,l,k)^2 + AmplCr(FileCounter, AktBeam,l,k)^2)
        Next
    Next
    EC_Worst = ((A^2 + B^2) / (C*D))^0.5 * 100
    If EC_Worst > EC((FileCounter-1) / 2, AktBeam) Then EC((FileCounter-1) / 2, AktBeam) = EC_Worst

    BT_Worst = 20 * Log( BT_Worst / (((FensterTheta+1)*(FensterPhi+1)) * ((PRad(FileCounter-1, AktBeam) + PRad(FileCounter, AktBeam))/2)) ) / Log(10)
    If BT_Worst > BT((FileCounter-1) / 2, AktBeam) Then BT((FileCounter-1) / 2, AktBeam) = BT_Worst
Next

FensterTheta and FensterPhi are user-inserted values, let Sector = 180.


texts: Using ReactJS. Div changes color on hover. On Click drops down description

texts:
I have a ReactJS component that I feel is a little bulky. The component holds the information for an event, and clicking on it shows the description for the event. Clicking the event component again will hide the description. The event component also has a triangle symbol that changes from down to up when the Event component is clicked. When the mouse overs over the Event component it changes from grey to maroon. Below are images of the component expressing this functionality.

The code for the entire Event Component:

import React, { Component } from 'react';

class Event extends Component {
   constructor(props) {
    super(props);
    this.state = { des:false, titleHov: false };
  }
  showDescription = ( ) => {
    if ( this.state.des == true ) {
        this.setState({
            des:false
        });
    } else {
        this.setState({
            des:true
        });
    }
  }
  onMouseEnter = () => {
      this.setState({
        titleHov:true
      });
   }
  onMouseLeave = () => {
    this.setState({
      titleHov:false
    });
  }
  render() {
    var eve = this.props.eve;
    var des;
    var tUp = '△';
    var tDown = '▽';
    var AtriangleCLS = 'Atriangle';

    if (this.state.des == true) {
        AtriangleCLS = 'Atriangle titleHover';
        des = (

                      {eve.title} - {eve.date}
                   {tUp}

                  Start Time: {eve.st} - End Time: {eve.et}

                  {eve.description}

        );
    } else {
      var titleCLS = '';
      if (this.state.titleHov == true) {
        titleCLS = 'eTitle titleHover';
        AtriangleCLS = 'Atriangle titleHover';
      } else {
        titleCLS = 'eTitle nottitleHover';
        AtriangleCLS = 'Atriangle nottitleHover';
      }

      des = (

                 {eve.title} - {eve.date}
                  {tDown}

      );
    }
    return (

 {des}

    );
  }
}
export default Event;

Next CSS used:

#eventslist li {
    list-style-type: none;
}

#eventslist .eTitle {

    display: block;
    margin-top: 1em;
    padding: 0.75em;
    cursor: pointer;
    width: 60%;
    min-width: 270px;
}
#eventslist .eDescription {
    color: rgb( 77, 0, 38 );
    background: rgb(232, 234,240 );
    display: block;
    padding: 0.75em;
    width: 60%;
    min-width: 270px;
}
.titleHover {
    background: rgb( 77, 0, 38 );
    color: rgb(232, 234,240 );
}
.nottitleHover {
    color: rgb( 77, 0, 38 );
    background: rgb(232, 234,240 );
}
.Atriangle  {
    padding: 0.2em;
    float: right;
    margin-left: 1em;
    display: block;
    font-family: 'consolas';
}

My concerns are that onMouseEnter and onMouseLeave are inefficient. I'd use CSS hover, but I want the Event component to stay maroon when the description is extended.

I am concerned about my use of the triangle symbol. I would like to know the best way to handle and display Unicode symbols.

My concern for showDescription is that it could be bulky and inefficient.

Interested in any advice.

To see my coding style, these are links to gits for event.js, events.css, and events.js. This isn't finished production code yet, just working code. Where I'm at after I get the component working.

Event.js

Events.css

Events.js (Parent Component)


texts: Separate areacode from phone number string with MySQL Database

texts:
I have a database with 5000 entries of local area codes to separate the area code from a phone number string. I'm not sure if the code
I use is the fastest way to solve these job.

I shrink the number of db entries with the first three digits from phone number string. After this I put the entries found in db in an array and finally search these array for a match.

What do you think guys? Would you do it the same?

<?php
$phonenumber = '03522522492';
$country = 'DE';
$link = mysqli_connect('Host', 'DB', 'Pass','User') or die(mysqli_error());
$db_selected = mysqli_select_db( $link, 'DB');
$fristthree = substr($phonenumber,0,3);
$array = array();
$query = mysqli_query($link, "SELECT * FROM `Areacodes` WHERE `Country` LIKE '".$country."%' AND `Areacode` like '".$fristthree."%' ORDER BY CHAR_LENGTH(Areacode) ASC");
while($row = mysqli_fetch_assoc($query)){
  $array[] = $row;
}
foreach ($array as $areacode) {
    $subString = substr($phonenumber, 0, strlen($areacode["Areacode"]));
    if ($subString == $areacode["Areacode"]) {
        $phone = $subString." ".substr($phonenumber, strlen($areacode["Areacode"]));
        $location = $areacode["Location"];
    }
}
if (!empty($phone)) {
    echo $phone;
    echo '

';
    echo $subString;
    echo '

';
    echo $location;
}

else {
    echo "No Areacode found.";
}
?>


texts: Equivalent of Python's dict.update for STL maps in C++

texts:
dict objects in Python have an update method that can be used to extend one dictionary with all items from another, possibly overwriting entries that already exist.  I find this function very useful from time to time.

The associative containers from the C++ standard library (std::map and std::unordered_map) do not provide a direct analogue for this functionality so I wrote the following utility functions.

Comments regarding any aspect of the code are welcome.

#include <cassert>
#include <utility>

namespace codereview
{

    template <typename DictT>
    void update(DictT& dst, const DictT& src)
    {
        for (const auto& [key, value] : src) {
            dst.insert_or_assign(key, value);
        }
    }

    template <typename DictT>
    void update(DictT& dst, DictT&& src) noexcept
    {
        // Equal allocators are a precondition for splicing nodes
        assert(src.get_allocator() == dst.get_allocator());
        dst.merge(src);
        while (!src.empty()) {
            auto node = src.extract(src.cbegin());
            dst.extract(node.key());
            dst.insert(std::move(node));
        }
    }

}  // namespace codereview


texts: Is this the way of truncating the fractional part of a BigDecimal when its scale is zero in Java?

texts:
I need to remove the fractional part of a BigDecimal value when its scale has a value of zero. For example,

BigDecimal value = new BigDecimal("12.00").setScale(2, RoundingMode.HALF_UP);

It would assign 12.00. I want it to assign only 12 to value in such cases.

BigDecimal value = new BigDecimal("12.000000").setScale(2, RoundingMode.HALF_UP);

should assign 12,

BigDecimal value = new BigDecimal("12.0001").setScale(2, RoundingMode.HALF_UP);

should assign 12.

BigDecimal value = new BigDecimal("12.0051").setScale(2, RoundingMode.HALF_UP);

should assign12.01

BigDecimal value = new BigDecimal("12.99").setScale(2, RoundingMode.HALF_UP);

should assign 12.99.

BigDecimal value = new BigDecimal("12.999").setScale(2, RoundingMode.HALF_UP);

should assign13

BigDecimal value = new BigDecimal("12.3456").setScale(2, RoundingMode.HALF_UP);

should assign 12.35 and alike.

I have this question on StackOverflow.

For this to be so, I'm doing the following.

String text="123.008";
BigDecimal bigDecimal=new BigDecimal(text);

if(bigDecimal.scale()>2)
{
    bigDecimal=new BigDecimal(text).setScale(2, RoundingMode.HALF_UP);
}

if(bigDecimal.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO)==0)
{
    bigDecimal=new BigDecimal(text).setScale(0, BigDecimal.ROUND_HALF_UP);
}

System.out.println("bigDecimal = "+bigDecimal);

It's just as an example. Is there a better way to do this?


texts:
The c# newbie is back :) I have another problem with my threads. Here is what i am trying to achieve:

I am starting 5 threads which are performing the same task but on different URLs. So i am keeping a "masterLogFile.txt" to keep track of what URLs have already been visited.
Each thread compares its own "thread1LogFile.txt" to the "masterLogFile.txt" before deciding whether to execute the task.

My question is, is there any more efficient way to handle this? Currently each thread runs this piece of code before deciding if the URL is ok or not:

using (FileStream fs = File.Open("masterLogFile.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
{
    byte[] bff = new byte[1024];
    UTF8Encoding temp = new UTF8Encoding(true);

    while (fs.Read(bff,0,bff.Length) > 0)
    {
        if (temp.GetString(bff).Contains(variableWithUrlFrom_thread1LogFile.txt))
        {
            found = true;
        }

    }
    fs.Close();
}


texts: Basic memory pool, alignment, thread safety

texts:
Mainly for practicing purposes, I'm trying to implement a simple, yet efficient memory pool. It's basically a linked list that is able to grow, with fixed sized members. Each node has a flag if it's free or not. I'm not sure if I'm doing it the right way, and especially confused about how to deal with alignment, and thread safety. I know the basic concept, just don't know how to implement in this case. Could you please help me how to improve my code? This is what I have now:

#include <stdbool.h>
#include "mem_pool.h"

typedef struct block Block;

typedef struct block
{
    Block *next;
    void *ptr;
    bool free;
} Block;

struct mem_pool
{
    Block *head;
    void *memory;
    size_t memory_size;
    size_t memb_size;
};

#define get_ptr_and_increase(pool, size) pool->memory; pool->memory += size

#define add_block_size(pool) pool->memory_size += sizeof(Block) + pool->memb_size

static Block *new_block(MemoryPool *pool, bool is_free)
{
    Block *block = get_ptr_and_increase(pool, sizeof(Block));
    block->ptr = get_ptr_and_increase(pool, pool->memb_size);
    block->next = NULL;
    block->free = is_free;

    return block;
}

MemoryPool *pool_init(size_t memb_size)
{
    MemoryPool *pool = malloc(sizeof(MemoryPool));
    pool->memb_size = memb_size;
    pool->memory_size = 0;
    add_block_size(pool);
    pool->memory = malloc(pool->memory_size);
    pool->head = new_block(pool, true);

    return pool;
}

static Block *find_free(MemoryPool *pool)
{
    Block *current = pool->head;

    while (NULL != current && false == current->free) {
        current = current->next;
    }

    return current;
}

static void add_new_head(MemoryPool *pool)
{
    Block *tmp = pool->head;
    pool->head = new_block(pool, false);
    pool->head->next = tmp;
    add_block_size(pool);
    pool->memory = realloc(pool->memory, pool->memory_size);
}

void *pool_alloc(MemoryPool *pool)
{
    Block *free = find_free(pool);

    if (NULL != free) {
        return free->ptr;
    }
    add_new_head(pool);

    return pool->head->ptr;
}

void pool_free(MemoryPool *pool, void *block)
{
    Block *current = pool->head;

    while (current->ptr != block) {
        current = current->next;
    }

    current->free = true;
}

void pool_destroy(MemoryPool *pool)
{
    free(pool->memory - pool->memory_size);
    free(pool);
}


texts:
The task
is taken from leetcode

  There is a robot starting at position (0, 0), the origin, on a 2D
  plane. Given a sequence of its moves, judge if this robot ends up at
  (0, 0) after it completes its moves.

  The move sequence is represented by a string, and the character
  moves[i] represents its ith move. Valid moves are R (right), L (left),
  U (up), and D (down). If the robot returns to the origin after it
  finishes all of its moves, return true. Otherwise, return false.

  Note: The way that the robot is "facing" is irrelevant. "R" will
  always make the robot move to the right once, "L" will always make it
  move left, etc. Also, assume that the magnitude of the robot's
  movement is the same for each move.

  Example 1:

  Input: "UD" Output: true  Explanation: The robot moves up once, and
  then down once. All moves have the same magnitude, so it ended up at
  the origin where it started. Therefore, we return true.

  Example 2:

  Input: "LL" Output: false Explanation: The robot moves left twice. It
  ends up two "moves" to the left of the origin. We return false because
  it is not at the origin at the end of its moves.

const arr = "UD";

My imperative solution:

function judgeCircle(moves) {
  let horizontal = 0;
  let vertical = 0;

  [...moves].forEach(m => {
    switch(m) {
      case "U":
        ++vertical;
        break;
      case "D":
        --vertical;
        break;
      case "R":
        ++horizontal;
        break;
      case "L":
        --horizontal;
        break;
      default:
        // be a good code
    }
  });
  return !(horizontal) && !(vertical);
};

console.log(judgeCircle(arr));

My functional solution:

const judgeCircle2 = moves => {
  const {h, v} = [...moves].reduce((acc,m) => {
    switch(m) {
      case "U":
        ++acc.v;
        return acc;
      case "D":
        --acc.v;
        return acc;
      case "R":
        ++acc.h;
        return acc;
      case "L":
        --acc.h;
        return acc;
      default:
        // be a good code
    }
  }, {h: 0, v: 0});
  return !h && !v;
};

console.log(judgeCircle2(arr));


texts: Pretty print directory structure in a JSON recursively

texts:
I am trying to pretty print the directory structure defined in a JSON. I do have a solution using recursion but I'm looking for feedback on how this solution can be improved or if there's any better approach.
Problem Statement
A deeply nested directory contains following information:

Name
Data (can be an array of sub directories or file content)

Desired output: Print the directory structure in below format:
root_dir
|__dir_a
|____file_00.txt
|____dir_b
|______dir_c
|________file_01.txt
|________file_02.txt
|________file_03.txt
|________file_04.txt
|______file_05.txt
|______file_06.txt
|____dir_d
|______file_07.txt
|______file_08.txt

Solution:
My idea is to traverse data recursively till a file is not found (because beyond it there is no further nesting) and keep pushing directories and files in an array which would then be pretty printed with help of template literals.
P.S. I don't want to reverse the arrays twice, how can I fix that?

const indentation = 2;
const flatDirStructure = [];

const dirStructure = [
  {
    name: 'root_dir',
    data: [
      {
        name: 'dir_a',
        data: [
          { name: 'file_00.txt', data: 'file_00 content' },
          {
            name: 'dir_b',
            data: [
              {
                name: 'dir_c',
                data: [
                  { name: 'file_01.txt', data: 'file_01 content' },
                  { name: 'file_02.txt', data: 'file_02 content' },
                  { name: 'file_03.txt', data: 'file_03 content' },
                  { name: 'file_04.txt', data: 'file_04 content' }
                ]
              },
              { name: 'file_05.txt', data: 'file_05 content' },
              { name: 'file_06.txt', data: 'file_06 content' }
            ]
          },
          {
            name: 'dir_d',
            data: [
              { name: 'file_07.txt', data: 'file_07 content' },
              { name: 'file_08.txt', data: 'file_08 content' }
            ]
          }
        ]
      }
    ]
  }
];

const flattenDirStructure = (data, depth) => {
  if (typeof data === 'string') {
    return true;
  } else {
    data.reverse().forEach(({ name, data }) => {
      const isFile = flattenDirStructure(data, depth + indentation);

      flatDirStructure.push({
        name,
        depth,
        isFile,
      });
    });

    return false;
  }
};

const prettyPrint = () => {
  const output = [];

  flatDirStructure.reverse().forEach(({ name, depth }) => {
    const indentation = new Array(depth).fill('_').join('');
    output.push(`${indentation ? '|' : ''}${indentation}${name}`);
  });

  console.log(output.join(`\n`));
}

flattenDirStructure(dirStructure, 0);
prettyPrint();


texts:
I'm trying to convert this Objective-C code (originally found in this Stack Overflow question) which turns an NSString into NSData to Swift:

- (NSData *)dataFromHexString {
    const char *chars = [self UTF8String];
    int i = 0, len = self.length;

    NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
    char byteChars[3] = {'\0','\0','\0'};
    unsigned long wholeByte;

    while (i < len) {
        byteChars[0] = chars[i++];
        byteChars[1] = chars[i++];
        wholeByte = strtoul(byteChars, NULL, 16);
        [data appendBytes:&wholeByte length:1];
    }

    return data;
}

My first pass looked like this:

func hexStringToBytes(hexString: String) -> NSData? {
    guard let chars = hexString.cStringUsingEncoding(NSUTF8StringEncoding) else { return nil}
    var i = 0
    let length = hexString.characters.count

    let data = NSMutableData(capacity: length/2)
    var byteChars: [CChar] = [0, 0, 0]

    var wholeByte = CUnsignedLong()

    while i < length {
        byteChars[0] = chars[i++]
        byteChars[1] = chars[i++]
        i+=1
        wholeByte = strtoul(byteChars, nil, 16)
        data?.appendBytes(&wholeByte, length: 1)
    }

    return data
}

I realized I could optimize this further, since ++ is deprecated and will be removed in Swift 3:

func hexStringToBytes(hexString: String) -> NSData? {
    guard let chars = hexString.cStringUsingEncoding(NSUTF8StringEncoding) else { return nil}
    var i = 0
    let length = hexString.characters.count

    let data = NSMutableData(capacity: length/2)
    var byteChars: [CChar] = [0, 0, 0]

    var wholeByte: CUnsignedLong = 0

    while i < length {
        byteChars[0] = chars[i]
        i+=1
        byteChars[1] = chars[i]
        i+=1
        wholeByte = strtoul(byteChars, nil, 16)
        data?.appendBytes(&wholeByte, length: 1)
    }

    return data
}

And then as an extension on String:

extension String {

    func dataFromHexString() -> NSData? {
        guard let chars = cStringUsingEncoding(NSUTF8StringEncoding) else { return nil}
        var i = 0
        let length = characters.count

        let data = NSMutableData(capacity: length/2)
        var byteChars: [CChar] = [0, 0, 0]

        var wholeByte: CUnsignedLong = 0

        while i < length {
            byteChars[0] = chars[i]
            i+=1
            byteChars[1] = chars[i]
            i+=1
            wholeByte = strtoul(byteChars, nil, 16)
            data?.appendBytes(&wholeByte, length: 1)
        }

        return data
    }
}

A few questions:

How can I optimize the ugly i+=1 lines?
Is cStringUsingEncoding(NSUTF8StringEncoding) the correct way to get the [CChar] from the string?
Since this is almost a direct translation from Objective-C, is there any way to make this more "Swifty," say by using map or stride, without sacrificing speed?


texts: Project Euler #4: Finding the largest palindrome that is a product of two 3-digit numbers

texts:
Amateur c++ programmer here, working my way through the Project Euler problems (problem 4). I would love for someone to take a look at my ~40 lines of code and give suggestions on improving the effectiveness of the code, and how/what to change to better follow the general guidelines for the flow of a c++ program.
The task states as such: "A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers."
// Largest palindrome product (4)
#include <iostream>
#include <time.h>
bool is_palindrome(int &num) { // Determine if a given number is a palindrome or not
    int reverse=0, copy=num, digit;
    do {
        digit = copy % 10;
        reverse = reverse*10 + digit;
        copy /= 10;
    } while (copy != 0);
    return (reverse == num);
}
int main(void) {
    double time_spent = 0.0;
    clock_t begin = clock();

    int largest_palindrome = 0;
    for (int i=999; i>99; i--) {
        for (int j=999; j>99; j--) {
            if (i < largest_palindrome/1000) { // Optimalization
                // std::cout << "Any value lower than " << i << " will, when multiplied by 999, never exceed the largest palindrome (" << largest_palindrome << ")."<< '\n';
                std::cout << "No larger palindromes possible." << '\n';
                i = 0;
                j = 0;
            } else {
                int product = i*j;
                if (is_palindrome(product) && product>largest_palindrome) {
                    std::cout << "Found palindrome! " << i << " * " << j << " == " << product << '\n';
                    largest_palindrome = product;

                    // More optimalization (no product of the current iteration of i can be larger than the current palindrome, so skip to next iteration)
                    j = 0;
                }
            }
        }
    }

    // Program execution time
    clock_t end = clock();
    time_spent += (double)(end - begin) / CLOCKS_PER_SEC;
    std::cout << "Elapsed time is " << time_spent << " seconds." << std::endl;
    return 0;
}


texts: Min / Max function of 1D array in C / C++

texts:
Due to software constraints, I cannot use the standard libraries, <math.h>, <algorithm>, templates, inline, or Boost. I am also using standard C (ISO C99) such that array is not a reserved keyword like it is in Visual Studio.

Is this the "best" possible implementation of a min function? This needs to be robust and fast. Is there a more efficient C++ implementation?

double min(double* array, int size){
    // returns the minimum value of array
    static double val = array[0];
    for (int i = 1; i < size; ++i){
        val = val <= array[i] ? val : array[i];
    }
    return val;
}


texts: AJAX-based PHP server-side form validation

texts:
I am still a newbie at coding in general. Over the years the amount of programming that I have done in PHP has always been procedural. I am now working on a project for my course, and was hoping to use it as an opportunity to learn OOP since I come across it everywhere.

I am still trying to really get my head around OOP. I understand the basics (I hope).

Here is my very first attempt. I am working on an AJAX based server-side (PHP) form validation. I have tried to write my validation code along OOP principles.

Does this make sense from an OOP perspective?

    require_once 'db.php';

class Registree {

    /*Some of the properties*/
    var $Username;
    var $Email;
    var $Password;
    var $Password_repeat;

    /*Function to check that the $ProposedUsername is not already taken*/
    function checkUsername($ProposedUsername) {

        $this->$username = $ProposedUsername;

        /*Only start checking once the user has entered 4 or more characters into the username field*/
        if (strlen($ProposedUsername) => 4) {

            /*Make a query from the users table based on the $ProposedUsername*/
            $result = mysqli_query($dblink, "SELECT * FROM users WHERE `username` = '$ProposedUsername'")
            or die(mysqli_error($dblink));

            /*If any rows were affected, then this username is taken*/
            if (mysqli_affected_rows($dblink)) > 0) {
                echo 'Username already taken';
            } else {
                    echo 'Username available';
                }
        }
    }
}


texts: NodeJS executing multiple database queries using async library

texts:
I have a use case where I need to run multiple tasks in series. Each task is required to perform some database operations. In my code step_1, step_2 and step_3 are these task which get executed in series (Async Waterfall)
Following is my code
const config = require('config.json');
var mysql = require('mysql');
var async = require("async");

const pool = mysql.createPool({
  host: config.database.dbhost,
  user: config.database.dbuser,
  password: config.database.dbpassword,
  database: config.database.dbname
});

exports.handler = (event, context, callback) => {

    pool.getConnection((err, connection) => {
    if (err) throw new Error("Unable to get connection " + JSON.stringify(err));

      async.waterfall([
            step_1,
            step_2,
            step_3
        ], function (err, result) {
            if(err){
                throw new Error("something went south : "+ JSON.stringify(err));
            }else{
                connection.release();
                callback(null, "SUCCESS: " + JSON.stringify(result));
            }
        });

        function step_1(cb){
            connection.query("step 1 query", function (error, response) {
                      if (error){
                        cb(null,error,null);
                      }
                      let id=result.insertId;
                      cb(null,null,id);
            });
        }

        function step_2(error,id,cb){
            if(error){
                cb(null,error);
            }else{
                connection.query("step 2 query",,function (err,result){
                        if (err){
                          connection.query("error logging query",
                          function(er,result){
                            if (er) cb(null,er,null);
                          });
                          cb(null,err,null);
                        }
                    cb(null,null, id, result);
                });
            }
        }

        function step_3(error, id,result,cb){
            if(error){
                cb(error,null);
            }else{
                connection.query("step 3 query",function(err,result){
                    if (err) cb(err,null);
                    cb(null,result);
                });
            }
        }

    });
};

Although I have used a library to avoid nesting callbacks within callbacks, it still feels like bit callback-ish. Is there a better way to achieve my use case? Anything I can improve in my code, any suggestions please.
I have only included relevant parts of code, kindly let me know if any additional information is required.


texts: Merge dataframes on timestamps and time intervals using data.table in R

texts:
I have two dataframes (x and y) that I need to join, conditional on the timestamp in x falling within the time interval of two columns in y.  I've accomplished this using data.table::foverlaps() by adapting some of the code in this stackexchange question), but in order to get it to work on my data I had to set the key of data.table x, which according to the documentation of foverlaps(), isn't supposed to be necessary.

Am I using this foverlaps()incorrectly? If so, new ideas for how to accomplish this data merging task are welcome.

library(data.table)

Data snippets

x <- structure(list(TagID = c(20161L, 23055L, 45428L, 2627L), DateTimePST = structure(c(1415481096,
1380768444, 1474560076, 1511384035), class = c("POSIXct", "POSIXt"
), tzone = "Pacific/Pitcairn"), Receiver = c(102140L, 112568L,
112568L, 121907L)), class = "data.frame", row.names = c(NA, -4L
))

y <- structure(list(Station = c("YBAAG4", "YBAAG4", "YBCSSW", "YBCSSW",
"YBBCD", "YBAWW"), Receiver = c(102140L, 102140L, 112568L, 112568L,
121907L, 121907L), Start = structure(c(1464979020, 1409256300,
1369945920, 1470761034, 1505494980, 1409246700), class = c("POSIXct",
"POSIXt"), tzone = "Pacific/Pitcairn"), End = structure(c(1473357300,
1421878500, 1382638020, 1479838293, 1513282440, 1421871360), class = c("POSIXct",
"POSIXt"), tzone = "Pacific/Pitcairn")), class = "data.frame", row.names = c(NA,
-6L))

# preview data
> x
  TagID         DateTimePST Receiver
1 20161 2014-11-08 13:11:36   102140
2 23055 2013-10-02 18:47:24   112568
3 45428 2016-09-22 08:01:16   112568
4  2627 2017-11-22 12:53:55   121907

> y
  Station Receiver               Start                 End
1  YBAAG4   102140 2016-06-03 10:37:00 2016-09-08 09:55:00
2  YBAAG4   102140 2014-08-28 12:05:00 2015-01-21 14:15:00
3  YBCSSW   112568 2013-05-30 12:32:00 2013-10-24 10:07:00
4  YBCSSW   112568 2016-08-09 08:43:54 2016-11-22 10:11:33
5   YBBCD   121907 2017-09-15 09:03:00 2017-12-14 12:14:00
6   YBAWW   121907 2014-08-28 09:25:00 2015-01-21 12:16:00

Because some Receiver numbers are associated with more than one Station, it is important to merge these two datasets on the timestamp (DateTimePST), not on the receiver number.

Prep data

x <- as.data.table(x); x$Start = x$DateTimePST; x$End = x$DateTimePST # needs these start and end columns, otherwise foverlaps throws an error
y <- as.data.table(y)
# set keys: if I omit setting the key on x, forverlap() throws an error
setkey(y, Start, End); setkey(x, Start, End)

foverlaps() join, then discard incorrect Receiver pairs

result <- data.frame(foverlaps(x, y, type = "within"))
result <- result[result$Receiver == result$i.Receiver, ] # this filters down to the correct receiver matches

Clean up results

rm_col <- c("i.Receiver", "i.Start", "i.End")
result <- result[ , !(colnames(result) %in% rm_col)]
result

Station Receiver               Start                 End TagID         DateTimePST
1  YBCSSW   112568 2013-05-30 12:32:00 2013-10-24 10:07:00 23055 2013-10-02 18:47:24
3  YBAAG4   102140 2014-08-28 12:05:00 2015-01-21 14:15:00 20161 2014-11-08 13:11:36
4  YBCSSW   112568 2016-08-09 08:43:54 2016-11-22 10:11:33 45428 2016-09-22 08:01:16
5   YBBCD   121907 2017-09-15 09:03:00 2017-12-14 12:14:00  2627 2017-11-22 12:53:55

Wrap in a function:

getStation <- function(x, y) {
  x <- as.data.table(x); x$Start = x$DateTimePST; x$End = x$DateTimePST
  y <- as.data.table(y)
  setkey(y, Start, End); setkey(x, Start, End)
  result <- data.frame(foverlaps(x, y, type = "within"))
  result <- result[result$Receiver == result$i.Receiver, ]
  result <- result[ , !(colnames(result) %in% c("i.Receiver", "i.Start", "i.End"))]
}

res <- getStation(x, y)


texts: Angular directive to toggle sidebar visibility based on window width

texts:
I changed the normal way of using Angular. I'm using my controllers just to talk to my API routes and am using directives to manipulate the data and DOM as well.

I am using the object literal pattern where I have my INIT method that initializes global variables (object) and then calls other methods, bind clicks methods, etc. So, the logic is all the directives.

I'm finding it very confusing and would like the opinion of someone better.

'use strict';
var eventSidebarDirective = {

    /**
     * Initialize sidebar directive and return the link
     * calling all nested methods.
     *
     */
    init: function() {
        return {
            link: function(scope) {
                scope.$watch('events', function() {
                    if (scope.events === undefined) {
                        return;
                    }

                    /**
                     * Every time the user access the event page, this methods
                     * will be called.
                     *
                     */
                    EventSidebar.init();
                });
            },
            restrict: 'M'
        };
    }
};

var EventSidebar = {
    init: function() {
        this.element        = $('[data-event-sidebar]');
        this.indicator  = $('[data-event-sidebar-to]');

        /**
     * To manipulate the element, bind a click in the indicator.
     *
     */
        this.indicator.bind('click', this._toggle.bind(this));
    },

    _toggle: function(e) {
        var state = $(e.currentTarget).data('event-sidebar-to');

        this.element
            .css({

                /**
                 * If the window width is less than 768px, i just want toggle
                 * between display block and none.
                 *
                 */
                display: 768 >= $(window).width()
                        ? (state
                            ? 'block'
                            : 'none')
                        : false
            })
            .animate({

                /**
                 * But if the window.width is bigger the 768px, i want show
                 * or hide the sidebar.
                 *
                 */
                right: 768 <= $(window).width()
                        ? (state
                            ? '0'
                            : '-500')
                        : false
            });
    }
};

angular
    .module('adminApp')
    .directive('eventSidebarDirective', eventSidebarDirective.init.bind(eventSidebarDirective));


texts: Remove elements existing in a list built from an enum

texts:
The objective of this code is to make the difference inbetween two lists of items, that is knowing which items are missing in the second list in regards to the first one.

The first list is built from an enumerator with the following method:

keysToPress = Enum.GetValues(enumType).ToList();

Once this list is built, now the second list, the one we desire to compare has to be retrieved. In my code, I ask a device I am testing the information of a  register. Processing this register returns me a list of type enumType.

// ReadKeyboard method retrieves a list of all the keys that have been
// pressed at least one time during the device test.
// (Read notes to know why the code is missing, I feel like it is not needed)
keysPressed = GetKeyList();

Once both list have been retrieved, I only have to make the difference in between them with the following code:

keysPressed.ForEach(x=> keysToPress.Remove(x));

This way, I remove every item in the keysPressed list from the keysToPress list.

The resulting code is as follows:

private List<enumType> CheckKeysToPress()
{
    List<enumType> keysToPress = Enum.GetValues(typeof(enumType)).Cast<enumType>().ToList();

    // ReadKeyboardMask returns a enumType list
    List<enumType> keysPressed = GetKeyList();

    // Here I try to remove all the items in the keysPressed list from the keysToPress list
    keysPressed.ForEach(x=> keysToPress.Remove(x));

    return keysToPress;
}

As you can see, the return value of the method is a list of all remaining keys to press.

An example for the following code, given the enum:

[Flags]
public enum Keys
{
    NONE = 0x0000,
    UP = 0x0001,
    DOWN = 0x0002,
    LEFT = 0x0004,
    RIGHT = 0x0008,
    OK = 0x0010,
    POWER = 0x0020
}

The keysToPress list would have the following items:

NONE
UP
DOWN
LEFT
RIGHT
OK
POWER

With a reading from the device that returns a list with the following items.

UP
DOWN
LEFT
RIGHT

would output the following list:

NONE
OK
POWER

I want to know, as the information retrieved is a set of bit flags, if it is better to provide the bit flags and then remove those items that match the enum, to optimise and make less error prone the code.

Note: The code regarding GetKeyList() is missing because  it is a function that interacts with a device to retrieve information from it communicating through ModBus protocol.


texts:
I am working on a node.js sails.js app that handles a number of API calls and uses Bluebird for promises. The API calls have been reliable but I would like to build in handling for if they do not respond. I'm wondering if there is a good standard practice for handling timeouts (or a different approach) if the API services are down or do not respond.

Here is the code I have found/modified to work with, 15000 is a 15 second timeout on the API. Is this approach good, is there a better way?

var Promise = require('bluebird');

return new Promise(function (resolve, reject) {
  //resolve my API call here.
})
.timeout(15000)
.cancellable()
.catch(Promise.CancellationError, function(error) {
  // ... must neatly abort the task ...
  console.log('Task cancelled', error);
})
.catch(Promise.TimeoutError, function(error) {
  // ... must neatly abort the task ...
  console.log('Task timed out', error);
});


texts: Add currency fields to get a subtotal, then add other values but only if the relevant checkbox is checked

texts:
I have some currency fields which need to be added together. However, some of them have a checkbox nearby. If this is ticked, the field is added to the subtotal, if not, nothing is added.

I'm currently using the code below, which works, but doesn't seem very elegant or easy to maintain. I'm sure there is an easier way but I'm struggling to think of any other methods to use. There will be more checkboxes added later on, which will only lengthen the code. The below example is for two checkboxes.

decimal ditem1Cost = 0;
bool item1Checked = false;
if (Item1RateYN.Checked) {
    if (decimal.TryParse(item1Cost.Value.ToString(), out ditem1Cost))
        item1Checked = true;
}

decimal ditem2Cost = 0;
bool item2Checked = false;
if (Item2RateYN.Checked) {
    if (decimal.TryParse(item2Cost.Value.ToString(), out ditem2Cost))
        item2Checked = true;
}
//Add up some values which are always part of the subtotal
decimal subtotals = val1 + val2 + val3 + val4 + val5 + val6 + val7 + val8;

//Only add the ones which are near the checkboxes, if the checkbox is checked
subtotals = item1Checked ? subtotals + ditem1Cost : subtotals;
subtotals = item2Checked ? subtotals + ditem2Cost : subtotals;


texts:
I'm working on a problem of finding the minimal numbers of airplanes needed, given the schedule of each flight, while schedules may overlap. For example, schedule (0,1) means a flight starts at clock 0 and lands at clock 1.

The major idea is to find the max overlap. Any advice is highly appreciated, in terms of code bug, performance improvements in terms of time complexity and code style.

One specific issue I have in my code and want to see if any improvement area is that I am using schedule_map_start and schedule_map_end to track both start time and end time. Since for flight schedule (0, 1) and (1, 2), at 1 clock, there should be one flight other than zero flight needed. If I use a single schedule_map, the value of 1 clock will be 0 other than 1. If there are any better ideas to improve the code and using only one schedule_map, it will be great.

In the example of below program, output is 3 since minimal 3 air planes are needed, since for the following 3 schedule -- (6,9),(6,9),(7,10), they are overlap with each other, in other words, it means needs at least 3 air planes operates at the same time.

import sys
from collections import defaultdict
def find_max_overlap(flight_schedules):
    schedule_map_start = defaultdict(int)
    schedule_map_end = defaultdict(int)
    start_min = sys.maxint
    end_max = -sys.maxint - 1
    for s in flight_schedules:
        start_min = min(start_min, s[0])
        end_max = max(end_max, s[1])
        schedule_map_start[s[0]] += 1
        schedule_map_end[s[1]] -= 1
    cur_value = 0
    result = 0
    for i in range(start_min, end_max+1):
        cur_value += schedule_map_start[i]
        result = max(cur_value, result)
        cur_value += schedule_map_end[i]
        result = max(cur_value, result)

    return result

if __name__ == "__main__":
    schedules = [(0,1),(1,2),(2,5),(4,5),(6,9),(6,9),(7,10)]
    print find_max_overlap(schedules)


texts: Printing out JSON data from Twitter as a CSV

texts:
I'm extremely new to Python, and the Twitter API, but I found an example online that walked me through the process. Now that I've been playing around with it for awhile, I've begun to push the limits of what my laptop can handle in terms of processing power with my current code. I was hoping someone here could check over it and make recommendations on optimizing it.

Goal: Take JSON output from the Twitter streaming API and print out specific fields to a CSV file. (The sysarg is used to pass the input and output filenames).

# import necessary modules
import json
import sys

# define a new variable for tweets
tweets=[]

# import tweets from JSON
for line in open(sys.argv[1]):
    try:
        tweets.append(json.loads(line))
    except:
        pass

# print the name of the file and number of tweets imported
print "File Imported:", str(sys.argv[1])
print "# Tweets Imported:", len(tweets)

# create a new variable for a single tweets
tweet=tweets[0]

# pull out various data from the tweets
tweet_id = [tweet['id'] for tweet in tweets]
tweet_text = [tweet['text'] for tweet in tweets]
tweet_time = [tweet['created_at'] for tweet in tweets]
tweet_author = [tweet['user']['screen_name'] for tweet in tweets]
tweet_author_id = [tweet['user']['id_str'] for tweet in tweets]
tweet_language = [tweet['lang'] for tweet in tweets]
tweet_geo = [tweet['geo'] for tweet in tweets]

#outputting to CSV
out = open(sys.argv[2], 'w')
print >> out, 'tweet_id, tweet_time, tweet_author, tweet_author_id,    tweet_language, tweet_geo, tweet_text'

rows = zip(tweet_id, tweet_time, tweet_author, tweet_author_id,    tweet_language, tweet_geo, tweet_text)

from csv import writer
csv = writer(out)

for row in rows:
    values = [(value.encode('utf8') if hasattr(value, 'encode') else value) for value in row]
    csv.writerow(values)

out.close()

# print name of exported file
print "File Exported:", str(sys.argv[2])


texts: Very unorthodox placement of if-else clauses in C for handling special cases

texts:
I've encountered a situation with an if-else clause. Specifically, the positive case has only 1 expression, whereas the negative case is a sequence of statements wrapped in braces. Like this:
if( i >= list->count ) *result = 0; else
{
    *result = i * 32 + 31;
    while( mask >> (*result % 32) ) (*result)--;
}

I personally don't see this as bad formatting, as it's common to see something like this in POSIX shell scripts:
if [ "not-null-string" ] ; then
    # the "then" clause didn't start on a new line
    commands >redirections | pipeline
fi

And sometimes, the condition can be even more complex in shell scripts (at least, I may write that way if I see fit and logically intuitive)
But I know, the better style of writing that if-else clause should be like this:
if( i < list->count )
{
    *result = i * 32 + 31;
    while( mask >> (*result % 32) ) (*result)--;
}
else *result = 0;

So is there some kind of strong arguments against if-else clause formatting such as that in my first fragment of C code?


texts:
I want to interpolate temperature in correlation with height. I have temperature data from stations with coordinates and height in this format:

Lat     Lon     Temp     Height

46.2956 16.3978 10.71196 120

45.9776 16.0159 11.78539 150

45.8521 15.9598 11.18838 133

etc.

After reading the data there are 4 arrays (y, x, temp, and height) and variable z which represents correlation between temperature and height, e.g., z = -0.005 which means that for each meter of height temperature decreases for 0.005 °C.

Z is calculated like this: z = np.polyfit(height, temp, 1,2)

After that I can calculate temperature on 0 meters for each station:

for i in range(len(temp)):
            temp0m.append((temp[i])-(height[i]*z))

I also have data with heights in meters with resolution of 0.003333333333 degrees and I want to use these heights and interpolated temperature to create map.

Heights are in "dem_final2.txt" (ncolums = 2700, nrows = 1560)

1653 1571 1493 1429 1354...
1730 1699 1620 1528 1399...

So this is what I've done so far, everything is working but it's very slow:

if __name__ == '__main__':
    nx, ny = 1080,624
    chunkSize = 10
    t = []
    grid2 = []
    xEast = 12
    ySouth = 42
    xWest = 21
    yNorth = 47.2
    res = 0.003333333333
    x,y,temp0m,z = downloadData()

    xi = np.linspace(xEast+0.1, xWest-0.1, nx)
    yi = np.linspace(ySouth+0.1, yNorth-0.1, ny)
    xi, yi = np.meshgrid(xi, yi)
    xi, yi = xi.flatten(), yi.flatten()

    l = len(xi)/chunkSize
    for i in range(chunkSize):
        interp = rbfInterp(x,y,temp0m,xi[(l*i):(l*(i+1))],yi[(l*i):(l*(i+1))])
        grid2 = grid2 + list(interpData(xi[(l*i):(l*(i+1))],yi[(l*i):(l*(i+1))],z,interp,xEast,ySouth,xWest,yNorth,res))[(l*i):(l*(i+1))]

    grid2 = np.array(grid2, np.float)
    grid2 = grid2.reshape((ny, nx))
    plot (x,y,temp0m,grid2) #plotting to png with matplotlib

def rbfInterp(x, y, temp0m,xi,yi):
    interp = Rbf(x, y, temp0m, function='linear')
    return interp(xi,yi)

def interpData(xi,yi,z,interp,xEast,ySouth,xWest,yNorth,res):
    append = t.append
    row= -1
    for i in xrange(len(xi)):
        tmp = int(round((yi[i]-ySouth)/res,0))
        tmp1 = int(round((xi[i]-xEast)/res,0)+1)
        if (row!=tmp):
            tmp2 = linecache.getline('dem_final2.txt', tmp).split(' ')
        if (float(tmp2[tmp1])>-10):
            append ((float(tmp2[tmp1]))*z+float(interp[i]))
        else:
            append (None)
        row = tmp
    return t

I divided into chunks because a lot of memory was used without them and I think this can be used to speed up things maybe with more processes or something like that but I don't have knowledge to do that without any help. Of course, any other help is also welcome.

Btw this script runs for about 25-30 sec


texts: Get better conclusions from a javascript randomizer

texts:
I have a simple javascript randomizer that compares two random numbers with values 1 to 6.

I want to get a good estimate about the probability of the first been greater than the second. I could do it using math, probability theory e.t.c. but lets say that I want to stick to javascript. Using millions or billions of itterations gives better estimates but I can't push that too far (especially since codepen, jsFiddle e.t.c. don't allow that many). Am I missing something? Is there a better way to estimate this probability? Right now, I just run the program (with 1000 itterations) a couple of times and calculate the average value but that gives values in quite a wide range, I'd like to get more restricted results.

var xIsGreater = 0;
var yIsGreater = 0;
for(j=0;j<1000;j++){
  var x = Math.floor(Math.random() * 6) + 1  ;
  var y = Math.floor(Math.random() * 6) + 1  ;
  if(x>y){
    xIsGreater++;
  }else if(y>x){
    yIsGreater++;
  }
}
var draw = 1000-xIsGreater-yIsGreater;
console.log(xIsGreater+'--'+yIsGreater+'--'+draw);


texts: Populating a vector with alternating numbers

texts:
This code inserts the number 4 into a vector's even indexes.

vector<double> vecCoeffs;
    // Put the coefficient 4 into each even index and 2 for each odd index
    for(int i = 0; i <= 10; i++){
        vecCoeffs[i];
        if(i % 2 == 0 ){
            vecCoeffs.push_back(4);
        }else{
            vecCoeffs.push_back(2);
        }
        // Starting and ending with coefficient 1
        vecCoeffs[0] = 1;
        vecCoeffs[10] = 1;


texts: Sorting a 2-dimensional array with counting sort

texts:
The task I'm solving is:

Sort a list by its keys
Print out the corresponding values on one line separated by whitespace
Replace the values of the first half of the input to "-"
Use Counting Sort

The following code works, but times out when given 1 million entries:

public class Solution {

static String[] countingSort(String[][] arr) {
    String[] result = new String[arr.length];
    int[] count = new int[100];
    for(int i=0;i<arr.length;i++) {
        count[Integer.parseInt(arr[i][0])]++;
    }
    for(int i=1;i<count.length;i++) {
      count[i] += count[i-1];
    }
    for(int i=arr.length-1;i>=0;i--) {
        result[count[Integer.parseInt(arr[i][0])]-1] = arr[i][1];
        count[Integer.parseInt(arr[i][0])]--;
    }
    return result;
}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    String[][] arr = new String[n][2];
    for(int a0 = 0; a0 < n; a0++){
        int a = in.nextInt();
        arr[a0][0] = Integer.toString(a);
        if(a0<n/2) {
            String s =in.next();
            arr[a0][1] = "-";
        } else {
            String s = in.next();
            arr[a0][1] = s;
        }
    }
    in.close();
    String[] result = countingSort(arr);
    for(int i=0;i<result.length;i++) {
        System.out.print(result[i]+" ");
    }
}

input is being put into 2 dimensional array. values are being replaced with "-" for first half of the values. [array: arr]
Array is passed to method [array: arr, method: countingSort]
New array of size 100 is being created as the keys are 0 < key < 100 [array: count]
occurrences of each key are added in the newly created array [array: count]
values of the array are being accumulated [array: count]
the values of the corresponding key are being sorted into the result array according to the count array.
result is being returned.

Particular concerns:

How can the code be improved in order to increase performance and avoid timeout using counting sort?
Are there any other possibilities (sorting algorithms) which have higher performance (can solve the problem faster)?


texts: Map Character to Characters Most Frequently Found With it (in list of strings)

texts:
For an interview, I was tasked with writing a program that consumes a list of strings, and produces a mapping between every character in the list, and the characters found most frequently with it (let's call them Companion Characters).

For example, if it was given ["aabc", "bcdddd", "cde"], it would return {a=[b, c], b=[c], c=[b, d], d=[c], e=[c, d]}. a maps to b, c because they were together in the first word, b maps to c because they were together in two words ("aabc" and "bcddd"), while a and d were only with it for one word, etc.

To solve it, I used two HashMaps – One which mapped every character to a map of companion characters, to integers (the number of times found), and another which mapped character to the list of companion characters found most frequently with it. My code (which compiles and works) is below.

import java.util.*;

public class MaxMap {
   private Map<Character, Map<Character, Integer>> charMap;
   private Map<Character, List<Character>> maxMap;

   public MaxMap() {
       charMap = new HashMap<>();
       maxMap = new HashMap<>();
   }

   public void computeMap(List<String> strs) {
       for(String str: strs) {
           //Will contain all of the starting letters encountered in the string
           Set<Character> seenOriginal = new HashSet<>();
           for(int i = 0; i < str.length(); i++) {
               char original = str.charAt(i);
               if(!charMap.containsKey(original)) {
                   charMap.put(original, new HashMap<>());
               }
               //Haven't yet calculated the mappings for this character - and dups don't matter
               if(!seenOriginal.contains(original)) {
                   seenOriginal.add(str.charAt(i));
                   Set<Character> seenMapping = new HashSet<>();
                   for(int j = 0; j < str.length(); j++) {
                       //This is the same character, or a character previously encountered.
                       if(i == j || str.charAt(i) == str.charAt(j) || seenMapping.contains(str.charAt(j))) continue;
                       char added = str.charAt(j);
                       seenMapping.add(added);
                       int num = charMap.get(original).getOrDefault(added, 0);
                       num++;
                       charMap.get(original).put(added, num);
                       setMaxMapping(original, added);
                   }
               }
           }
       }
   }

   public void setMaxMapping(char original, char added) {
       List<Character> current = maxMap.getOrDefault(original, new ArrayList<>());
       int oldCount = 0;
       if(current.size() > 0) {
           oldCount = charMap.get(original).get(current.get(0));
           //Special case, in case the first char in list was the one adjusted
           if(current.get(0) == added) {
               oldCount--;
           }
       }

       int addedCount = charMap.get(original).get(added);
       if(addedCount > oldCount) {
           current = new ArrayList<>(Arrays.asList(added));
       } else if (addedCount == oldCount) {
           current.add(added);
       }
       maxMap.put(original, current);
   }

   public Map<Character, List<Character>> getMaxMap() {
       return this.maxMap;
   }
}

The main class which constructed and called it is

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        List<String> strings = new ArrayList<>(Arrays.asList("aabc", "bcdddd", "cde"));
        MaxMap mm = new MaxMap();
        mm.computeMap(strings);
        System.out.println(mm.getMaxMap());
    }
}

I didn't get the job, because my code wasn't optimal enough. How should I improve it?


texts:
I have tried to implement a Bloom Filter in Java here.

https://github.com/srirammanoj/skynet/tree/master/bloomfilter

I just wanted to know if my implementation can be called  'thread-safe' , and if there is an improvement to be made on the locking I have used here. I opted for locks instead of 'sychronized', as I wanted multiple simultaneous reads. I tried to minimize the section of the code inside the lock.

The optimistic read lock of Stamped Lock seems fragile and will give me erroneous reads and I would rather block a read than fail it and retry.

I wanted to know if there is an obvious improvement to be made here.

The actual methods in the code containing the lock. ----

private void addElement(byte[] element) {
    if (null == element) {
        throw new NullPointerException();
    }

    long hash1 = Integer.toUnsignedLong(Murmur3Hash.murmurhash3_x86_32(element, 0, element.length, filterParams.seed1));
    long hash2 = Integer.toUnsignedLong(Murmur3Hash.murmurhash3_x86_32(element, 0, element.length, filterParams.seed2));

    writeLock.lock();
    try {
        for (int i = 1; i <= filterParams.k; i++) {
            long hash = hash1 + i * hash2;

            int mod = ( int ) ( hash % filterParams.bucketLength );

            int offset = (i - 1) * filterParams.bucketLength;

            int index = offset + mod;
            bitSet.set(index);
        }

        elementsAdded++;
    } finally {
        writeLock.unlock();
    }

}

public boolean containsElement(byte[] element) {
    if (null == element) {
        throw new NullPointerException();
    }

    long hash1 = Integer.toUnsignedLong(Murmur3Hash.murmurhash3_x86_32(element, 0, element.length, filterParams.seed1));
    long hash2 = Integer.toUnsignedLong(Murmur3Hash.murmurhash3_x86_32(element, 0, element.length, filterParams.seed2));

    readLock.lock();
    try {
        for (int i = 1; i <= filterParams.k; i++) {
            long hash = hash1 + i * hash2;

            int mod = ( int ) ( hash % filterParams.bucketLength );
            int offset = (i - 1) * filterParams.bucketLength;
            int index = offset + mod;
            if (index < 0)
                index = -index;

            if (!bitSet.get(index)) {
                return false;
            }
        }
    } finally {
        readLock.unlock();
    }

    return true;
}

Thanks.


texts: Bash - Automating creation of test files

texts:
I'm in the process of understanding shell scripting - this is my simple code for adding test files for python unittest
I'm looking for best practice pointers, variable naming, and of course comments on structure and readability.
EDIT: Script is called by, for example
./create_tests.sh math tensor_add

dir_name="$1"
file_name="$2"
test_dir="test/${dir_name}"
file_in_dir="${test_dir}/${file_name}.py"

addFile() {
    if [[ -f "${file_in_dir}" ]]
    then
        echo "File already exists in directory, exiting."
        exit 0
    else
        touch "${file_in_dir}"
    fi
}

if [[ -d "${test_dir}" ]]
then
    echo "Directory already exists, adding the file to this directory."
    addFile
else
    echo "Directory and __init__.py created."
    mkdir "${test_dir}"
    touch "${test_dir}/__init__.py"
    addFile
fi