texts:
In order to do its work, a DataProcessor needs Data and otherData.

One instance of Data will be shared over a set of DataProcessor,
but each DataProcessor has its own otherData.

For sharing Data instances, fields of Data could not be defined inside DataProcessor,
thus, there are two hierarchies: Data and DataProcessor.

Each subClass of DataProcessor relates a subClass of Data.

And I have tried three design to fit the requirement, which way is the best? why?

Is my design bad? Why?

Is there any other solution?

Is there any existing design pattern to solve this kind of problem?

It is said that this is a "parallel inheritance hierarchy". Should I avoid this? How? Or is it a good design for my requirement, and do I not need to avoid?

Data hierarchies

abstract class Data {
    int field1;
}

abstract class AData extends Data {
    int field2;
}

class AAData extends AData {
    int field3;
}

class BData extends Data {
    int field4;
}

DataProcessor hierarchies way 1, each super class instance keeps a private reference to Data

abstract class DataProcessor {
    private Data data;
    protected Object otherData;
    DataProcessor(Data data){
        this.data = data;
    }
    void doSomethingUsingDataAndOtherData(){}
}

abstract class ADataProcessor extends DataProcessor {
    private AData data;
    ADataProcessor(AData data) {
        super(data);
        this.data = data;
    }
    void doSomethingUsingADataAndOtherData(){}
}

class AADataProcessor extends ADataProcessor {
    private AAData data;
    AADataProcessor(AAData data) {
        super(data);
        this.data = data;
    }
    void doSomethingUsingAADataAndOtherData(){}
}

class BDataProcessor extends DataProcessor {
    private BData data;
    BDataProcessor(BData data) {
        super(data);
        this.data = data;
    }
    void doSomethingUsingBDataAndOtherData(){}
}

DataProcessor hierarchies way 2, only top superclass instance keeps a protected reference to Data, when subclass needs to use the data, it has to cast the data to its expected Data subclass. And I don't want to define DataProcessor as DataProcessor, because once introducing generic types, I have to use generic types everywhere, and sometimes using generic types is not so simple (i.e. we can not create a generic array in java).

abstract class DataProcessor {
    protected Data data;
    protected Object otherData;
    DataProcessor(Data data) {
        this.data = data;
    }
    void doSomethingUsingDataAndOtherData(){}
}

abstract class ADataProcessor extends DataProcessor {
    ADataProcessor(AData data) {
        super(data);
    }
    void doSomethingUsingADataAndOtherData(){}
}

class AADataProcessor extends ADataProcessor {
    AADataProcessor(AAData data) {
        super(data);
    }
    void doSomethingUsingAADataAndOtherData(){}
}

class BDataProcessor extends DataProcessor {
    BDataProcessor(BData data) {
        super(data);
    }
    void doSomethingUsingBDataAndOtherData(){}
}

DataProcessor hierarchies way3, only bottom sub class instance keep a priavte reference to Data, super class use a abstract method getData() to retrieve the Data

abstract class DataProcessor {
    protected Object otherData;
    protected abstract Data getData();
    void doSomethingUsingDataAndOtherData(){}
}

abstract class ADataProcessor extends DataProcessor {
    protected abstract AData getData();
    void doSomethingUsingADataAndOtherData(){}
}

class AADataProcessor extends ADataProcessor {
    private AAData data;
    protected AAData getData() {
        return data;
    }
    AADataProcessor(AAData data) {
        this.data = data;
    }
    void doSomethingUsingAADataAndOtherData(){}
}

class BDataProcessor extends DataProcessor {
    private BData data;
    protected BData getData() {
        return data;
    }
    BDataProcessor(BData data) {
        this.data = data;
    }
    void doSomethingUsingBDataAndOtherData(){}
}


texts:
I am trying to format my code properly. I have already read the programming standards document and I believe that my code follows these rules. I have also used the CtrlShiftF keys in Eclipse which should format the code automatically.

Could someone tell me if this looks ok?  It would be nice to get some feedback back and to see if it is being created automatically. I already know that the program does work. Any help would be great.  If someone knows a better way to format the code, it would be great to hear it as well.

public class UniString {
    public static void main(String[] args) {
        char[] det = { '\u20ac', '1', '1', '8' };
        // char[]det is an array of characters.

        for (char a : det) {
            /*
            * the for loop takes in the char values and prints them off in
            * order the "det" array enters into the for loop  through "det" ,
            * goes into char a and can be written to the console through
            * System.out.println(a).
            */
            System.out.print(a);
        }
        System.out.println();

        char[] name = { 'j', 'o', 'e' };
        // This is another char array.

        String nameString = new String(name);
        /*
        * The char array is made into a String by loading "name" into a String
        * class
        */

        String changeCase = nameString.toUpperCase();
        /*
        * The String "nameString" is changed to Upper case letters. The string
        * is then stored as "caseChange".
        */

        System.out.println(changeCase);
        // "caseChange" is printed out.
    }
}


texts:
I'm trying to implement a suffix array for use in programming competitions. I'm using the CodeForces example and trying to "make it my own" so I can make sure I understand it and feel better about using it.

Here's what I have so far:

struct SuffixArray {
    vector<int> sa, pos, tmp;
    int n, gap;

    SuffixArray(string s) {
        n = s.length();
        sa = pos = tmp = vector<int>(n);
        for (int i=0; i<n; i++) sa[i] = i, pos[i] = s[i], tmp[i] = 0;
        for (gap = 1;; gap *= 2) {
            quickSort(sa, n, 0, n - 1);
            for (int i=0; i<n-1; i++) tmp[i+1] = tmp[i] + sufCmp(sa[i], sa[i+1]);
            for (int i=0; i<n; i++) pos[sa[i]] = tmp[i];
            if (tmp[n-1] == n - 1) break;
        }
    }

    bool sufCmp(int i, int j) {
        if (pos[i] != pos[j]) return pos[i] < pos[j];
        i += gap;
        j += gap;
        return (i < n && j < n) ? pos[i] < pos[j] : i > j;
    }

    int partition(vector<int> &arr, int lo, int hi) {
        int p = arr[hi];
        int pi = lo;
        for (int i=lo; i<hi; i++) {
            if (sufCmp(arr[i], p)) {
                swap(arr[i], arr[pi]);
                pi++;
            }
        }
        swap(arr[hi], arr[pi]);
        return pi;
    }

    void quickSort(vector<int> &arr, int sz, int lo, int hi) {
        if (lo < hi) {
            int p = partition(arr, lo, hi);
            quickSort(arr, sz, lo, p-1);
            quickSort(arr, sz, p+1, hi);
        }
    }
};

This works, but it is hopelessly slower than the original. On this problem from SPOJ, it scores in the range expected by a naive solution which is \$O(n^2 \log n)\$.

My question is, why? My guess is it either has to do with the way I am storing and accessing data (wrapping everything in a struct, using vectors instead of pre-allocated arrays), or it could be an issue with my quickSort implementation (since the suffix array will already be 'mostly' sorted on all but the first iteration, using the last element as pivot could be bad), but I don't understand enough about what's going on under the hood to be sure.

I tested the pivot theory by using the middle element instead of the last element as the pivot for the quicksort... still way too slow.


texts:
I have the main form with a list inside and i need to open another form and edit the list in the main. Generally i'm doing something like ...

    public class Form1 : Form
            {
                List<objectType> obj = new List<objectType>();
                private void button_EDIT_BUTTONS_Click(object sender, EventArgs e)
                {
                    EDIT_BUTTONS edit_b = new EDIT_BUTTONS(this);
                    edit_b.Show();
                }
            }
      public partial class EDIT_BUTTONS : Form
     {
        Form1 main;
        public EDIT_BUTTONS(Form1 mainP)
        {
            InitializeComponent();
            main = mainP;
        }
        button = main.obj.Find(x => x.ID == object.ID);
............................................................
        //modify button

     }

My question is to pass the main form like this only to expose the list object or i should Create setters and getters in main form ?


texts:
The program below basically reads configuration data from an .ini file in ini format. The exemplary configuration file was also added to this post . Let me know how I can improve it, please.

using Sahara.Core.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace Sahara.Core.Config
{
    class ConfigManager
    {
        private readonly string configFilePath;
        private readonly Dictionary<string, string> configItems;
        private readonly LogManager logManager;

        public ConfigManager(string configFile)
        {
            configFilePath = configFile;
            configItems = new Dictionary<string, string>();

            logManager = Sahara.GetServer().GetLogManager();

            try
            {
                if (File.Exists(configFilePath))
                {
                    Stopwatch stopwatch = Stopwatch.StartNew();

                    configItems = File.ReadLines(configFilePath)
                    .Where(IsConfigurationLine)
                    .Select(line => line.Split('='))
                    .ToDictionary(line => line[0], line => line[1]);

                    stopwatch.Stop();
                    logManager.Log("Loaded Config Data [" + stopwatch.ElapsedMilliseconds + "ms]", LogType.Information);
                }
                else
                {
                    logManager.Log("Using config defaults", LogType.Information);

                    configItems.Add("database.host", "localhost");
                    configItems.Add("database.username", "root");
                    configItems.Add("database.password", "");
                    configItems.Add("database.name", "database");
                    configItems.Add("database.port", "3306");
                    configItems.Add("database.max_connections", "10000");
                }
            }
            catch (Exception exception)
            {
                if (logManager != null)
                {
                    logManager.Log("Error in loading config: " + exception.Message, LogType.Error);
                    logManager.Log(exception.StackTrace, LogType.Error);
                }
            }
        }

        private bool IsConfigurationLine(string line)
        {
            return !line.StartsWith("#") && line.Contains("=");
        }

        public string GetConfigElement(string key)
        {
            if (!IsInitialized)
                throw new NotImplementedException("Config data has not get been implemented.");

            if (!configItems.ContainsKey(key))
                throw new KeyNotFoundException("Unable to find key " + key + " in config items dictionary.");
            return this.configItems[key];
        }

        public bool IsInitialized
        {
            get { return configItems != null; }
        }
    }
}

Config File (.ini):

database.host=127.0.0.1
database.username=root
database.password=*********
database.name=******
database.port=3306
database.max_connections=10000


texts:
This is the first program (that is not doing much basically), and I know usually you define classes in separate files.  I just wanted to see if I got the syntax right, and the concept of using objects from the first chapter of the book.

#import <Foundation/Foundation.h>

//interface section
@interface Watch: NSObject

-(void) setHours: (int) h;
-(void) setMinutes: (int) m;
-(int) getHours;
-(int) getMinutes;
-(void) printTime;

@end

//implemetation section

@implementation Watch

{
    int hours;
    int minuts;
}

- (void) setHours: (int) h
{
    hours = h;
}

- (void) setMinutes:(int) m
{
    minuts = m;
}

- (int) getHours
{
    return hours;
}

- (int) getMinutes
{
    return minuts;
}

-(void) printTime
{
    NSLog(@"Time is %i:%i", hours, minuts);
}

@end

//the program section

int main(int argc, const char * argv[])
{

    @autoreleasepool
    {

        Watch *myWatch = [[Watch alloc]init];

        [myWatch getHours];

        [myWatch getMinutes];

        [myWatch setHours: 5];

        [myWatch setMinutes: 30];

        [myWatch printTime];

    }
    return 0;
}


texts: Function to find midpoint of two floats where one of the floats might be an empty string

texts:
There must surely be a nicer way of writing this.

The wrinkle of complexity is that prev_seq or next_seq might be an empty string if the user moves the question to the first or last position, but it could also validly be '0.0' so I can't just rely on 'falsiness'.

