texts:
This question is related to this topic.

Context:

class OperationDevice(Device):
    def __init__(self):
        super(OperationDevice, self).__init__()

    def operation_start(self):
        # Do operation specific code
        self.start()

    def operation_stop(self):
        # Do operation specific code
        self.stop()

class SimulationDevice(Device):
    def __init__(self):
        super(SimulationDevice, self).__init__()

    def simulation_start(self):
        # Do simulation specific code
        self.fsm.start()

    def simulation_stop(self):
        # Do simulation specific code
        self.fsm.stop()

class DualModeDevice(OperationDevice, SimulationDevice):
    def __init__(self, mode='simulation'):
        super(DualModeDevice, self).__init__()
        self._mode = mode
        self._start_map = {
            'simulation': self.simulation_start,
            'operation': self.operation_start
        }
        self._stop_map = {
            'simulation': self.simulation_stop,
            'operation': self.operation_stop
        }

    def start(self):
        self._start_map[self._mode]()

    def stop(self):
        self._stop_map[self._mode]()

Here I have to define in OperationDevice and SimulationDevice different method name like simulation_start and operation_start (because of MRO).

I actually want to define the same method name for both class and be able to call each one from DualModeDevice or subclasses.
For example operation_start from OperationDevice and simulation_start from SimulationDevice will become start. Is it possible and how?
This solution is a way to switch between class OperationDevice and SimulationDevice following value of mode. I am wondering wether is it possible to define automatically all method from SimulationDevice linked with mode = "simulation" (same for OperationDevice with "operation") without having to specify for each method (self._start_map for example) in constructor (init) of DualModeDevice.


texts:
I have written a code which works very good for small data-files (see below). The data file 'WSPL.dat' which I want to evaluate has a size of 2.6 GB and the data file  'VELOC.dat' has a size of 4.3 GB. The production of the data 'inputv.dat' takes almost 45 minutes and it has a size of 2.6 GB. At the final step, the code should produce a 'output_veloc_max.dat'. After 30 hours of calculations the last output could not be produced. Nothing was written in the final data. I can imagine that the opening of such a big data and writing a new data which grows continusly can lead to this problem.

My questions:

Can I optimize this code in such a way that it works faster?
If the code cannot be further optimized, should I rewrite the code in multiprocessing code?
If rewriting for multi processing helps, how should I do it?

from __future__ import print_function
import time
import re
c=[]

def get_num(x):
    return int(''.join(ele for ele in x if ele.isdigit()))

with open('WSPL.dat', 'r') as f:
    for line in f:
            if "ND" in line:
                print(line)
                c=get_num(line)
                print(c)
                break

linenum = 0
print("Anzahl der Knoten: ",c)

print('Program started.\n')
maxima = [[float('-inf'), ''] for _ in range(c)]

with open('WSPL.dat') as f:
    for line in f:
        if line.startswith('TS'):
            for maximum, line in zip(maxima, f):
                linenum += 1
                value = float(line)
                if value > maximum[0]:
                    maximum[:] = value, linenum,line

with open('VELOC.dat', 'r') as f, open('inputv.dat', 'w') as outfile:
    for line in f:
        try:
            line = line.strip()
            columns = line.split()
            vx = float(columns[0])
            vy = float(columns[1])
            print("{:.2f}\t{:.2f}".format(vx, vy), file=outfile)
        except ValueError:
            pass

linenum=[x[1] for x in maxima]
i=1
d = {}
with open('inputv.dat', 'r') as f5, open('output_veloc_max.dat', 'w') as out:
    out.write('VECTOR\nND    {0:2d}\nST  0\nTS      0.00\n'.format(c))
    for num, line1 in enumerate(f5, 1):
        if num in linenum:
            d[num] = line1
    out.writelines([d[i] for i in linenum])

print('Programm ist beendet.')
name3 = input("Eingabedatei drucken ")

A very small example for 'WSPL.dat' can be like this:

SCALAR
ND    3
ST  0
TS        10.00
    666.0000
    0.0000
    0.0000
SCALAR
ND    3
ST  0
TS      3600.47
  355.1744
  255.0201
  255.2748
SCALAR
ND    3
ST  0
TS      7200.42
  555.5984
  255.4946
  355.7014

A very small example for 'VELOC.dat' can be like this:

VECTOR
ND    3
ST  0
TS        10.00
   0.000   0.000
   0.000   0.000
   0.000   0.000
VECTOR
ND    3
ST  0
TS      3600.47
  -0.280   1.385
  -0.494   1.239
  -0.574   1.647
VECTOR
ND    3
ST  0
TS      7200.42
  -0.609   2.114
  -0.900   1.734
  -0.871   2.293

The lines under the TS in VLOC.dat and WSPL.dat belong to a node. for this small example we got 3 nodes (ND=3). The program finds the maximum value for each node in WSPL.dat and writes the line numbers in inputv.dat. Then opens the inputv.dat and VLOC.dat and finds the values for the given line numbers and write in another file 'output_veloc_max.dat'.


texts:
Is there a way to write this simpler?

if(criteria.SortBy =="name")
{
    if (criteria.SortDirection == "ascending")
    {
        physicians.Sort((x, y) => string.Compare(x.Name, y.Name));
    }
    else
    {
        physicians.Sort((x, y) => string.Compare(y.Name,x.Name ));

    }
}

if (criteria.SortBy == "birth")
{
    if (criteria.SortDirection == "ascending")
    {
        physicians.Sort(new Comparison<Physician>((x, y) => DateTime.Compare(x.DateOfBirth ?? DateTime.MinValue,y.DateOfBirth ?? DateTime.MinValue)));
    }
    else
    {
        physicians.Sort(new Comparison<Physician>((x, y) => DateTime.Compare(y.DateOfBirth ?? DateTime.MinValue, x.DateOfBirth ?? DateTime.MinValue)));

    }
}


texts: Optimization over 7 constants, running a function 10,000,000 times

texts:
I am not quite sure how to attach my data, but it is 5737 observations of 3 variables. Variables V and P are strictly < 0, and variable R is -2 < R < 2.

The last function, correcttot, will help me find the optimal constants, or ranges of constants, for this function. However, the function that it runs over, percentcorrect, takes several seconds to run, which means that repeating it 10,000,000 times is not feasible.

Data

setwd("~/Desktop")
dat<-read.csv(file="data.csv",sep=",",header=T)
attach(dat)
###################################################################################
voltoalph<-function(v,c){  # Where V is a data vector and C is a constant
  alpha<-c(rep(0,length(v)))
  for(i in 1:length(v)){
    alpha[i+1]<-abs(c*(v[i]/max(v,na.rm=TRUE)))
  }
  alpha
}
voltoenen<-function(v,c){  # Where V is a data vector and C is a constant
  enen<-c(rep(1,length(v)))
  for(i in 1:length(v)){
    enen[i+1]<-abs((v[i]/max(v,na.rm=TRUE)))
  }
  enhelp<-1/(enen)
  enhelp2<-c*(enhelp/max(enhelp))
  enhelp2
}

ema<-function(v,n,a){     # Where V is a data vector and n is a contant and a is a constant
  avevec<-c(rep(0,n))
  for(i in 1:n){
    avevec[i]<-((1-a[i])^(n-i))*v[i]}
  divvec<-c(rep(0,n))
  for(i in 1:n){
    divvec[i]<-((1-a[i])^(n-i))
  }
  sum(avevec)/sum(divvec)
}
betaema<-function(v,n,a,l){ # Where V is a data vector and n,a,l are constants
  secondvec<-c(rep(0, length(v)))
  for(i in l:length(v)){
    secondvec[i]<-ema(v[(i-n[i]+1):i],n[i],a)
  }
  secondvec
}
#################################################################################################################
howright<-function(v,r,c,l){   # Where v and r are data vectors and c,l are constants
  rightvec<-0
  for(i in l:(length(r)-c)){
    if((v[i]*mean(r[i+1]:r[i+c]))>0){
      rightvec<-rightvec+1
    }
    else{
      rightvec<-rightvec
    }
  }
  rightvec/(length(r)-l-c)
}
#################################################################################################################
percentcorrect<-function(ca1,ca2,cn1,cn2,e,d,c,v,p,r){   ###V, P, and R are data vectors, rest constant
  vol1<-voltoalph(v,ca1)
  vol2<-voltoalph(v,ca2)
  ens1<-voltoenen(v,cn1)
  ens2<-voltoenen(v,cn2)
  als<-c(vol1)
  als2<-c(vol2)
  n1<-c(ens1)
  n2<-c(ens2)
  anotherema1<-betaema(p,n1,als,max(cn1,cn2))
  anotherema2<-betaema(p,n2,als2,max(cn1,cn2))
  slope1<-c(rep(0,length(p)))
  slope2<-c(rep(0,length(p)))
  for(i in (max(cn1,cn2)+d):length(anotherema1)){
    slope1[i]<-(anotherema1[i]-anotherema1[i-d])/d
  }
  for(i in (max(cn1,cn2)+e):length(anotherema2)){
    slope2[i]<-(anotherema2[i]-anotherema2[i-e])/e
  }
  sig<-slope1-slope2
  hvec<-howright(sig,r,c,max(cn1,cn2))
  hvec
}
##########################################################################################
correcttot<-function(v,p,r){    ###Where v, p, and r are data vectors
  correct3<-array(0,dim=c(10,10,10,10,10,10,10))
  for(i in 1:10){
    for(j in 1:10){
      for(k in 1:10){
        for(l in 1:10){
          for(m in 2:10){
            for(n in 2:10){
              for(o in 1:10){
                correct3[i,j,k,l,m,n,o]<-percentcorrect((i/10),(j/10),(20*k),(20*l),m,n,o,v,p,r)
              }
            }
          }
        }
      }
    }
  }
  print(correct3)
}
newvec<-correcttot(vl,p,rt)  # run it on the vectors vl, p and rt
which(newvec==max(newvec2),arr.ind=TRUE)


texts:
Recently, our High School teacher gave us a pseudocode assignment for the preparation of CAIE's which was a Railway Management System. Everyone completed the task in pseudocode which for me was quite an inflexible program. So I tried my own code which is very much flexible than others. It took me a day to complete the code but there were some bugs and errors which took me almost another day to fix. Hence, can anyone comment on my code and my programming skills? And guide me with some improvements where necessary?
departure = ['09:00', '11:00', '13:00', '15:00'] # Timings of Train Departures
arrival = ['10:00', '12:00', '14:00', '16:00'] # Timings of Train Arrivals
depart_trains = 4
arrival_trains = 4
coaches = 6
total_seats = 80
total_passengers = [0]*len(departure)
ticket_price = 25

