texts: Flexible presentation of a user's name based on a combination of available properties

texts:
The goal is to add a new displayValue property to each object depending on what it has available out of Firstname, Lastname, Nickname and Name.

I'd like this cleaned up.

var data = [
    {
        Id: 132,
        Name: null,
        Firstname: "Sam",
        Lastname: null,
        Nickname: "Dim",

    },
    {
        Id: 162,
        Name: null,
        Firstname: "Junior",
        Lastname: "Dimmer",
        Nickname: null,
    },
    {
        Id: 132,
        Firstname: null,
        Lastname: null,
        Nickname: "Dimmest",
    },
    {
        Name: "No Light",
        Id: 132,
        Firstname: null,
        Lastname: null,
        Nickname: null
    }
]

function formatPeople(data) {

    var yesProp = function (prop) {
        return data[i].hasOwnProperty(prop) && data[i][prop] !== null;
    }

    var noProp = function (prop) {
        return data[i].hasOwnProperty(prop) && data[i][prop] === null;
    }

    for (var i = 0, len = data.length; i < len; i += 1) {
        // if it has the property Name
        if (yesProp('Name')) {
            data[i].displayValue = data[i].Name;
        }
        if (yesProp('Lastname')) {
            if (yesProp('Firstname')) {
                // if it has the property Lastname and Firstname
                data[i].displayValue = data[i].Lastname + ', ' + data[i].Firstname;
            } else {
                if (yesProp('Nickname')) {
                    // if it has the property Lastname and Nickname but not Firstname
                    data[i].displayValue = data[i].Lastname + ', ' + data[i].Nickname;
                } else {
                    // if it has the property Lastname but not Firstname or Nickname
                    data[i].displayValue = data[i].Lastname;
                }
            }
        } else {
            if (yesProp('Firstname')) {
                if (yesProp('Nickname')) {
                    // if it does not have the property Lastname but does have Firstname and Nickname
                    data[i].displayValue = data[i].Firstname + ', ' + data[i].Nickname;
                } else {
                    // if it does not have the property Lastname or Nickname but does have Firstname
                    data[i].displayValue = data[i].Firstname;
                }
            } else {
                if (yesProp('Nickname')) {
                    // if it does not have the property Lastname or Firstname but does have Nickname
                    data[i].displayValue = data[i].Nickname;
                }
            }
        }
    }

    return data;
};


texts: Unit tests code for a Java class that that checks whether an array is sorted

texts:
I'm trying to write unit tests code for a java class. The class tests an array for sorted (either way) or not.

Here is the Unit Tests code:

public class SortedOrNotTest
{

   @Test
   public void test()
   {
      int[] A = { 32, 32, 32, 32, 32, 32, 32, 32, 34 };
      assertEquals(true, SortedOrNot.isSorted(A));

      int[] B = { 32, 32, 34, 33 };
      assertEquals(false, SortedOrNot.isSorted(B));

      int[] C = { 32 };
      assertEquals(true, SortedOrNot.isSorted(C));

      int[] D = {};
      assertEquals(true, SortedOrNot.isSorted(D));

      int[] E = { 32, 32, 31, 30, 32 };
      assertEquals(false, SortedOrNot.isSorted(E));
   }
}

Here is the Class, it checks an array is sorted or not in either way:

public class SortedOrNot
{

   public static boolean isSorted(int[] arr)
   {
      int n = arr.length;

      if(n<2) return true;

      int i = 0;
      while (i < n - 1 && arr[i] == arr[i + 1]) // same elements at the beginning
      {
         i++;
      }

      if (i == n - 1)
         return true;   // all same elements considered as sorted.

      if (arr[i] < arr[i + 1]) // candidate for ascending, non-decreasing
      {
         i++;

         for (; i < n - 1; i++)
         {
            if (arr[i] > arr[i + 1])
               return false;
         }

         return true;
      }

      else // candidate for descending, non-increasing
      {
         i++;

         for (; i < n - 1; i++)
         {
            if (arr[i] < arr[i + 1])
               return false;
         }
         return true;
      }
   }
}

Tests works, need to make sure that I'm doing in correct way.


texts: Return a list of values from a single column in a DataTable

texts:
I have this code that I was asked to maintain, it is a notification system for a third party application event system (a lot more involved than that but for the sake of this question...)

The Code uses a class DataTable Variable with 4 columns, it takes one of the columns and takes the distinct values and outputs them to a list, but the person that wrote the code made it no so dynamic values are static.

What I am looking for is a way that the underlying DataTable will determine the List<string> instead of having to go through all these if statements that have the wonderful magic strings.

private List<string> GetBaseTypes()
{
    List<string> baseTypes = new List<string>();
    var result = (
       from myRow in _allEventsList.AsEnumerable()
       select myRow.Field<string>("BaseTypeDesc"))
       .Distinct();

    var item = result
       .SingleOrDefault(e => e == "Order");
    if (item != null)
        baseTypes.Add(item);
    item = result
       .SingleOrDefault(e => e == "Motion");
    if (item != null)
        baseTypes.Add(item);
    item = result
       .SingleOrDefault(e => e == "Service");
    if (item != null)
        baseTypes.Add(item);
    item = result
       .SingleOrDefault(e => e == "Original Filing Document");
    if (item != null)
        baseTypes.Add(item);
    item = result
       .SingleOrDefault(e => e == "Amended Filing Documents");
    if (item != null)
        baseTypes.Add(item);
    item = result
       .SingleOrDefault(e => e == "Case Event Text");
    if (item != null)
        baseTypes.Add(item);
    item = result
       .SingleOrDefault(e => e == "Other Event Types");
    if (item != null)
        baseTypes.Add(item);
    item = result
       .SingleOrDefault(e => e == "Attorney Assignment");
    if (item != null)
        baseTypes.Add(item);
    item = result
       .SingleOrDefault(e => e == "Court Administration");
    if (item != null)
        baseTypes.Add(item);
    item = result
       .SingleOrDefault(e => e == "Physical Filing Location");
    if (item != null)
        baseTypes.Add(item);

    return baseTypes;
}

Does anyone see something that sticks out where I could simplify this code?

I have been tasked with changing the data going into the DataTable and I don't want to enter in new entries every time something is added to the "BaseTypeDesc" .


texts: Assembler-program which reverses the content of EAX

texts:
Following exercise:

  Write a program that takes a number (of size 4 bytes) x as input, and then
      reverses all the bits of x, and outputs the result. By reversing all bits we
      mean that the bit with original location i will move to location 31-i.
      Small example (for the 8 bit case):
        if x == {01001111}_2, then the output is {11110010}_2.
        In this example we reversed only 8 bits. Your program will be able to
        reverse 32 bits.

Full exercise-description can be seen here: XORPD GitHub

I tinkered out the following idea. Please take into account my comments too.

format PE console
entry start

include 'win32a.inc'

; ===============================================
section '.text' code readable executable

start:
    mov     eax,    0x4f    ; 0x4f is equal to 01001111 (from the exercise-description example).
    mov     cl,     0x1f    ; cl becomes the control variable. 0x1f == 31 decimal
    xor     edx,    edx     ; edx will accumulate the different states of ebx during the runtime.
process_bit:
    shr     eax,    0x1     ; Kick the right-most bit out ...
    jc      add_one         ; If it was a 1 jump to 'add_one' ...
    mov     ebx,    0x0     ;  ... otherwise write a 0 ...
    jmp     now_rotate
add_one:
    mov     ebx,    0x1
now_rotate:
    rol     ebx,    cl      ; The right-most bit has been fresh written. Now move it n-positions to the left.
    or      edx,    ebx     ; "Save" or "Add" the current positive bits (1-bits) of ebx to edx.
    loop    process_bit

    mov     eax,    edx
    call    print_eax_binary

    ; Exit the process:
    push    0
    call    [ExitProcess]

include 'training.inc'

I guess it works right.

Please compare the result on the screenshot with the example-value from the exercise-description.

What to think about my solution?

Is it valid? Or does it have to be improved?

Is there a better way to solve the described task?

Looking forward to read your hints and comments.


texts: php highlight search keywords [working solution]!

texts:
I just spent the whole night writing this little script for my search engine. Now i want to improve it.

Any ideas?

<?php
echo "KEYWORDS : ".  $searchstring  = "the and";

$sentence = "Skype Home is unavailable at the moment. Check back later to see your news and alerts.  It's easy to start a conversation on Skype:  Choose a contact and start talking Call a phone or mobile from the dial pad, or send an SMS.";

echo "

ORIGINAL STRING

$sentence";

$kt=split(' ',$searchstring); //Breaking the string to array of words

$num=1;

while(list($key,$val)=each($kt)){
    // do not load sentence from session on first run!

    if($num<=1){
    } else {
        $sentence  = $_SESSION['NewSentence'];
    }
    if($val<>" " and strlen($val) > 0){

        // make keyword bold and send entire sentence to session

        $_SESSION['NewSentence']    = eregi_replace ("$val", "$val", $sentence);
        // output sentence with added keyword

        echo "

$num bolding:  $val

  ".$_SESSION['NewSentence'];

        $num++;
    }
}

// make all bold keywords to red`

echo '

FINAL STRING

';
echo  $_SESSION['NewSentence'] = eregi_replace ("", "", $_SESSION['NewSentence']);

//destroy  session
unset($_SESSION['NewSentence']);
session_unregister($_SESSION['NewSentence']);?>


texts: Calculate function with optional operator argument

texts:
I am currently learning javascript at university. We have an assignment where we shall write various functions for calculating values. In one case, we shall write a function which returns the sum of two values, if only those two values were passed as arguments. If there is the third optional argument, which shall be an operation like subtract or multiply, than it should return the result of this operation.

Now, my question is: Is this code written in good way or is it like really bad style?

Btw: One assignment before, we should write the add, subtract and multiply functions in inside of this calculate function. So this was set.

 let rechne2b = function(a, b, ...operator){

   let addiere = function(a, b){
     return a + b;
   }

   let subtrahiere = function(a, b){
     return a - b;
   }

   let multipliziere = function(a, b){
     return a * b;
   }

   let argsLength = arguments.length

   if(argsLength > 2){
     switch(arguments[2].operation){

      case "subtrahiere":
       return subtrahiere(a, b);
       break;

     case "multipliziere":
      return multipliziere(a, b);
      break;
     }
   } else {
     return a + b;
   }

}

console.log(rechne2b(4, 5, {operation: "multipliziere"}))


texts:
Here is my first attempt to solve Jumble puzzle:

import argparse
from itertools import permutations

parser = argparse.ArgumentParser(description='Solver for Jumble')
parser.add_argument('jumbledwords', nargs='+',
                    help='One or more jumbled words')
argv = parser.parse_args()

# http://www-01.sil.org/linguistics/wordlists/english/wordlist/wordsEn.txt
words = [line.rstrip() for line in open('wordsEn.txt')]
for jumbledword in argv.jumbledwords:
    perms = set([''.join(p) for p in permutations(jumbledword)])
    legalwords = [word for word in perms if word in words]
    # print(len(perms))
    print(jumbledword, legalwords)

Any suggestions for improvement?


texts: Find two missing elements from a sorted array in given range

texts:
Looking for reviewers to suggest optimization and improvements, and to evaluate coding practices.

final class Variables {
    private final int x;
    private final int y;

    Variables(int x2, int y2) {
        this.x = x2;
        this.y = y2;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    @Override public String toString()  {
        return "x = " + x + " y = " + y;
    }
}

public final class FindMissing {