I hope it's clear what I'm trying to achieve from the below (with the comments).

How can I improve this?

def update_sequence(self):

    prev_seq = self.request.get('prev_seq')
    next_seq = self.request.get('next_seq')
    question_id = int(self.request.get('id'))
    question = db.get(db.Key.from_path('Questions', question_id))

    try:
        # to slot a question between two numbers we compute the midpoint
        # for, example, to insert a question between 2.1 and 3.4, the
        # question would get the sequence of 2.75
        new_position = (float(prev_seq) + float(next_seq)) / 2
    except ValueError:
        # if we get here, either prev_seq or next_seq was not submitted
        # in the request which means the user pushed the question to the
        # first or last position.
        try:
            float(prev_seq)
        except ValueError:
            # in this case the question has been moved to the first
            # position so we should make:
            # the new position = the next position - 1
            new_position = float(next_seq) - 1
        try:
            float(next_seq)
        except ValueError:
            # in this case the question has been moved to the last position
            # so we should make:
            # the new position = the previous position + 1
            new_position = float(prev_seq) + 1

    question.sequence_float = new_position
    question.put()


texts: Data Access Layer method with transaction handling

texts:
I just want to know whether I've done transaction handling well. Also what about the other types of transactions available in .NET with regard to this code snippet?

Also are there any redundant things in this code?

    public void InsertAttendance(BindingList<IAttendance> attendanceList)
    {
        string selectStatement = @"IF NOT EXISTS (SELECT Attendance.Atten_ID FROM Attendance WHERE Atten_ID = @aid) BEGIN INSERT INTO attendance (EID,PID,in_time,out_time,shift) VALUES(@eid,@pid,@inT,@outT,@shift) END ";
        using (SqlConnection sqlConnection = new SqlConnection(db.ConnectionString))
        {
            sqlConnection.Open();
            using (SqlTransaction trans = sqlConnection.BeginTransaction())
            using (SqlCommand sqlCommand = new SqlCommand(selectStatement, sqlConnection, trans))
            {
                sqlCommand.Parameters.Add("@aid", SqlDbType.Int);
                sqlCommand.Parameters.Add("@pid", SqlDbType.Char);
                sqlCommand.Parameters.Add("@eid", SqlDbType.Int);
                sqlCommand.Parameters.Add("@inT", SqlDbType.DateTime);
                sqlCommand.Parameters.Add("@outT", SqlDbType.DateTime);
                sqlCommand.Parameters.Add("@shift", SqlDbType.Char);
                //sqlConnection.Open();

                try
                {
                    foreach (Attendance obj in attendanceList)
                    {
                        sqlCommand.Parameters["@aid"].Value = obj.AttendanceID;
                        sqlCommand.Parameters["@pid"].Value = obj.PointID;
                        sqlCommand.Parameters["@eid"].Value = obj.EmployeeID;
                        sqlCommand.Parameters["@inT"].Value = obj.InTime;
                        sqlCommand.Parameters["@outT"].Value = obj.OutTime;
                        sqlCommand.Parameters["@shift"].Value = obj.ShiftType;

                        sqlCommand.ExecuteNonQuery();
                    }
                    trans.Commit();
                }
                catch { trans.Rollback(); throw; }
            }
        }
    }


texts:
I am trying to encrypt the input string using the following rule:

1st Character of string will be increment by 4 ( a will become e )
2nd Character of string will be increment by 1 ( a will become b )
3rd Character of string will be increment by 7 ( a will become h )
Rest of the characters will be replaced using the above rules.

Examples:

(Before Enc)    (After Enc)
""              ""
"b"             "f"
"x"             "b"
"imagine"       "mnhkjui"
"abcdef"        "ecjhfm"
"xz"            "ba"

I have written the following code to achieve this:

public static string Puzzle(string str)
{
    string result = "";
    var w = s.a;
    string x = "";
    foreach (var item in str)
    {
        if (item + (int)w > 122)
        {
            x += (char)(96 + ((item + (int)w) % 122));
        }
        else
        {
            x += (char)((int)w + item);
        }
        w = Convert(w);
    }
    return x;
}

enum s { a = 4, b = 1, c = 7 };

private static s Convert(s w)
{
    if (w == s.a)
    {
        w = s.b;
    }
    else if (w == s.b)
    {
        w = s.c;
    }
    else
    {
        w = s.a;
    }
    return w;
}

What I want is a better and more efficient solution than the one I have written.


texts:
Having a general utility function to see if the input is empty makes sense to me. Empty means different things depends on the type. I just spent ~5 minutes writing this one up, so I'm sure it's missing edge cases, and maybe I'm approaching the whole problem incorrectly.

Function

function isEmpty(input: any) {
    switch (typeof input) {
        case 'string':
            return input.length === 0;
        case 'object':
            return (input instanceof Array)? input.length === 0: Object.getOwnPropertyNames(input).length === 0;
        case 'number':
        default:
            return input === undefined;
    }
}

Basic [SONA!] testing

let s = '';
let o = {};
let n: number;
let a = [];

console.log('isEmpty(s): ' + isEmpty(s));
console.log('isEmpty(o): ' + isEmpty(o));
console.log('isEmpty(n): ' + isEmpty(n));
console.log('isEmpty(a): ' + isEmpty(a));

I'm tempted to modify the object line to check if the length property is defined, rather than restricting to Arrays, but that's all I can think of offhand. Any other ideas on making this more general?


texts:
The scenario is the following. I get the string from an HTML element via outerHTML and I need to convert the 'rgb(r, g, b)' part into the hexadecimal representation. I tried this with regex and it seems to work but I have a feeling there are better ways to deal with this.

One particular thing I don't like is where I directly access color[1] from my regex match. I'm open to any feedback.

private cleanupRichText(richText: string) {
    const rx = /rgb\((.+?)\)/ig
    const color = rx.exec(richText)
    if (color !== null) {
        const hexparts = color[1].split(',').map(str => parseInt(str.trim(), 10).toString(16))
        let hexString = '#'
        hexparts.forEach(element => {
        hexString += element.length === 1 ? '0' + element : element })
        text = text.replace(/rgb\(.+?\)/ig, hexString)
    }
}

To give an example input:

'rgb(234, 112, 30)'

Expected output:

'#ea701e'


texts:
Would you consider this to be idiomatic Scala? If not, what would you do to improve it?

def fibonaccis(max: Int): List[Int] = { fibonaccis(max, 2, 1) }
private def fibonaccis(max: Int, prev: Int, prevPrev: Int): List[Int] = prev >= max match {
  case true => List[Int](prevPrev)
  case false => prevPrev :: fibonaccis(max, prev + prevPrev, prev)
}


texts: Emacs module that generates templates for my blog's static site generator

texts:
I wrote a simple emacs module that generates standard templates that I use for my blog's static site generator.

(defun hakyll-site-location ()
  "Return the location of the Hakyll files."
  "~/Sites/hblog/")

(defun hakyll-new-post (title tags)
  "Create a new Hakyll post for today with TITLE and TAGS."
  (interactive "sTitle: \nsTags: ")
  (let ((file-name (hakyll-post-title title)))
    (set-buffer (get-buffer-create file-name))
    (markdown-mode)
    (insert
     (format "---\ntitle: %s\ntags: %s\ndescription: \n---\n\n" title tags))
    (write-file
     (expand-file-name file-name (concat (hakyll-site-location) "posts")))
    (switch-to-buffer file-name)))

(defun hakyll-new-note (title)
  "Create a new Note with TITLE."
  (interactive "sTitle: ")
  (let ((file-name (hakyll-note-title title)))
    (set-buffer (get-buffer-create file-name))
    (markdown-mode)
    (insert (format "---\ntitle: %s\ndescription: \n---\n\n" title))
    (write-file
     (expand-file-name file-name (concat (hakyll-site-location) "notes")))
    (switch-to-buffer file-name)))

(defun hakyll-post-title (title)
  "Return a file name based on TITLE for the post."
  (concat
   (format-time-string "%Y-%m-%d")
   "-"
   (replace-regexp-in-string " " "-" (downcase title))
   ".markdown"))

(defun hakyll-note-title (title)
  "Return a file name based on TITLE for the note."
  (concat
   (replace-regexp-in-string " " "-" (downcase title))
   ".markdown"))

Now, this works, but it could do with DRYing up a little bit, but I don't know enough elisp to do it myself.

hakyll-new-post and hakyll-new-note are very similar and could do with DRYing up, but I'm not sure how to pass the correct parameter to any refactored function
I'm hard coding hakyll-site-location. Is there any way that I can request for and store a configuration in my emacs dotfiles?

Any help or pointers to documentation are welcome.


texts: Expression evaluator with Shunting-Yard algorithm

texts:
I am especially concerned about:

Correctness: Does my algorithm always output the correct answer given a correct input?
Readability: Is my algorithm easy to understand for an experienced Ruby programmer (or, in other words: how many WTFs does a experienced Ruby programmer say while reading my code?)