while departure:
    print(f"""{depart_trains} trains departing at: {departure}
{arrival_trains} trains arriving at: {arrival}
Price of Ticket/person: {ticket_price} dollars
Each Train has {coaches} coaches, each coach holding {total_seats} passengers :)
""")
    commute = input("Enter Departure time: ").strip()
    if commute in departure:
        index_train = departure.index(commute)
        print(f"""You chose Train departing at: {departure[index_train]}
""")
        run = True
        while run:
            current_passengers = int(input("How many passengers are to sit: "))
            if current_passengers <= coaches*total_seats:
                total_passengers[index_train] += current_passengers
                if total_passengers[index_train] == coaches*total_seats:
                    departure.remove(departure[index_train])
                    arrival.remove(arrival[index_train])
                    total_passengers.pop(index_train)
                    depart_trains -= 1
                    arrival_trains -= 1
                    print(f"""Your total price is: {current_passengers*ticket_price} dollars
""")
                    run = False
                elif total_passengers[index_train] < coaches*total_seats:
                    print(f"""Your total price is: {current_passengers*ticket_price} dollars
""")
                    run = False
                elif total_passengers[index_train] > coaches*total_seats:
                    total_passengers[index_train] -= current_passengers
                    print(f"""The Train departing at {departure[index_train]} has only {(coaches*total_seats)-total_passengers[index_train]} seats left :(
""")
            else:
                print(f'''Only {coaches*total_seats} seats are available in Train departing at {departure[index_train]} :(
''')
else:
    print("All Trains are reserved. Come Tomorrow :( ")


texts:
The archived material for the Stanford University course on cryptography at coursera.org includes a problem where you have to predict the next output of a weak PRG. It can be briefly restated as follows:

  $$\begin{align*}
                   P =&\ 295075153 \\
                 z_n =&\ x_n \oplus y_n,\qquad \textrm{where}\ 0 \le x_0, y_0 \lt P\ \textrm{(unknown random integers)} \\
             x_{n+1} =& (2x_n + 5) \mod P \\
             y_{n+1} =& (3y_n + 7) \mod P \\
(z_0, z_1, ..., z_8) =& (210205973, 22795300, 58776750, \\
                      &\ \ 121262470, 264731963, 140842553, \\
                      &\ \ 242590528, 195244728, 86752752) \\
                 z_9 =& ???
\end{align*}$$

I wrote a small program in C to solve this by brute force, and it finds a solution in just over 2 seconds:

#include <stdio.h>
#define P 295075153L

int main() {
  long seq[] = { 210205973, 22795300, 58776750, 121262470, 264731963,
                 140842553, 242590528, 195244728, 86752752 };
  long i, x, y, x0, y0;

  for (x0=0; x0<P; x0++) {   /* Try every value of x_0 */
    y0 = seq[0] ^ x0;        /* Calculate y_0 from x_0 */
    for (x=x0,y=y0,i=1; i<9; i++) {
      x = (2 * x + 5) % P;   /* Iterate PRG and check values */
      y = (3 * y + 7) % P;
      if ((x ^ y) != seq[i]) break;
    }
    if (i==9) {
      printf ("Solution found: x0=%ld, y0=%ld\n",x0, y0);
      for (x=x0,y=y0,i=1; i<10; i++) {
        x = (2 * x + 5) % P;
        y = (3 * y + 7) % P;
      }
      printf("Next value: %ld\n",x^y);
      return 0;
    }
  }
  puts("No solution found");
  return 0;
}

I also tried to solve this problem in Python, but ran into two problems:

Although it does find the same solution, it takes about 3½ minutes to do so. This means it is about a hundred times slower than the C program. Surely this can't be right?
I'm also not happy with the way I'm checking for a match with the sequence values. In the C code, i is incremented at the end of each for() loop iteration, so when i==9 I can be sure that every value was matched successfully. But this incrementing happens somewhere else in Python, so instead I have to check for i==8 and will report a successful match even if the last comparison fails. How can I do this properly?

from itertools import count

seq = [210205973,22795300,58776750,121262470,264731963,
       140842553,242590528,195244728,86752752]
P = 295075153L
for x0 in count():   # better than range(0,P), which is **extremely** slow
    if x0==P:
        break
    y0 = seq[0] ^ x0
    x, y = x0, y0
    for i in range(1,9):
        x = (2 * x + 5) % P
        y = (3 * y + 7) % P
        if (x ^ y) != seq[i]:
            break
    if i==8:        # will be true even if seq[8] not matched :-(
        break

if i==8:
    print "Solution found: x0=%d, y0=%d" % (x0,y0)
    x, y = x0, y0
    for i in range(1,10):
        x = (2 * x + 5) % P
        y = (3 * y + 7) % P
    print "Next value: %d" % (x ^ y)
else:
    print "No solution found"


texts: Finding the smallest number whose digits sum to N

texts:
I tried my hand at a grade XII Board exam program:

  Given two positive numbers M and N, such that M is between 100 and 10000 and N is less than 100, find the smallest integer that is greater than M and whose digits add up to N. For example, if M = 100 and N = 11, the minimum number is 119 whose digits add up to N. Write a program to accept the numbers M and N from the user and print the smallest required number whose sum of all its digits is equal to N. Also, print the total number of digits present in the required number. The program should check for the validity of the inputs and display an appropriate message for an invalid input.

I solved the program, but as a curious person, I would love to know how to increase it's efficiency, compiler time delays, and if the program could be even shorter in length. So the primary question is, what modifications need be made in my code so that it becomes more compiler-friendly and efficient?

import java.util.Scanner;
public class ISC {
static Scanner sc =new Scanner(System.in);
static int m,n; static int ndigit;
void input(){
System.out.println("Enter the value of M: ");
m = sc.nextInt();
if (m>=100&&m<=10000) {
}
else {
    System.out.println("INVALID, Enter again: ");
    while (!(m>=100&&m<=10000)){
        m = sc.nextInt();
    }
}

System.out.println("Enter the value of N: ");
n = sc.nextInt();
if (n>=1&&n<=100){
    //do nothing
}
else {
    System.out.println("INVALID INPUT, Enter again");
    while (!(n>=1&&n<=100)){
        n = sc.nextInt();
    }
 }
}
 static int sumOfDigits(int n){
int sum = 0;
String a = Integer.toString(n); int digit;
for (int i = 0; i<a.length();i++){
    digit = Integer.parseInt(Character.toString(a.charAt(i)));
    sum += digit;
  }
return sum;
}
 static int getNo(){
ndigit = 0;
for (int i = m; i<=10000;i++){
    if (sumOfDigits(i)==n){
        ndigit = (Integer.toString(i)).length();
        return i;
    }
 }
return 0;
}
 public static void main(String[] args){
ISC a = new ISC();
a.input();
if (getNo()==0) System.out.println("NO NUMBER FOUND");
else {
  System.out.println("Minimum number is: " + getNo());
  System.out.println("Total number of digits: " + ndigit);
}
}
}


texts:
I have designed this by using the stack data structure (similar to balanced parentheses problem) checking if the previous element is decreasing the number or not.

package test;

import main.algorithms.RomanConversion;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class RomanConversionTest {

    RomanConversion romanConversion;

    @Before
    public void setUp(){
        romanConversion = new RomanConversion();
    }

    @Test
    public void testRomanConversion(){
        Assert.assertEquals(154, romanConversion.convert("CLIV"));
        Assert.assertEquals(101, romanConversion.convert("CI"));
        Assert.assertEquals(43, romanConversion.convert("XLIII"));
    }

}

package main.algorithms;

import java.util.HashMap;
import java.util.Stack;

public class RomanConversion {

    public HashMap createMap(){
        HashMap<String, Integer> romanMap = new HashMap<>();
        romanMap.put("I" , 1);
        romanMap.put("IV",4);
        romanMap.put("V" ,5);
        romanMap.put("IX",9);
        romanMap.put("X" ,10);
        romanMap.put("XL",40);
        romanMap.put("L" ,50);
        romanMap.put("XC",90);
        romanMap.put("C" ,100);
        romanMap.put("CD",400);
        romanMap.put("D" ,500);
        romanMap.put("CM",900);
        romanMap.put("M" ,1000);

        return romanMap;
    }

    public int convert(String letter) {

        int result=0;
        HashMap<String, Integer> map = new HashMap<>();
        map = createMap();
        String str;
        char[] array = letter.toCharArray();
        Stack<Character> stack = new Stack<>();

        for(char c: array){
            if(stack.isEmpty()){
                result += map.get(String.valueOf(c));
                stack.push(c);
            }else{
                char lastElement= stack.peek();
                if(map.containsKey(lastElement+""+c)) {
                    result -= map.get(String.valueOf(lastElement));
                    result += map.get(String.valueOf(lastElement) + String.valueOf(c));
                    stack.push(c);
                }else{
                    result += map.get(String.valueOf(c));
                    stack.push(c);
                }
            }

        }
        return result;
    }
}


texts:
Is this a proper way to implement an equality check?  In Equals method, I am relying on    bad_cast exception to know if the objects are of the same class or not.

Is there any other way to implement Equals() in C++?

class Shape
{
public:
    virtual ~Shape() = 0;
    bool operator==(const Shape& s)
    {
        return Equals(s);
    }

    virtual bool Equals(const Shape& s) = 0;
};

class Circle : public Shape
{

    bool Equals(const Shape& c) override
    {
        try
        {
            const Circle& other = dynamic_cast<const Circle&>(c);
                      // condition to check equality.
        }
        catch(std::bad_cast&)
        {
            return false;
        }
        catch(...)
        {
            throw;
        }
    }
};

class Square : public Shape
{
    bool Equals(const Shape& s)  override
    {
        try
        {
            const Square& other = dynamic_cast<const Square&>(s);
                      // condition to check equality.
        }
        catch(std::bad_cast&)
        {
            return false;
        }
        catch(...)
        {
            throw;
        }
    }
};

typedef std::shared_ptr<Shape> ShapePtr;
typedef std::vector<ShapePtr> Shapes;

Shapes LoadShapes()
{
    Shapes shapes;
    shapes.push_back(std::make_shared<Circle>(42));
    shapes.push_back(std::make_shared<Circle>(52));
    shapes.push_back(std::make_shared<Circle>(62));
    shapes.push_back(std::make_shared<Square>(10));
    return shapes;
}

int main()
{
    auto circle = std::make_shared<Circle>(42);
    auto shapes = LoadShapes();
    for ( auto& shape : shapes)
    {
        if ( *shape == *circle)
        {
            std::cout << *shape << "\n";
        }
    }
}

EDIT

Made the operator== as non-virtual method.


texts:
I recently found an Objective-C extension on NSData that encodes and decodes data with AES-128.  I made an attempt to port this code to Swift 2.2:

NSData+AES.swift

extension NSData {

    struct AES {
        static let privateKey = "DefaultPrivateKey"
    }

    func AES128EncryptedDataWithKey(key: String = AES.privateKey) -> NSData? {
        return AES128Operation(CCOperation(kCCEncrypt), key: key)
    }

    func AES128DecryptedDataWithKey(key: String = AES.privateKey) -> NSData? {
        return AES128Operation(CCOperation(kCCDecrypt), key: key)
    }