    private FindMissing() {};

    /**
 * Takes an input a sorted array with two variables that repeat in the
 * range. Remaining variable are consecutive. and returns two variables that repeats
 *
 * eg: for a range of 1,2,3,4, a valid input is [1, 4], [1, 3] etc.
 *
 * @param a : the sorted array.
 */
/*
 * Why is start needed ?
 * If start is not given then if a1 is empty how do we know if missing numbers were
 * [1, 2] or [4, 5] ??.
 */
public static Variables sortedConsecutiveTwoMissing (int[] a, int startOfRange) {
    if (a == null) throw new NullPointerException("a1 cannot be null. ");

    int low = startOfRange;
    // calculating the highest value of the range. it needs to be 2 more than length since all elememts are consecutive.
    int high = startOfRange + (a.length - 1) + 2;

    int i = 0;
    boolean foundX = false;
    int x = 0;

    while (i < a.length) {
        if (a[i] != low) {
            if (foundX) {
                return new Variables(x, low);
            } else {
                x = low;
                foundX = true;
            }
        } else {
            i++;
        }
        low++;
    }

    return new Variables(x, high);
 }

public static void main(String[] args) {
        // unsortedConsecutiveTwoMissing
        int[] a6 = {1, 4};
        System.out.println("Expected 2 and 3, Actual " + sortedConsecutiveTwoMissing(a6, 1));
        // unsortedConsecutiveTwoMissing
        int[] a7 = {-4, -1};
        System.out.println("Expected -3 and -2, Actual " + sortedConsecutiveTwoMissing(a7, -4));
        int[] a8 = {-4, -3, -2, -1};
        System.out.println("Expected 0 and 1, Actual " + sortedConsecutiveTwoMissing(a8, -4));
        int[] a9 = {5};
        System.out.println("Expected 4 and 6, Actual " + sortedConsecutiveTwoMissing(a9, 4));
        }
     }


texts:
I am creating a volume converter. It allows users to enter a value and select the unit to convert from and the one it will be converted into. It uses a <select> tag for user input selection.

The <select> looks like this:

<select name="from">
  <option value=0>--select--</option>
  <option value=1>cm3</option>
  <option value=2>m3</option>
  <option value=3>Feet3</option>
  <option value=4>Gallons(UK)</option>
  <option value=5>Gallons(US)</option>
  <option value=6>Inches3</option>
  <option value=7>Litres</option>
  <option value=8>Yards3</option>
  <option value=9>Quart(UK)</option>
</select>

And there is another one similar to this with the name "to".

After that I did the following in PHP:

$from=$_POST['from'];
$to=$_POST['to'];

function assign($from,$val)
      {
          switch ($from)
          {
              case 1:
                  $fromu="cm3";
                  $cm=1;
                  $me=0.000001;
                  $ft=0.000035315;
                  $gk=0.000219969;
                  $gs=0.000264172;
                  $in=0.061024;
                  $li=0.001;
                  $ya=0.000001308;
                  $qtk=0.000879877;
                  break;
               case 2:
                    $fromu="m3";
                    $cm=1000000;
                    $me=1;
                    $ft=35.32;
                    $gk=220;
                    $gs=264;
                    $in=61024;
                    $li=1000;
                    $ya=1.308;
                    $qtk=879.877;
                    break;

There are 7 more cases based on the html select "from" and each holds a value of conversion for each unit relative to the selection made.

It ends with:

        echo "

 ",$val," ",$fromu," equivalent is

 ",(double)($val*$cm)," CentiMeter3

 ",(double)($val*$me)," Meter3

 ",(double)($val*$ft)," Feet3

 ",(double)($val*$gk)," Gallons(UK)

 ",(double)($val*$gs)," Gallons(US)

 ",(double)($val*$in)," Inches3

 ",(double)($val*$li)," Litres

 ",(double)($val*$ya)," Yards3

 ",(double)($val*$qtk)," Quart(UK)

";
   }
   assign($from,$val);
}

How do I optimize this in a way that I can save all the conversion values (I'm thinking possibly in an associative array) and still be able to display one conversion based on user selection in the "to" select instead of outputting all of the converted units as seen above?


texts: Exercise for playing wordgames with user input

texts:
I'm trying to getting integer keyboard input to call the corresponding method.
invalid input works, keyboard input 3 works, input 2 exits, input 1 calls the wrong method.
I've not yet worked on the subtring and points problem method yet.
Regards, and I appreciate your feedback.
import java.io.File;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;

public class WordGames {

public static void main(String[] args) throws FileNotFoundException {

    getSelection();
    File file = new File("DICTIONARY.txt");
        if (file.isFile() == true) {
        }
        else {
            System.out.println("File doesn't exist.  Exiting.");
            System.exit(0);
        }

    subStringProblem();
    pointsProblem();

    }

    static String getSelection() {
        Scanner keyboardInput = new Scanner(System.in);
        System.out.println("Welcome to the Word Games program menu.");
        System.out.println("Select from one of the following options.");
        System.out.println("1. Substring problem.");
        System.out.println("2. Points problem.");
        System.out.println("3. Exit.");
        System.out.println("Enter your selections: ");

        if ( ! keyboardInput.hasNextInt()) {

           System.out.println("Invalid option.  Try again.");
           getSelection();

        } else if (keyboardInput.hasNextInt(1)){
            subStringProblem();
            getSelection();

        } else if (keyboardInput.hasNextInt(2)){
            pointsProblem();
            getSelection();

        } else if (keyboardInput.hasNextInt(3)){
        }    System.out.println("Good Bye!");
             System.exit(0);
        return null;
    }

    static String subStringProblem() {
        System.out.println("Substring problem.");
        System.out.println("Enter a Substring:");
    return null;
    }
    static String pointsProblem() {
        System.out.println("Points problem.");

    return null;
    }
}


texts:
The following code transforms multi-line input into the the Brainfuck equivalent. One line turns into one program. The resulting programs are split by newlines for readability.

Brainf.cpp

#include "Brainf.hpp"

int main()
{
    std::vector<std::string> userInput;
    std::string currentLine = " "; // do not start empty

    while (currentLine.length() != 0) // escape input by an empty line
    {
        std::getline(std::cin, currentLine);
        userInput.push_back(currentLine);
    }

    std::vector<std::string>::size_type userInputSize = userInput.size();

    for (unsigned i = 0; i < userInputSize; i++)
    {
        std::cout << modifyString(userInput[i]) << std::endl << std::endl;
    }
}

Brainf.hpp

#ifndef BRAINF_HPP
#define BRAINF_HPP

#include <iostream>
#include <map>
#include <string>
#include <vector>

std::string modifyChar(char input, int carry)
{
    std::string output;
    int next = input - carry;
    if (next > 0)
    {
        for (unsigned i = 0; i < next; ++i)
        {
            output += "+";
        }
    }
    if (next < 0)
    {
        for (unsigned i = 0; i < abs(next); ++i)
        {
            output += "-";
        }
    }
    output += ".";

    return output;
}

std::string modifyString(std::string input)
{
    std::string output;
    int traveller = 0;
    for (unsigned i = 0; i < input.length(); ++i)
    {
        output += modifyChar(input[i], traveller);
        traveller = (int)input[i];
    }
    return output;
}

#endif

Explanation:

The print statement in Brainfuck is .. The resulting Brainfuck prints the original string character-by-character, so there will be as much . as there are characters to print. Between those . there will be either + if the ASCII is higher than the previous character and - if it's lower.

The Brainfuck doesn't think. It increments, decrements or prints.

Example usage:

Input:

Hello World!

Output:

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++
++++++++++++++++++++++.+++++++..+++.--------------------------------------------
-----------------------------------.++++++++++++++++++++++++++++++++++++++++++++
+++++++++++.++++++++++++++++++++++++.+++.------.--------.-----------------------
--------------------------------------------.

Input:

FizzBuzz
Foo!Bar!

Output:

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++
++++++++++++++++++++++++++.+++++++++++++++++..----------------------------------
----------------------.+++++++++++++++++++++++++++++++++++++++++++++++++++.+++++
..

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.+++++++++
++++++++++++++++++++++++++++++++..----------------------------------------------
--------------------------------.+++++++++++++++++++++++++++++++++.+++++++++++++
++++++++++++++++++.+++++++++++++++++.-------------------------------------------
--------------------------------------.

Points of concern:

I'm bad at naming things.
My user-input handling feels bad.
There's a cast in my code which feels like a design flaw.
I may be needlessly repeating myself in one case while not splitting responsibilities far enough in another.
It's not modular.
It may not be idiomatic C++11.
It may not be safe (although IMHO, there's not much which can go wrong).


texts:
This a basic filter I created with Angular that does temperature conversion. I'd like to get thoughts on how to improve this code from both an Angular and general JS perspective.

The filter should take 2 arguments:

scale: The temperature scale to convert to
label: Whether to append a degree symbol to the number

In the view:

// should output: 99
{{ 37 | formatTemperature: 'F' }}

// should output: 99°
{{ 37 | formatTemperature: 'F':true }}

// should output: 37
{{ 98.6 | formatTemperature: 'C' }}

The filter:

(function() {
  'use strict';

  angular.module('example')
    .filter('formatTemperature', [
      function() {
        return function(input, scale, label) {
          var value = parseInt(input, 10),
              convertedValue;

          if (isNaN(value)) throw new Error('Input is not a number');

          if (scale === 'F') {
            convertedValue = Math.round(value * 9.0 / 5.0 + 32);
          } else if (scale === 'C') {
            convertedValue = Math.round((value - 32) * 5.0 / 9.0);
          } else {
            throw new Error('Not a valid scale');
          }

          return label ? convertedValue += '\u00B0' : convertedValue;
        };
      }
    ]);
})();

Testing the filter:

(function() {
  'use strict';

  describe('formatTemperature test', function() {
    beforeEach(module('example'));

    var filter;

    beforeEach(inject(function(_$filter_) {
      filter = _$filter_('formatTemperature');
    }));

    it('should convert temperature from Celsius to Fahrenheit', function() {
      expect(filter(37, 'F')).toEqual(99);
    });

    it('should convert temperature from Fahrenheit to Celsius', function() {
      expect(filter(98.6, 'C')).toEqual(37);
    });

    it('should append a % to the converted value', function() {
      expect(filter(37, 'F', true)).toEqual('99\u00B0');
    });

    it('should throw an error if the scale is invalid', function() {
      expect(function() {
        filter(37, 'G');
      }).toThrow(new Error('Not a valid scale'));
    });

    it('should throw an error if value is not a number', function() {
      expect(function() {
        filter('test', 'F');
      }).toThrow(new Error('Input is not a number'));
    });
  });

})();


texts: Parsing an XML file with elements for keys and values

texts:
I'm parsing an XML file that is structured like this:

<root>
  <entry>
    <elem1> key </elem1>
    <elem2> value </elem2>
  </entry>
  <entry>
  ....
  </entry>
</root>

</root>

My first code was using .parse() and .getRoot() but I had memory issues (1.5G memory use for 350M file). I solved my problem using an iterator and .clear() after reading this paper.

import xml.etree.ElementTree

myDict = {}

xmlIterator = xml.etree.ElementTree.iterparse('file.xml')

while True:
    try:
        _ , elem1 = next(xmlIterator)
        _ , elem2 = next(xmlIterator)
        _ , _     = next(xmlIterator)

    except StopIteration:
        break

    myDict[elem1.text]=elem2

    elem1.clear()
    elem2.clear()
    _.clear()

The issue is I need to access several children at the same time:

The first one is my key <elem1>
The second one is the value I need <elem2>
The third is not relevant <entry>

I would like to know if this is a good practice, or if there is a better way to do that (better performance or readability).

I also tried to follow the "Easier to ask for forgiveness than permission" principle with the exception block for ending the loop, but I'm not sure about multiple statements in the same exception block.

In fact, I also don't understand why the third element I get with next() is <entry>.


texts: Chart.js - Getting data from database using sql server and asp.net mvc5

texts:
I displayed and styled the chart.js and am also using mock data in the array, I just can't get my head around how to populate the data in the chart.js using MVC 5. I have tried lots of different methods and it's displaying data but not displaying the chart. Ideally, I need two datasets; one is for the weekly expense and one for the monthly expense. If anyone can suggest or point me in the right direction it would be much appreciated.

Index.cshtml

 <div style="width: 80%;">
        <canvas id="barChart" heigh="400" width="400"></canvas>
    </div>
    <script>

        var chart = document.getElementById("barChart").getContext('2d');
        Chart.defaults.global.animation.duration = 2000;
        var barChart = new Chart(chart,
            {
                type: 'bar',
                data: {
                    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                    datasets: [{
                            label: 'Weekly Expenses',
                            fill: true,
                            barTension: 0.1,
                            borderColor: '#2C3E50',
                            borderWidth: 2,
                            borderCapStyle: 'butt',
                            borderDash: [],
                            borderDashOffset: 0.0,
                            borderJoinStyle: 'miter',
                            pointBorderColor: "#2C3E50",
                            pointBackgroundColor: "#fff",
                            pointBorderWidth: 2,
                            pointHoverRadius: 8,
                            pointHoverBackgroundColor: "#2C3E50",
                            pointHoverBorderColor: "#2C3E50",
                            pointHoverBorderWidth: 5,
                            pointRadius: 10,
                            PointHitRadius:10,
                            data: [20,30,40,50,60,70,80,90,100,120,140,50]
                    },
                        {
                            label: 'Monthly Expenses',
                            fill: true,
                            barTension: 0.8,
                            backgroundColor: '#2C3E50',
                            borderColor: '#f0c419',
                            borderWidth: 2,
                            borderCapStyle: 'butt',
                            borderDash: [],
                            borderDashOffset: 0.0,
                            borderJoinStyle: 'miter',
                            pointBorderColor: "#f0c419",
                            pointBackgroundColor: "#fff",
                            pointBorderWidth: 1,
                            pointHoverRadius: 5,
                            pointHoverBackgroundColor: "#f0c419",
                            pointHoverBorderColor: "#f0c419",
                            pointHoverBorderWidth: 2,
                            pointRadius: 1,
                            PointHitRadius:1,
                            data: /*[10,20,30,40,50,60,70,80,90,100,110,120]*/ data
                        }
                    ]
                },
                options: {
                    scales: {
                        yAxes: [
                            {
                                ticks: {
                                    beginAtZero: true,
                                },
                            }]
                    }
                }

            });
    </script>


texts:
This algorithm finds the longest palindrome that is a  subsequence of a given input string in \$\Theta(n^2)\$.

Example

Input: character
Output: carac

Code

enum direction { vertical, horizontal, diagonal };

template<typename T>
using matrix = std::vector<std::vector<T>>;

void longest_palindrome_fill_tables(const std::string& input,
                       matrix<int> &lengths,
                       matrix<direction> &path) {

    int N = input.length();
    for (int i = 0; i < N; ++i) {
        lengths[i][i] = 1;
    }
    for (int range = 2; range <= N; ++range) {
        for (int i = 0, to = N - range + 1; i < to; ++i) {
            int j = i + range - 1;
            if (input[i] == input[j]) {
                path[i][j] = diagonal;
                lengths[i][j] = lengths[i + 1][j - 1] + 2;
            }
            else if (lengths[i][j - 1] > lengths[i + 1][j]) {
                path[i][j] = vertical;
                lengths[i][j] = lengths[i][j - 1];
            }
            else {
                path[i][j] = horizontal;
                lengths[i][j] = lengths[i + 1][j];
            }
        }
    }
}

void generate_palindrome(int i, int j ,
                        const matrix<direction>& paths,
                        const std::string &input,
                        std::deque<char> &palindrome) {
    if (i > j) {
        return;
    }
    if (i == j) {
        return palindrome.push_front(input[j]);
    }
    switch (paths[i][j]) {
    case diagonal:
        generate_palindrome(i + 1, j - 1, paths, input, palindrome);
        palindrome.push_back(input[j]);
        return palindrome.push_front(input[j]);
    case vertical:
        return generate_palindrome(i, j - 1, paths, input, palindrome);
    case horizontal:
        generate_palindrome(i + 1, j, paths, input, palindrome);
    }
}

std::string longest_palindrome(const std::string& input) {
    int N = input.length();
    matrix<int> lengths(N, std::vector<int>(N, 0));
    matrix<direction> paths(N, std::vector<direction>(N, diagonal));

    std::deque<char> palindrome;
    longest_palindrome_fill_tables(input, lengths, paths);
    generate_palindrome(0, N - 1, paths, input, palindrome);
    return std::string(palindrome.begin(), palindrome.end());
}


texts: Return index of array where sum first passes n

texts:
I have an array of integers and a number n.  I want to sum the elements of the array and return the index where the sum passes n, as efficiently as possible.

For example, assume:

theString = "6-7-7-10-7-6"
theNumber = 33

expected result: 5

This does the trick but not very efficiently: (and error prone; will check for errors when I've found the best solution)

Public Function getIndexFromSum(theString As String, theNumber As Integer) As Integer
    Dim theSides As Variant
    Dim sum As Integer
    Dim index As Integer

    theSides = Split(theString, "-")

    While sum <= theNumber
        sum = sum + theSides(index)
        index = index + 1
    Wend

    getIndexFromSum = index
End Function

I haven't been able to describe this to google succinctly enough to get any meaningful results, and searching for any combination of the keywords involved produces links to tons of unrelated stuff.  I'm sure this problem will have been encountered before (and likely has a smart solution out there somewhere), but I haven't been able to find any sites that can help.

Any help/advice would be very much appreciated!

EDIT - more info

1) theString will always be stored in the format "x-x-x".

2) theNumber will always be smaller than or equal to the sum of the numbers in theString.

3) The length of theString will be short - usually between 2 and 10 numbers, each less than 100.

4) The function will be called with small inputs, but many times.  Low overhead is top priority.