Performance is not a main goal (if I had performance as a main goal, I wouldn't use Ruby), yet I want to know if I did something really bad somewhere in my code.

My method to transform a string into a list of symbols (which is called symbolize) is really poor but it doesn't matter. It does not need to be reviewed. And yes, it accepts only positive numbers.

Shunting-Yard implementation

class ShuntingYard
  def initialize
    @precedence = {
      "(" => 0,
      ")" => 0,
      "+" => 1,
      "-" => 1,
      "*" => 2,
      "/" => 2,
      "^" => 3,
    }

    @associativity = {
      "+" => :left,
      "-" => :left,
      "*" => :left,
      "/" => :left,
      "^" => :right
    }
  end

  def symbolize input
    stripped = input.lstrip

    if stripped.size == 0 then
      []
    elsif is_operator stripped[0] then
      [stripped[0]].concat symbolize stripped[1..-1]
    else
      n = stripped[/\d+(\.\d+)?/, 0]
      [n.to_f].concat symbolize stripped[n.size..-1]
    end
  end

  def parse input
    @stack = []
    @rpn = []

    (symbolize input).each do |symbol|
      shunt symbol
    end

    @rpn.concat @stack.reverse
  end

  def shunt symbol
    if not is_operator symbol then
      @rpn << symbol
    elsif symbol == "(" then
      @stack << symbol
    elsif symbol == ")" then
      until @stack.last == "("
        @rpn << @stack.pop
      end

      @stack.pop
    elsif @stack.empty? or @stack.last == "(" then
      @stack << symbol
    elsif is_higher_or_right symbol then
      @stack << symbol
    else
      until @stack.empty? or (is_higher_or_right symbol)
        @rpn << @stack.pop
      end

      @stack << symbol
    end
  end

  def is_higher_or_right symbol
    higher = @precedence[symbol] > @precedence[@stack.last]
    equal = @precedence[symbol] == @precedence[@stack.last]
    right = @associativity[symbol] == :right

    higher or (equal and right)
  end

  def is_operator symbol
    not not @precedence[symbol]
  end
end

Interpreter implementation

class Interpreter
  def initialize
    @eval = {
      "+" => lambda { |a, b| a + b },
      "-" => lambda { |a, b| a - b },
      "*" => lambda { |a, b| a * b },
      "/" => lambda { |a, b| a / b },
      "^" => lambda { |a, b| a ** b },
    }
  end

  def evaluate input
    result = []

    (ShuntingYard.new.parse input).each do |symbol|
      result << (if @eval[symbol] then
                  right = result.pop
                  left = result.pop
                  @eval[symbol].call left, right
                else
                  symbol
                end)
    end

    result.pop
  end
end

Some tests to easily run it all

inputs = {
  "15 * 2 - 30 / 3 + 7" => 27,
  "5 + ((1 + 2) * 4) - 3" => 14,
  "10 * (30 / (2 * 3 + 4) + 15)" => 180,
  "25 + (14 - (25 * 4 + 40 - (20 / 2 + 10)))" => -81,
}

interpeter = Interpreter.new

inputs.each do |input, expected|
  puts "Got:      #{input}"
  puts "Expected: #{expected}"
  puts "Result:   #{interpeter.evaluate input}"
  puts
end

For completeness, I am using this Ruby interpreter

ruby 2.3.1p112 (2016-04-26) [x86_64-linux-gnu]


texts: Is my Angular Material MessageBox component well build?

texts:
My angular knowledge is limited, so I don't know much yet about it's garbage collection etc to make sure my component can be used without any strange side effects or memory leaks.
I've created a stackblitz with a working version of the component here: https://stackblitz.com/edit/angular-material-messagebox?file=src/app/app.component.ts
So I have a button that will trigger the 'message box dialog' like this:
  openMessageBox(buttons: Buttons) {
    // mb is injected in constructor
    let dialog = this.mb.show('Title','Message',buttons);

    dialog.dialogResult$.subscribe(result=>{
      console.log("Button pressed: ", Button[result])
    });
  }

After clicking one of the buttons available the dialog will close and will inform what button was pressed.
My dialog provider looks like this:
@Injectable()
export class MessageBox {
  constructor(private dialog: MatDialog) {
  }

  private dialogResultSubject!: Subject<Button>;
  dialogResult$!: Observable<Button>;

  show(message: string, title?: string, buttons?: Buttons): MessageBox {

    let dialogRef = this.dialog.open(MessageBoxDialog, {
        data: {
          message,
          title,
          buttons: buttons ?? Buttons.Ok
        }
      }
    );

    this.dialogResultSubject = new Subject<Button>();
    this.dialogResult$ = this.dialogResultSubject.asObservable()

    dialogRef.componentInstance.dialogResult$.subscribe(pressedButton => {
      this.dialogResultSubject.next(pressedButton);
      this.dialogResultSubject.complete();
      dialogRef.close();
    });

    return this;
  }
}

I complete the subject in the provider because the mb instance (of provider) is not destroyed.
The MessageBoxDialog is a simple Component that displays the Title and a Message along with the chosen buttons:
import { Component, Inject } from "@angular/core";
import { Buttons, Button } from "../common";
import { MAT_DIALOG_DATA } from "@angular/material/dialog";
import { Subject } from "rxjs";

@Component({
  templateUrl: './message-box.component.html',
  styleUrls: ['./message-box.component.scss']
})
export class MessageBoxDialog {

  title = '';
  message = '';
  buttons: Buttons = Buttons.Ok;

  constructor(
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.title = data.title;
    this.message = data.message
    this.buttons = data.buttons;
  }

  dialogResultSubject = new Subject<Button>();
  dialogResult$ = this.dialogResultSubject.asObservable();

  public get Buttons(): typeof Buttons {
    return Buttons;
  }

  public get Button(): typeof Button {
    return Button;
  }

  click(button: Button) {
    this.dialogResultSubject.next(button);
  }
}

{{title}}

<mat-dialog-content>{{ message }}</mat-dialog-content>
<mat-dialog-actions *ngIf="buttons === Buttons.Ok">
  <button mat-raised-button (click)="click(Button.Ok)">Ok</button>
</mat-dialog-actions>
<mat-dialog-actions *ngIf="buttons === Buttons.YesNo ">
  <button mat-raised-button (click)="click(Button.Yes)" tabindex="-1">Yes</button>
  <button mat-raised-button (click)="click(Button.No)" class="mat-primary">No</button>
</mat-dialog-actions>

I hope to receive feedback about whether I created this all in a good way (or not) and some tips to improve.


texts: Calculating doubling times from data points

texts:
In the code below, noisy data points with unique errors are created. From this, an exponential function is fitted to the data points, and then doubling times (10 unit windows) are calculated.

I'm uncertain how to show the unique errors in the data points in the fitted function or doubling times.

Output:

from scipy import optimize
from matplotlib import pylab as plt
import numpy as np
import pdb
from numpy import log

def exp_growth(t, x0, r):
    return x0 * ((1 + r) ** t)

def doubling_time(m, x_pts, y_pts):
    window = 10

    x1 = x_pts[m]
    y1 = y_pts[m]
    x2 = x_pts[m+window]
    y2 = y_pts[m+window]

    return (x2 - x1) * log(2) / log(y2 / y1)

# First, artificially create data points to work with
data_points = 42

# Create the x-axis
x_pts = range(0, data_points)

# Create noisy points with: y = x^2 + noise, with unique possible errors
y_pts = []
y_err = []
for i in range(data_points):
    random_scale = np.random.random()
    y_pts.append((i * i) + data_points * random_scale)
    y_err.append(random_scale * 100 + 100)

x_pts = np.array(x_pts)
y_pts = np.array(y_pts)
y_err = np.array(y_err)

# Fit to function
[x0, r], pcov  = optimize.curve_fit(exp_growth, x_pts, y_pts, p0=(0.001, 1.0))
fitted_data = exp_growth(x_pts, x0, r)

# Find doubling times
x_t2 = range(32)
t2 = []
t2_fit = []
for i in range(32):
    t2.append(doubling_time(i, x_pts, y_pts))
    t2_fit.append(doubling_time(i, x_pts, fitted_data))

# Plot
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, sharex=True)

ax1.plot(x_pts, y_pts, 'bo')
ax1.errorbar(x_pts, y_pts, yerr=y_err)
ax1.set_ylim([0, 2000])
ax1.set_title('Artificially created raw data points with unique errors', fontsize=8)

ax2.plot(fitted_data, 'g-')
ax2.set_ylim([0, 2000])
ax2.set_title('Fitted exponential function', fontsize=8)

ax3.plot(x_t2, t2, 'ro', label='From points')
ax3.plot(x_t2, t2_fit, 'bo', label='From fitted')
ax3.set_title('Doubling time at each point (10 unit window)', fontsize=8)
ax3.legend(fontsize='8')

plt.show()


texts: Header-only variadic console output and runtime input validation in C++ using templates

texts:
Template IO Module

This is a single-file, header-only input validation with two variadic output functions. One output function simply inserts a new line char after every output and the other one inserts a space; this is the only difference.

The end goal of this project is a convenient, cross-platform IO module, and I thought that the static type-checking and compile-time generation of templates would be the perfect combination of type safety without run-time overhead, with the added bonus of the simplicity of adding a header-only module to an existing project.

Source

#ifndef _INPUT_VALIDATION_HPP
#define _INPUT_VALIDATION_HPP

/** Required STL Header Files for this module:
*  #include <iostream>
*  #include <limits>
*  #include <typeinfo>
*
*/

namespace IO {

    template <typename T>
    void print(const T& input)
    {
        std::cout << input << ' ';
    }

    template <typename T, typename... Types>
    void print(const T& firstArg, const Types&... arguments)
    {
        std::cout << firstArg << ' ';
        print(arguments...);
    }

    template <typename T>
    void println(const T& input)
    {
        std::cout << input << std::endl;
    }

    template <typename T, typename... Types>
    void println(const T& firstArg, const Types&... arguments)
    {
        std::cout << firstArg << std::endl;
        println(arguments...);
    }

    template <typename T>
    T get()
    {
        auto IO_status_flag = false;

        T response;
        std::cin >> response;

        do {
            if (std::cin.fail()) {

                IO::print("[Error] Please enter a valid response:");
                std::cin.clear();
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

                std::cin >> response;
            } else {
                IO_status_flag = true;
            }
        } while (IO_status_flag != true);

        return response;
    }

}

#endif /* _INPUT_VALIDATION_HPP */

Test Code

#include <iostream>
#include <limits>
#include <typeinfo>

#include "input-validation.hpp"

int main()
{
    IO::print("Please enter username:");
    auto username = IO::get<std::string>();

    IO::print("Please enter age:");
    auto age = IO::get<int>();

    IO::print("\nName:", username);
    IO::print("\nAge:", age);

    auto array = { "one", "two", "three", "four", "five", "six" };

    IO::println("\n");

    for(auto str : array)
    {
        IO::println(str);
    }

}

Output

Please enter username: Jose
Please enter age: 23

Name: Jose
Age: 23

one
two
three
four
five
six


texts:
This is what I coded to realize a command line program to make it easier to manage emails on ovh shared hostings. It's working ok but it seems ugly.

I'm a beginner with Python and docopt.  What would you suggest?

#!/usr/bin/env python
# -*- coding: utf-8 -*-
''' OVH Email Manager (ovhEmailMan)
A small script that helps to add and remove one or more email addresses on the OVH shared domains

    Usage:
        ovh_mails.py list [--ugly]
        ovh_mails.py add (<address> [--pswd=<password>][--description=<description>] | --file <filename> [--notify])
        ovh_mails.py remove (<address> | --file <filename>)
        ovh_mails.py (-h | --help)

    Arguments:
        <password>                        Password to access the mailbox (if not provided it's random generated)
        <filename>                        Name of the files to process (csv). Check README to see how to format it

    Options:
        -h, --help                        Show this help message
        -u, --ugly                        Print without nice tables
        -p, --pswd=<password>             Set the password to the one provided
        -n, --notify                      If set, notification mail is sent using smtp credentials in ovh.conf

    Commands:
        list                              list all the email addresses currently configured
        add                               add one or more (configured in <filename>) email addresses
        remove                            remove one ore more (configured in <filename>) email addresses
    '''

import ovh
from docopt import docopt
from ovhem import EmailManager
from ovhem import fileprocesser as fp

if __name__ == '__main__':
    args = docopt(__doc__)
    #Validate args ---- TODO
    eman = EmailManager()

    # 'List' command parsing
    if args['list']:
        if args['--ugly']:
            eman.niceoutput = False

        eman.list_emails()
    # 'Add' command parsing
    elif args['add']:
        if args['<address>']:

            emails = (
                      {
                       'address': args['<address>'],
                       'password': None,
                       'description': None,
                       },
                      )
            if args['--description']:
                emails[0]['description'] = args['<description>']
            if args['--pswd']:
                emails[0]['password'] = args['<password>']
        if args['--file']:
            emails = fp.process_file(args['<filename>'])

        # Getting back the emails dict
        emails=eman.add_emails(emails)
        if args['--notify']:
            fp.send_notifications(emails)

    # 'remove' command parsing
    elif args['remove']:
        if args['<address>']:

            emails = (
                      {
                       'address': args['<address>'],
                       },
                      )
        if args['--file']:
            emails = fp.process_file(args['<filename>'])
        eman.remove_emails(emails)


texts: Monitor asynchronous tasks, tracking their running times

texts:
Scenario: I'm getting requests through a (thread-safe) queue. Each request then needs to be handled in a separate thread. There is a chance that the function (which is actually calling a Java-program via popen, and polling its output) takes a very long time.  From the main thread I need a mechanism to indicate that situation (basically, measuring thread-running-time).

In my example I'm trying to 'enrich' std::future with some time information. The sample runs seamlessly - but I'm uncertain if this is the correct way.

Here is a very simple demo that mimics what I'm trying to achieve (where ThreadFunc stands in for my real processing code):

#include <iostream>

#include <thread>
#include <future>
#include <chrono>
#include <vector>
#include <random>

typedef std::future<int> FutureResultInt;