    private func AES128Operation(operation: CCOperation, key: String) -> NSData? {
        var keyPtr = [CChar](count: kCCKeySizeAES128 + 1, repeatedValue: 0)
        key.getCString(&keyPtr, maxLength: keyPtr.count, encoding: NSUTF8StringEncoding)

        let dataLength = self.length
        let bufferSize = dataLength + kCCBlockSizeAES128
        let buffer = malloc(bufferSize)

        var numBytesEncrypted = 0
        let cryptStatus = CCCrypt(operation, CCAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), keyPtr, kCCBlockSizeAES128, nil, self.bytes, dataLength, buffer, bufferSize, &numBytesEncrypted)

        if cryptStatus == CCCryptorStatus(kCCSuccess) {
            // bytesNoCopy will transfer ownership to the NSData object returned, so we don't need to explicitly call free here
            return NSData(bytesNoCopy: buffer, length: numBytesEncrypted)
        }

        // If the operation failed, we never transferred memory ownership, so free the buffer
        free(buffer)

        return nil
    }
}

A few notes:

I keep a default key as a private struct in the extension so the operation function can be called without arguments for encoding/decoding with a default key.
No need to call bzero anymore since we init the buffer with a repeatedValue of 0.
In my first pass of this in Swift, I accidentally was passing in the size of the array (pointer) as the maxLength parameter in getCString (Stack Overflow question here).  Is there any way I could make the code clearer so I don't do that in the future?
Is it necessary to malloc a buffer?  Can I use a Swift [Int8] instead?
According to my boss in a passive comment, AES-128 is "known to be compromised."  How complex would it be to refactor this code to use AES-256 or (192) bit encryption?


texts:
I've written this implementation of a binary search algorithm, and wanted to know if it was efficient and where I can improve.

function search(el, list) {
    // list = list || LIST;
    var LIM = Math.ceil(Math.log2(list.length)),
        lb = 0,
        ub = list.length - 1,
        i;
    while (el !== list[i = ~~((lb + ub) / 2)] && el !== list[++i]) {
        if (!--LIM) return ("NOT FOUND");
        if (el > list[i]) lb = i;
        else ub = i;
    }
    return i;
}


texts: Regex to first match, then replace found matches

texts:
In my C# program I am using Regular expressions to:

Loop through a list of possible words in need of replacing.
For each word, to find out if a string I am given has any matches.
If it does, I perform some (slightly costly) logic to create the replacement.
I then perform the actual replacement.

My current code looks roughly as follows:

string toSearchInside; // The actual string I'm going to be replacing within
List<string> searchStrings; // The list of words to look for via regex

string pattern = @"([:@?]{0})";
string replacement;

foreach (string toMatch in searchStrings)
{
    var regex = new Regex(
                            string.Format(pattern, toMatch),
                            RegexOptions.IgnoreCase
                            );
    var matches = regex.Matches(toSearchInside);

    if (matches.Count == 0)
        continue;

    replacement = CreateReplacement(toMatch);

    toSearchInside = regex.Replace(toSearchInside, replacement);
}

And I can get this working, but it seems somewhat inefficient in that it is using the regex engine twice - Once to find the matches (regex.Matches()) and once for the replacing regex.Replace()). I was wondering if there was a way to simply say replace the matches you already found?

Also, if has been asked what is within the CreateReplacement() method since it could be possibly done via a Match Elevator, but it is actually a separate method that's fairly costly and not really what I'm asking in this case - My bigger question here is how to deal with this situation of having to use Regex twice - Once to find the matches and then a second time to replace them.

I hope that what I'm trying to find out how to do actually makes sense.


texts:
I want to create a production-ready producer/consumer that could help me avoid thread synchronization hell. Is this thread-safe? The main issue is to be safe with exceptions that can arrive.

public class AsynchSimpleProducer<T> : IDisposable
{
    private readonly Action<Exception> error;
    private readonly BlockingCollection<T> blockingCollection = new BlockingCollection<T>(50);

    public event Func<T, Task> NewItem;

    public AsynchSimpleProducer(Action<Exception> error)
    {
        this.error = error;

        Task.Factory.StartNew(() =>
                              {
                                  //this loop is ends only when blockingCollection.CompleteAdding called
                                  Parallel.ForEach(blockingCollection.GetConsumingPartitioner(), SendItem);
                              });
    }

    private void SendItem(T item)
    {
        try
        {
            if (NewItem !=null)
                NewItem(item).Wait();
        }
        catch (Exception ex)
        {
            error(ex);
        }
    }

    public void Send(T newValue)
    {
        blockingCollection.Add(newValue);
    }

    public void Dispose()
    {
        blockingCollection.CompleteAdding();
    }
}

Example of usage:

simpleProducer = new AsynchSimpleProducer<int>(Error);
simpleProducer.NewItem += simpleProducer_NewItem;
//this part can be in task
var next = random.Next(0, 1000);
simpleProducer.Send(next);


texts: Is this Android click handler using threads correctly?

texts:
I am implementing a thread like the following.  Is my implementation correct?

It works well, but I need a check.

myList.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, final View view,
            int position, long id) {
        // TODO Auto-generated method stub
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                Looper.prepare();
                Context context = view.getContext();

                final String      titleItem = (String) ((TextView) view.findViewById(R.id.titleItem)).getText();
                final String        descItem = (String) ((TextView) view.findViewById(R.id.descItem)).getText();
                final Bitmap        bitmap = (Bitmap) ((BitmapDrawable) ((ImageView) view.findViewById(R.id.imgItem)).getDrawable()).getBitmap();

                Toast.makeText(context, "Item Title: " + titleItem + ", Item Desc: " + descItem, Toast.LENGTH_SHORT).show();
                myHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub

                        Intent intent = new Intent(getApplicationContext(), ItemDetails.class);

                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                        byte[] bytes = stream.toByteArray();

                        intent.putExtra("title", titleItem);
                        intent.putExtra("BMP",bytes);
                        intent.putExtra("desc", descItem);

                        Log.i("ON ITEM CLICK", "OK");
                        startActivity(intent);
                    }
                });
                Looper.loop();
            }
        };
        new Thread(runnable).start();
        stopThread(Thread.currentThread());
    }
});

Can you please tell me if you see something wrong or if there is a better way of doing the same or to optimize it?


texts:
This reads a list of points from a file with a certain format:

<number of points>
x1 y1
x2 y2

How I can make it better?

from collections import namedtuple
Point = namedtuple('Point ', ['x', 'y'])
def read():
    ins = open("PATH_TO_FILE", "r")
    array = []
    first = True
    expected_length = 0
    for line in ins:
        if first:
            expected_length = int(line.rstrip('\n'))
            first = False
        else:
            parsed = line.rstrip('\n').split ()
            array.append(Point(int(parsed[0]), int(parsed[1])))
    if expected_length != len(array):
        raise NameError("error on read")
    return  array


texts: Is there a more succinct way of writing this simple JavaScript loop?

texts:
This seems a bit redundant to me, but I'm not sure of how else I might be able to write this.  Normally I'd use a switch statement, but I don't think that'll work here.  I realize I could also do this in a for loop, but the main heart of the question is what's inside the loop itself.  "arr" is an array, just in case it's not obvious.

var i = 0, x = arr.length;

while (i < x) {
    if (typeof arr[i] === 'object' && !Array.isArray(arr[i])) {
        attr = arr[i];
    }
    else if (typeof arr[i] === 'string') {
        text = arr[i];
    }
    else if (typeof arr[i] === 'object' && Array.isArray(arr[i])) {
        child = arr[i];
    }
    i++;
}


texts: Looking through a directory tree for certain folders

texts:
I've written a script that recursively goes through a directory tree and looks for folders containing folders with NOT INVOICED in the folder name. If it finds one it prints the name of the containing folder and the names of any folders inside it with NOT INVOICED in the folder name.

The output is:

FOLDER 1
    NOT INVOICED FOLDER 1
    NOT INVOICED FOLDER 2
FOLDER 3
    NOT INVOICED FOLDER 1

The idea is that FOLDER 1 contains a few other folders that don't have NOT INVOICED in their name, FOLDER 2 doesn't contain any folders with NOT INVOICED in their name, and so on.

It works, but the only problem is this is what it looks like:

import os
import re

rootDir = '.'

with open('names.txt', 'w') as f:
        for dirName, subdirList,fileList in os.walk(rootDir):
                for fname in subdirList:
                        if re.match("NOT INVOICED", fname):
                                f.write(dirName + '\n')
                                for i in subdirList:
                                        if re.match("NOT INVOICED", i):
                                                f.write('\t%s\n' % i)
                                        else:
                                                pass
                        else:
                                pass

There's got to be a way to write this without six indentations.


texts:
I have this code, this code querying employee schedules in a month, in a work unit. If the List<Employee> count are few, the code works great, but if the List<Employee> count are many, the code runs slowly.  How I can optimize this code?

The DataRow is datagrid row containing employee id, name, etc..

await Task.Run(() =>
{
    List<Employee> employees = DatabaseHelper.GetEmployees(unitId, false, false);
    for (int i = 0; i < employees.Count; i++)
    {
        int no = i + 1;
        DataRow row = DataTableJadwal.Rows.Add(no + ".", employees[i].Nama, employees[i].ID);
        DatabaseHelper.GetUserSchedules(ref row, month, year);
    }

    Thread.Sleep(300);
});

public static void GetUserSchedules(ref DataRow row, int month, int year)
{
    using (SqlConnection sqlConn = new SqlConnection(string.Format(constring, UserID, Password, Server, Database)))
    {
        using (SqlCommand sqlComm = new SqlCommand(
            "SELECT Date, Shift FROM ScheduleList WHERE (ID = @ID) AND (MONTH(Date) = @Month) AND (YEAR(Date) = @Year)"
            , sqlConn))
        {
            try
            {
                sqlComm.Parameters.AddWithValue("@ID", row["ID"]);
                sqlComm.Parameters.AddWithValue("@Month", month);
                sqlComm.Parameters.AddWithValue("@Year", year);

                sqlConn.Open();
                using (SqlDataReader sqlReader = sqlComm.ExecuteReader())
                {

                    int totalHour = 0;
                    while (sqlReader.Read())
                    {
                        DateTime dt = (DateTime)sqlReader["Date"];
                        string shift = (string)sqlReader["Shift"];

                        // a user may had 1,2,3 schedule a day
                        string cellText = row[dt.Day.ToString("00")].ToString();
                        if (cellText.Length < 1)
                            cellText = shift;
                        else
                            cellText += "," + shift;

                        // count schedule hour total
                        if (Utilities.FreeScheduleList.IndexOf(shift.ToUpper()) == -1)
                        {
                            if (shift == "M" || shift == "Q")
                                totalHour += 10;
                            else
                                totalHour += 7;
                        }

                        row[dt.Day.ToString("00")] = cellText;
                    }

                    row["Total"] = totalHour;
                }
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(ex.Message, "GetUserSchedules Error", MessageBoxButton.OK, MessageBoxImage.Stop);
            }
        }
    }
}


texts: First ever unit test. Am I headed in the right direction?