texts: Drawing a chessboard pattern using a nested for loop

texts:
I've been messing around with a software called Processing, used for user interactions and a lot of cool things. I programmed a pattern from a Chess set but I'm not sure if it's the best way to program it.

void setup() {
   size(400, 400);
   background(255);
}

int patternColor = 255;
void draw() {
   for (int y = 0; y < width; y += 50) {
      for (int x = 0; x < height; x += 50) {
         fill(patternColor);
         rect(x, y, 50, 50);

         if (patternColor == 255) {
            patternColor = 0;
         }
         else {
            patternColor = 255;
         }
      }

      if (patternColor == 0) {
         patternColor = 255;
      }
      else {
         patternColor = 0;
      }
   }
}


texts:
I am using CTR mode (it is a cipher in itself) in this code. I just wanted to see what you thought about it before I finish it.

(Yes, I know that the plaintext length and key length must be highly specific. I will take care of that with padding later.)

I just wanted to know if you thought if this code was cryptographically secure and if I could speed it up a little.

class Encrypt
{
    public string CTR(string p, string key)
    {
        StringBuilder sb = new StringBuilder();

        for (uint c = 0; c < (p.Length / key.Length); c++ )
        {
            char[] kc = key.ToCharArray();
            char[] E = new char[key.Length];

            char[] cc = c.ToString().ToCharArray();
            int inc = 0;
            foreach (char ch in kc)
            {
                E[inc] = (char)(ch ^ cc[0]); // Something goes wrong here when there are 2 digits in uint c. (CodeReview plz help)
                inc++;
            }

            char[] pc = p.ToCharArray();

            for (int i = 0; i < E.Length; i++)
            {
                sb.Append((char)(pc[i] ^ E[i]));
            }
        }

        return sb.ToString();
    }
}


texts: Two sprite-drawing functions for Amara game

texts:
Ideally I would have one draw method in the parent class (Player).

But I can't figure out how to do this. I don't know if there is anyway to decouple it totally. I don't mind modifying the sprite sheet so that it can handle this sort of thing.

Any tips are very welcome!!

Both classes inherit from Player.

var skeleton =  Player(x, y, hp, name, moveSpeed);
//drawing the fly

var draw = function(ctx) {

if (flyAnimate >= 30){
  flyAnimate = 0;
}
var bugX = canvas.width/2 + fly.getDrawAtX() - localX - 50;

if (fly.getAlive()){
  ctx.fillStyle="#FF0000";
  ctx.fillRect(bugX+30,fly.getDrawAtY()-50,((fly.getHp()/2.2)),6);
} else {
  ctx.fillText("DEAD", bugX + 37, fly.getDrawAtY()-40);
}

if (flyAnimate <= 10){
  ctx.drawImage(flySprite,0,0, 100, 100, bugX,fly.getDrawAtY()-50, 100, 100);
}

else if (flyAnimate <= 20){
  ctx.drawImage(flySprite,100,0, 100, 100, bugX,fly.getDrawAtY()-50, 100, 100);
}
else if (flyAnimate <= 30){
  ctx.drawImage(flySprite,200,0, 100, 100, bugX,fly.getDrawAtY()-50, 100, 100);
}
ctx.drawImage(silverShield, bugX+ 20, fly.getDrawAtY()-3);

if (descendAttack || rightMouseActionHappening){
  if (!rightMouseActionHappening){
    rightMouseActionHappening = true;
  }
  //200 is pretty badass
}

if (descendAttack) {
  ctx.save();
  ctx.translate(bugX+60, fly.getDrawAtY()-40 + 90);
  ctx.rotate(Math.PI);
  ctx.drawImage(silverSword, 0, -10);
  ctx.restore();
} else {
  ctx.drawImage(silverSword, bugX+ 60, fly.getDrawAtY()-40);
}
flyAnimate++;

ctx.fillStyle = "black";
ctx.font = "bold 13px sans-serif";
ctx.fillText(name, bugX + 22, fly.getDrawAtY()-60);
};

// drawing what I call a redhatter

var draw = function(ctx) {
//var drawAtX = skeleton.getX()-50;
if (skeleton.getMoveDirection() === "left"){
  facing_left = true;
} else if (skeleton.getMoveDirection() === "right"){
  facing_left = false;
}
if (facing_left){
  spritesheet_offset_y = 102;
}
else {
  spritesheet_offset_y = 0;
}
var   drawAtX = canvas.width/2 + skeleton.getDrawAtX() - localX - 50;

if (skeleton.getAlive()){
  ctx.fillStyle="#FF0000";
  ctx.fillRect(drawAtX+30,skeleton.getY()-50,((skeleton.getHp()/2.2)),6);
  ctx.fillStyle = "black";
} else { /* If it's dead, just write DEAD */
  ctx.fillText("DEAD", drawAtX + 37, skeleton.getY()-40);
}
ctx.fillStyle = "black";
ctx.font = "bold 13px sans-serif";
ctx.fillText(name, drawAtX + 25, skeleton.getY()-60);

/* Decides what sprite to draw*/
if (skeleton.getAnimate() <= 20){
  ctx.drawImage(RedhatterSprite,0,spritesheet_offset_y, 100, 100, drawAtX,skeleton.getY()-50, 100, 100);
}
else if (skeleton.getAnimate() <= 40){
  ctx.drawImage(RedhatterSprite,100,spritesheet_offset_y, 100, 100, drawAtX,skeleton.getY()-50, 100, 100);
}
else if (skeleton.getAnimate() <= 60){
  ctx.drawImage(RedhatterSprite,200,spritesheet_offset_y, 100, 100, drawAtX,skeleton.getY()-50, 100, 100);
} else{
  ctx.drawImage(RedhatterSprite,200,spritesheet_offset_y, 100, 100, drawAtX,skeleton.getY()-50, 100, 100);
}
};