int ThreadFunc( )
{
  std::random_device rd;
  std::mt19937 mt(rd());

  const int iRand = std::uniform_int_distribution<int>(2000, 6000)(mt);

  std::cout << "ThreadFunc waiting for [" << iRand << "] ms ... " << std::endl;

  std::this_thread::sleep_for(std::chrono::milliseconds(iRand));

  std::cout << "ThreadFunc [" << iRand << "] done" << std::endl;

  return iRand;
}

class CFutureTest
{
public:
  CFutureTest() = delete;

  CFutureTest(FutureResultInt&& fr)
    : m_start(std::chrono::system_clock::now())
    , m_result()
  {
    m_result = std::move(fr);
  };

  int GetAge() const
  {
    return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - m_start).count();
  }

// private:
  FutureResultInt m_result;
  std::chrono::time_point<std::chrono::system_clock> m_start;
};

int main()
{
  std::vector< CFutureTest > futures;
  for (int i = 0; i < 5; i++)
    futures.push_back(std::move(std::async(std::launch::async, ThreadFunc)));

  while (futures.size() > 0)
  {
    for (std::vector< CFutureTest >::iterator it = futures.begin(); it != futures.end(); ++it)
    {
      CFutureTest& future = *it;

      const std::future_status stat = future.m_result.wait_for(std::chrono::milliseconds(1));

      switch (stat)
      {
      case std::future_status::timeout:
        if (future.GetAge() > 4000)
        {
            std::cout << "Thread has exceeded the time limit" << std::endl;
        }
        continue;

      case std::future_status::deferred:
        std::cout << "std::future_status::deferred" << std::endl;
        continue;
      }

      const int iResult = future.m_result.get();

      std::cout << "future returned [" << iResult << "] (removing!)" << std::endl;
      futures.erase(it);

      if (futures.size() < 1)
        break;

      it = futures.begin();
    }
  }
  return 0;
}


texts: Pythonic loop logic for Tic-Tac-Toe game board

texts:
I have a while loop below, but I'm not quite sure if it's the most 'pythonic' thing. I've omitted most of the code, and have the skeletal structure below (but have all the code necessary to understand my game_status() function). And the main thing in question is whether/how to use a function as a condition in a while statement. (In my case, the game_status() function).

#Legal board positions
BOARD_POSITIONS = list(range(1, 10))

#All possible combinations of board positions giving 8 winning lines.
WINNING_LINES = [[1, 2, 3], [4, 5, 6], [7, 8, 9],
                 [1, 4, 7], [2, 5, 8], [3, 6, 9],
                 [1, 5, 9], [3, 5, 7]]

def game_status(board):
    """Updates the status of the game based on three outcomes:
       Returning 'X' or 'O' is either has three in a row; 'tie' if the
       board is full, but no players have won; or 'unfinished' otherwise"""
    for i, j, k in WINNING_LINES:
        if not available(board, i) and board[i] == board[j] == board[k]:
            return board[i]
    if any(available(board, i) for i in BOARD_POSITIONS):
        return 'unfinished'
    return 'tie'

while True:
    game_board = (' ' for i in range(10))
    while game_status(game_board) is 'unfinished':
        #Main game code
    else:
        if game_status(game_board) is 'X':
            #Code for X winning goes here
        elif game_status(game_board) is 'O':
            #Code for O winning goes here
        else:
            #Code for a tie goes here

As you notice, I've got to call game_status() multiple times in the else part of my while statement in order to check the value of game_status() so that I know to print who won or if the game was a tie.

One idea I had is the following:

else:
    status = game_status(game_board)
    if status = 'X':
        #Code
    elif status = 'O':
        #Code

and so on. However, I am quite curious as to the most pythonic way to do things, as well as whether or not using a function as a conditional is pythonic.


texts:
A Base10 Pandigital Number is a number which uses all the digits 0-9 once:

1234567890
2468013579
etc...

My naive solution was just to use a bunch of nested loops to do this but it's quite slow. And I'm blanking on a more efficient way to do it? The following takes ~6 seconds.

IEnumerable<long> GeneratePandigital()
{
    var other=Enumerable.Range(0,10);

foreach(var a in other)
foreach(var b in other.Except(new int [] {a}))
foreach(var c in other.Except(new int [] {a,b}))
foreach(var d in other.Except(new int [] {a,b,c}))
foreach(var e in other.Except(new int [] {a,b,c,d}))
foreach(var f in other.Except(new int [] {a,b,c,d,e}))
foreach(var g in other.Except(new int [] {a,b,c,d,e,f}))
foreach(var h in other.Except(new int [] {a,b,c,d,e,f,g}))
foreach(var i in other.Except(new int [] {a,b,c,d,e,f,g,h}))
foreach(var j in other.Except(new int [] {a,b,c,d,e,f,g,h,i}))
{
    yield return a * 1000000000L +
    b * 100000000L+
    c * 10000000L+
    d * 1000000+
    e * 100000+
    f * 10000+
    g * 1000+
    h * 100+
    i * 10+
    j;
}
}


texts: Implementing an enum field for peewee.Model

texts:
I implemented an enum field class EnumField inheriting from peewee.CharField.
The reason that I use a character-based field is that I require human-readability of the enumeration values on the database level.

I currently use the funcion is_enum to detemine whether the provided enum constraint is an enum.Enum.
Knowing this is important, since enum.Enum instances need to be translated, unlinke sets of strings, back and forth between the enum value and string value.
I'd especially like to improve this translation.

class InvalidEnumerationValue(ValueError):
    """Indicates that an invalid enumeration value has been specified."""

    def __init__(self, value):
        super().__init__('Invalid enum value: "{}".'.format(value))

def is_enum(obj):
    """Determines whether the object is an enum.Enum."""

    try:
        return issubclass(obj, Enum)
    except TypeError:
        return False

class EnumField(peewee.CharField):
    """CharField-based enumeration field."""

    def __init__(self, enum, *args, max_length=None, null=None, **kwargs):
        """Initializes the enumeration field with the possible values.

        :enum: The respective enumeration.
        :max_length: Ignored.
        :null: Ignored.
        """
        super().__init__(*args, max_length=max_length, null=null, **kwargs)
        self.enum = enum

    @property
    def enum(self):
        """Returns the enumeration values."""
        return self._enum

    @enum.setter
    def enum(self, enum):
        """Sets the enumeration values."""
        if is_enum(enum):
            self._enum = enum
        else:
            self._enum = set(enum)

    @property
    def values(self):
        """Yields appropriate database values."""
        if is_enum(self.enum):
            for item in self.enum:
                yield item.value
        else:
            for value in self.enum:
                yield value

    @property
    def max_length(self):
        """Derives the required field size from the enumeration values."""
        return max(len(value) for value in self.values if value is not None)

    @max_length.setter
    def max_length(self, max_length):
        """Mockup to comply with super class' __init__."""
        if max_length is not None:
            LOGGER.warning(
                'Parameter max_length=%s will be ignored since it '
                'is derived from enumeration values.', str(max_length))

    @property
    def null(self):
        """Determines nullability by enum values."""
        return any(value is None for value in self.values)

    @null.setter
    def null(self, null):
        """Mockup to comply with super class' __init__."""
        if null is not None:
            LOGGER.warning(
                'Parameter null=%s will be ignored since it '
                'is derived from enumeration values.', str(null))

    def db_value(self, value):
        """Coerce enumeration value for database."""
        if is_enum(value):
            if value in self.enum:
                return value.value
        elif value in self.values:
            return value

        raise InvalidEnumerationValue(value)

    def python_value(self, value):
        """Coerce enumeration value for python."""
        if is_enum(self.enum):
            for item in self.enum:
                if item.value == value:
                    return item
        elif value in self.values:
            return value

        raise InvalidEnumerationValue(value)


texts: Find minimum XOR values in a given array

texts:
I am implementing an algorithm to find the pair of integers in the given array which have minimum XOR value.

Ex:

Input:

   0 2 5 7

Output:

   2 (value of 0 XOR 2).

Then bellow is my solution:

    public int findMinXor(List<int> A)
    {
        var min = int.MaxValue;

        for (int i = 0; i < A.Count - 1; i++)
        {
            for (int j = i + 1; j < A.Count; j++)
            {
                var tmp = A[i] ^ A[j];

                if (tmp < min)
                {
                    min = tmp;
                }

            }
        }

        return min;
    }

What should I do to improve the solution (clean code, performance, DRY,...)?
Any help are appriciate!


texts: Implement numbering scheme like A,B,C... AA,AB,... AAA..., similar to converting a number to radix26

texts:
I want to implement numbering scheme like Microsoft Word uses for numbering.
first one gets = A,next is  B, next is C, .... then AA, then AB,....and so on.
as shown below

 A
 B
 C
 .
 .
 AA
 AB
 AC
 .
 .
 AAA
 AAB
 ....

'=>' here means converted to.

some examples:

1 => A
26 => Z
27 => AA
52 => AZ
53 => BA

and heres the code for it:

   var convertToNumberingScheme = function(n){
        var x = n-1,
            r26 = x.toString(26),
            baseCharCode = "A".charCodeAt(0);

        var arr = r26.split(''),
            len = arr.length;

        var newArr =arr.map(function(val,i){
            val = parseInt(val,26);

            if( (i === 0) && ( len > 1)){
                val = val-1;
            }

            return String.fromCharCode(baseCharCode + val);
        });
        return newArr.join('');
    }

It seems to work fine, but any ideas if there are some potential bugs or ways to  optimize this.


texts:
I'm building a HTTP API and this part should return a JSON list of posts and their attached photos, like this:

[
    {
        "id": "788",
        "content": "Foo bar! Foo foo, bar bar.",
        "photos": [181, 282, 182]
    },
    ...
]

And this is my PHP code handling the request:

// get all the posts and their photos
$st = $db->prepare ('SELECT * FROM `posts` ' .
                    'LEFT JOIN `photos` ON `photo_post` = `post_id`');
$st->execute ();

// init our results array
$posts = array ();

// get the first post (plus it's JOINed photo)
$row = $st->fetch (PDO::FETCH_OBJ);
// if there's more left
while (false !== $row) {
    // init our post array
    $post = array (
        'id' => $row->id,
        'content' => $row->content,
        'photos' => array ()    // to fill with the photos
    );
    do {
        // don't add a `null` if there's no photos
        if (null !== $row->screenshot)
            $post ['photos'] [] = $row->photo_id;
    // get the row, repeat if it's another photo
    } while (false !== ($row = $st->fetch (PDO::FETCH_OBJ)) &&
             $row->id === $post ['id']);

    // add this post to the list
    $posts [] = $post;
}

// and send it back
echo json_encode ($posts);

Pretty simple JOIN parsing job, right?  But the code is anything but nice or simple!

How can I parse MySQL's JOIN results elegantly into the JSON heirarchy that I need?


texts: Finding equivalent to % for the inner if clauses

texts:
I have a static list of descriptions in a resource and I am filtering down the list based on the index positions of the text in the array

Here is my multi converter:

using OCLMEditor.Data.StudentInfo.Enums;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Data;

namespace OCLMEditor.ValueConverters
{
    public class StudentAssignmentTypeFilterConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            StudentAssignmentType[] allTypes = values[0] as StudentAssignmentType[];
            List<StudentAssignmentType> filteredTypes = new List<StudentAssignmentType>();
            int iNumberOfClasses = values[1] != null ? (int)values[1] : 0;

            if (iNumberOfClasses == 3) // Main hall, Class 1 and Class 2
                return allTypes;

            if(iNumberOfClasses == 0)
            {
                // What to return? It should not get here as the combo is disabled if
                return allTypes;
            }