texts:
I'm learning backbone.js in parallel with unit testing.  I've just made a simple model and wanted to unit test it.  Do I have the right idea? I am simply making a model with some default values.

Person = Backbone.Model.extend({
defaults: {
    name: "fetus",
    age: 0,
    child: ''
},

initialize: function() {
    console.log("Welcome to this world");
}
});

var test_Person = {};

var test_Person.Defaults = function() {
    var person = new Person();

    person.assertString(person.defaults.initialize,"Welcome to this world");
    person.assertString(person.defaults.name,"fetus");
    person.assertNum(person.defaults.age,0);
    person.assertString(person.defaults.child,"");
}();


texts:
I've recently been tasked with migrating some code stacks for an applicatin that is moving from using Access to using SQL-Server.

I don't usually use PIVOT all that much, and most of my code is scripting intended for in-house administration of our SQL Servers. As such my code is not that great.

How could I clean up this code, and make it easier to maintain? My main concern is, I want this simpler, but how?

USE [Database1]
GO
SELECT
       Region,
       Year,
       Month,
       SalesPersonNR,
       (ISNULL(SUM(SalesA),0) + ISNULL(SUM(SalesB),0) + ISNULL(SUM(SalesC),0) + ISNULL(SUM(Sales),0) + ISNULL(SUM(NA),0)) AS Total,
       SUM(Sales) Sales,
       SUM(SalesA) SalesA,
       SUM(SalesB) SalesB,
       SUM(SalesC) SalesC
FROM
(
SELECT
       Region,
       Year,
       Month,
       SalesPersonNR,
       COUNT(SalesNumber) as total,
       expr1
FROM (
       SELECT A.Region,
       Year([Date]) AS Year,
       Month([Date]) AS Month,
       A.SalesPersonNR,
       A.SalesNumber AS SalesNumber,
       CASE
             WHEN B.DateSalesC IS NOT NULL THEN 'SalesC'
             WHEN B.DateSalesB IS NOT NULL THEN 'SalesB'
             WHEN B.DateSalesA IS NOT NULL THEN 'SalesA'
             WHEN B.DateSales IS NOT NULL THEN 'Sales'
             ELSE 'NA'
       END AS expr1
FROM [Table1] A
       JOIN [Table2] B
       ON A.SalesNumber = B.SalesNumber
WHERE
       A.Status = 99
       ) Internal
GROUP BY
       Region,
       Year,
       Month,
       SalesPersonNR,
       expr1
) AS x
PIVOT
(
       SUM(Total)
       FOR expr1 IN (SalesC, SalesB, SalesA, Sales, NA)
       ) AS y
GROUP BY
Region,
Year,
Month,
SalesPersonNR


texts: Handling GetTickCount() overflow in timeouts

texts:
This is code which must run on XP, so no GetTickCount64, and which should correctly handle the value wrapping around after 49 days. Can it be improved?

// DWORD timeoutMs is a given parameter.

DWORD beginMs = (timeoutMs == INFINITE ? 0 : ::GetTickCount());
DWORD endMs = beginMs + timeoutMs; // unsigned arithmethic is Mod(MAX+1)
DWORD currentMs;

// Create Process, omitted for brevity

while ((waitResult = ::WaitForSingleObject(pi.hProcess, DEFAULT_WAIT_MS)) == WAIT_TIMEOUT)
{
    if (timeoutMs != INFINITE)
    {
        bool timeoutReached = false;
        currentMs = ::GetTickCount();
        if (beginMs <= endMs) // normal case
        {
            if (currentMs > endMs)
            {
                timeoutReached = true;
            }
        }
        else // special case: tick count wrapped around after 49 days uptime
        {
            if (currentMs < beginMs && currentMs > endMs)
            {
                timeoutReached = true;
            }
        }

        if (timeoutReached)
        {
            ::TerminateProcess(pi.hProcess, 0);
            break;
        }
    }
}


texts: Checking for an undefined nested variable in a JS object

texts:
Is there a better or shorthand way to perform a check on whether or not a variable within (possibly several levels of) an object is null or undefined?

What I would currently do to check is:

if (typeof json !== 'undefined' || typeof json.data !== 'undefined' || typeof json.data.formkeys !== 'undefined') {}

Is there a shorthand way to check for whether or not "json.data.formkeys" is undefined without the concern that one or all of the higher level properties or the object itself might not currently exist?


texts: Maintaining current session across multiple requests

texts:
I am trying to migrate from request to axios, since request has been deprecated.

Suppose that the URL 'https://www.example.com' receives a post request with formdata that contains login information, and also suppose that I need to maintain the current session across multiple requests (for that I need a cookieJar).

Using axios I need cookieJar support from an external library therefore I use axios-cookiejar. Also, to send formdata using axios I have to use the external library form-data, and I also have to set the headers manually since axios doesn't do that for me.

I have the following code, which uses axios that does just that:

axios = require('axios')
FormData = require('form-data')
axiosCookieJarSupport = require('axios-cookiejar-support').default
tough = require('tough-cookie')
axiosCookieJarSupport(axios)
cookieJar = new tough.CookieJar()
form = new FormData()
form.append('email', 'example@gmail.com')
form.append('password', '1234')
axios({
    method: 'post',
    url: 'https://www.example.com',
    data: form,
    headers: {'Content-Type': `multipart/form-data; boundary=${form._boundary}` },
    jar: cookieJar,
    withCredentials: true
}).then(function (response) {
    console.log(response['data'])
})

Using request this becomes much simpler:

request = require('request')
requestCookieJar = request.jar()
request.post({
    url: 'https://www.example.com',
    method: 'POST',
    jar: requestCookieJar,
    formData: {
        'email': 'example@gmail.com',
        'password': '1234'
    }
}, function(error, response, body) {
    console.log(body)
})

As you can see the request API is much more elegant. Is there a way to use axios more elegantly or is there a different elegant API, which isn't deprecated, that I could use to support my needs stated at the beginning of this question?


texts: Adding, deleting elements as per autocomplete results

texts:
I am working on a bookmarker project for replacing storage of bookmarks in a web browser. It will be storing bookmarks as per categories in a database. I have written some jQuery for the WIP search page.

A bit about functionality

There is a search box for categories with autocomplete which is done by my app
On clicking Enter category is added to the web page via this jQuery. There are checks whether the category is in the autocomplete and whether it is already present on page or not.

The JS file can be viewed on GitHub if anyone prefers that. Please review as I don't know about best practices of javascript and am using JQuery for the first time. This JS is associated with this HTML page. I am not placing the HTML page here as I am interested in Javascript review only. I am using Python 3.4.0 with Django 1.6.4.

Please tell if any other information required for review.

/**
 * Created by Aseem on 5/22/14.
 */

var cur_location = location.protocol + '//' + location.hostname + (location.port ? ':' + location.port : '');
var static_url = '/static/BookMarker';
var static_img_url = cur_location + static_url + '/img';

var category_input = $("#category_inp");

$(function () {
    category_input.autocomplete({
        source: "auto/"
    });
});

//Add Bindings for keys
category_input.keyup(function (e) {
    if (e.keyCode == 13) {
        $(this).trigger("enterKey");
    }
});

category_input.bind("enterKey", function (e) {

    var is_category = false;

    $(".ui-menu-item").each(function (index) {
            if (category_input.val() == $.trim($(this).text())) {
                is_category = true;
                return false;
            }
        }
    )

    if (is_category == false) {
        alert("Not a category");
        return false;
    }

    var already_present = false;

    $(".category").each(function (index) {
            if (category_input.val() == $.trim($(this).text())) {
                alert("Category already added");
                already_present = true;
                return false;
            }
        }
    )

    if (already_present == false) {
        $("#category_list").append(
            '
' +
                ' ' +
                category_input.val() +
                '
'
        );
    }
    category_input.val("");
});

$(document).on('click', ".delete-cat", function (e) {
    var classList = $(this).attr('class').split(/\s+/);
    $.each(classList, function (index, item) {
        if (item != 'delete-cat') {
            $('.category.' + item).remove();
        }
    });
})


texts:
I've written a function that searches for the nth occurrence of a character in the given string. A positive value for n will search from left-to-right, while a negative value will search from right-to-left. Zero is not a valid value for n.

Left-to-Right Search

"AABAXYAMN".NthIndexOf('A', 1) -> 0
"AABAXYAMN".NthIndexOf('A', 2) -> 1
"AABAXYAMN".NthIndexOf('A', 3) -> 3

Right-to-Left Search

"AABAXYAMN".NthIndexOf('A', -1) -> 6
"AABAXYAMN".NthIndexOf('A', -2) -> 3
"AABAXYAMN".NthIndexOf('A', -3) -> 1

Code:

/// <summary>
/// Searches for the nth occurrence of a character in the given string. A positive value for n will search from
/// left-to-right while a negative value will search from right-to-left. Zero is not a valid value for n.
/// </summary>
public static int NthIndexOf(this string input, char charToFind, int n) {
    int position;

    switch (Math.Sign(n)) {
        case 1:
            position = 0;
            while (((position = input.IndexOf(charToFind, position)) != -1) && ((--n) > 0)) { position++; }
            break;
        case -1:
            position = input.Length - 1;
            while (((position = input.LastIndexOf(charToFind, position)) != -1) && ((++n) < 0)) { position--; }
            break;
        default:
            throw new ArgumentOutOfRangeException(message: "param cannot be equal to 0", paramName: nameof(n));
    }

    return position;
}


texts: Project Euler #4 "Largest Palindrome product" in Python

texts:
Given

  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.

Solution

import time

def reverse(num):
    dreverse = 0
    while (num > 0):
        dreverse = dreverse * 10 + num % 10
        num /= 10
    return dreverse

def is_palindrome(num):
    if (num < 0):
        raise ValueError('Non-negative integers only')
    return num == reverse(num)

def main():
    largest_palindrome = 0
    lower = 999
    while lower >= 100:
        upper = 999
        while upper >= lower:
            if upper * lower <= largest_palindrome:
                break
            if is_palindrome(upper * lower):
                largest_palindrome = upper * lower
            upper -= 1
        lower -= 1
    return largest_palindrome

start_time = time.time()
print main()
print("--- %s seconds ---" % (time.time() - start_time))
o/p: 906609
--- 0.0150721073151 seconds ---

I am including timing metric from now on. This solution seems \$O(N^2)\$. Can I improve it further?


texts:
I have this function which parses Beautiful Soup elements:

def get_info():
    holder = []
    problem_dict = {}
    selection_container = []
    for moselect in base_page.find_all('div', attrs={'class': 'Moselect'}):
        if moselect.find('div', attrs={'id': 'noSize'}):
            holder.append(moselect.find_all('div')[1:])

    for held_item in holder[0]:
        if held_item.find_all('option')[1:]:
            for m in held_item.find_all('option')[1:]:

                append_dict(selection_container, m)

                if len(m.text.split(' ')) > 1:
                    stock_info = {
                        'message': reduce(lambda x, y: x + ' ' + y, m.text.split(' ')[1:])[1:-1],
                        'status': 'pre-order'
                    }
                    problem_dict.update({'stock': stock_info})

        else:
            for m in held_item.find_all('option'):

                append_dict(selection_container, m)

                if len(m.text.split(' ')) > 1:
                    stock_info = {
                        'message': reduce(lambda x, y: x + ' ' + y, m.text.split(' ')[1:])[1:-1],
                        'status': 'pre-order'
                    }
                    problem_dict.update({'stock': stock_info})

    problem_dict.update(dict(selections=selection_container))
    return problem_dict