Here is the full source on GitHub.


texts:
I need a little help in finding a better solution. In the screen shot below any change to the forecast line I need to find the value in column B. The screen shot is only a sample in my production sheet the row count is currently 4200.

           Column A  Col B   Col C   Col D  Col E
Row 5              January
Row 6      Prg Desc   SD      FG      GH      DF
Row 7      Forecast    1       2       3       4
Row 8      Actual
Row 9      Compare

My current code does what I need it to, however, I'm sure there is a better method of accomplish my goal. In my production sheet the value in B is in row 5.

CurMonth = target.Offset(5 - target.Row).Value
        If CurMonth = "" Then
                CurMonth = target.Offset((5 - target.Row), -1).Value
            If CurMonth = "" Then
                CurMonth = target.Offset((5 - target.Row), -2).Value
            If CurMonth = "" Then
                CurMonth = target.Offset((5 - target.Row), -3).Value
            End If
            End If

        End If
    Debug.Print CurMonth

Any suggestions would be very appreciated.


texts: Sidekiq worker to validate survey participants

texts:
I have worker code that looks like this:

class VerificationWorker
  include Sidekiq::Worker

  def perform(panel_id)
    members = MembersAPI.members.fetch

    members.each do |member|
      survey = Survey.find_by(number: member.data_number)
      next if survey.nil?

      if survey.id != member.data['survey_id']
        survey.fail!('survey_id does not match')
        next
      end

      survey.recipient_id = member.id if survey.recipient_id.blank?
      survey.recipient_id == member.id ? survey.verify! : survey.fail_panel!('recipient_id does not match member id')
    end
  end
end

What do you think about this code? Is it good enough?


texts:
This is my implementation of Project Euler #2 in C#.  It takes 0 milliseconds to run, and I believe it is correct - I have seen nothing to indicate otherwise!

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

static void GetFibos(ref List<int> nums, int maxVal)
{
    nums.Add(1);
    int lastNum = 2;

    while (lastNum <= maxVal)
    {
        nums.Add(lastNum);
        lastNum = nums[nums.Count - 2] + nums[nums.Count - 1];
    }
}

static void Main(string[] args)
{
    Stopwatch s = new Stopwatch();
    s.Start();

    List<int> fiboNums = new List<int>();
    GetFibos(ref fiboNums, 4000000);

    int sumEvenFibos = 0;

    foreach (int i in fiboNums) { if (i % 2 == 0) sumEvenFibos += i; }

    s.Stop();

    Console.WriteLine(sumEvenFibos);
    Console.WriteLine(s.ElapsedMilliseconds);
}

Is there anything I should be doing different?


texts: Dynamically adding rows to an accessible HTML form

texts:
Given the following HTML form (fragment):

<fieldset id="timesheet-rows">
    <legend>Add Entries</legend>

      Project
      <select id="project-0" name="project-0" required>
        <option value="" />
      </select>

      Department
      <select id="department-0" name="department-0" required>
        <option value="" />
      </select>

      Task:
      <select id="task-0" name="task-0" required>
        <option value="" />
      </select>

      Hours:
      <input type="number" step="0.25" id="hours-0" name="hours-0" width="1" placeholder="2.0" required />

      Comment:
      <input type="text" id="comment-0" name="comment-0" width="50" />

    <input type="button" id="add-row" name="add-row" value="Add row" />

  </fieldset>

I have implemented the following jQuery (fragment) to clone each 'timesheet row'
 along with the  tags, which are not caught by $(':input'):

$(document).ready(function() {

  var current_id = 0;
  $('#add-row').click(function(){
    next_element($('#timesheetrow-0'));
  })

  function next_element(element){
    var new_element = element.clone(),
        id = current_id + 1;
    current_id = id;
    new_element.attr("id",element.attr("id").split("-")[0]+"-"+id);

    // Ajuster les `id` et `name` dans les <input />s et <select />s
    $(':input', new_element).each(function(){
      var field_id = $(this).attr("id"),
          field_name = $(this).attr("name");
      $(this).attr("id", field_id.split("-")[0]+"-"+id );
      $(this).attr("name", field_name.split("-")[0]+"-"+id );
    });

    // Ajuster le for="" dans les s
    $('label', new_element).each(function(){
      field_for = $(this).attr("for");
      $(this).attr("for", field_for.split("-")[0]+"-"+id );
    });
    new_element.appendTo($("#timesheet-rows"));
  };
});