            for(int i = 0; i < allTypes.Length; i++)
            {
                if(iNumberOfClasses >= 1)
                {
                    if (i == 0 || i == 3 || i == 6 || i == 9 || i == 12 || i == 15 || i == 18)
                        filteredTypes.Add(allTypes[i]);
                }

                if(iNumberOfClasses >= 2)
                {
                    if (i == 1 || i == 4 || i == 7 || i == 10 || i == 13 || i == 16 || i == 19)
                        filteredTypes.Add(allTypes[i]);
                }

                if (iNumberOfClasses == 3)
                {
                    if (i == 2 || i == 5 || i == 8 || i == 11 || i == 14 || i == 17 || i == 20)
                        filteredTypes.Add(allTypes[i]);
                }
            }

            return filteredTypes;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
}

Do you think the if clauses inside can be simplified somehow?

Specifcally these three if clauses. Eg:

if(iNumberOfClasses >= 1)
{
    if (i == 0 || i == 3 || i == 6 || i == 9 || i == 12 || i == 15 || i == 18)
        filteredTypes.Add(allTypes[i]);
}

I know about using % to get the (modulus(?)) remainder of a division. So if my numbers were 1, 5, 10, 15, 20 I could use number % 5 == 0 to get all of them. But ican't see that I can do that here?


texts: Maximum score, using only elements near the beginning or end of a list

texts:
Input list has n elements, each element has a score. The goal is to assemble a group (of size ‘team’) of elements together and to find their total score.
Inputs:

score [] of size n,
team which is the team size,
m tells us how to slice the list

Selection of elements from the list is done in the following way:

During each selection, we have to choose an element with the highest score among either the first m in available elements or the last m available elements in the list. The element is then removed from the list and added to the team total score.
If there are multiple elements with the same highest score among the first or last in available elements, the element closest to the start of the line is picked.
If there are less than in available elements. then we pick the highest scored element from all available elements.

Sample Input and Output:
Sample 1
n:9, score:[17,12,10,2,7,2,11,20,8,],team:3,m:4
OUTPUT : 49

Sample 2
n:8,score:[18,5,15,18,11,15,9,7],team:5,m:1
OUTPUT : 60

Need an optimal solution for this Python code. I am getting the desired output. But I am looking for a better solution.
def teamFormation(score, team, m):
    total_score = 0
    for _ in range(team):
        if len(score) < 2*m:
            total_score += score.pop(score.index(max(score)))
        elif max(score[:m]) > max(score[-m:]):
            total_score += score.pop(score[:m].index(max(score[:m])))
        else:
            total_score += score.pop(score[-m:].index(max(score[-m:]))-m)
    return total_score


texts: Search for a value in tuple of lists/vectors

texts:
I guess there is some smarter way to implement such simple piece of code, but I couldn't figure out other solution by myself. Could it be done recursively without some sort of if's?

import           Data.Vector (Vector)
import qualified Data.Vector

type SeqV = (Vector Integer, Vector Integer, Vector Integer)

seqv :: SeqV
seqv = (Data.Vector.fromList[1..5], Data.Vector.fromList[10..15], Data.Vector.fromList[20..25])

-- | searchs for n in SeqV from left to right
-- returns first found value
find :: Integer -> SeqV -> Maybe Integer
find n (a,b,c) =
  case f a of
       Just v -> Just v
       Nothing -> case f b of
         Just v  -> Just v
         Nothing -> f c

  where f v = let f = Data.Vector.filter (==n) v
                  in if Data.Vector.length f > 0 then
                                               Just (Data.Vector.head f)
                                               else Nothing


texts: Testing individual nodes launched by naught using supertest

texts:
The purpose: an express node.js server which can be launched using naught, with an integration test using supertest. Each worker naught runs will test itself on a unique port, and only if passes it will listen in on the main port and join the pool.

Major concerns are - no idea what I'm doing.  How I provision the ports for the test nodes, closing the test servers (need to clear up memory)?

This just a POC, structuring is required for a production app.

var testport = 10000 + process.pid;
var server = app.listen(testport, function() {
    console.log('pid %d listening on port %d ...', process.pid, testport);

    supertest(server)
    .get('/test')
    .expect(200)
    .end(function(err, res){

        if (err) {
            console.log(err);
            if (process.send) process.send('offline');
            process.exit(-1);
        }
        else {
            console.log('pid %d tested OK, closing test server and launching main one...', process.pid);
            server.close();
            listenToMainport();
        }

    });
});

You can see the full context of the example here.


texts: Iterative Implementation of Negamax Alpha-Beta

texts:
Please help me check the correctness of this c# iterative implementation of negamax! Thank you! Your help highly appreciated! Also, please help me out how to add alpha beta pruning to this(it was supposed to be alpha beta with negamax, but i forgot the alpha beta part... :<)! Thanks in advance!

EDIT: I DO think that the implementaqtion works. I only want it to be checked. Also, i simply want SUGGESTIONS and GUIDANCE on how to add alpha beta to the algorithm, not someone write the code for me. Please do not be mistaken. Thank you.

Random r = new Random();

Stack<int> maxs = new Stack<int>();

Stack<int> levels = new Stack<int>();
Stack<string> todo = new Stack<string>();

Stack<string> undo = new Stack<string>();

maxs.Push(int.MinValue);

var le = legals(bd);
while (le.Any())
{
    var mv = le[r.Next(le.Count)];
    le.Remove(mv);
    todo.Push(mv);
    levels.Push(1);
}

while (todo.Any())
{
    //init
    string mv = todo.Pop();
    int level = levels.Pop();
    undo.Push(mv);
    if (level != depthleft) maxs.Push(int.MinValue);
    move(mv, level % 2 == 0 ? "b" : "w");

    //expand children/do operations,cleanup
    if (level == depthleft)
    {
         int score = -eval(bd, level % 2 == 0);
         if (score > maxs.Last())
         {
              maxs.Pop();
              maxs.Push(score);
         }
         unmove(undo.Pop());

         int diff = level - levels.Last();
         if (diff != 0)
         {
              for (; diff > 0; diff--)
              {
                   score = -maxs.Pop();
                   if (score > maxs.Last())
                   {
                        maxs.Pop();
                        maxs.Push(score);
                   }
                   unmove(undo.Pop());
              }
         }
     }
     else
     {
          var ls = legals(bd);
          while (ls.Any())
          {
              var child = ls[r.Next(ls.Count)];
              ls.Remove(child);
              todo.Push(child);
              levels.Push(level + 1);
          }
     }
}


texts: Algorithm to return unique values from unsorted input

texts:
I need to create an efficient algorithm that returns unique values from an unsorted input. I don't know the length of the input.

As the function that will call this algorithm can abort the reading at any time, I think that using a well defined Iterable implementation is the right way, so I will not waste extra processing power for the uneeded input.

Today, I am using a Set to keep track of the values I've already read. But I don't know if this is the most efficient algorithm, as my input length can be huge.

The code below is my today's working algorithm:

import java.util.Iterator;
import java.util.HashSet;
import java.util.Set;
import java.util.NoSuchElementException;
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;

public class UniqueValues implements Iterable<String> {
    private final Iterator<String> iterator;

    public UniqueValues(BufferedReader r) {
        this.iterator = new UniqueValuesIterator(r);
    }

    public Iterator<String> iterator() {
        return iterator;
    }

    static class UniqueValuesIterator implements Iterator<String> {
        private final BufferedReader r;

        private final Set<String> values = new HashSet<>();

        // When 'next' is null, need to get the next value
        private String next;

        public UniqueValuesIterator(BufferedReader r) {
            this.r = r;
        }

        public boolean hasNext() {
            // Good point from OldCurmudgeon
            if(next != null) return true;

            try {
                String line;
                while((line = r.readLine()) != null) {
                    if(values.add(line)) { // add() returns 'true' when it is not a duplicate value.
                        next = line;
                        return true;
                    }
                }
            } catch(IOException e) { }

            return false;
        }

        public String next() {
            if(next == null) {
                if(! hasNext() ) throw new NoSuchElementException();
            }

            final String temp = next;
            next = null;
            return temp;
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    }

    // For testing
    public static void main(String... args) {
        final StringReader r = new StringReader("value1\nvalue6\nvalue1\nvalue3\nvalue3\nvalue6\nvalue1\nvalue6");

        for(final String value : new UniqueValues(new BufferedReader(r)) ) {
            System.out.println(value);
        }

        /* Output is (order is not important):
         *
         * line 1
         * line 6
         * line 3
         */
    }
}

Does it have any better algorithm to do this?


texts: find substring with count and return even frequency substring list

texts:
I have one following question and write a function for it. can anyone give me some suggestion how my code can be better and better way to handle to build up return list with even frequency?

  One message system contains two device type message that each message is formatted with device type identifier with
  device id and message count. Write a function to parse the message based on device type and message count and return
  a list with each device id in even message frequency
  rule: input string: message
  device identifier
  1:iOS device ID identifier: start with 'I' following with 3 character, total length is 4 character
  2:Android device ID identifier: start with 'A' following with 2 character, total length is 3 character
  3:message count is following by device id until next device ID
  ex:
  input: Asq2: {'Asq': 2} Asq with 2 message count
  output: ['Asq', 'Asq']

  input: Akb2IAld3: ID: {'Akb': 2, 'IAld2': 3}  Akb with 2 message count,  IAld with 3 message count
  output: ['Akb', 'IAld', 'Akb', 'IAld', 'IAld']

  input: Aqp1Iasd2Aqp4IAbd1: {'Aqp': 5, 'Iasd': 2, 'IAbd': 1}
  output: ['Aqp', 'Iasd', 'IAbd', 'Aqp', 'Iasd', 'Aqp', 'Aqp', 'Aqp']

from typing import List

def parse_message(string) -> List:
    i, j, ids_map, n, ids = 0, 0, dict(), len(string), ''