It will return dict with:

problem_dict = {'selection': [{'key': 'value'},{'key': 'value'},]}

and sometimes it returns:

problem_dict = {'selection': [{'key': 'value'},{'key': 'value'}], 'stock': {'key': 'value', 'key': 'value'} }

How can I refactor and optimize this method?


texts: Python script searching for string in textfile and inserting another textfile before match

texts:
I'm very new to Python, and far away from writing my own scripts. For my work with lilypond I needed a script that parses a text file, searches for a string and inserts another textfile before the match. I have been searching quite a lot for this kinda script and I did not find any. I ended up combining the snippets I found on here and other sites and came up with this script, which is working:

#!/usr/bin/env python

# usage:
# $ python thisfile.py text.txt searchstring insert.txt

import sys

f2 = open(sys.argv[3])
data = f2.read()
f2.close()

with open(sys.argv[1], "r+") as f1:
    a = [x.rstrip() for x in f1]
    index = 0
    for item in a:
        if item.startswith(sys.argv[2]):
            a.insert(index, data)
            break
        index += 1
    f1.seek(0)
    f1.truncate()
    for line in a:
        f1.write(line + "\n")

I also got a very detailed answer on Stack Overflow, telling what is actually going on in the code, before I was far away from understanding any detail.

What I got out of it so far is the following problem:

  If anything would go wrong with reading in the data from f1 or f2, f1.truncate() would delete the original content of f2, then not being able to (re)write the appropriate content the content would get lost. A much more secure way would be using some kind of temporary file, or at least moving the original content of f1 there before calling truncate().

I would be glad for any comments on this "problem", and any others if there are.


texts: Pure Swift solution for socket programming

texts:
I have spend quite some time now to find out how exactly to do socket programming in Swift (Xcode 6.1). There are a few examples out there, but most of them no longer work for the latest release of Swift.

Finally I came up with the following (see below). That seems to work, but I am not 100% certain that it is fully correct. Maybe some of you can have a look at it and see if I made any errors that might cause future (i.e. currently under the hood) problems.

The calls to "log...." refer to a self made logging facility, but that should be clear enough I think.

Any suggestions on how to improve this are welcome.

var status: Int32 = 0

// Protocol configuration

var hints = addrinfo(
    ai_flags: AI_PASSIVE,       // Assign the address of my local host to the socket structures
    ai_family: AF_UNSPEC,       // Either IPv4 or IPv6
    ai_socktype: SOCK_STREAM,   // TCP
    ai_protocol: 0,
    ai_addrlen: 0,
    ai_canonname: UnsafeMutablePointer<Int8>.null(),
    ai_addr: UnsafeMutablePointer<sockaddr>.null(),
    ai_next: UnsafeMutablePointer<addrinfo>.null())

// For the result from the getaddrinfo

var servinfo = UnsafeMutablePointer<addrinfo>.null()

// Get the info we need to create our socket descriptor

status = getaddrinfo(UnsafePointer<Int8>.null(), ap_servicePortNumber, &hints, &servinfo)

// Cop out if there is an error

if status != 0 { return }

// Print a list of the found IP addresses

if ap_applicationInDebugMode {

    var info = servinfo

    while info != UnsafeMutablePointer<addrinfo>.null() {

        // Check for IPv4
        if info.memory.ai_family == AF_INET {

            var ipAddressString = [CChar](count:Int(INET_ADDRSTRLEN), repeatedValue: 0)
            inet_ntop(
                info.memory.ai_family,
                info.memory.ai_addr,
                &ipAddressString,
                socklen_t(INET_ADDRSTRLEN))
            let addressStr = String.fromCString(&ipAddressString)
            var message = addressStr == nil ? "No IPv4 address found" : "IPv4 address: " + addressStr!
            log.atLevelDebug(source: SOURCE, object: nil, message: message)

        } else { // Should be IPv6

            var ipAddressString = [CChar](count:Int(INET6_ADDRSTRLEN), repeatedValue: 0)
            inet_ntop(
                info.memory.ai_family,
                info.memory.ai_addr,
                &ipAddressString,
                socklen_t(INET6_ADDRSTRLEN))
            let addressStr = String.fromCString(&ipAddressString)
            var message = addressStr == nil ? "No IPv6 address found" : "IPv6 address: " + addressStr!
            log.atLevelDebug(source: SOURCE, object: nil, message: message)
        }

        info = info.memory.ai_next
    }
}

// Get the socket descriptor, use the results from the getaddrinfo call earlier

var socketDescriptor = socket(servinfo.memory.ai_family, servinfo.memory.ai_socktype, servinfo.memory.ai_protocol);

log.atLevelDebug(source: SOURCE, object: nil, message: "Socket value: " + socketDescriptor.description)

// Since we will be listening, bind the socket descriptor to our socket

status = bind(socketDescriptor, servinfo.memory.ai_addr, servinfo.memory.ai_addrlen);

log.atLevelDebug(source: SOURCE, object: nil, message: "Status from binding: " + status.description)

// Cop out if there is an error

// PS: Need to handle "in use" errors

if status != 0 {
    let message = "Binding error, status = " + status.description + ", error = " + errno.description
    log.atLevelEmergency(source: SOURCE, object: nil, message: message)
    setApplicationError(ErrorCode.initPortForListeningBindingError, message)
    return
}

// Don't need this anymore

freeaddrinfo(servinfo)


texts:
What I can do to make this code more efficient?

It is supposed to be like one of those slot machines where you gamble on it and stuff (like at a casino).

#include <iostream>
#include <conio.h>
#include <string>
#include <ctime>
#include <iomanip>

using namespace std;

int main() {

    srand(time(0));

    int slot1;
    int slot2;
    int slot3;
    double total_money = 0;
    double total_wins = 0;
    double total_tries = 0;
    double win_percentage;
    char play_again;

    cout << "Welcomes to Virtual Slots." << endl;  // Welcome the user
    cout << "Match 2, win that amount." << endl;  // Explain prizes
    cout << "Match 3, win 3x that amount.\n" << endl;

    do {

        slot1 = rand() % 10 + 1;     // Get random numbers for slots
        slot2 = rand() % 10 + 1;
        slot3 = rand() % 10 + 1;

        cout << "****SLOTS!!****" << endl;
        cout << "***************" << endl;
        cout << "* [" << slot1 << "] [" << slot2 << "] [" << slot3 << "] *" << endl;  // Show slots
        cout << "***************\n" << endl;

        if (slot1 == slot2 == slot3) {  // If all three slots match, user getx 3x money

            cout << "THREE TIMES MATCH!!" << endl;
            cout << "You win $" << (slot1 * 3) << ".\n" << endl;

            total_money += slot1;  // Count money
            total_wins++;  // Count wins
        }

        else if (slot1 == slot2 || slot1 == slot3 || slot2 == slot3) {  // if user gets 2 slots matched, user gets that amount of money

            cout << "TWO TIMES MATCH!!" << endl;
            cout << "You win $" << slot1 << ".\n" << endl;

            total_money += slot1;  // Count money
            total_wins++;  // Count wins
        }

        else {  // No match, no money

            cout << "NO MATCH.\n" << endl;
        }

        total_tries++;  // Count tries

        win_percentage = (total_wins / total_tries);  // Percentage of wins

        cout << "Current Total: $" << setprecision(4) << total_money << endl;                // Show user his statistics
        cout << "Win Percentage: " << setprecision(3) << win_percentage << "%" << endl;

        cout << "Play Again? (Y/N) " << endl;  // Ask the user if s/he wants to play again
        cin >> play_again;

        system("PAUSE");
        system("CLS");

    } while (play_again != 'N');  // Keep going until user says No

    cout << "See you next time!" << endl;

    _getch();
    return 0;
}


texts: What Data Annotations need to be shared/different between my Model & ViewModel to keep seperation of concerns?

texts:
I read this question and answers, about if Display Annotations on model properties violates the separation of concerns between view and model.  And my interpretation of their answer was "No, not if you're using a ViewModel for Display Annotations".  But additional separation of concerns questions arose as I began implementing.

I have two questions but both are kind of related to each other. In both, I am wondering if I am violating the separation of concerns:

I'm using localized strings from my views/resources.resx in my Model for Display Attributes, does this violate the separation of concerns since it's a resource in my views folder intended for views?
Do I need a ViewModel for my Model to keep separation of concerns?  And if so, which Annotations need to go on my model's properties, and which need to go on the ViewModel properties?

I think I need to keep all the Display Annotations and Validation Annotations (like [required] and [range(x,y)]) that I have in my ViewModel. In my Model I think I need to keep just the Validation Annotations.  But, If this is true, then I have two classes to maintain Validation Annotations if I decide to add another property!?

The reason I think that I need Validation Annotations on both classes is so that the Model class can tell EF to put the correct constraints into database when I change schema with DbMigrations.  Also, so the ViewModel tells the browser to tell the user when he's putting an invalid value in.

The ViewModel

public class RestaurantReviewViewModel
{
    public int Id { get; set; }
    [Range(1, 10)]
    [Required]
    public int Rating { get; set; }

    [Required]
    [StringLength(1024)]
    [Display(Name = Resources.Description)]
    public string Body { get; set; }

    [Display(Name = Resources.UserName)]
    [DisplayFormat(NullDisplayText = "[Anonymous]")]
    public string ReviewerName { get; set; }
    public int RestaurantId { get; set; }
}

The attributes that I commented out in the next class are the attributes I think i need to remove for the Model.

The Model

public class RestaurantReviewModel
{
    public int Id { get; set; }
    [Range(1, 10)]
    [Required]
    public int Rating { get; set; }

    [Required]
    [StringLength(1024)]
    //[Display(Name = Resources.Description)]
    public string Body { get; set; }

    //[Display(Name = Resources.UserName)]
    //[DisplayFormat(NullDisplayText = "[Anonymous]")]
    public string ReviewerName { get; set; }
    public int RestaurantId { get; set; }
}


texts: Printing of status message during execution of the bash script

texts:
As a part of my bash routine I am printing some message in terminal regarding status of the workflow. The message in splited into two parts (part 1: begining of the task, part 2: status of its finishing)
echo -n "Dataset is being processed ! "; execution of some AWK script; echo " Processing has been COMPLETED!"