(Above jQuery was inspired by http://jsfiddle.net/32RgL/ ).

Is there a more elegant or complete way of doing this?


texts:
I'm kind of new to Java but I am writing an Android app. Right now I'm working on an async task to calculate Pi but when I run it the memory usage increases alarmingly (+5MB per second). This one piece of code may need to run thousands of times so it is important that it be very optimized.

protected BigDecimal doInBackground(Object... params) {
        digits = (int)params[0];
        piView = (TextView)params[1];
        boolean add = true;
        BigDecimal pi = new BigDecimal(0.0);
        for(int i=1; pi.setScale(digits, BigDecimal.ROUND_DOWN).equals(realPi) == false; i++){
            if(add){
                pi = pi.add(new BigDecimal(4.0 / (-1 + (i*2))));
                add = false;
            }
            else {
                pi = pi.subtract(new BigDecimal(4.0 / (-1 + (i*2))));
                add = true;
            }
        }
        return pi;
    }

This one piece of code may need to run thousands of times so it is important that it be very optimized.


texts:
What would be the most elegant way to refactor the following method?

 public void AddOrUpdateDesignCVT(DesignInformation designInformation,
                            CommonTransformerProperties commonTransformerProperties,
                            SecondaryWindings secondaryWindings,
                            CapacitorVoltageDivider capacitorVoltageDivider,
                            IntermediateVoltageTransformer intermediateVoltageTransformer,
                            SpecialDesignInformation specialDesignInformation,
                            TransformerLimits transformerLimits)
    {

        GenerateWindingInstructions(designInformation);

        Design design;
        using (var context = new DesignContext())
        {

            if (!DesignExist(designInformation.DesignID))
            {

                context.DesignInformation.Add(designInformation);
                context.CommonTransformerPropeteries.Add(commonTransformerProperties);
                context.SecondaryWindings.Add(secondaryWindings);
                context.CapacitorVoltageDivider.Add(capacitorVoltageDivider);
                context.IntermediateVoltageTransformer.Add(intermediateVoltageTransformer);
                context.SpecialDesignInformation.Add(specialDesignInformation);
                context.TransformerLimits.Add(transformerLimits);
                context.SaveChanges();
                return;
            }
        }

            using (var newcontext = new DesignContext())
            {
                design = GetDesingByNameFromDatabase(newcontext, designInformation.DesignID, designInformation.Technology);

                UpdateSecondaryWindings(design, newcontext, designInformation, secondaryWindings);

                UpdateSpecialWires(design, newcontext, designInformation, specialDesignInformation);

                newcontext.SaveChanges();
            }
            int dbId = design.DesignInformation.DataBaseID;

            design.DesignInformation = designInformation;
            design.DesignInformation.DataBaseID = dbId;

            design.CommonTransformerProperties = commonTransformerProperties;
            design.CommonTransformerProperties.DataBaseID = dbId;

            design.SecondaryWindings = secondaryWindings;
            design.SecondaryWindings.DataBaseID = dbId;

            design.CapacitorVoltageDivider = capacitorVoltageDivider;
            design.CapacitorVoltageDivider.DataBaseID = dbId;

            design.IntermediateVoltageTransformer = intermediateVoltageTransformer;
            design.IntermediateVoltageTransformer.DataBaseID = dbId;

            design.SpecialDesignInformation = specialDesignInformation;
            design.SpecialDesignInformation.DataBaseID = dbId;

            using (var newcontext = new DesignContext())
            {
                newcontext.Entry(design.CommonTransformerProperties).State = System.Data.Entity.EntityState.Modified;
                newcontext.Entry(design.SecondaryWindings).State = System.Data.Entity.EntityState.Modified;
                newcontext.Entry(design.CapacitorVoltageDivider).State = System.Data.Entity.EntityState.Modified;
                newcontext.Entry(design.IntermediateVoltageTransformer).State = System.Data.Entity.EntityState.Modified;
                newcontext.Entry(design.SpecialDesignInformation).State = System.Data.Entity.EntityState.Modified;
                newcontext.Entry(design.DesignInformation).State = System.Data.Entity.EntityState.Modified;
                newcontext.SaveChanges();
                return;
            }
    }


texts:
I am using below command to assign a value, Is there a alternative way to get by tweaking the code
var=hdfs dfs -ls /hdfs_path/ | grep col=2020_03 | awk -F' ' '{system("hdfs dfs -count "$8)}' | awk -F' ' '{if ($3 != 0) print $4}' | awk -F'=' '{print $2}'|sort -nr | uniq | head -1

Basically i am need to find the latest month value that holds data in hdfs directory. For eg
hdfs_path/col=2020_03_21/data.part - this has no data
    hdfs_path/col=2020_03_20/data.part - this has data
    hdfs_path/col=2020_03_19/data.part - this has data

hence output should be val = 2020_03_20


texts: Java blocking queue download process scenario

texts:
I have the following scenario .
I have incoming file download requests and each download is happening in different thread until pool size is exceeded. And after  a download completed, a processor processes the downloaded item. So I created the following. I wonder if uses of thread and executors make sense
DownloadTaskProcessor
public class DownloadTaskEnqueuer {
    private static final BlockingQueue<Task> downloadQueue = new LinkedBlockingQueue<>();
    private static final BlockingQueue<Task> processQueue = new LinkedBlockingQueue<>();
    private static final ExecutorService executor = Executors.newCachedThreadPool();

    public void offer(Task task) {
        return downloadQueue.offer(task);
    }

    public void createPool(int size) {
        for (int i = 0; i < size; i++) {
            executor.execute(new DownloadTask(downloadQueue, processQueue);
            executor.execute(new ProcessTask(processQueue));
        }
    }
}

Download task
public class DownloadTask implements Runnable {
    private BlockingQueue<Task> downloadQueue;
    private BlockingQueue<Task> processQueue;

    // constructor for initing two queue

    public void offer(Task task) {
        return processQueue.offer(task);
    }

    @Override
    public void run() {
        while (true) {
           Task task = downloadQueue.poll();
           if (task != null) {
               task.getDownloadTask().download();
               offer(task);
           } else {
               // sleep 250 ms
           }
        }
    }
}

Process task
public class ProcessTask implements Runnable {
    private BlockingQueue<Task> processQueue;

    // constructor for initing queue

    @Override
    public void run() {
        while (true) {
           Task task = processQueue.poll();
           if (task != null) {
                task.getProcessTask().process();
           } else {
               // sleep 250 ms
           }
        }
    }
}

Use case (pseudo)
createPool(10);

listener.listen((task) -> {
    downloadTaskEnqueuer.offer(task);
}


texts:
This is a little net health monitoring project I made in NodeJS. It pings Google every second and stores the result (true/false) along with the date in a database (MongoDB). I've collected enough data and I want to represent it for the past week.

I created a 2x2 array of 7 days and 24 hours each. I go through each record and map it to the appropriate day and hour of the week. And I give that hour a little score: if true +1, if false -5. And it creates a little matrix like this:

[
    [2015, 1724, 1733, 1679, ...
    [1818, 1909, 1614, 1829, ...
    [1632, 1778, 1726, 1657, ...
    ...
]

The only problem is computation takes ~10-15 seconds and lots of CPU for going through ~200k records of just 3 days.

Is there some scope for improvement here?

days = days || 3;
var counter = 0
this.find({
    date: {
        // Date greater than (Now - X days)
        $gt: new Date(Date.now() - days * 24 * 3600 * 1000),
    },
}, function(err, datums) {
    var week = new Array(days);
    for (var i = 0; i < week.length; i++)
        week[i] = new Array(24);
    // Empty Week Matrix (7x24)
    datums.forEach(function(data) {
        counter++;
        var date1 = data.date;
        var date2 = new Date();
        var timeDiff = Math.abs(date2.getTime() - date1.getTime());
        var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
        //stackoverflow.com/q/3224834/1266650

        var day = days - diffDays;
        if (day < 0) return;
        var hour = data.date.getHours();

        if (!week[day][hour]) week[day][hour] = 0;
        if (data.isNetAlive)
            week[day][hour]++;
        else
            week[day][hour] -= 5;
    });
    console.debug(week);
    console.debug(counter, 'records');
});


texts:
These two functions act on a stack, an array of integers (whose first element is the top of the stack, LIFO).

The first function retrieves the first element and puts it at the end. The other is the opposite.

I would like to combine these two functions into only one function, if possible. (I have a constraint, 25 lines maximum)

int     *reverse(int value, int size, int *stack)
{
    int     value;
    int     i;
    int     *previous;

    value = *stack;
    previous = stack;
    if (!(stack = (int*)malloc(sizeof(int) * size)))
        return (NULL);
    i = 1;
    while (i < size)
    {
        stack[i - 1] = previous[i];
        i++;
    }
    stack[i - 1] = value;
    free(previous);
    return (stack);
}

int     *sv_reverse(int value, int size, int *stack)
{
    int     value;
    int     i;
    int     *previous;

    value = stack[size - 1];
    previous = stack;
    if (!(stack = (int*)malloc(sizeof(int) * size)))
        return (NULL);
    *stack = value;
    i = 1;
    while (i < size)
    {
        stack[i] = previous[i + 1];
        i++;
    }
    free(previous);
    return (stack);
}


texts: Encoding/decoding protocol messages to/from various bits of hardware

texts:
The basic idea is for users of these classes to create derived polymorphic protocol specific messages. There is no protocol type in the interface, it is all hidden behind the scenes.  But the serialised messages can be retrieved with the getMessage functions.

Does this look a logical approach?  Any suggestions?

//base protocol class - interface only
//ref_type is a smart pointers class - not really so relevant to my question
class BaseMessage : public ref_type
{
public:
    virtual ~BaseMessage() {}
    virtual const char* ProtocolName() const = 0;
    virtual bool Encode() = 0;
    virtual bool Decode() = 0;
    //for binary protocols
    virtual void getMessage(unsigned char*& serialised, size_t& length) {};
    //for text/xml protocols
    virtual void getMessage(std::string& serialised) {}
};

A specific protocol might then be implemented like this:

class ABCMessage : public BaseMessage {
public:
   ABCMessage(ABC* msg) : m_msg(msg), m_data(0), m_length(0) {}
   ABCMessage(unsigned char* data, int length) : m_length(length), m_msg(0)
   {
      m_data = new unsigned char[length]();
      memcpy(m_data, data, length);
   }
   virtual ~ABCMessage();
   virtual const char* ProtocolName() const;
   virtual bool Encode();
   virtual bool Decode();

   virtual void getMessage(unsigned char*& serialised, size_t& length);

protected:
   ABC* m_msg;
   unsigned char* m_data;
   size_t m_length;
};


texts: Swap Elements in Array if first characters match but only once per first character

texts:
This is my solution to CodingBat problem p150113.  My Java knowledge is from 2011 and I'd like to know if this is still the optimal way to approach such a problem. and if my code is clean and understandable.

  We'll say that 2 strings "match" if they are non-empty and their first chars are the same. Loop over and then return the given array of non-empty strings as follows: if a string matches an earlier string in the array, swap the 2 strings in the array. A particular first char can only cause 1 swap, so once a char has caused a swap, its later swaps are disabled. Using a map, this can be solved making just one pass over the array.

firstSwap(["ab", "ac"]) → ["ac", "ab"]
firstSwap(["ax", "bx", "cx", "cy", "by", "ay", "aaa", "azz"]) → ["ay", "by", "cy", "cx", "bx", "ax", "aaa", "azz"]
firstSwap(["ax", "bx", "ay", "by", "ai", "aj", "bx", "by"]) → ["ay", "by", "ax", "bx", "ai", "aj", "bx", "by"]

public String[] firstSwap(String[] strings) {
  HashMap<String,Integer> hashMap = new HashMap<>();
  int counter = 0;
  int index = 0;
  for (String s : strings){
    String firstChar = s.substring(0,1);
    if(hashMap.containsKey(firstChar)){
      // make the switch in the array
      if(hashMap.get(firstChar) > -1){
        index = hashMap.get(firstChar);
        String temp = strings[counter];
        strings[counter] = strings[index];
        strings[index] = temp;
        // make sure it doesn't get swapped again:
        hashMap.put(firstChar,-1);
      }
    } else {
      hashMap.put(firstChar,counter);
    }

    counter = counter + 1;
  }
  return strings;
}


texts: Pausing task until designated time using sleep()

texts:
I have been playing around with schedule from GitHub.  How can I improve the code?

def main():
    wipe()

    run_at_time = user_choice()

    if run_at_time:

        schedule.every().day.at(run_at_time).do(multi_processing)
        print('Schedule starts at: ''' + run_at_time + ' - Waiting for time...')
        print(space)
        idle = int(round(schedule.idle_seconds()))

        Hours = (idle / 60) / 60
        Minutes = (idle / 60)

        print("Hours left:   " + str(float("%.2f" % ((Hours)))) + "h")
        print("Minutes left: " + str(float("%.2f" % ((Minutes)))))
        print("Seconds left: " + str(float("%.2f" % ((idle)))))

        print(space)

        while True:
            schedule.run_pending()
            time.sleep(1)
            idle = int(round(schedule.idle_seconds()))
            if (idle < 6.0) and (idle >= 0.0):
                print('Starting in: ' + str(idle))

    else:
        multi_processing()

def user_choice():

    while True:
        user_input = input('To run Schedule task - Press y\nTo run directly - Press n\n').lower()
        print(user_input)
        if (user_input == 'y'):
            print(Fore.RESET + space)
            time_user = input('What time to start script? Format - HH:MM\n')
            print(space)
            return time_user

        elif (user_input == 'n'):
            return False

        print(space)
        print("Wrong input - Try again")’’’


texts:
Challenge

Write a program which reads a file containing Morse Code and outputs the conversion.

Specifications

The first argument is a path to a file.
The file contains multiple lines.
Each line is a string of Morse code.

Each letter is separated by a space.
Each word is separated by two spaces.

Constraints

The input file is correctly formatted.
The Morse Code strings are alphanumeric.

Sample Input

.- ...- ..--- .-- .... .. . -.-. -..-  ....- .....
-... .... ...--

Sample Output

  AV2WHIECX 45
  BH3

Source

My Solution:

import sys
import re

morse_alphabet = {
    ''      : ' ',
    '.-'    : 'A',
    '-...'  : 'B',
    '-.-.'  : 'C',
    '-..'   : 'D',
    '.'     : 'E',
    '..-.'  : 'F',
    '--.'   : 'G',
    '....'  : 'H',
    '..'    : 'I',
    '.---'  : 'J',
    '-.-'   : 'K',
    '.-..'  : 'L',
    '--'    : 'M',
    '-.'    : 'N',
    '---'   : 'O',
    '.--.'  : 'P',
    '--.-'  : 'Q',
    '.-.'   : 'R',
    '...'   : 'S',
    '-'     : 'T',
    '..-'   : 'U',
    '...-'  : 'V',
    '.--'   : 'W',
    '-..-'  : 'X',
    '-.--'  : 'Y',
    '--..'  : 'Z',
    '-----' : '0',
    '.----' : '1',
    '..---' : '2',
    '...--' : '3',
    '....-' : '4',
    '.....' : '5',
    '-....' : '6',
    '--...' : '7',
    '---..' : '8',
    '----.' : '9'
}

def decode(morse):
    decoded = ''
    line = re.split('\s', morse)
    for letter in line:
        decoded += morse_alphabet.get(letter)
    return decoded

def main(filename):
    with open(filename) as input_file:
        for line in input_file:
            print(decode(line))

if __name__ == "__main__":
    try:
        main(sys.argv[1])
    except:
        sys.exit("No argument provided / file not found.")

Applying the insight gained from my previous question. It seems fairly succinct but I wonder is it pythonic?


texts: More efficient version of an ID calculator in JavaScript

texts:
The following function takes two numbers that are linked with a "user" and calculates an ID number based on that. I have been trying to make this as clean as possible, and would like some advice on how to make this more efficient. an example of the input would be  "12195491" for the num and "3120" for the ts, which would output "8511"

function getidnumber(num, ts) {
            num = num.substr(4, 4);
            ts = ((ts == undefined) ? "3452" : (ts));
            var _local5 = "";
            var _local1 = 0;
            while (_local1 < num.length) {
                var _local4 = Number(num.substr(_local1, 1));
                var _local3 = Number(ts.substr(_local1, 1));
                var _local2 = String(_local4 + _local3);
                _local5 = _local5 + _local2.substr(_local2.length - 1);
                _local1++;
            }
            return("@user" + _local5);
};


texts:
I have two accordions on the same page

First, I have a page, Freemarker, that includes two other Freemarkers that have the accordion.

[#include "page1.ftl"]
[#include "page2.ftl"]

On page1:

&nbsp;&nbsp;&nbsp;&nbsp;Page1

On page2:

&nbsp;&nbsp;&nbsp;&nbsp;Page2

In the Javascript file:

$(document).ready(function(){
  $('#toggle-image').attr("class", "toggle-image-expand");
    //Hide (Collapse) the toggle containers on load
    $(".toggle-container").hide();

    $("h3.trigger").click(function(){
        $(this).toggleClass("active").next().slideToggle("slow");

        if($('#toggle-image').attr("class") == "toggle-image-collapse") {
            $('#toggle-image').attr("class", "toggle-image-expand");
        } else {
            $('#toggle-image').attr("class", "toggle-image-collapse");
        }
        return false;
    });
});

$(document).ready(function(){
  $('#toggle-image2').attr("class", "toggle-image-expand");
    //Hide (Collapse) the toggle containers on load
    $(".toggle-container2").hide();

    $("h3.trigger2").click(function(){
        $(this).toggleClass("active").next().slideToggle("slow");

        if($('#toggle-image2').attr("class") == "toggle-image-collapse") {
            $('#toggle-image2').attr("class", "toggle-image-expand");
        } else {
            $('#toggle-image2').attr("class", "toggle-image-collapse");
        }
    return false;
});

It works fine, but the redundant code I used in JS is typical and the difference is on the variable it uses. How could I make it dynamic?


texts:
I'm trying to figure out how to do this more dynamically. Right now I save each and every form field individually/manually. I would love to maybe have some kind of master form list that I could loop through. I'm fairly new to C#, so I don't know many tricks yet. Please let me know what you think.

Here is my simplified version of my code:

Note: None of the variable names are numbered in my real code. I changed them for simplicity in my example. So I can't loop through form names by iterating.

//BINDED FORM COLLECTION
public class FormLink
{
    private string _fObj1;
    private string _fObj2;
    private string _fObj3;
    private string _fObj4;
    private bool _fObj5;
    private bool _fObj6;
    private bool _fObj7;

    public string fObj1
    {
        get
        {
            return this._fObj1;
        }
        set
        {
            this._fObj1 = value;
        }
    }

    public string fObj2 { /*...*/ }
    public string fObj3 { /*...*/ }
    public string fObj4 { /*...*/ }
    public bool fObj5 { /*...*/ }
    public bool fObj6 { /*...*/ }
    public bool fObj7 { /*...*/ }
}

//SETTINGS HANDLE
public class Settings
{
    private string SettingsFile = "settings.xml";
    FormLink form;

    public Settings(FormLink form)
    {
        this.form = form;
    }

    public void iStart()
    {
        if (!File.Exists(this.SettingsFile))
        {
            this.createDefaultsFile();
        }

        this.iLoad();
    }

    public void iEnd()
    {
        this.alterNodeValue(this.SettingsFile, "Settings", "fObj1", this.form.fObj1.ToString());
        this.alterNodeValue(this.SettingsFile, "Settings", "fObj2", this.form.fObj2.ToString());
        this.alterNodeValue(this.SettingsFile, "Settings", "fObj3", this.form.fObj3.ToString());
        this.alterNodeValue(this.SettingsFile, "Settings", "fObj4", this.form.fObj4.ToString());
        this.alterNodeValue(this.SettingsFile, "Settings", "fObj5", this.form.fObj5.ToString());
        this.alterNodeValue(this.SettingsFile, "Settings", "fObj6", this.form.fObj6.ToString());
        this.alterNodeValue(this.SettingsFile, "Settings", "fObj7", this.form.fObj7.ToString());
    }

    private void createDefaultsFile()
    {
        XDocument xml = new XDocument(
            new XElement("Settings",
                new XElement("fObj1", "string"),
                new XElement("fObj2", "string"),
                new XElement("fObj3", "string"),
                new XElement("fObj4", "string"),
                new XElement("fObj5", false),
                new XElement("fObj6", false),
                new XElement("fObj7", false),
            ));
        xml.Save(this.SettingsFile, SaveOptions.None);
    }

    private void iLoad()
    {
        var settings = this.getNodes(XDocument.Load(this.SettingsFile, "Settings");

        this.form.fObj1 = Help.getDictVal(settings, "fObj1");
        this.form.fObj1 = Help.getDictVal(settings, "fObj2");
        this.form.fObj1 = Help.getDictVal(settings, "fObj3");
        this.form.fObj1 = Help.getDictVal(settings, "fObj4");
        this.form.fObj1 = Help.getDictVal(settings, Help.stringToBool("fObj5"));
        this.form.fObj1 = Help.getDictVal(settings, Help.stringToBool("fObj6"));
        this.form.fObj1 = Help.getDictVal(settings, Help.stringToBool("fObj7"));
    }

    private void alterNodeValue(string xmlFile, string parent, string node, string newVal)
    {
        /* Alters a single XML Node and saves XML File */
    }

    private Dictionary<string, string> getNodes(XDocument xml, string parent)
    {
        /* Retrieves all Child Nodes of specified Parent and returns them in a Dictionary */
    }
}

//Basic Utilies class
public static class Help
{
    public static bool stringToBool(string BoolMe)
    {
        /* Safely converts String to Bool */
    }

    public static string getDictVal(Dictionary<string, string> dict, string key)
    {
        /* Safely gets value from Dictionay based on Key*/
    }
}


texts:
I have a query that populates an array from the database. In some cases, this query returns a great amount of data, (let's say for purpose of an example, 100.000 records). Each row of the database has at least 6 or 7 columns.

$results = [
  ['id' => 1, 'name' => 'name', 'status' => true, 'date' => '10-01-2012'],
  ['id' => 2, 'name' => 'name 2', 'status' => false 'date' => '10-01-2013'],
  ...
]

I need to perform a substitution of some of the data inside the $results array, based on another one that give me some information about how i would change the values in the rows.

$model = [
    'status' => ['function' => 'formatStatus', params => ['status']],
    'date' => ['function' => 'formatDate', params => ['date']]
]

Now that I have all the data, what do I do with it? I have the following routine:

foreach ($results as &$itemResult) {
        $oldValues = $itemResult;
        foreach ($itemResult as $attribute => &$value) {
            if (isset($model[$attribute]['function'])) {
                $function = $model[$attribute]['function'];
                $params = $model[$attribute]['params'];
                $paramsSize = count($params);
                for ($i = 0; $i < $paramsSize; $i++) {
                    $newParams[] = $oldValues[$params[$i]];
                }
                $itemResult[$attribute] = call_user_func_array([$this, $function], $newParams);
                $newParams = null;
            }
        }
    }

So, for each attribute for each row of my data array, I run check for the existence of a function and params information. When the attribute in question needs to be replaced, I call the function via call_user_func_array and replace the value with the function return value.

Also notice that I am replacing the current array, not creating another, by passing the reference &$itemResult inside the loop, so in the end, I have the same array from the beginning but with all columns that needed to be replaced with its new values.

The thing is, for little arrays, this method is quite good. But for big ones, it becomes a pain. I do believe that an array this size consumes so much RAM that makes the whole algorithm slow.

Could you provide me with some alternative to the problem? Should I use another data structure instead of the PHP array?


texts: Module for providing users easy access to all social networking websites

texts:
The following piece of code will act as a single access to all social networks. It aims to connect different social networks to get a broader picture of the social life of a user. I have just committed the code for Twitter access, but similar access will be provided to Facebook and Github.

The code is available here.

I'd appreciate any and all comments-- correctness, style, best practices, logging, error handling.

import tweepy
import TwitterConfig as config_twitter

class Twitter :

def __init__(self):
    self.CONSUMER_KEY = config_twitter.get_consumer_key()
    self.CONSUMER_SECRET = config_twitter.get_consumer_secret()
    self.oauth_token = None
    self.oauth_verifier = None
    self.api = None

def get_auth_url(self):
    self.auth = tweepy.OAuthHandler(self.CONSUMER_KEY, self.CONSUMER_SECRET)
    return self.auth.get_authorization_url()

def get_request_token(self):
    return (self.auth.request_token.key,self.auth.request_token.secret)

def set_token(self,token):
    self.oauth_token = token

def set_verifier(self,verifier):
    self.oauth_verifier = verifier

def set_request_token (self,ReqToken):
    self.request_token = ReqToken

def get_access_token (self):
    self.auth = tweepy.OAuthHandler(self.CONSUMER_KEY, self.CONSUMER_SECRET)
    token = self.request_token
    #session.delete('request_token')
    self.auth.set_request_token(token[0],token[1])
    self.auth.get_access_token(self.oauth_verifier)

def authorize (self):
    key = self.auth.access_token.key
    secret = self.auth.access_token.secret
    self.auth = tweepy.OAuthHandler(self.CONSUMER_KEY, self.CONSUMER_SECRET)
    self.auth.set_access_token(key, secret)
    self.api = tweepy.API(self.auth)

def update_status(self,status):
    if self.oauth_token == None or self.oauth_verifier == None or self.api == None :
        return "Verification Problem"
    self.api.update_status (status)
    return "Done"

def user_information (self):
    # returns information of the authenticate user
    if self.oauth_token == None or self.oauth_verifier == None or self.api == None :
        return "Verification Problem"
    return self.api.me()

def get_friends (self):
    if self.oauth_token == None or self.oauth_verifier == None or self.api == None :
        return ["Verification Problem"]
    return self.api.GetFriends(self.user_information().name)

def get_followers (self):
    if self.oauth_token == None or self.oauth_verifier == None or self.api == None :
        return ["Verification Problem"]
    return self.api.GetFollowers()

def get_followers_id (self):
    if self.oauth_token == None or self.oauth_verifier == None or self.api == None :
        return "Verification Problem"
    return self.api.followers_ids()

def get_friends_ids (self):
    # returns ids of the friends
    if self.oauth_token == None or self.oauth_verifier == None or self.api == None :
        return "Verification Problem"
    return self.api.friends_ids()

def get_rate_limit_status (self):
    #returns the rate limit status of the authenticated user
    return self.api.rate_limit_status()

def get_tweets(self):
    if self.oauth_token == None or self.oauth_verifier == None or self.api == None :
        return ["Verification Problem"]
    me = self.user_information()
    statuses = self.api.GetUseerTimeline(me.name)
    return statuses

def get_messages(self):
    if self.oauth_token == None or self.oauth_verifier == None or self.api == None :
        return ["Verification Problem"]
    return self.api.GetDirectMessages()


texts:
I'm using the following pattern to pool D3D objects globally in my application. Is it a good idea (alternatives)? Is it thread-safe?

CComPtr<ID3D11Texture2D> create_texture(const D3D11_TEXTURE2D_DESC& desc)
{
    static concurrent_unordered_map<D3D11_TEXTURE2D_DESC,
                                    concurrenct_vector<CComPtr<ID3D11Texture2D>>
                                    d3d_texture2d_desc_hash,
                                    d3d_texture2d_desc_equal_to> pools;

    auto& pool = pools[desc];

    auto it = std::find_if(pool.begin(), pool.end(), [](const CComPtr<ID3D11Texture2D>& texture)
    {
        assert(texture);

        IUnknown* unknown = texture;
        auto ref_count = unknown.AddRef();

        if(ref_count != 2)
            unknown->Release(); // Only release if we don't want ownership.

        return ref_count == 2;
    });

    CComPtr<ID3D11Texture2D> texture;

    if(it != pool.end())
    {
        texture = *it; // Take ownership.

        IUnknown* unknown = texture;

        // Release the extra ref-count once we have taken ownership.

    #ifndef _DEBUG
        unknown->Release();
    #else
        assert(unknown->Release() == 2);
    #endif
    }
    else
    {
        HR(get_default_device()->CreateTexture2D(&desc, nullptr, &texture));

        pool.push_back(texture);
    }

    assert(texture);

    return texture;
}


texts:
I have implemented this delete function for BST. Tt takes care of all the three cases, deleting node with 0, 1, or 2 children.

I have added comments throughout to explain my decisions. Is it sloppy or acceptable? Will I get full marks if this was a question in an exam to implement the delete function of a BST?

//I am having the node start parameter, so I can specify from where the
//deletion starts. So I can use it for recursion for the third case,
//where the node to be deleted has 2 children.
public void delete(Node start, int data) {
    if(root == null) return;

    /*If I want to call this method from any other class, I will pass in
    null as the start node, since I don't have reference to the root in
    that class.
    I have this start parameter because in the case of a node having 2
    children, I am calling this method recursivly to delete, but I don't
    want to start from the root in that case. See below, last else */
    Node parent = start == null ? root : start;
    Node current = parent;
    boolean isLeftNode = false;

    while(data != current.getData() && current != null) {
        parent = current;

        if(data < current.getData()) {
            current = current.getLeftNode();
            isLeftNode = true;
        }
        else {
            current = current.getRightNode();
            isLeftNode = false;
        }
    }

    //If not found.
    if(current == null) return;

    if(current == root) {
        root = null;
        return;
    }
    //Case 1: If node to be removed is a leaf, no children.
    if(current.getLeftNode() == null && current.getRightNode() == null) {
        if(isLeftNode)
            parent.setLeftNode(null);
        else
            parent.setRightNode(null);
    }
    //Case 2: If node to be removed has only 1 child.
    else if(current.getLeftNode() != null && current.getRightNode() == null) {
        if(isLeftNode)
            parent.setLeftNode(current.getLeftNode());
        else
            parent.setRightNode(current.getLeftNode());
    }
    else if(current.getLeftNode() == null && current.getRightNode() != null) {
        if(isLeftNode)
            parent.setLeftNode(current.getRightNode());
        else
            parent.setRightNode(current.getRightNode());
    }
    //Case 3: If node to be deleted has 2 children.
    else {
        Node smallest = findSmallest(current.getRightNode());
        current.setData(smallest.getData());
        //Calling recursion to delete the smallest. Because the smallest
        //might have a right subtree. Explanation above relates to this.
        delete(current.getRightNode(), smallest.getData());
        //Calling the delete method to start deleting from the right sub
        //tree since at this point there is a duplicate value, I can't
        //start from the root.
    }
}

public Node findSmallest(Node start) {
    //This is so in the main method, I can call findSmallest and pass in
    //null to search the whole tree. Because in main, I won't have reference
    //to the root. I have the start parameter so I can specifiy where to
    //start the search, because of the way I am dealing with deleting
    //a node with 2 children. See above.
    Node smallest = start == null ? root : start;

    while(smallest.getLeftNode() != null) {
        smallest = smallest.getLeftNode();
    }
    return smallest;
}


texts: Encapsulating snprintf to avoid repetition of sizeof


texts: Change upper or lowercase vowels to [0,1,2,3,4] respectively and leave the rest the same

texts:
The objective was the following to be solved in Python:

  Given a string, def a function that
  returns another string with the vowels
  (upper or lowercase) replaced by
  0,1,2,3,4 respectively.

  Example input:

"bB nN aei ou AEIOU"

  Desired Output:

"bB nN 012 34 01234"

This is in fact quite trivial and can be solved in several ways, one way may be this:

def crypt(s):
    vow = ["a","e","i","o","u"]
    stringL = []

    for x in s:
        if x in vow or x.lower() in vow:
            stringL.append(str(vow.index(x.lower())))
        else:
            stringL.append(x)

    return "".join(stringL)

I was told this was over-complicated for such a simple task, that code like this would be difficult to debug etc.

Would you consider this approach a "bad" one, which way would you have gone instead, is it unclear?


texts: Unit tests for a single JavaScript function

texts:
Here is the question: What is the better way to unit test this specific function?  Should all the test items be included in one test or is it better to break up the tests so each test is testing for something more specific?

Function being tested:

$scope.saveFailure = function (response) {
        var errs = [];
        response.data.forEach((entry) => errs.push("options." + entry.dataField));
        if (errs.length > 0) $scope.$emit('datafields:errors', errs);

        $scope.gotoTop();
        $scope.processing = false;
    };

Method 1: Multiple Unit Tests

var mockFailureResponse;

beforeEach(function () {
    mockFailureResponse = {
        data: [],
    };
});

it('saveFailure should set processing to false', function () {
    $scope.processing = true;
    $scope.saveFailure(mockFailureResponse);
    expect($scope.processing).toBe(false);
});
it('saveFailure should call goToTop()', function () {
    spyOn($scope, 'gotoTop');
    $scope.saveFailure(mockFailureResponse);
    expect($scope.gotoTop).toHaveBeenCalled();
});
it('saveFailure should emit datafield errors when present', function () {
    spyOn($scope, '$emit');
    mockFailureResponse = {
        data: [{dataField: "field"}],
    };
    $scope.saveFailure(mockFailureResponse);
    expect($scope.$emit).toHaveBeenCalledWith('datafields:errors', ['options.field']);
});
it('saveFailure should not emit datafield errors non are present', function () {
    spyOn($scope, '$emit');
    $scope.saveFailure(mockFailureResponse);
    expect($scope.$emit.calls.count()).toEqual(0);
});

Method 2: Single Unit Test

it('saveFailure should handle failed requests', function () {
    spyOn($scope, '$emit');
    let mockFailureResponse = {
        data: [],
    };
    $scope.saveFailure(mockFailureResponse);
    expect($scope.$emit.calls.count()).toEqual(0);

    mockFailureResponse = {
        data: [{ dataField: "field" }],
    };
    $scope.saveFailure(mockFailureResponse);
    expect($scope.$emit).toHaveBeenCalledWith('datafields:errors', ['options.field']);

    spyOn($scope, 'gotoTop');
    $scope.saveFailure(mockFailureResponse);
    expect($scope.gotoTop).toHaveBeenCalled();

    $scope.processing = true;
    $scope.saveFailure(mockFailureResponse);
    expect($scope.processing).toBe(false);
});


texts: Improving many for loops, any more efficient alternative?

texts:
I'm working through an introduction to computer science book, this is not homework for me but me trying to learn in my spare time, I'm not asking for homework help!

The output is below, and this is all ok, but I'm just certain there is a more efficient way of doing this. I have been trying for many hours now and this is still the best solution I can come up with, if anyone can improve upon this and possibly explain how, I would highly appreciate it.

The code:

naught = 0
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
seven = 0
eight = 0
nine = 0

for i in range (0, 10):
    print("")
    for i in range (0,1):
        print(naught, end = " ")
    for i in range (0,1):
        print(one, end = " ")
        one += 1
    for i in range (0,1):
        print(two, end = " ")
        two += 2
    for i in range (0,1):
        print(three, end = " ")
        three += 3
    for i in range (0,1):
        print(four, end = " ")
        four += 4
    for i in range (0,1):
        print(five, end = " ")
        five += 5
    for i in range (0,1):
        print(six, end = " ")
        six += 6
    for i in range (0,1):
        print(seven, end = " ")
        seven += 7
    for i in range (0,1):
        print(eight, end = " ")
        eight += 8
    for i in range (0,1):
        print(nine, end = " ")
        nine += 9

The output is below and that is all correct, that's no problem.

0 0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9
0 2 4 6 8 10 12 14 16 18
0 3 6 9 12 15 18 21 24 27
0 4 8 12 16 20 24 28 32 36
0 5 10 15 20 25 30 35 40 45
0 6 12 18 24 30 36 42 48 54
0 7 14 21 28 35 42 49 56 63
0 8 16 24 32 40 48 56 64 72
0 9 18 27 36 45 54 63 72 81

As I said I'm getting the right answer, just I'm not satisfied that it's in the best way.
Many thanks,
Matt.


texts: Using binary search to find the index of an item in a sequence

texts:
Here's my script:

def index(seq, item):
    """Returns the index of an item in an increasingly-sorted
       sequence (if exists) otherwise returns the index where
       it would be inserted, using binary search.

       seq: a sequence.

       precondition: seq is sorted increasingly.
       """
    # Updates the sequence with the item using a
    # set to avoid duplicates.
    seq = set(seq)
    seq.update([item])

    # Converts the sequence to a list and re-sorts it.
    sorted_seq = sorted(seq)

    middle = len(sorted_seq) // 2
    middle_value = sorted_seq[middle]

    first_half = sorted_seq[:middle]
    second_half = sorted_seq[middle:]

    if item == middle_value:
        return middle

    elif item < middle_value:
        return index(first_half, item)

    elif item > middle_value:
        return index(second_half, item) + len(first_half)

How can it be refactored and optimized?

Notes:

I'm a hobbyist and beginner (in programming in general, and Python in particular).
I'm new to binary search I just understand the basic idea.


texts: Iterating over a range of dates in a shell script

texts:
I have been working on a script that can be used to automatically pull the batch ids that were processed 4 days ago and which need to be processed tomorrow on the server. The batch IDs from 3 days ago need to be processed the day after tomorrow, etc.

The script only needs to output the processing dates for all batch IDs from the last 4 days and send the output via email with the format below.

Please have a look and let me know of any improvement we can make, especially to the performance.

#!/bin/bash

matchdate () { date +%Y%m%d --date "$1" }

touch $result

dbhost='192.168.0.1'
dbuser='test_db'
dbpass='temp#100'
dbschema='demo'

batchdate=$(matchdate "4 days ago")

current_date=$(matchdate "today")

while [[ $batchdate != $current_date ]]; do

  batchdate=$(matchdate "$batchdate + 1 day")

   batchwupos=$(date -d "$batchdate" +%Y-%m-%d)

   processdate=$(date +%d-%m-%Y -d "$matchdate + 1 day")

  #echo "$batchdate and $batchwupos"

 recordpull=`mysql -h $dbhost -u $dbuser -p $dbpass -e "use $dbschema;SELECT il.BatchID FROM tbl_batch_table il WHERE il.batch_name like '%$batchdate%' and il.batch_name like '%$batchwupos%' and il.status='SUCCESS'"`

batch_result="`cat $recordpull | tr -s ' ' | cut -d " " -f2- | tr '\n' ',' | sed 's/,$//' | sed 's/........//' $recordpull`"

echo -e "\n Below are the expected batches which we will processing on server on specified date." >> $result

echo -e "\n $processdate : $batch_result" >> $result

done

Here are the expected batches which will process on the server on the specified date:

12-09-2016: (10642, 10643, 10644, 10646, 10647)
13-09-2016: (10648, 10649, 10654, 10655, 10656, 10659)
14-09-2016: (10657, 10658, 10661, 10665, 10666)
15-09-2016: (10668, 10669, 10670, 10671)


texts: Fill a list of 2 lists from split string

texts:
This might be too trivial of a question for Code Review, but here goes:

Assume I have text file with content:

A 1
B 2
C 3
D 4

And I want a list like [[1,2,3,4],["A","B","C","D"]] created by Python's list comprehensions.

My code accomplishes this, but it seems like I jump through way too many loops:

with open('textFile.txt') as f:
    lines = f.readlines()

z = [y for y in map(list, list(zip(*[x.split() for x in lines])))]

Is there an easier way to achieve this using list comprehension?


texts: Rearrange string to an anagram of the string - get new position, old position values

texts:
I'm writing a function to take an anagram pair (words or phrases spelled with the same letters) and determine how you could move the letters to change one into the other.

For example: Admirer -> Married

The results would be something like this:

[[0, 1], [1, 6], [2, 0], [3, 4], [4, 2], [5, 5], [6, 3]]

The character in the 0 (a) position moves to 1, the character in position 1 (d) moves to 6, etc. I've already successfully solved this but perhaps there's a better way!

Language of choice (required!) is javascript. Here's my current, working function:

function _get_new_positions(source, target) {
    // convert both strings to arrays - uppercase so we can find the destination
    // spot without worrying about cases
    source = source.toUpperCase().split('');
    target = target.toUpperCase().split('');

    var transform = [];
    var repeated = [];
    var found = 0;

    for(var i=0; i<source.length; i++) {
        // keep track of how many times we've found and 'moved' this letter
        repeated[source[i]] = repeated[source[i]] ? repeated[source[i]] + 1 : 1;
        found = 0;
        want  = repeated[source[i]];
        for(var j=0; j<target.length; j++) {
            if( target[j] == source[i] ) {
                found++;
                console.log('found is ' + found);
                if( found == want ) {
                    transform.push([i,j]);
                    break;
                }
            }
        }
    }
    return transform;
}

Thank you for your input.


texts:
You probably know the following problem: You have written a small program that runs in your console and want the user to enter something. of course, it is very inconvenient when the user types the wrong things, so we have to prepare for any small child hacking like a madman on the keyboard.
Most functions wait for a valid input, which results in the problem that nasty line breaks occur when the user ONLY presses the enter key.
the problem is also normally easy to solve under Linux: read a character with getchar, determined the position of the cursor with the ANSI escape sequences and provided the whole thing with a do while loop.
BUT: I was not able to find a simple function to read in numbers in the same elegant way. The function must be able to read in numbers, but also be able to prevent line breaks. to achieve this, I used getchar and store the characters in a char array, whose indices I then convert to the corresponding numbers, which I then add to the actual number.
But maybe there is an easier way? or you have ideas how to optimize the function?
#include <iostream>
#include "TheGameHeaders.h"

#define CLEAR_LINE printf("\033[K")
#define POSITION(Ze, Sp) printf("\033[%d;%dH", Ze, Sp)
#define CLEAR printf("\033[2J")

int getint(int pos_ze, int pos_sp, int qntty_of_incs)
{
    int i = 0;
    char fake_nbr;
    char fake_nbrs[qntty_of_incs];

    int real_nbr = 0;
    int real_nbrs[qntty_of_incs];

    do
    {
        POSITION(pos_ze, pos_sp);
        while((fake_nbr = getchar()) != '\n')
        {
            if(fake_nbr == '0' || fake_nbr == '1' || fake_nbr == '2' || fake_nbr == '3' || fake_nbr == '4' || fake_nbr == '5' || fake_nbr == '6' || fake_nbr == '7' || fake_nbr == '8' || fake_nbr == '9')
            {
                if(i <= (qntty_of_incs-=1))
                {
                    fake_nbrs[i] = fake_nbr;
                    i++;
                    qntty_of_incs++;
                }
                else
                {
                    return 1;
                }
            }
            else
            {
                return 0;
            }
        }
    }
    while(i < 1);

    for(int a = 0; a < i; a++)
    {
        fake_nbrs[a] -= '0';
        real_nbrs[a] = fake_nbrs[a];
    }

    int i_fix = i;
    int i_fix_2 = i-=1;

    for(int a = 0; a < i_fix; a++)
    {
        i = i_fix_2;
        real_nbrs[a] *= pow(10, i-=a);
    }

    for(int a = 0; a < i_fix; a++)
    {
        real_nbr += real_nbrs[a];
    }

    return real_nbr;
}

oh and pow is a simple function:
int pow(int base, int exponent)
{

    if(exponent == 0)
    {
        return 1;
    }

    exponent -= 1;
    int fixBase = base;

    for(int i = 0; i < exponent; i++)
    {
        fixBase *= base;
    }

    return fixBase;
}


texts: Transforming between hiccup and enlive/clojure.xml data structures using spec

texts:
I've made functions that transform hiccup <-> enlive

Example: [:div [:p {:class "foo"} "bar"]] <-> {:tag :div :attrs {} :content [{:tag :p :attrs {:class "foo"} :content ["bar"]}]}

It only depends on spec, and can be used from both clj and cljs.

It exists because hiccup is nice to work with in the context of reagent and friends, while enlive is better for programmatic manipulation. (Enlive has the hiccup->enlive part already enlive.core/html, but can't be used in cljs.)

I would love any feedback in general, and more specifically on my usage of spec for this task.

(ns foo.bridge
  (:require
   [clojure.string :as str]
   [clojure.spec :as s]))

(s/def ::tag simple-keyword?)

(s/def ::attrs map?)

;; Needs to be a string because js includes the slashes
;; (str #"foo") => java: "foo" javascript: "/foo/"
(def valid-ident-regex-str
  "A regex that will match a valid class or id name.
   Taken from http://stackoverflow.com/a/449000"
  "-?[_a-zA-Z]+[_a-zA-Z0-9-]*")

(defn split-tag-classes
  "Split a tag with id and class shortcuts
   into the bare tag, classes and ids.

   Example: (split-tag-classes :foo#bar.baz.quux)
        => {:bare-tag :foo, :ids (\"bar\") :classes (\"baz\" \"quux\")}"
  [x]
  (let [[tag more] (->> (name x)
                        (split-with (complement #{\. \#}))
                        (map (partial apply str)))
        class-regex (re-pattern (str "\\.(" valid-ident-regex-str ")"))
        id-regex (re-pattern (str "#(" valid-ident-regex-str ")"))]
    {:bare-tag (keyword tag)
     :ids (->> more (re-seq id-regex) (map second))
     :classes (->> more (re-seq class-regex) (map second))}))

(defn- merge-strs [current more]
  (str current (when (some? current) " ") (str/join " " more)))

(s/def ::hiccup->enlive
  (s/and vector?
         (s/cat :tag ::tag
                :attrs (s/? ::attrs)
                :content (s/* (s/and (s/or :str string?
                                           :elem ::hiccup->enlive)
                                     (s/conformer second))))
         (s/conformer (fn [{:keys [tag] :as elem}]
                        (let [{:keys [bare-tag classes ids]} (split-tag-classes tag)]
                          (-> elem
                              (assoc :tag bare-tag)
                              (update :attrs (fnil identity {}))
                              (update :content (fnil identity []))
                              (cond->
                                  (seq classes)
                                  (update-in [:attrs :class] merge-strs classes)

                                  (seq ids)
                                  (update-in [:attrs :id] merge-strs ids))))))))

(s/def :foo.bridge.enlive/content
  (s/* (s/and (s/or :str string?
                    :elem ::enlive->hiccup)
              (s/conformer second))))

(s/def ::enlive->hiccup
  (s/and (s/keys :req-un [::tag]
                 :opt-un [::attrs :foo.bridge.enlive/content])
         (s/conformer
          (fn [{:keys [tag attrs content]}]
            (cond-> [tag]
              (seq attrs) (conj attrs)
              (seq content) (into content))))))

(defn parse-with [spec x]
  (let [ret (s/conform spec x)]
    (if (not= ret ::s/invalid)
      ret
      (throw (ex-info "Invalid input" (s/explain-data spec x))))))

(defn hiccup->enlive [h]
  (parse-with ::hiccup->enlive h))

(defn enlive->hiccup [e]
  (parse-with ::enlive->hiccup e))

(comment

  (= {:tag :div,
      :attrs {:style {:color :green}},
      :content
      [{:tag :h1,
        :content ["foo" {:tag :strong, :content ["!!!"], :attrs {}}],
        :attrs {:id "headline"}}
       {:tag :p, :content ["bar"], :attrs {}
       {:tag :p, :content ["baz"], :attrs {:class "small"}}]}

     (hiccup->enlive
      [:div {:style {:color :green}}
       [:h1#headline "foo" [:strong "!!!"]]
       [:p "bar"]
       [:p.small "baz"]]))

  )


texts:
Please be brutal, and treat this as a top 5 technical interview. I am trying to follow Google's way of writing Java code, as per their .pdf file online of code review. (Side note: do any of you see any improvement in me?)

Suppose I am asked to find the minimum number of coins you can find for a particular sum.  That is, say, coins are 1, 3, 5, the sum is 10, so the answer should be 2, since I can use the coin 5 twice.

Time Complexity = \$O(n^2)\$
Space Complexity = \$O(n)\$

private static int findMinCoins(final int[]coins, final int sum){
    int[] calculationsCache = new int[sum+1];
    for(int i = 0; i <= sum; i++){
        calculationsCache[i] = Integer.MAX_VALUE;
    }
    calculationsCache[0]=0;/*sum 0 , can be made with 0 coins*/
    for(int i = 1; i <= sum; i++){
        for(int j = 0; j < coins.length; j++){
            if(i >= coins[j] && i - coins[j] >= 0 && calculationsCache[i-coins[j]]+1 < calculationsCache[i]){
                calculationsCache[i] = calculationsCache[i-coins[j]]+1;
            }
        }
    }
    return calculationsCache[sum];
}


texts:
In AngularJS, I currently have a directive and 2 services which permit me to bind the window resize event, and broadcast it to my application.

I would like to know if you could see anything that could be improved in my code, in term of optimization, naming or possible cross browser issues.

I have:

A directive which binds resize event. It will broadcast the event 300ms after the last resize (to avoid flood).
A factory to get window's dimensions
A service to detect browser's name (chrome, safari, etc...). In this case, it is used to target Safari which doesn't calculate window's dimensions the same way.

Here is a plunkr to illustrate the code.

Detect Browser Service

/*
 * Detects on which browser the user is navigating
 *
 * Usage:
 * var browser = detectBrowser();
 *
 */
commonApp.service('detectBrowser', ['$window',
    function( $window ) {

        // http://stackoverflow.com/questions/22947535/how-to-detect-browser-using-angular
        return function() {
            var userAgent = $window.navigator.userAgent,
                browsers  = {
                    chrome  : /chrome/i,
                    safari  : /safari/i,
                    firefox : /firefox/i,
                    ie      : /internet explorer/i
                };

            for ( var key in browsers ) {
                if ( browsers[key].test(userAgent) ) {
                    return key;
                }
            }

            return 'unknown';
        }
    }]);

Window Dimensions Factory

/*
 * Get window height and width
 *
 * Usage:
 * windowDimensions.height();
 * windowDimensions.width();
 *
 */
commonApp.factory('windowDimensions', ['$window', 'detectBrowser',
    function( $window, detectBrowser ) {
        var browser = detectBrowser();

        return {
            height: function() {
                return ( browser === 'safari' )
                          ? document.documentElement.clientHeight
                          : window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
            },

            width : function() {
                return ( browser === 'safari' )
                          ? document.documentElement.clientWidth
                          : window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth
            }
        }
    }]);

Window Resize Event Directive

/*
 * Watch window resizing event to set new window dimensions,
 * and broadcast the event to the app
 *
 * Usage:
 * <html watch-window-resize>...</html>
 *
 * Bind the resize event:
   $scope.$on('watchWindowResize::resize', function() {
       // Do something
   });
 *
 */
app.directive('watchWindowResize', ['$window', '$timeout', 'windowDimensions',
    function( $window, $timeout, windowDimensions ) {

        return {
            link: function( $scope ) {
                // Get window's dimensions
                $scope.getDimensions = function() {

                    // Namespacing events with name of directive + event to avoid collisions
                    // http://stackoverflow.com/questions/23272169/what-is-the-best-way-to-bind-to-a-global-event-in-a-angularjs-directive
                    $scope.$broadcast('watchWindowResize::resize', {
                        height: windowDimensions.height(),
                        width : windowDimensions.width()
                    });
                }

                // On window resize...
                angular.element($window).on('resize', function( e ) {

                    // Reset timeout
                    $timeout.cancel($scope.resizing);

                    // Add a timeout to not call the resizing function every pixel
                    $scope.resizing = $timeout( function() {

                        $scope.getDimensions();
                    }, 300);
                });
            }
        }
    }]);