    while i < n:
        if string[i] in ('I', 'A') or i == n - 1:
            if ids:
                if i == n - 1:
                    ids_map[ids] = ids_map.get(ids, 0) + int(string[j:])
                else:
                    ids_map[ids] = ids_map.get(ids, 0) + int(string[j:i])
            j = i + 4 if string[i] == 'I' else i + 3
            ids = string[i:j]
            i = j - 1
        i += 1
    res = []
    while any(i > 0 for i in ids_map.values()):
        for k, v in ids_map.items():
            if v > 0:
                res.append(k)
                ids_map[k] -= 1
    return res


texts:
I've made my first simple game in HTML5. Unfortunately, it runs so slowly. But there are only few rectangles! On my PC, frame rate is between 20 and 25. I expected something like 60-70 but no 20! You can see this game here: http://mygames.jcom.pl/ (and you can see code by clicking Ctrl+Shift+C in Chrome). What can I do to speed up my game? Why my (so simple) game doesn't run as smoothly as another (bigger and prettier) games in HTML5?

var gameCanvas = document.getElementById('gameCanvas');
var ctx = gameCanvas.getContext("2d");

var mapa = loadFromFile("level1");
var gracz = new Obiekt("square", 40, 40);
var blokczarny = new Obiekt("square", 80, 80);

var FPS = 0;

var gameWidth = gameCanvas.width;
var gameHeight = gameCanvas.height;
var gameTranslationX = 0;
var gameTranslationY = 0;

// Handle keyboard controls
var keysDown = {};

var graczData = {
    posOnScreenX: gameWidth / 2,
    posOnScreenY: gameHeight / 2,
    fallSpd: 300,
    runSpd: 300,
    jumpSpd: 600,
    fell: true,
    resetjumpSpd: 600,
    isJumping: false,
    yWhenStartedJump: 0,
    kierunek: 1
};

addEventListener("keydown", function(e) {
    keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function(e) {
    delete keysDown[e.keyCode];
}, false);

var reset = function() {
    gracz.y = 0;
    gracz.x = 0;
    ctx.setTransform(1, 0, 0, 1, graczData.posOnScreenX, graczData.posOnScreenY);
};

// Update game objects
var update = function(modifier) {
    this.zmianaX = 0;
    this.zmianaY = 0;
    if (38 in keysDown && !graczData.isJumping && graczData.fell) {// Player holding up
        graczData.isJumping = true;
    }
    if (40 in keysDown) {// Player holding down

    }
    if (37 in keysDown) {// Player holding left

    }
    if (39 in keysDown) {// Player holding right

    }
    //ochrona przed "wejsciem w sciane" X
    var newMapPosX = getPositionOnMap(gracz.x + this.zmianaX, gracz.y, blokczarny);
    if (mapa[newMapPosX[1]][newMapPosX[0]] == 0) {
        gracz.x += this.zmianaX;
    }
    //spadanie
    if (getTypeOfTile(gracz.x, gracz.y + (graczData.fallSpd * modifier), blokczarny, mapa) == 0) {
        gracz.y += graczData.fallSpd * modifier;
    } else {
        graczData.fell = true;
    }
    //skakanie
    if (getTypeOfTile(gracz.x, gracz.y - (graczData.fallSpd * modifier), blokczarny, mapa) == 0 && graczData.isJumping) {
        gracz.y -= graczData.jumpSpd * modifier;
        graczData.jumpSpd -= 500 * modifier;
        graczData.fell = false;
        if (graczData.jumpSpd < 0) {
            graczData.jumpSpd = graczData.resetjumpSpd;
            graczData.isJumping = false;
        }
    }
    //bieganie
    if (getTypeOfTile(gracz.x + (graczData.runSpd * modifier * graczData.kierunek), gracz.y, blokczarny, mapa) == 0) {
        gracz.x += graczData.runSpd * modifier * graczData.kierunek;
    } else {
        graczData.kierunek *= -1;
    }
    //document.write("GraczY: " + gracz.y + "GraczX: " +gracz.x);
};

var clear = function() {
    ctx.fillStyle = "rgb(255, 255, 255)";
    //ctx.beginPath();
    ctx.rect(0, 0, gameCanvas.width, gameCanvas.height);
    //ctx.closePath();
    ctx.fill();
}

var oldgracz = {
    x: 0,
    y: 0
}
var render = function() {

    ctx.translate(-(gracz.x - oldgracz.x), -(gracz.y - oldgracz.y));
    gameTranslationX = gracz.x - graczData.posOnScreenX;
    gameTranslationY = gracz.y - graczData.posOnScreenY;
    clear();

    console.log("FPS" + FPS);

    ctx.fillStyle = "rgb(255, 0, 0)";
    gracz.draw(ctx);
    ctx.fillStyle = "rgb(0, 0, 0)";
    drawMap(mapa, blokczarny, ctx);
    oldgracz.x = gracz.x;
    oldgracz.y = gracz.y;
}

// The main game loop
var main = function() {
    var now = Date.now();
    var delta = now - then;

    FPS = 1000 / delta;

    update(delta / 1000);
    render();

    then = now;
};

// Let's play this game!
reset();
var then = Date.now();
setInterval(main, 100);


texts: Giving multiple choices that lead to different scenarios

texts:
I'm doing a Java text based game as a course project.

Everything is fine but the part where it shows a conversation, then gives you 2-4 options, then each actions will lead to different text and stats changes.

For now I can only come up with declaring a string array to store all the text, looping through the text until the multiple choice is given, then declaring an int to store the choice of the player, switch the choice to give different text and stats bonuses.

This is quite inefficient and takes a lot of lines, so I wonder if there is a better way to do that.

int[] statsChanged = new int[] {0, 0, 0, 0};
int i;
String[] event = eventDial.getFirstNight();
for (i = 0; i < 7; i++) {
    say(event[i]);
    next();
}
int choice = -1;
while (choice > 2 || choice < 0) {
    try {
        say(event[7]);
        choice = input.nextInt();
    } catch (InputMismatchException e) {
        next();
    }
    switch (choice) {
        case 0:
            say(event[8]); say(event[9]);
            statsChanged[0] = 2;
            break;
        case 1:
            say(event[10]); say (event[11]);
            statsChanged[1] = 2;
            break;
        case 2:
            say(event[12]);
            break;
    }
}
say(event[13]);
return statsChanged;

event is the string array that stores the text. statchanges stores all the bonuses to 4 main stats. next() is just an empty input. (input.nextLine())
say(str) is System.out.println(String str);


texts:
I have a view that performs some rolling totals. In this instance, it must be in a view. The issue is that it takes about 10 minutes to run, returning 2700 records. There should be a faster way, but I am not privy at the moment. I asked a question here in order to get this far.

I am running SqlServer 2008 R2, so advanced over() functionality doesn't work, just Partition by Order by)

The difference between my question and what code I have below is that my requirements changed slightly, requiring that the OutOfPocket not be a total, but rather simply reflect the amount of the deduction (IssCost) once the $400 is exhausted. The only exception is on the deduction that exhausts the $400, the leftover is displayed, not the full deduction. A CROSS APPLY was used to achieve this effect. I couldn't quite figure out how to achieve the new requirement based upon the answer I selected in my question linked above, so I used a different answer that worked.

The concept of the view is that someone starts with $400 to spend. Every deduction (IssCost in the code), deducts from the initial $400. If a person starts going over the $400, the money will come from their own pocket (OutOfPocket).

Some sample data and the view code are as follows:

CREATE TABLE Payroll (
EmployeeID int,
PlanCode varchar(10),
IssCost int NULL
)
GO

INSERT INTO Payroll (EmployeeID, PlanCode, IssCost)
VALUES (1, 'Medical', 200)
  ,(1, 'Dental', 250)
  ,(1, 'Vision', 300)
  ,(2, 'Medical', 100)
  ,(2, 'Dental', 150)
  ,(2, 'Vision', 100)
  ,(2, 'Disability', 100)
  ,(2, 'Life', 140)

  --View starts here
  WITH C AS (
    SELECT EmployeeID
          ,PlanCode
          ,IssCost
          ,rownum = ROW_NUMBER() over (Partition BY EmployeeID Order by PlanCode)
    FROM Payroll

), C2 AS (
    SELECT EmployeeID
          ,PlanCode
          ,IssCost
          ,T.Ytd
    FROM C
    CROSS APPLY (SELECT ytd = SUM(IssCost)
                 FROM C CC
                 WHERE C.EmployeeID = CC.EmployeeID
                    AND C.rownum >= CC.rownum) T(ytd))

SELECT EmployeeID
        ,PlanCode
        ,IssCost
        ,OutOfPocket = CASE WHEN ytd < 400 THEN 0
                            WHEN (ytd > 400) AND (ytd < (400 + IssCost)) THEN ytd - 400
                            ELSE IssCost
                            END
FROM C2


texts:
This is my first Python project. Let me know how I did, and where I can improve it.

# Random Lottery Number Pick Tool
# It has U.S. national lottos and two from Nebraska
# I'll add more to it later.

import random

# here is a giant body function I wonder if I could make this easier to deal with?
# it is basically my program's menu items.

def workerFunction():
    while True:
        try: x=input( '\n\n Select an option:\n\n'
                      'Press 1+Enter for Pick Three\n'
                      'Press 2+Enter for Pick Five\n'
                      'Press 3+Enter for Powerball picks\n'
                      'Press 4+Enter for Mega Millions picks\n'
                      'Q+Enter to quit \n\n'  )

        #This is my end of file logic that kills the program
        # Provided you pass Q + Enter

        except EOFError: pass
        if x.lower().startswith('q'):
            print("done")
            break

        # Otherwise you are passing something else that requires work from my factory!

        elif x == '1': print( '\n\n Nebraska Pick Three',
                              factory.repeater( 3, factory.factoryLogic, [0, 9, 1] ) )
        elif x == '2': print( '\n\n Nebraska Pick Five',
                              factory.factoryLogic( 1, 38, 5 ) )
        elif x == '3': print( '\n\n Powerball',
                              factory.factoryLogic( 1, 55, 5 ),
                              factory.factoryLogic( 1, 42, 1 ) )
        elif x == '4': print( '\n\n Mega Millions',
                              factory.factoryLogic( 1, 75, 5 ),
                              factory.factoryLogic( 1, 15, 1 ) )

# My factory class (self is set to something)...
# Not sure how to use it yet outside of the program I know it is like "this" in javascript.

class factory:

    # so I am defined self which looks like a struct. I assign it 0 (to shut up the syntax checker)

    def __init__( self ): self.a = 0

    # My logic module picks numbers based on a start and end position.
    # Not sure why I use +1 in the range function.
    # And then there are the number of interators I need.

    def factoryLogic( startPosi, endPosi, interateNumber ):
        a = random.sample( range( startPosi, endPosi+1 ), interateNumber )
        a.sort()
        return a

    # This is a repeater utility I made because pick three needs to be called three times.
    # The neat thing is that I am als passing a functions and args as a list and breaking them out.
    # I could make it more terse but why? It also returns an appended list. Neat!

    def repeater( times, f, functionArgs ):
        return_list = []
        for i in range( times ): return_list.append( f( functionArgs[0], functionArgs[1], functionArgs[2]  ) )
        return return_list

# This name main holds my worker function. I call it workerFunction! Amazing, yes?
if __name__ == '__main__':
    workerFunction()


texts:
I read the following question: Searching an element in a sorted array and I thought that I could give it a try in Python.

Given a sorted list of integers and an integer. Return the (index) bounds of the sequence of this element in the list.

Example:

l = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 6, 7, 8, 9, 9, 9, 9]

0 not found in list
1:(0, 0)
2:(1, 2)
3:(3, 5)
4:(6, 11)
5 not found in list
6:(12, 12)
7:(13, 13)
8:(14, 14)
9:(15, 18)

Here is my program (using Python 3).
It uses a dichotomic search and returns the bounds to help the search of the start and end of the sequence.

def main():
    l = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 6, 7, 8, 9, 9, 9, 9]
    print(l)
    for i in range(10):
        try:
            print(find_sequence(i, l))
        except Exception as e:
            print(str(e))

def find_sequence(x, l):
    """Return a tuple (begin, end) containing the index bounds of the sequence of x"""
    left, found, right = dichotomic_search(x, l)
    begin = outside_bound(x, l, left, found)
    end = outside_bound(x, l, right, found)
    return begin, end

def outside_bound(x, l, outside, inside):
    """Return the outside bound of the sequence"""
    if l[outside] == x:
        return outside

    middle = -1
    previous_middle = -2
    while middle != previous_middle:
        previous_middle = middle
        middle = (outside + inside) // 2
        if l[middle] == x:
            inside = middle
        else:
            outside = middle
    return inside

def dichotomic_search(x, l):
    """Return a tuple of indexes (left, found, right)

    left: leftmost index where x might be found
    found: index where x is
    right: rightmost index where x might be found
    """
    left = 0
    right = len(l) - 1

    if l[left] > x or l[right] < x:
        raise Exception(str(x) + ' not found in list')

    if l[left] == x:
        return left, left, right
    if l[right] == x:
        return left+1, right, right # we know that l[left]!=x

    while left < right:
        middle = (left + right) // 2
        if l[middle] == x:
            return left, middle, right
        elif l[middle] < x:
            left = middle + 1 # to prevent fixed point
        elif l[middle] > x:
            right = middle # impossible to do -1 because of the integer division

    raise Exception(str(x) + ' not found in list')