Here is realisation in bash contained a part of the AWK code:
# print pharase 1: initiation of the process
echo -n "Dataset is being rescored.. Please wait"; sleep 0.5
# this is the process: makedir for the result and execute AWK code to process input file
mkdir ${results}
# Apply the following AWK code on the directory contained input file
while read -r d; do
awk -F, '
}'  "${d}_"*/target_file.csv > "${results}/"${d%%_*}".csv"
done < <(find . -maxdepth 1 -type d -name '*_*_*' | awk -F '[_/]' '!seen[$2]++ {print $2}')
# print pharase 2: finish of the result, which would appear in the terminal near phrase 1
# this will print "COMPLETED" letter-by-letter with the pause of 0.2 sec between each letter
echo -n " C"; sleep 0.2; echo -n "O"; sleep 0.2; echo -n "M"; sleep 0.2; echo -n "P"; sleep 0.2; echo -n "L"; echo -n "E"; sleep 0.2; echo -n "T"; echo -n "E"; sleep 0.2; echo "D!"

While executing this script in bash, everything seems to be OK and I have not noticed any problems related to the parts of the code between both 'echo -n' blocks. May such splitting of the status phrase using "echo -n" lead to some bugs of the routine in bash ? Any suggestions for realisation of such status message in bash using another syntax?


texts:
I had to write some code for an interview, to print out the name attribute of each node. I started off going in the wrong direction, so I didn't get to finish.  I wanted to finish writing the code, so I created my console app similar to what they had a button event doing.  Please let me know what you think of the code and what I can do better.

class XMLRecursionReader
{
    private StringBuilder _outputString = new StringBuilder();
    private XmlNode _root;

    public XMLRecursionReader(XmlDocument xDoc)
    {
        _root = xDoc.ChildNodes[1];
    }
    public string ReturnNameAsString (XmlNode node)
    {
        return node.Attributes["name"].InnerXml.ToString();
    }
    public void buildString (XmlNode node)
    {
        _outputString.AppendLine(ReturnNameAsString(node));
        if (node.HasChildNodes)
        {
            foreach (XmlNode childNode in node.ChildNodes)
            {
                buildString(childNode);
            }
        }
    }
    public void PrintOutput ()
    {
        buildString(_root);
        Console.WriteLine(_outputString.ToString());
        Console.ReadLine();
    }
}

similar sample to what I was coding against.  but the code needed to be generic and able to go as deep as necessary depending on the document that was fed in, but the structure is always going to be similar to this.

<?xml version="1.0" encoding="UTF-8"?>
<report name="ReportName">
    <agency name="agency1">
        <office name="office1"></office>
        <office name="office2"></office>
        <office name="office3"></office>
    </agency>
    <agency name="agency2">
        <office name="office1">
            <agent name="agent Amy"></agent>
    <address name="address line"></address>
        </office>
        <office name="office2"></office>
        <office name="office3"></office>
    </agency>
    <agency name="agency3">
        <office name="office1">
        <agent name="agent Bettie">
            <subagent name="sub-agent bob">
            <phone name="456-789-1230"></phone>
            </subagent>
            <subagent name="sub-agent billy"></subagent>
        </agent>
        <address name="address line">
            <faxnumber name="1234567890"></faxnumber>
        </address>
        </office>
        <office name="office2"></office>
        <office name="office3"></office>
    </agency>
</report>

The Results:


texts:
Does the following code is written correct witout redundant code ?
or maybe using Jquery it can be written better?

I need to find matching between properties insdie oData &  oPushObj
and fill aSelData with this content.

This code is working as expected

        jQuery.each(aDataCollection, function(iIndex, oData) {
            oPushedObject = {};

            fnAddEnt(aProperties, oData, oPushObj);

            Object.getOwnPropertyNames(oData).forEach(function(key) {
                if (oPushObj.hasOwnProperty(key)  {

                    var source = oData[key].results[iIndex];
                    var destination = oPushObj[key];

                    Object.getOwnPropertyNames(source).forEach(function(sourceKey) {
                        if (destination.hasOwnProperty(sourceKey)) {
                            var sourceItem = source[sourceKey];
                            destination[sourceKey] = sourceItem;
                        }
                    });
                }
            });

            aSelData.push(oPushObj);
        });
        return aSelData;
    };


texts: Optimising a user's-choice sorting algorithm

texts:
With the help of some nice folks at Stack Overflow, I wrote an algorithm that will give a user three buttons: option a neither option b Clicking on a button will add one to the score of a object, and it will systematically go through each match-up to get an equal amount of questions for each character.

Here's the meat of the function:

var pos1 = 0; //position in the array
var pos2 = 1; //ditto

var array = [ //array used
    {name: "apple", score: 0},
    {name: "pear", score: 0},
    {name: "cherry", score: 0},
    {name: "banana", score: 0},
    {name: "orange", score: 0},
    {name: "watermelon", score: 0},
    {name: "bread" score: 0},
    {name: "a duck" score: 0}
]

var option1 = array[0]; //keeps track of which option is shown in the button
var option2 = array[1]; //ditto

function select(slot) { //called when user presses button
    if (slot == 1) { //left button
        array[pos1].score++;
    } else if (slot == 2) { //right button
        array[pos2].score++;
    } //for neither, it does select(0)

    if (pos2 < array.length - 1) {
        pos2++;
        option2 = array[pos2];
    } else if (pos1 < array.length - 2) {
        pos1++;
        pos2 = 1 + pos1;
        option1 = array[pos1]
        option2 = array[pos2]
    } else {
        output(); //sorts and displays
        return;
    }
}

It works pretty well for smaller numbers of objects, but it gets totally absurd at higher numbers. For example, in practice, one of my sets has around 50 objects, resulting in ~1500 questions, which takes hours!

As a side note, I found this website. Ignoring the content, it's able to sort a similar number (55) of objects with only 170 questions. It's also somehow able to generate a percentage of completion, but that's just a bonus.

Conveniently, the author has the code embedded directly in the HTML, so the JavaScript is easy to view. However, I can't figure out how it works, but it's the type of efficiency I'm looking for.


texts: Keeping an observable collection up to date

texts:
I'm using an ObservableCollection in a WPF app.  The source of the data doesn't provide changes. It provides snapshots instead.  The method I wrote to update the ObservableCollection works but it seems inelegant. Is there a better way to do this?

    public static void UpdateMarketOrderList(
                          ObservableCollection<MarketOrder> oldList,
                          List<MarketOrder> newList)
    {
        int oi = 0; // old list iterator
        int ni = 0; // new list iterator

        while (ni < newList.Count)
        {
            if (oi == oldList.Count)
            {
                oldList.Insert(oi, newList[ni]);
            }
            else if (oldList[oi].Price == newList[ni].Price)
            {
                if (oldList[oi].Quantity != newList[ni].Quantity)
                {
                    oldList[oi].Quantity = newList[ni].Quantity;
                }
                ++oi;
                ++ni;
            }
            else if (oldList[oi].Price < newList[ni].Price)
            {
                oldList.RemoveAt(oi);
            }
            else if (oldList[oi].Price > newList[ni].Price)
            {
                oldList.Insert(oi, newList[ni]);
            }
        }

        while (oldList.Count > ni)
        {
            oldList.RemoveAt(ni);
        }
    }

If it matters, the definition MarketOrder can be considered to be this:

public class MarketOrder
{
    public decimal Price { get; set; }
    public decimal Quantity { get; set; }
}


texts:
I built a merge sort in python just to have a more thorough understanding of how the algorithm works.  What I have written works fine, but I assume there is room for improvement and ways to make my implementation more efficient.

I would appreciate any feedback or critiques!

"""
2019-10-17

This project simply re-creates common sorting algorithms
for the purpose of becoming more intimately familiar with
them.
"""

import random
import math

#Generate random array
array = [random.randint(0, 100) for i in range(random.randint(5, 100))]
print(array)

#Merge Sort
def merge(array, split = True):
    split_array = []
    #When the function is recursively called by the merging section, the split will be skipped
    continue_splitting = False
    if split == True:
        #Split the array in half
        for each in array:
            if len(each) > 1:
                split_array.append(each[:len(each)//2])
                split_array.append(each[len(each)//2:])
                continue_splitting = True
            else:
                split_array.append(each)
    if continue_splitting == True:
        sorted_array = merge(split_array)
        #A return is set here to prevent the recursion from proceeding once the array is properly sorted
        return sorted_array
    else:
        sorted_array = []
        if len(array) != 1:
            #Merge the array
            for i in range(0, len(array), 2):
                #Pointers are used to check each element of the two mergin arrays
                pointer_a = 0
                pointer_b = 0
                #The temp array is used to prevent the sorted array from being corrupted by the sorting loop
                temp = []
                if i < len(array) - 1:
                    #Loop to merge the array
                    while pointer_a < len(array[i]) or pointer_b < len(array[i+1]):
                        if pointer_a < len(array[i]) and pointer_b < len(array[i+1]):
                            if array[i][pointer_a] <= array[i + 1][pointer_b]:
                                temp.append(array[i][pointer_a])
                                pointer_a += 1
                            elif array[i + 1][pointer_b] < array[i][pointer_a]:
                                temp.append(array[i + 1][pointer_b])
                                pointer_b += 1
                        #If the pointer is equal to the length of the sub array, the other sub array will just be added fully
                        elif pointer_a < len(array[i]):
                            for x in range(pointer_a, len(array[i])):
                                temp.append(array[i][x])
                                pointer_a += 1
                        elif pointer_b < len(array[i + 1]):
                            for x in range(pointer_b, len(array[i + 1])):
                                temp.append(array[i + 1][x])
                                pointer_b += 1
                else:
                    for each in array[i]:
                        temp.append(each)
                sorted_array.append(temp)
            if len(sorted_array) != 1:
                #Recursively sort the sub arrays
                sorted_array = merge(sorted_array, False)
    return sorted_array

sorted_array = merge([array])[0]
print()
print(sorted_array)


texts: Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height

texts:
I'm trying to find the complexity of this code and some suggestions for improving the code quality. and handling the code gracefully, esp in the areas of exception handling, checking edge cases, presentation, etc.

// Node Class

class Node {
    int id;
    Node left;
    Node right;
    Node(int id) {
        this.id = id;
        left = null;
        right = null;
    }
}

// ArrayIntoBinaryTree Class

import java.util.Scanner;
public class ArrayIntoBinaryTree {

    /*
     Algorithm:
        1. Insert into the tree the middle element of the array.
        2. Insert (into the left subtree) the left subarray elements
        3. Insert (into the right subtree) the right subarray elements
        4. Recurse
     */

    ArrayIntoBinaryTree arrayIntoBinaryTree = new ArrayIntoBinaryTree();

    public static void main(String[] args) {
        int[] arr = initializeArray();
        if (arr == null) {
          throw new NullPointerException("Input array is empty");
        }
        Node node = addToTree(arr, 0, arr.length);
    }

    // find Subarray - Use Recursion.
    static Node addToTree(int[] arr, int first, int last) {
        // Exit condition
        if(first<last) {
            return null;
        }
        int midElement = arr[(first+last)/2];
        Node newNode = new Node(arr[midElement]);
        newNode.left = addToTree(arr, first, midElement-1);
        newNode.right = addToTree(arr, midElement+1, last);
        return newNode;
    }

    static int[] initializeArray() {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the size of array: ");
        int size = sc.nextInt();

        if (size < 1) {
          return null;
        }

        System.out.println("Now enter " + size + " number of elements.");
        int[] arr = new int[size];
        for(int i=0; i<size; i++) {
            arr[i] = sc.nextInt();
        }
        return arr;
    }
}


texts: Short wrapper for fetch (similar to axios)

texts:
I was looking to replace my use of axios with just fetch, but I didn't like how verbose fetch was with regard to handling JSON output (having to have a separate then call just to return the json). Unfortunately calling text() first to see if it's a JSON response and then only calling json() if so seems wasteful because it first has to parse the response as text. If you have a large response payload (as I do in several cases) then double parsing seems inefficient.

So this isn't as complex as it could be because I only really need something simple. All of my requests are prefixed with /api/ except one that has to call AWS, so I used startsWith for that case. Also, the only time I call PUT in the entire application is when I need to update an AWS resource.

  initializeRequestFactory = () => {
    const prefix = "/api/";

    let thenFunction = response => {
      // only time response isn't from app server is when it's from AWS
      // avoid expensive text() call in general case
      let data = response.ok && response.url.startsWith("https://s3") ? response.text() : response.json();

      if (response.ok) {
        return data.then(json => {
          return { data: json, response: response };
        }).catch(err => {
          return { response: response };
        });
      } else {
        return { response: response };
      }
    };

    window.request = {
      get: url => {
        let theUrl = url.startsWith("http") ? url : prefix + url;

        return fetch(theUrl, {
          method: "GET",
          credentials: 'include',
          headers: {
            'sseid': window.globals.sseid
          }
        }).then(thenFunction);
      },
      post: (url, body) => {
        let theUrl = url.startsWith("http") ? url : prefix + url;

        return fetch(theUrl, {
          method: "POST",
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json',
            'sseid': window.globals.sseid
          },
          body: JSON.stringify(body)
        }).then(thenFunction);
      },
      put: (url, body, config) => {
        let theUrl = url.startsWith("http") ? url : prefix + url;

        return fetch(theUrl, {
          method: "PUT",
          credentials: 'omit',
          headers: config.headers,
          body: body
        }).then(thenFunction);
      }
    };
  }

I generally call it like this:

window.request.post("reply-to-thread", {
  thread_id: this.props.data.thread_id
});

window.request.get("get-my-profile").then(response => {
  this.setState({ profile: response.data });
});

It all seems to work but I was wondering if anyone had any ideas for improvements. Thanks for reading!


texts: Django REST custom methods for generic views

texts:
I'm intern and work on a project where I develop DRF API that need to interact with mobile app written by my colleague with Ionic framework.

We are creating new user. My view method is following:

class NewUser(generics.CreateAPIView):
    model = User
    permission_classes = [permissions.AllowAny]
    serializer_class = NewUserSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        token, created = Token.objects.get_or_create(user=serializer.instance)
        return Response({'token': token.key}, status=status.HTTP_201_CREATED, headers=headers)

When someone wants to create new user via POST request if user name has't been taken yet, then API return 201 status code and token in JSON, if user name already taken it returns 400 status and error message in JSON. MY colleague request me to change status message to 200 when he tries to create username with name that already exist. He says that he can't consume the ERROR response.

His code looks like:

$http.post(url,{
username:$scope.tel,
password:$scope.passwd
}).success(function(data){
alert(data);
$ionicLoading.hide();
console.log(data);
})

Questions:

Should I tweak my API to send 200 status instead of more logical 400 for 'user already register' error?

I tried to change my code, But i couldn't find the method to override in CreateAPIView/ModelSerializer of DRF. I ended up rewriting my view class to method:

@api_view(['POST'])
def newUser(request):
    """
    Saves a new user on the database
    """
    if request.method == 'POST':

        serializer = NewUserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            token, created = Token.objects.get_or_create(user=serializer.instance)
            return Response({'token': token.key}, status=status.HTTP_201_CREATED, headers=serializer.data)
        else:
            return Response(serializer.errors, status=status.HTTP_200_OK)

If I want to change behavior of API and response, which method should I override?
I'm new to Django and still don't quite know where we should use generic views VS. @.... methods.


texts: Project Euler #11"numbers in a grid" in Rust

texts:
To learn more about Rust, I implemented Project Euler #11 "Numbers in a grid". Contrary to some people, I prefer not having the actual data grid in my code, so I put it in a file, which I read in the beginning.

I'm wondering how 'Rustic' my code is. Specially I wonder about the following points:

How to most concisely read a table of integers into a data structure? Is it possible to create an array of a certain size? Do I need all this spliting and from_str mapping?
Have I handled the array indices in the right way? I'm not used to needing all this casting.
I my max function sufficiently generic?

use std::io;
fn max(a:int, b:int) -> int {if a > b {a} else {b}}
fn main() {
    let n = 20;
    let mut ar:Vec<Vec<int>> = vec![];
    for line in io::stdin().lines() {
        let s = line.unwrap();
        let ss = s.as_slice().trim().split(' ');
        let xs:Vec<int> = ss.map(|s|from_str::<int>(s).unwrap()).collect();
        ar.push(xs);
    }
    let mut best = 0;
    for i in range(0i,n) {
        for j in range(0i,n) {
            for &(di, dj) in [(0,1),(1,1),(1,0),(1,-1i)].iter() {
                if i+di*3 < n && j+dj*3 < n && j+dj*3 >= 0 {
                    let mut p = 1;
                    for k in range(0i,4) {
                        p *= ar[(i+di*k) as uint][(j+dj*k) as uint]
                    }
                    best = max(best, p);
                }
            }
        }
    }
    println!("{}", best);
}


texts:
Suppose I have a nested class structure like this:

namespace My.Namespace {
    public class Foo {
        public class Bar {
            public class Baz {
                public string Test { get; set; }
            }
        }
    }
}

I need to get the nested type name of Baz without the namespace, i.e. Foo+Bar+Baz in a generic method. Unfortunately, .Name will just return Baz and .FullName will give me the namespace as well. Right now I'm using this:

protected T LoadSample<T>(string fileName)
{
    var t = typeof(T);
    var nestedTypeName = t.Namespace == null
        ? t.FullName                                 // T is declared outside of a namespace
        : t.FullName.Substring(t.Namespace.Length + 1);
    ...
}

But this just looks ugly. Is there a more standard method for getting just Foo+Bar+Baz in this situation?

To clarify what's going on inside this method, this is part of a unit test for an XML serialization class. LoadSample will load an XML file, wrap it in a little more XML to create an 'envelope', attempt to parse it, and return the result if it succeeds. The problem is that the 'envelope' that the XML serialization class expects the XML to specify the type name in a particular format. For example:

<baz>
    <test>Testing</test>
</baz>

Will be wrapped in an evelope like this:

<evelope>
    <messageType>urn:My.Namespace:Foo+Bar+Baz</messageType>
    <message>
        <test>Testing</test>
    </message>
</evelope>


texts: Dividing a long (arbitrary-precision) number by an integer

texts:
As part of a (slightly) larger program, I needed to write a function that could take an arbitrarily large number and divide it by a small number. In this program, I will be dividing this number specifically by 2 or 5, but from my (rudimentary) testing, my function seems to work for larger divisors as well. All of the inputs in this function will be valid (they are checked before passed to this function in a different part of the program). A valid input is a non-negative, properly-represented number, things like: "123\0" but not "-1000\0" or "00100\0". So input validation is not necessarily to that extent.

#include <stdlib.h>
#include <string.h>

static inline int toNumber(char c) {
    return c - '0';
}

static inline char toCharacter(int n) {
    return n + '0';
}

char *divide(char *a, unsigned int divisor) {
    int length = strlen(a);
    char *quotient = malloc(length + 1);
    if (quotient == NULL) {
        return NULL;
    }
    int i, j;
    int localDivident = 0;
    for (i = 0, j = 0; i < length; i++) {
        if (a[i] == '0' && localDivident == 0) {
            quotient[j++] = '0';
        } else {
            if (localDivident != 0) {
                localDivident = localDivident * 10 + toNumber(a[i]);
            } else {
                localDivident = toNumber(a[i]);
            }
            int localQuotient = localDivident / divisor;
            if (localQuotient > 0) {
                quotient[j++] = toCharacter(localQuotient);
                localDivident -= localQuotient * divisor;
            }
        }
    }
    quotient[j++] = '\0';
    char *resized = realloc(quotient, j);
    return (resized == NULL) ? quotient : resized;
}

I have tested a variety of inputs and I have found that this function works surprisingly well, especially since I initially designed it with the intention of only handling single-digit divisors. However, I have found that it returns "\0" when the divisor is greater than the numeric interpretation of the input string. For example, divide("8\0", 9) returns "\0". One possible solution is adding a basic check like:

if (strtol(a, NULL, 10) < divisor) {
    char *trivialQuotient = malloc(2);
    if (trivialQuotient == NULL) {
        return NULL;
    }
    trivialQuotient[0] = '0';
    trivialQuotient[1] = '\0';
    return trivialQuotient;
}

But I find this solution inelegant, especially since the added computation of strtol will be pointless for the vast majority of executions, and I feel that there is a more elegant way for my algorithm to account for this scenario. I know that the line:

if (localQuotient > 0) {

is responsible for the result, but I could not think of a good way to modify it.

Also, I am torn between replacing the use of the static inlined functions like toNumber with a simple macro, like:

#define CTON(X) ((X) - '0')

I have read that the compiler may not always inline functions that are attributed with the inline modifier, and I know that the function should be inlined, which is why I am considering just using the macro.

(Also, I am aware that this function returns memory allocated using malloc which means that callers need to eventually free it.)


texts: UDP server for a multiplayer game using socketserver

texts:
I am making a multiplayer platforming game, and currently there are server performance issues once I have about 7+ clients connected. I was told earlier last week that I should investigate socketserver since previously I had been writing my own server using merely socket.

Well, after 6 hours of implementation I've got my server working with the new code.

As it stands now, I've seen no performance increase, but that's not surprising. I'm hoping that someone here could point me in the right direction and show me how to get more performance out of this thing.

The server is currently 600 lines of code, but I believe the bottleneck is the socketserver stuff.

So here is (hopefully) the relevant stuff.
And as always... thank you very much :)

import socket
import sys
import threading
import time
import pygame
import random
import json
import levels
import socketserver

class MyUDPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        data = self.request[0].strip()
        socket = self.request[1]
        gameserver.listen(data, self.client_address)

class ThreadingUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer):
    pass

class GameServer():
    def __init__(self):
        self.message_count = 100000
        self.message_dump = None
        self.text_block = []
        self.client_list = []
        self.client_hero_dict = {}
        self.client_obj_dict = {}
        self.queue = []

    def listen(self, data, addr):
        if addr not in self.client_list:
            Client(addr, self.dataHandler(data)) #Makes a client object for future reference
            print("Accepted connection: " + repr(addr))
            print("List of all connections: " + repr(self.client_list))

            for line in servermap.map: #This sends the map to the newly connected client
                line = "TILE" + line
                threading.Thread(target=self.clientHandler(line, addr))
            for obj in identifier.object_dict:
                threading.Thread(target=self.clientHandler(identifier.object_dict[obj]))
        self.dataHandler(data, addr)

    def textHandler(self, data):
        if data:
            data = "^^%s^^" % str(self.message_count) + data
            self.message_count += 1
            threading.Thread(target=self.clientHandler(data))

    def dataHandler(self, data, addr=None):
        data = data.decode()
        if data[0:2] == "^^": # if data is a chat message
            self.textHandler(data[2:])
        if data[0:2] == "*^": # if data is a movement request
            self.client_hero_dict[addr].actionfsm(data[2:])
        if data[0:6] == "**UN**": #if data is a username
            # self.client_obj_dict[addr] = data[6:]
            return data[6:]
            # self.client_hero_dict[addr].name = data[6:]
            # print(self.client_hero_dict[addr].name + " is the Username for " + repr(str(addr)))

    def clientHandler(self, message_to_send, specific_client=None):
        if type(message_to_send) == dict: #I use dictionaries as simple ways to send object (player/sprite) update information
                message_to_send = json.dumps(message_to_send)
        if specific_client:
            server.socket.sendto(message_to_send.encode(), specific_client)
        else:
            for client in self.client_list:
                server.socket.sendto(message_to_send.encode(), client)

I'm using threads but I'm not sure about the best way to utilize them. Having said that, I've also called socketserver.ThreadingMiIn but I not sure how to utilize it.


texts:
Trying to script a simple command line tool for ingesting media to a target location following a structured naming convention.

It's functional in its current state but I'd like to know if there are things to improve.

#!/usr/local/bin/bash

#make target directory for transfer

make_directory(){

    echo -e "\n\nFollow the prompt to create a project directory.\n\n"
    sleep .5

    while [[ -z "$target_directory" ]]
        do
                echo -e "Path of target directory?"
                read target_directory
        done

    while [[ -z "$brand" ]]
        do
            echo -e "\nBrand Prefix?"
            read brand
        done

    while [[ -z "$project" ]]
        do
            echo -e "\nProject Name?"
            read project
        done

    while [[ -z "$media_type" ]]
        do
            echo -e "\nMedia Type?"
            read media_type
        done

    while [[ -z "$location" ]]
        do
            echo -e "\nLocation?"
            read location
        done

    while [[ -z "$employee" ]]
        do
            echo -e "\nEmployee?"
            read employee
        done

    path=${target_directory}/$(date +'%Y%m%d')_${brand}_${project}_${media_type}_${location}_${employee}

    echo -e "\nCreating directory: ${path}\n\n"

    mkdir -p "${path}"

}

# construct rsync command

construct_rsync(){

    echo -e "\n\nFollow the prompt to construct the rsync command.\n\n"
    while [[ -z "$source_path" ]]
    do
        echo -e "Path to source media?"
        read source_path
    done

    if [[ "$option" == "2" ]]; then
        while [[ -z "$target_directory" ]]
        do
            echo -e "Target directory?"
            read target_directory
        done
    path=$target_directory
    fi

    while true;
    do
        read -p "Additional rsync options? [y/n] " rsync_add
        case $rsync_add in
            [Yy]* )
                echo -e "\nEnter additional rsync parameters:"
                read rsync_options
                break;;
            [Nn]* )
                break;;
            *) echo "Please enter y or no!"
        esac
 done

    echo -e "\nConstructing rsync command...\n"
    sleep .5
    echo -e "Running rsync command:\n
    rsync \n
    -r \n
    --info=progress2 \n
    --log-file=${path}/$(date +'%Y%m%d')_transfer_log.txt \n
    ${rsync_options} \n
    ${source_path}/ \n
    ${path} \n"

    rsync -r --info=progress2 --log-file="${path}/$(date +'%Y%m%d')_transfer_log.txt" ${rsync_options} "${source_path}/" "${path}"
}