if __name__ == "__main__":
    main()

I'm not so fond of the middle != previous_middle, but I didn't find a more elegant way (yet).


texts:
I've seen so many different ways of doing this all seem very complex and all seem to be done in MySQL. I'm using PDO in my project so I've had a go myself to see what I could come up with.

Is this safe?
Is there something I've missed a better way of doing it?

    //build query to insert users_contracts
$sth = "INSERT INTO `users_contracts` (users_id,contracts_id) VALUES (:user,:contract)";
$q = $conn->prepare($sth);

//take each item in the contract array from _POST and bind to the above INSERT query
foreach($contract as $contract => $contract_id)
{
    try {
       $q->execute(array(':user'=>$last_id,':contract'=>$contract_id));
    } catch (PDOException $e) {
       $errors[] = array(
          'message' => "Could not insert \"$contract\", \"$contract_id\".",
          'error' => $e
          );
    }
}

Its intended purpose is to allow the admin user to assign contracts to users via a checkbox list.


texts: Hash Table: adding and finding functions

texts:
I made this function to teach myself about hash tables. Any ideas? I commented out free(addition) because it was giving me a compiler error, but I need to figure out how to deallocate the memory.

#define hashSize 1000

typedef struct hashElem{
    char* date;
    char* holiday;
}hashElem;

typedef struct hash{
    struct hashElem element;
    struct hash* next;
}hash;

hash* hashTable[hashSize];

// Hash function
size_t murmurHash(const void *keyPtr, size_t keySize)
{
     /*  DESCRIPTION:    Very fast string hashing algorithm with excelleng distribution and
     *                  collision resistance. This source code has been released into the public
     *                  domain.
     *
     *  NOTES:          http://murmurhash.googlepages.com
     *
     *  RETURNS:        Hashtable index for the key
     *
     */

    /* 'm' and 'r' are mixing constants generated offline.         */
    /* They're not really 'magic', they just happen to work well.  */

    const unsigned int m = 0x5bd1e995;
    const int r = 24;

    size_t hashValue = 0;

    /* Mix 4 bytes at a time into the hash */

    const unsigned char * data = (const unsigned char *)keyPtr;

    while(keySize >= 4)
    {
        unsigned int k = *(unsigned int *) data;

        k *= m;
        k ^= k >> r;
        k *= m;

        hashValue *= m;
        hashValue ^= k;

        data += 4;
        keySize -= 4;
    }

    /* Handle the last few bytes of the input array */

    switch(keySize)
    {
        case 3: hashValue ^= data[2] << 16;
        case 2: hashValue ^= data[1] << 8;
        case 1: hashValue ^= data[0];
                hashValue *= m;
    };

    /* Do a few final mixes of the hash to ensure the last few  */
    /* bytes are well-incorporated.                             */

    hashValue ^= hashValue >> 13;
    hashValue *= m;
    hashValue ^= hashValue >> 15;

    return (hashValue % hashSize);
}

// strlen: return length of string
int strlen(char *s)
{
    char* p = s;

    while (*p != '\0')
        ++p;
    return p - s;
}

// Add Holiday into hash table
void addHoliday(char* date, char* holiday)
{
   char* key;
   int keyLen;
   size_t keyHash;
   hash* addition = malloc(sizeof(*addition));

   key = date;
   addition->element.date = key;
   addition->element.holiday = holiday;

   // Add holiday to Hash Table
   if (hashTable[murmurHash(key, strlen(key))] == NULL)
   {
       addition->next = NULL;
       hashTable[murmurHash(key, strlen(key))] = addition;
   }
   else  //If there is already an element at the index, add current holiday to beginning of list
   {
       addition->next = hashTable[murmurHash(key, strlen(key))];
       hashTable[murmurHash(key, strlen(key))] = addition;
   }

   //free(addition);
}

// If a date is entered, retrieve holiday from hash function index
char* getHoliday(char* date)
{
    return(hashTable[murmurHash(date, strlen(date))]->element.holiday);
}

void main(void)
{
   addHoliday("01/01/13", "New Years Day");
   printf("%s\n", getHoliday("01/01/13"));

   getchar();
}


texts: Solving for equilibrium index in an array

texts:
I did a sample on Codility and finished the test task.

  The problem description is very short:

  The equilibrium index of a sequence is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in a sequence A:

  $$A[0]=-7, A[1]=1, A[2]=5 ,A[3]=2, A[4]=-4, A[5]=3, A[6]=0$$

  \$3\$ is an equilibrium index, because:

  $$A[0]+A[1]+A[2]=A[4]+A[5]+A[6]$$

  \$6\$ is also an equilibrium index, because:

  $$A[0]+A[1]+A[2]+A[3]+A[4]+A[5]=0$$

  (The sum of zero elements is zero) \$7\$ is not an equilibrium index - because it is not a valid index of sequence A. If you still have doubts, here is a precise definition: The integer \$k\$ is an equilibrium index of a sequence \$A[0],A[1]\dots,A[n-1]\$ if and only if \$0\le k\$ and \$\sum(A[0\dots(k-1)])=\sum(A[(k+1)\dots(n-1)])\$. Assume the sum of zero elements is equal to zero.

The code I wrote gives the correct result, but, I only scored 8% on correctness and a 54% on performance. Here is my code:

// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');

function solution(A) {

    // write your code in JavaScript (Node.js 4.0.0
    var arrLen = A.length;

    var i = 0;

    for(i = 0; i < arrLen; i++){

        //console.log("i: " + i);

         var firstSum = 0;
        var secSum = 0;

        var currIndex = i + 1;

        //get first chunk
        var j = 0;
        var lenJ = currIndex;

        for(j = 0; j < lenJ; j++){

            //console.log("firstChink: " + j);
            firstSum += A[j];

        }

        //get second chunk
        j = currIndex + 1;
        lenJ = arrLen;

        for(j; j < lenJ; j++){

            //console.log("secChunk: " + j);
            secSum += A[j];

        }

        if(firstSum == secSum){

            return currIndex;

        }

    }

    return arrLen;

}

Can somebody explain why my code scored so low? And what to do to improve?


texts: splitting multiple joined words, port from perl to PHP

texts:
Though i have never worked on perl, not even once.
I have ported the perl code into PHP and it seems like giving a correct result. But as I am going to use it on production server.

I want this code to get it reviewed, please let me know if there is any problem in the porting from perl to PHP.

#!/usr/bin/perl

use strict;

my $WORD_FILE = '/usr/share/dict/words'; #Change as needed
my %words; # Hash of words in dictionary

# Open dictionary, load words into hash
open(WORDS, $WORD_FILE) or die "Failed to open dictionary: $!\n";
while (<WORDS>) {
  chomp;
  $words{lc($_)} = 1;
}
close(WORDS);

# Read one line at a time from stdin, break into words
while (<>) {
  chomp;
  my @words;
  find_words(lc($_));
}

sub find_words {
  # Print every way $string can be parsed into whole words
  my $string = shift;
  my @words = @_;
  my $length = length $string;

  foreach my $i ( 1 .. $length ) {
    my $word = substr $string, 0, $i;
    my $remainder = substr $string, $i, $length - $i;
    # Some dictionaries contain each letter as a word
    next if ($i == 1 && ($word ne "a" && $word ne "i"));

    if (defined($words{$word})) {
      push @words, $word;
      if ($remainder eq "") {
        print join(' ', @words), "\n";
        return;
      } else {
        find_words($remainder, @words);
      }
      pop @words;
    }
  }

  return;
}

The PHP code which I want a review on:

<?php

$WORD_FILE = file_get_contents ("word.txt") ;

$temp_arr = explode("\n", $WORD_FILE);

foreach ($temp_arr as $str)
{
    $words [$str] = 1 ;
}

$processed = Array () ;

find_words ($argv[1]) ;
print_r ($processed) ;

function find_words ($str)
{
    global $words ;
    global $processed ;

    $string = $str ;
    $length = strlen ($str) ;

    for ($i = 1 ; $i <= $length + 1; $i++)
    {
        $word = substr ($string, 0, $i) ;
        $remainder = substr ($string, $i, $length - $i) ;

        if ($i == 1 && ($word != "a" && $word != "i")) ;

        if (array_key_exists ($word, $words))
        {
            array_push($processed, $word) ;
            if ($remainder == "")
            {
                return ;
            }
            else
            {
                find_words ($remainder, $words) ;
            }
            echo "popping the word " . array_pop ($words) . "\n";
        }
    }

    return ;
}

?>


texts: ConsumingRouter to consume based on condition

texts:
Started as to make a stream splitter to split stream based on condition, but finally found that I did ConsumingRouter, to consume based on condition and while have to provide consumers before using this router not as splited stream can provide consumers then , and use this router inside forEach of stream, please check it and provide me with your feedback and if there is another way to do it:

public class ConsumingRouter<T> implements Consumer<T> {
    private Map<Predicate<T>, Consumer<T>> map = new ConcurrentHashMap<>();

    public void sub(Predicate<T> p, Consumer<T> c) {
        map.put(p, c);
    }

    @Override
    public void accept(T t) {
        map.entrySet().forEach(e -> {
            if (e.getKey().test(t))
                e.getValue().accept(t);
        });
    }
}

How to use it :

public static void main(String[] args) {
    ConsumingRouter<Integer> router = new ConsumingRouter<Integer>();
    Predicate<Integer> p1 = (i) -> i % 2 != 0;
    Predicate<Integer> p2 = (i) -> i % 2 == 0;
    Consumer<Integer> c1 = i -> {
        System.out.println(Thread.currentThread().getName() + " Route 1 : "
                + i);
    };
    Consumer<Integer> c2 = i -> {
        System.out.println(Thread.currentThread().getName() + " Route 2 : "
                + i);
    };
    router.sub(p1, c1);
    router.sub(p2, c2);
    IntStream.range(0, 1000).boxed().forEach(router);
}


texts: Swap previous non-whitespace character in emacs buffer with some known analogue

texts:
Emacs command for quick substitution of previously-typed character. This is supposed to help input umlauts quicker by switching letters to their analogues and so on.

(defun krv/last-char-check (&optional pos)
  "Find previous non-whitespace character in current string.

Return in form of (position . character) cons nor nil"
  (save-excursion
    (let ((cur-pos (or (and pos (goto-char pos))
                       (point))))
      (loop for prev-char = (preceding-char) then (preceding-char)
            for back-pos = 0 then (1- back-pos)
            when (bolp) return nil
            ; known whitespaces listed
            unless (member prev-char (list ?\ ?\xA0 ?\t)) return (cons back-pos prev-char)
            else do (backward-char)))))

(defun krv/unwrap-list-to-alist (list-form)
  "Helper function for setting character substitutions"
  (loop with first = (car list-form)
        for (s1 s2 . nil) on list-form
        if s2 collect (cons s1 s2)
        else collect (cons s1 first)))

(defvar cycle-symbols-alist nil
  "list of characters used for symbol cycling")

(defgroup cycle-symbols nil
  "Group for cycling symbols")