# log exit code of rsync

log(){

    echo -e "\nCreating error log..."
    echo $? > "${path}/error_log.txt"

    sleep .5

    if [[ "$?" == "0" ]]; then
        echo -e "\nTransfer complete!"
    elif [[ "$?" != "0" ]]; then
        echo -e "\nError in transfer! Please refer to error_log.txt!"
    fi
}

# read user input and run appropriate functions

while true
do
read -p "Enter [1] to start an ingest or [2] to complete a partial ingest. " option

    case $option in

        1 )
            make_directory
            sleep .5
            construct_rsync
            sleep .5
            log
            break;;
      2 )
            construct_rsync
            sleep .5
            log
            break;;
      * )
            echo "Please enter a valid option!";;
    esac
done


texts: Finding unimplemented tasks on Rosetta Code using Requests

texts:
This is a Find unimplemented tasks task from Rosetta Code:

  Given the name of a language on Rosetta Code, find all tasks which are
  not implemented in that language.

There is already a solution that uses urllib, but I decided to add another one using Requests. I've never worked with this library before and would like my code to get reviewed. Any comments are welcome.

"""
Given the name of a language on Rosetta Code,
finds all tasks which are not implemented in that language.
"""
from functools import partial
from operator import itemgetter
from typing import (Dict,
                    Iterator,
                    Union)

import requests

URL = 'http://www.rosettacode.org/mw/api.php'
REQUEST_PARAMETERS = dict(action='query',
                          list='categorymembers',
                          cmlimit=500,
                          rawcontinue=True,
                          format='json')

def unimplemented_tasks(language: str,
                        *,
                        url: str,
                        request_params: Dict[str, Union[str, int, bool]]
                        ) -> Iterator[str]:
    """Yields all unimplemented tasks for a specified language"""
    with requests.Session() as session:
        tasks = partial(tasks_titles,
                        session=session,
                        url=url,
                        **request_params)
        all_tasks = tasks(cmtitle='Category:Programming_Tasks')
        language_tasks = set(tasks(cmtitle=f'Category:{language}'))
        for task in all_tasks:
            if task not in language_tasks:
                yield task

def tasks_titles(*,
                 session: requests.Session,
                 url: str,
                 **params: Union[str, int, bool]) -> Iterator[str]:
    """Yields tasks names for a specified category"""
    while True:
        request = session.get(url, params=params)
        data = request.json()
        yield from map(itemgetter('title'), data['query']['categorymembers'])
        query_continue = data.get('query-continue')
        if query_continue is None:
            return
        params.update(query_continue['categorymembers'])

if __name__ == '__main__':
    tasks = unimplemented_tasks('Python',
                                url=URL,
                                request_params=REQUEST_PARAMETERS)
    print(*tasks, sep='\n')

Current output for Python:

Calendar - for "REAL" programmers
Catmull–Clark subdivision surface
Checkpoint synchronization
Colour pinstripe/Printer
Compile-time calculation
Constrained genericity
Create an object at a given address
Deconvolution/2D+
Factorial base numbers indexing permutations of a collection
Fixed length records
Four is the number of letters in the ...
Function prototype
Hilbert curve
Parametric polymorphism
Pattern matching
Peano curve
Pinstripe/Printer
Rendezvous
Rosetta Code/Find bare lang tags
Start from a main routine
Suffixation of decimal numbers
Video display modes
Zeckendorf arithmetic


texts: Replacing files with symlinks to other files

texts:
I wrote a little Python script to replace some files in usr/bin with symlinks to files in a different location.

I wouldn't mind anyone telling me where I could do better.

#!/usr/bin/env python -tt

"""Xcode4 installs and expects to find a git installation at /usr/bin.
This is a pain if you want to control your own installation of git that
might be installed elsewhere. This script replaces the git files in
/usr/bin with symlinks to the preferred installation.

Update the 'src_directory' to the location of your preferred git installation.
"""
import sys
import os

#- Configuration  -----------------------------------------------------------------
src_directory = '/usr/local/git/bin/' # preferred installation
#----------------------------------------------------------------------------------

dest_directory = '/usr/bin/'
files = ('git','git-cvsserver','git-receive-pack','git-shell','git-upload-archive','git-upload-pack','gitk')

def main():
    if os.getuid():
        print "This script needs to be run as 'sudo python update_git.py'"
        sys.exit(1)

    for a_file in files:
        src_file = os.path.join(src_directory, a_file)
        dest_file = os.path.join(dest_directory, a_file)

        if os.path.exists(dest_file):
            os.remove(dest_file)

        os.symlink(src_file, dest_file)

if __name__ == '__main__':
    main()


texts:
In of my software engineering classes, I had to write a truth table calculator in the language of my choice.  This is what I came up with, and I would like to know what I should do better next time:

import copy
import sys

print("This program reads boolean equations and outputs the truth table.")
print("You may use the operators ~, ∨, and ∧, or")
print("their text equivalents, not, or, and and.")
print("You may use parenthesis, braces, and brackets to group your equations,")
print("and you must use single letters for your variable names, as 'a∨b'\n")

equation = input()
equation_copy = equation
equation_vars = []
equation = " " + equation + " "
equation = equation.replace("~", " not ")
equation = equation.replace("∨", " or ")
equation = equation.replace("∧", " and ")
equation = equation.replace("[", "(")
equation = equation.replace("]", ")")
equation = equation.replace("{", "(")
equation = equation.replace("}", ")")

for index in range(len(equation)):
    if equation[index] in " ()^":
        continue
    if equation[index + 1] in " ()" and equation[index - 1] in " ()" and equation[index] not in equation_vars:
        equation_vars.append(equation[index])

equation_vars.sort()

for equationIndex in equation_vars:
    sys.stdout.write(equationIndex + '\t')

print(equation_copy)

for equationIndex in range(pow(2,len(equation_vars))):
    vals = str(bin(equationIndex)).replace('0b','').zfill(len(equation_vars))

    for value in vals:
        sys.stdout.write(value + '\t')

    equation_vars_copy = copy.deepcopy(equation_vars)
    for index in range(len(equation_vars_copy)):
        equation_vars_copy[index] += " = " + vals[index]
        exec(equation_vars_copy[index])

    truthTable = "result = equation"
    truthTable = truthTable.replace('equation', equation)
    exec(truthTable)
    if result:print(1)
    else:print(0)

I have a working version at IdeOne.


texts:
I wanted to keep my API request logic separate form the controller logic. I therefore make use of a separate model (EmailChecker) that creates an instance of this class via EmailChecker.new(params).

Then I can check the new instance with valid?.

When it returns false I grep the errors and return it. This example only checks email but of course you can use any Rails validations on multiple parameters.

Problem is that I have to create a class for every API request you want to validate. Actually I don't mind because it makes the code easy to understand but it's not very DRY.

Any suggestions to improve this code?

class EmailChecker

  include ActiveModel::Validations
  include ActiveModel::Conversion
  include ActiveModel::Naming

  attr_accessor :email

  validates_format_of :email, :with => /\A[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}\z/i
  # validates :email, presence: true

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=",value)
    end
  end

  def persisted?
    false
  end

end #emailchecker