(defcustom cycle-symbols-lists-default
  (list (list ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 ?0) (list ?+ ?-) (list ?> ?< ?=))
  "Default lists for symbol cycling"
  :type 'sexp
  :set (lambda (s val)
         (set-default s val)
         (setq cycle-symbols-alist (mapcan #'unwrap-list-to-map val))))

(defun krv/cycle-symbols-command ()
  "Cycle previous non-whitespace if there is a known substitution"
  (interactive)
  (let* ((check-pair (krv/last-char-check))
         (pos (car check-pair))
         (char (cdr check-pair))
         (rchar (assoc char cycle-symbols-alist)))
    (when (and check-pair rchar)
      (forward-char pos)
      (delete-backward-char 1)
      (insert-char (cdr rchar))
      (backward-char pos))))


texts: Simple CodeReview Questions Notifications for OSX

texts:
Some days ago, I figured out that I'd like to get a notification every time a new question is asked here. So, I've made a really simple Python script, which uses pync (only OSX compatible) to do that for me.

I'd like to get some feedback regarding anything that comes to your mind, including good practices. That's not a complicated piece of code, but I'd like some feedback on it anyway.

import stackexchange
import time

from pync import Notifier

def get_notifications():
    """This method uses the SE API and pops up a notification everytime a new question is asked on CR"""
    cr = stackexchange.Site(stackexchange.CodeReview)

    old = []
    while True:
        questions = cr.recent_questions(filter='_b')
        for question in questions[:1]:
            if question.title not in old:
                old.append(question.title)
                Notifier.notify('Votes: {0} | Answers: {1} | Views: {2}'.format(
                    question.score, len(question.answers), question.view_count),
                    title='CodeReview: {0}'.format(question.title),
                    subtitle='Tags: {0}'.format(', '.join(question.tags)),
                    sound='default',
                    open=question.url)
            else:
                continue

        time.sleep(2)

if __name__ == '__main__':
    get_notifications()


texts: Is this a correct implementation/use of move semantics?

texts:
I'm trying to account for the fact that my program will contain calculations such as:

v(t) = w ∗ v(t−1)+ c1∗r1∗( pBest − x(t −1)) + c2∗r2∗(gBest − x(t−1))

where v, x, pBest, gBest are vectors (std::arrays). I'm a little worried if I make correct use of the move semantics.

Here's the relevant snippet:

template<class T, class F, size_t l> std::array<T, l> operator *(std::array<T, l>&& lhs, const F rhs ) {

    static_assert(std::is_arithmetic<T>::value, "The type parameter of the first argument is not of arithmetic type");
    static_assert(std::is_arithmetic<F>::value, "The passed scalar is not of arithmetic type");

    std::array<T, l> tmp = std::move(lhs);

    for(size_t i = 0; i < l; ++i)
        tmp[i] *= rhs;

    return tmp;
}

//calling the above operator
template<class T, class F, size_t l> std::array<T, l> operator *(const F rhs, std::array<T, l>&& lhs ) {

    return std::move(lhs) * rhs;
}

POST-ANSWER EDIT: As Loki Astari pointed out this SHOULD NOT be the sole implementation for operator* as this can bind to lvalues and will destroy them.


texts:
Looking at conduit's README, I used its magic function to try to achieve the following interleaved output:

I'm doing magic with 1
2
I'm doing magic with 2
4
...

Here's what I wrote:

import Conduit
import Control.Monad.Trans.List

-- author, conduit
magic :: Int -> IO Int
magic x = do
    putStrLn $ "I'm doing magic with " ++ show x
    return $ x * 2

interLeavedList :: ListT IO ()
interLeavedList = do
  x <- ListT $ return [1..10]
  ListT $ magic x >>= (\a -> print a >> return [])
  return ()

Here's what I get:

*Prelude> runListT interLeavedList
I'm doing magic with 1
2
I'm doing magic with 2
4
I'm doing magic with 3
6
I'm doing magic with 4
8
I'm doing magic with 5
10
I'm doing magic with 6
12
I'm doing magic with 7
14
I'm doing magic with 8
16
I'm doing magic with 9
18
I'm doing magic with 10
20
[]

Please critique interLeavedList. I reached for a ListT since I needed to sequence over a List using do notation, but needed the outer monad to be IO.

Also, how can I change interLeavedList to not print out the [] at the end?


texts:
Problem statement:

  Input is a rectangular bitmap like this:

0001
0011
0110

  The task is to find  for each black (0) "pixel", the distance to the
  closest white (1) "pixel". So, the output to the above should be:

3 2 1 0
2 1 0 0
1 0 0 1

Below is a working, heavily-commented 78-lines solution. It is very naive, though.  How can I make it faster? I know I can search for ones in rectangles centered at a given zero, but I am not sure I need it that complex. I just want to run it under 4s with 200*200 input on Pentium III.

#include <stdio.h>
#include <vector>
#include <utility>

using namespace std;

typedef unsigned short T;

//Maximum size of the array
const size_t MAX = 200;

//Converts string to unsigned integer
T atou(char* s) {
    T x = 0;
    while(*s) x = x*10 + *(s++) - '0';
    return x;
}

//Calculates absolute value
T abs(int a) {
    if(a >= 0) return a;
    else return -a;
}

int main() {
    T testCases, n, m, i, j, min, curDist;
    T A[MAX][MAX];
    char row[MAX];
    //Storing coordinates (i,j) of ones and zeroes from the input matrix
    //hopefully saves a bit of time searching for closest ones
    vector< pair<T,T> > cOnes;
    vector< pair<T,T> > cZeroes;
    pair<T,T> nextPair;
    scanf("%hu",&testCases);
    while(testCases--) {
        //Input matrix is n X m
        scanf("%hu",&n);
        scanf("%hu",&m);
        //Starting from i=1, j=1 for clarity: dealing with i-th row, j-th column
        for(i = 1; i <= n; i++) {
            scanf("%s",row);
            for(j = 1; j <= m; j++) {
                //But then have to subtract one when dealing with char[]
                A[i][j] = atou(&row[j-1]);
                if(row[j-1] == '1') {
                    cOnes.push_back(pair<T,T>(i,j));
                    //Clearing the array for the next test case
                    A[i][j] = 0;
                }
                else cZeroes.push_back(pair<T,T>(i,j));
            }
        }
        //For all zeroes find the closest one
        while(!cZeroes.empty()) {
            nextPair = cZeroes.back();
            i = nextPair.first;
            j = nextPair.second;
            cZeroes.pop_back();
            std::vector< pair<T,T> >::iterator it = cOnes.begin();
            min = abs(it->first - i) + abs(it->second - j);
            while(it != cOnes.end()) {
                curDist = abs(it->first - i) + abs(it->second - j);
                if(curDist < min) min = curDist;
                it++;
            }
            A[i][j] = min;
        }
        //Print the result
        for(i = 1; i <= n; i++) {
            for(j = 1; j <= m; j++) {
                printf("%hu ", A[i][j]);
                A[i][j] = 0;
            }
            printf("\n");
        }
    }
    return 0;
}


texts:
In a mysql db environment there's not really a custom global variable option. One may need that for example a certain date, in order to perhaps merge two sources of data: one legacy, and one current etc.

Using udf may slow down the queries quite a lot. Instead one could use a single row table:

CREATE TABLE `merge_date` (
  `SingleRow` enum('') COLLATE utf8_unicode_ci NOT NULL, -- enforce single row
  `Date` date NOT NULL, -- the actual value to be used
  UNIQUE KEY `merge_date_SingleRow_uindex` (`SingleRow`) -- enforce single row
)

Example usage:

SELECT *
FROM legacy_table lt
CROSS JOIN merge_date md
WHERE lt.Date <= md.Date
UNION ALL
SELECT *
FROM table t
CROSS JOIN merge_date md
WHERE md.Date < t.Date

I'd like to know if it could be further purified or improved in some other way.


texts:
public static int min(int a, int b, int c)
{
    int result = 0 ;
    if( a < b && a < c && b < c) result = a ;
    else if( a < b && a < c && b > c) result = a ;

    else if( a > b && a < c && b < c) result = b ;
    else if( a < b && b  > c &&  c < a) result = c ;

    else if( a > b && b < c && a > c) result = b ;
    else if( a > b && a > c && c < b) result = c ;
    return result ;
}

Is it better than nested if statements?  Is there a more readable solution than this? To me it looks pretty readable, but I'm not sure whether it can be improved.


texts: Cleaning up a class that contains the object it represents

texts:
I've recently started writing a tic-tac-toe game (following the Odin project) and am trying to write a class to hold the board game.

What I'm not sure about, is that the board class holds all the data related to the board in a variable called @board. Now after thinking about it I decided that the Board class shouldn't know about the game logic, and just hold the board itself, but now I'm not sure if it's redundant or not.

Main problem is that right now, when I try to add logic to the Game class, I get a function that looks like this:

class Game
  .
  def is_over?
    board = @board.board
    .
    .
  end
end

Which just feels wrong...
my current implementation for it is like so:

module TicTacToe
  class Board
    attr_reader :board
    def initialize(size)
      @board = create_empty_board(size)
      @size = size
    end

    def print_board
      @size.times { print "-----" }
      puts
      @board.each do |row|
        row.each do |c|
          print "| #{c} |"
        end
      puts
      @size.times { print "-----" }
      puts
      end
    end

    def make_move(move, sym)
      if board[x][y] == ' '
        board[x][y] = sym
      else
        raise ArgumentError, "Invalid, cell not empty"
      end
    end

  private
    def create_empty_board(size)
      board = Array.new
      size.times do
        row = Array.new
        size.times do
          row << ' '
        end
        board << row
      end
      board
    end
  end
end


texts: Plotting 2 types of data from DataFrame with different colors

texts:
This is the task:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid') # Plot style

# Some 'magic' so that the notebook will reload external python modules;
# see
# http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2

Let's define a synthetic dataset and experiment on it. We will need to define a pandas dataframe with 3 columns using the 3 arrays given below.
 x1 = np.array([5, 6, 7, 7, 8, 9, 0, 1, 2, 4, 5, 6])
 x2 = np.array([2, 1, 3, 5, 10, 3, 4, 8, 6, 10, 9, 11])
 y = np.array([1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1])

 ##### YOUR CODE STARTS HERE#####

 ##### YOUR CODE ENDS HERE #####

Plot the data in axes  x1  and  x2 , highlight two classes with different colors, name the axes.
def plot_data(data):
  plt.figure(figsize=(8, 6))
  ##### YOUR CODE STARTS HERE #####

  ##### YOUR CODE ENDS HERE #####

plot_data(data)

And here is my solution:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid') # Plot style

# Some 'magic' so that the notebook will reload external python modules;
# see
# http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2
x1 = np.array([5, 6, 7, 7, 8, 9, 0, 1, 2, 4, 5, 6])
x2 = np.array([2, 1, 3, 5, 10, 3, 4, 8, 6, 10, 9, 11])
y = np.array([1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1])

##### YOUR CODE STARTS HERE#####

    d = {"x1": x1, "x2": x2, "y": y}
    data = pd.DataFrame(d)

##### YOUR CODE ENDS HERE #####
    def plot_data(data):
      plt.figure(figsize=(8, 6))
      ##### YOUR CODE STARTS HERE #####
      negative = data[data['y'] < 0]
      positive = data[data['y'] > 0]
      plt.scatter(negative["x1"], negative["x2"], color="red")
      plt.scatter(positive["x1"], positive['x2'])
      ##### YOUR CODE ENDS HERE #####

    plot_data(data)

What can I improve here?


texts:
This function creates a series of links at a desired destination by the usage of a premade tag system.

Usage:

createMyTAGS_DATA passes in a single line of all the links as: LinkText;LinkAddress;;
createMyTAGS_LOCATION passes the destination to a div,span,... to render the result

Result would be:

LinkText1LinkText2 [...]

Note: each of tag(LinkText;LinkAddress;;) must have more than 10 characters.

click here