texts: Support multi functionality in server.js

texts:
i've node app that having the main function server.js(entry point)

Following is the server.js file code

var childModule = require("./controller/childModule");
var server = http.createServer(app);
var proxy= require('./controller/proxy');
var proc = require('./controller/runIntProcess');
var extLoader = require("./controller/extLoader");
....

var server = module.exports = {};

server.run = function () {
    proc.pre(function () {
        server.listen(app.get('port'), function (err) {
            if (err) {
                console.error(err);
            } else {
                console.log('application Listening on port: ' + app.get('port'));
            }
            proxy.web(server);
        });
    })
};

server.addNewFunctionlity= function(oDir){
    extLoader.load(oDir.folder);
};

module.exports = function () {
    server.run();
}();

server.childModule = childModule;

The code do this:

when user call to the server he need to write the following code

var myModule = require("myModule");
myModule.addNewFunctionlity({folderPath:__dirname + '/files'});
myModule.addNewFunctionlity({folderPath:__dirname + '/files2'});

The Code is working! but I've several questions :-)

Does I export the childModule OK?
Does the usage of my API is make sense?
Does the var server = module.exports = {} is OK?

The code is running a node app which can be cousume by CMD (call to the server.js) without any args or using it by code.
in addition I need to expose some API's like childModule


texts:
Project Euler problem #1:

  If we list all the natural numbers below 10 that are multiples of 3 or
  5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

  Find the sum of all the multiples of 3 or 5 below N.

My code is correct, but I don't know how I can optimize and make that faster.

N = gets.to_i
N.times do
  arr = []
  (0...gets.to_i).each { |j| arr << j if j % 3 == 0 || j % 5 == 0 }
  puts arr.reduce(:+)
end


texts: Find most occurred number in sorted array of numbers

texts:
I was asked in an interview to find the a number in an sorted array of numbers which has occurred maximum number of times. Also find the count of occurrence of that number.

I solved it in javascript, please follow the code

var numArray = [];

// takes the space separated numbers from commanline
// and inserts in array numArray.
process.argv.forEach(function(val, index, array){
   if(index > 1){
      numArray.push(parseInt(val));
   }
});

(findMaxOccuredNum)(numArray);

function findMaxOccuredNum(nums){
   var currentCount = 0,
       prevCount = 0,
       currentNum = 0,
       prevNum = 0;

   for(var i = 0; i < nums.length; i++){
       if((nums[i] === 0 && i === 0) || (i === 0 && nums[i] !== 0)){
          currentNum = nums[i];
          currentCount++;
       }else if(nums[i] === currentNum){
          currentCount++;
       }else {
          if(prevCount < currentCount){
              prevNum = currentNum;
              prevCount = currentCount;
              currentNum = nums[i];
              currentCount = 1;
          }else{
              currentNum = nums[i];
              currentCount = 1;
          }

       }//else
   }// for

   if(prevCount < currentCount){
      console.log("NUM "+currentNum+" occurred "+currentCount+" times");
   }else{
      console.log("NUM "+prevNum+" occurred "+prevCount+" times");
   }
} //findMaxOccuredNum

Below are some outputs

rahul@rahul:~/myPractise/Algo$ node NumCount.js 1 1 1 2 3 4 9 9
NUM 1 occurred 3 times

rahul@rahul:~/myPractise/Algo$ node NumCount.js 1 2 2 2 3 3 6 6
NUM 2 occurred 3 times

rahul@rahul:~/myPractise/Algo$ node NumCount.js 0 0 1 1 3 3 3 5 5
NUM 3 occurred 3 times

rahul@rahul:~/myPractise/Algo$ node NumCount.js 0 0 0 1 1 3
NUM 0 occurred 3 times

Requesting to please review my code and give your valuable comments on whether my code is the perfect solution for the above problem or it can be solved in better way.


texts: Find The One Element In An Array That is Different From The Others

texts:
https://www.codewars.com/kata/find-the-stray-number/train/javascript

I solved this challenge by sorting from least to greatest, and checking if the first element in the array matched the second element in the array.

If the first element does not match, then the different element is the first element.

If the first element does match, then the different element is the last element.

function stray(numbers) {
  numbers = numbers.sort((a, b) => a - b);
  if (numbers[0] !== numbers[1]) {
    return numbers[0];
  }
  else {
    return numbers[numbers.length - 1];
  }
}
console.log(stray([17, 17, 3, 17, 17, 17, 17]));

I'm wondering if / how this can be done with the filter() method instead?


texts:
The task

  Determine whether an integer is a palindrome. An integer is a
  palindrome when it reads the same backward as forward.

  Example 1:

  Input: 121 Output: true

  Example 2:

  Input: -121 Output: false Explanation: From left to right, it reads
  -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

  Example 3:

  Input: 10 Output: false Explanation: Reads 01 from right to left.
  Therefore it is not a palindrome. Follow up:

  Could you solve it without converting the integer to a string?

My solution
with converting number to string

const isPalindrome = n => n >= 0 && Number([...`${n}`].reverse().join("")) === n;

console.log(isPalindrome(121));

My solution
without converting number to string

const isPalindrome2 = n => {
  if (n < 0) { return false; }
  let num = Math.abs(n);
  const arr = [];
  let i = 1;
  while (num > 0) {
    const min = num % (10 ** i);
    num = num - min;
    i++;
    arr.push(min);
  }
  i = i - 2;
  let j = 0;
  return n === arr.reduce((res, x) => {
    const add = (x/ (10 ** j)) * (10 ** i);
    res += add;
    i--;
    j++;
    return res;
  }, 0);
};

console.log(isPalindrome2(121));


texts: Rails method to match users according to language fluency level

texts:
This code works fine, but I'm still learning, and feel like there is a more Railsy way to write this. Is there a good rails ActiveRecord method I should learn more about? Please let me know if you know a shorter, more direct way to run this same code.

Scenario: A user can have many languages, and level is an attribute of languages. I want to iterate through languages_users and find all the languages of a user, and then find where another user has 2 of the same languages, but at opposite levels.

user.rb

class User < ApplicationRecord
  has_many :languages_users
  has_many :languages, :through => :languages_users
end

controller

#Fluent languages and nonfluent languages can change depending on this situation, but here is good example:
@fluent_languages = LanguagesUser.where(user: current_user.id).where("level > 4")
@nonfluent_language = LanguagesUser.where(user: current_user.id).where("level < 5")

email_matches(@fluent_languages, @nonfluent_languages)

def email_matches(fluent_languages, nonfluent_languages)

    @fluent_languages = fluent_languages
    @nonfluent_languages = nonfluent_languages

    #array of user's fluent language_ids
    @fluent_langs = []
    @fluent_langs << @fluent_languages

    #array of user's nonfluent language_ids
    @nonfluent_langs = []
    @nonfluent_languages.each do |lang|
        @nonfluent_langs << lang.language_id
    end

    @fluent_les = LanguagesUser.select(:user_id).where(language_id: @fluent_langs, level: 1..4)
    @fluent_users_ids = []
    @fluent_les.each do |le|
        @fluent_users_ids << le.user_id
    end

    @nonfluent_les = LanguagesUser.select(:user_id).where(language_id: @nonfluent_langs, level: 5)
    @nonfluent_user_ids = []
    @nonfluent_les.each do |le|
        @nonfluent_user_ids << le.user_id
    end

    @matches = @fluent_users_ids & @nonfluent_user_ids

    @new_matches = User.where(id: @matches, status: "Active").order('last_seen DESC').limit(10)
    @new_matches.each do |user|
        UserMailer.new_match(user, current_user).deliver_later
    end
end

Let me know if I can provide anything else.


texts:
Aim of the code is to print all of the strings from one file that match strings from another file. Names of both of the files are provided by command line arguments.

Code:

int main(int argc, char *argv[]){
    ifstream answers(argv[1]);
    ifstream candidates(argv[2]);

    for (string s; getline(answers,s);){
        for (string h; getline(candidates,h);){
            if (!s.compare(h)){
                cout << h << ":" << s << endl;
            }
        }
        candidates.close();                 //I know theres better than this
        candidates.open(argv[2], ios::in);
    }
}

but I feel like reloading the file into memory every time is redundant. Is there anything that could be improved?


texts: Python program that gets basic information on a Github user

texts:
I've created a basic Python CLI script, which takes a Github username, and returns some basic information associated with said username. I use the requests for HTTP requests (I'm new to this area) and docopt for command-line handling.

#!/usr/bin/env python3

"""Github User Info

Get basic information on a Github user

Usage:
  github_user_info.py USERNAME
  github_user_info.py (-h | --help)
  github_user_info.py (-v | --version)

Arguments:
  USERNAME     Github username

Options:
  -h --help     Show this screen.
  -v --version  Show version.
"""

from docopt import docopt
import requests

import sys

def main():
    if len(sys.argv) == 1:
        sys.argv.append('-h')  # Show help screen if no arguments are passed

    cmd_arguments = docopt(__doc__, version='Github User Info v1.0')

    username = cmd_arguments["USERNAME"]

    if len(username.split()) != 1:
        print('Github usernames must be one word in length! Exiting!')
        return

    response = requests.get(f'https://api.github.com/users/{username}')

    if response.status_code != requests.codes.ok:
        if response.status_code == 404:  # No such user was found
            print(f'No Github user was found with username {username}!')
        else:
            print(f'An unexpected error occured! Exiting with error code: '
                  f'{response.status_code}')
        return

    responses_json = response.json()

    print(f'The following information was found on user: {username}',
          end='\n\n')
    print(f'Name: {responses_json["name"]}')
    print(f'Bio: {responses_json["bio"]}')
    print(f'Followers: {responses_json["followers"]}')
    print(f'Following: {responses_json["following"]}')

if __name__ == '__main__':
    main()

I'd mainly like to know if this is the correct way to handle HTTP requests (in terms of getting them, error handling, etc.). I'd also like to make sure that I follow good Python conventions.


texts:
This code is supposed to delete every node from a linked list with a given value.

Are there any logical errors with this implementation? Did I do anything wrong or is there an area of this implementation that needs significant improvement. Any suggestions?

public boolean delete(int d) {
    Node tmpNode = head;
    Node prevNode = null;
    boolean deletedANode = false;

    if (head == null) {
        return deletedANode;
    }

    while (tmpNode != null) {
        if (tmpNode.data == d) {
            if (tmpNode == head) {
                head = head.next;
            }
            else {
                prevNode.next = tmpNode.next;
            }
         deletedANode = true;
         }

         prevNode = tmpNode;
         tmpNode = tmpNode.next;
    }

    return deletedANode;
}


texts: Changing an element in a list when a predicate holds

texts:
My current project is a Settlers of Catan server in Haskell. I often manage to achieve my goals within Haskell, but the code is getting messier as the project grows.
My question is about the placeBuilding :: Board -> Building -> VertexCoordinate -> Board function that places a building on the board at a specified VertexCoordinate.
Board has a property vertices :: [Vertex], and Vertex is contains a property vertex_coordinate :: ((Int, Int), Int)
My question is about three different attempts for this function:
First of all, would you do anything different in any of the attempts?
For my first attempt I first found the vertex_index of [Vertex] that the building should be placed on, and then with the lens package I change it. This feels natural to me, but it looks rather ugly, especially because of the way I have to deal with the fromMaybe, for which I now make the assumption that the supplied VertexCoordinate must exist.
-- ATTEMPT 1
-- Return a board with the supplied building placed at the supplied coordinate
placeBuilding :: Board -> Building -> VertexCoordinate -> Board
placeBuilding board building coord = board {vertices = vertices'}
                      where v_index = fromMaybe 0 $ findIndex (\v -> vertex_coordinate v == coord) (vertices board)
                            vertices' = vertices board & element v_index .~ Vertex coord (Just building)

Now the second and third are kind of similar. Is one better than the other? Personally, I think the third is the most readable.
-- ATTEMPT 2
-- Return a board with the supplied building placed at the supplied coordinate
placeBuilding2 :: Board -> Building -> VertexCoordinate -> Board
placeBuilding2 board building coord = board {vertices = vertices'}
                      where vertices' = map (\v -> if vertex_coordinate v == coord then Vertex coord (Just building) else v) (vertices board)

-- ATTEMPT 3
-- Return a board with the supplied building placed at the supplied coordinate
placeBuilding3 :: Board -> Building -> VertexCoordinate -> Board
placeBuilding3 board building coord = board {vertices = map placeIfAtCoord $ vertices board}
                      where placeIfAtCoord v | vertex_coordinate v == coord = Vertex coord (Just building)
                                             | otherwise                    = v


texts: refactor helper for default state for rails select with enums

texts:
I've created a helper method that is essentially used to get the default state of an select:

<%= select_tag "question_main_frequency",
          options_for_frequency_state(frequency_segment(question)), { class: 'form-control' } %>

The helper method I've created to get the default state looks like this:

  def frequency_segment(question)
    return false if question.id.nil?
    question = Question.find(question.id)
    if question.weekly?
      'weekly'
    elsif question.odd_weeks? || question.even_weeks?
      'Biweekly'
    elsif question.start_of_month? || question.end_of_month?
      'Monthly'
    elsif question.start_of_quarter? || question.end_of_quarter?
      'Quarterly'
    end
  end

The reason why I need this is because that form populates a new select form with the methods you see in the helper. So if they select 'biweekly' then question.odd_weeks and question.even_weeksappear as two options.

and you don't have to be a genius to see that this isn't exactly beautiful. It's also causing:

Perceived complexity for frequency_segment is too high. [10/7]
Method has too many lines. [11/10]
Cyclomatic complexity for frequency_segment is too high.[9/6]

on rubocop. The thing is I'm not entirely sure how to refactor this. The Question methods are enum, set up like this:

class Question < ActiveRecord::Base
  enum frequency: { weekly: 0, odd_weeks: 1, even_weeks: 2,
                    start_of_month: 3, end_of_month: 4,
                    start_of_quarter: 5, end_of_quarter: 6 }

any ideas on how I can refactor this?


texts:
I have implemented a quite long program in R and I have noticed that one block, concearning a backward model selection, is too slow and I would like to receive some suggestions in order to speed up all the program. Here is the code:

library(MASS)
df.Cars <- na.omit(Cars93[-57, -c(1,2,4,6,27)])
rownames(df.Cars) <- 1:82
for(j in c(1, 5, 6, 12, 22)) { df.Cars[, j] <- as.numeric(df.Cars[, j]) - 1}
df.Cars$Cylinders <- as.numeric(as.character(df.Cars$Cylinders))
df.Cars <- data.frame(df.Cars, RPM2 = df.Cars$RPM^2)

pos <- sample(1:82, 82)
list_folds <- c(list(pos[1:9]), list(pos[10:18]), lapply(0:7, function(x) pos[19:26 + x*8]))
names(list_folds) <- paste0("fold_", 1:10)

best_models <- list()

for(j in 1:10) {

best_models[[j]] <- as.list(rep(NA,22))

}

The slow part begins now:

for(j in 1:length(list_folds)) {

   mydf <- df.Cars[unlist(list_folds[-j]),]

   best_models[[j]][[22]] <- glm(Origin ~., "binomial", mydf)

   for(i in 21:1) {

      matr <- colnames(model.matrix(best_models[[j]][[i+1]]))[-1]

      mod0 <- lapply(matr, function(x) {

          formul <- eval(parse(text=paste(".~. -", x)))

          update(best_models[[j]][[i+1]], formul)

          })

DEVmin <- which.min(sapply(mod0, deviance))

best_models[[j]][[i]] <- mod0[[DEVmin]]

    }

}


texts:
I've built a VBA Excel macro that works on a spreadsheet of duplicated files, and displays only groups in which at least one duplication is owned by the current user.

The spreadsheet lists file metadata, one file per row, grouped with other files whose content is identical, i.e. "duplicated". Each such duplication group is preceded by a title row in bold.

The macro uses text boldness to determine duplication groups, and checks within each group whether any file's owner (represented in column 7) is the currently logged user.
All groups with no file owned by the user get hidden.
(auto-filtering would not solve this problem because I want the user to see the other files in the duplication group, i.e. see files from other owners with the same content as theirs)

It works exactly as intended, but too slowly. It takes one or two minutes to run through a spreadsheet about 80 thousand lines long. Anyone can see a way to speed it up?

I had the idea of maybe hiding every row first (which I assume can be done much faster) and then de-hide what should be shown. But I couldn't find a command to mass-hide.

Also, since we're here, what best practices am I missing? I'm a complete novice to VBA, though I'm an experienced programmer in other languages.

Grateful for any help.

'Operates on .xslx report of network file duplication, as output by TreeSize tool.
'Hides all Duplication Groups not involving the currently logged user as a file Owner
'(regular filtering does not work because it hides the other duplicates which have a different owner)
'TODO: speed it up. It currently takes ~1min to run. Probably hide-all then unhide-selected will be faster.
Private Sub My_duplicates_Click()
    Dim hidIt As Boolean
    Dim foundInGroup As Boolean

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    login = Environ("Username")
    ownerCol = 7
    rowNum = 3 'skip header
    Do While Not IsEmpty(Cells(rowNum, 1))
        If Cells(rowNum, ownerCol).Font.Bold = True Then 'bold text indicates the beginning of a duplication group
            foundInGroup = False
            groupMemberRow = rowNum + 1
            Do While Not IsEmpty(Cells(groupMemberRow, 1)) And Not Cells(groupMemberRow, ownerCol).Font.Bold = True
                If Cells(groupMemberRow, ownerCol).Value2 = login Then
                    foundInGroup = True
                End If
                groupMemberRow = groupMemberRow + 1
            Loop
            If foundInGroup = False Then
                hidIt = True
            Else
                hidIt = False
            End If
            Cells(rowNum, ownerCol).EntireRow.Hidden = hidIt
            groupMemberRow = rowNum + 1
            Do While Not IsEmpty(Cells(groupMemberRow, 1)) And Not Cells(groupMemberRow, ownerCol).Font.Bold = True
                Cells(groupMemberRow, ownerCol).EntireRow.Hidden = hidIt
                groupMemberRow = groupMemberRow + 1
            Loop
            rowNum = groupMemberRow - 1 'counting on next increment to place it back on the next group header
        End If
        rowNum = rowNum + 1
    Loop
End Sub


texts: Moving circles along a ray to eliminate location check

texts:
I have a function that moves circles out of the way of an expanding circle. It moves them along a ray from the center of the expanding circle through the center of the circle to move. This allows all surrounding circles to move without overlapping.

Here's a diagram to better explain this:

I expand the size of the red circle from 100px to 200px. I want to move all the blue circles out of the way by half the difference ( (200-100)/2 = 50px, in this example ) along the gray line (with the gray line being different for each blue circle).

jsFiddle

$this.siblings( ".circle" ).each( function() {

    var $this = $( this ),
        circle = $this.data(),
        circleX = circle.left + circle.radius,
        circleY = circle.top + circle.radius,
        a = Math.abs( hoveredY - circleY ),
        b = Math.abs( hoveredX - circleX ),
        c = Math.sqrt( ( a*a ) + ( b*b ) ),
        A = Math.acos( b / c ),
        C = 90 * ( Math.PI / 180 ),
        B = C - A,
        sinA = Math.sin( A ),
        sinB = Math.sin( B ),
        sinC = Math.sin( C ),
        newc = c + ( expand / 2 ),
        newa = ( newc * sinA ) / sinC,
        newb = ( newc * sinB ) / sinC,
        newX = hoveredX + ( hoveredX > circleX ? -newb : newb ),
        newY = hoveredY + ( hoveredY > circleY ? -newa : newa ),
        left = newX - circle.radius,
        top = newY - circle.radius;

    $this.animate( {

        "left": left,
        "top": top

    }, 75 );

});

hoveredX and hoveredY are the left and top coordinates of the red circle and expand is how much the red circle is expanding in pixels.

Mathematically, I'm sure there is a better way to do this, but I got this way working, and it's fine (although I'm not opposed hearing better solutions). But the one part I don't like about this function are the two lines:

newX = hoveredX + ( hoveredX > circleX ? -newb : newb ),
newY = hoveredY + ( hoveredY > circleY ? -newa : newa ),

What bugs me is that I'm having to do the check at all. Those two lines are basically saying, "If the circle is on the left/top do it one way, and if it's on the right/bottom do it another way". I feel like I'm missing something earlier in the function that could be solved by switching the sides of operators, adding instead of subtracting, or getting the absolute value.


texts:
This question came up today on StackOverflow. I find it more unfortunate than (as some others said) idiotic. And it recalled an old function I have which I just remembered.

I have a user.config file which has some settings which can be updated through user action. My rationale was "if the setting is changed, it should be saved." So I made a static class to cover for those settings so as not to handle the operations each time. And I came up with this:

public static class UserSettings
{
    public static string ProcessPath
    {
        get { return _processPath; }
        set
        {
            _processPath = Settings.Default.ProcessPath = value;
            Settings.Default.Save();
        }
    }
    //Other functions and properties
}

Yes, I know, it reeks. I feel shame. I want to make this right. I'm thinking this:

the class is static, it should at least be a singleton;
the property should itself not be static;
there's no point in saving the settings every time, just on closing the app, and that would basically be safe in a destructor for the class be best suited for a dedicated function called SaveSettings. Any other object can call it when they see fit, no surprise effects. (further evidence of the need for a singleton).

Are these good intentions in the right direction?


texts: Enabling or disabling buttons on certain events

texts:
I need to run the following checks in two occasions:

When a certain modal is first shown or clicked,
When one of two inputs is filled.

How can I remove redundancy in the following code?

jQuery(document).ready( function($) {
    $(document.body).on( 'DOMNodeInserted click',  '.media-modal', function( event ) {
        var test = $('label.setting[data-setting=alt] input:visible').val();
        var test2 = $('input[data-setting=alt]:visible').val();
        if (!test && !test2) {
            $('.media-modal .media-button-insert').prop("disabled",true);
            $('.media-modal .media-button-select').prop("disabled",true);
        } else {
            $('.media-modal .media-button-insert').prop("disabled",false);
            $('.media-modal .media-button-select').prop("disabled",false);
        }
        $(document.body).on( 'input propertychange paste',  'label.setting[data-setting=alt] input, input[data-setting=alt]', function( event ) {
            var test = $('label.setting[data-setting=alt] input:visible').val();
            var test2 = $('input[data-setting=alt]:visible').val();
            if (!test && !test2) {
                $('.media-modal .media-button-insert').prop("disabled",true);
                $('.media-modal .media-button-select').prop("disabled",true);
            } else {
                $('.media-modal .media-button-insert').prop("disabled",false);
                $('.media-modal .media-button-select').prop("disabled",false);
            }
        });
    });
});


texts:
I have a simple application that can receive and send tcp data.
right now there's a thread used to start the listener and within this thread there's another thread to receive.

it works but it seems like a waste of resources. Can the connect be simplified?

    public partial class Form1 : Form
    {
    private readonly TcpListener server = new TcpListener(IPAddress.Any, 1980);
    private NetworkStream sendStream;
    private NetworkStream recvStream;
    private TcpClient client;
    private byte[] datalength = new byte[4];

    public Form1()
    {
        InitializeComponent();
    }

    public void ServerReceive()
    {
        recvStream = client.GetStream();
        new Thread(() =>
        {
            while (recvStream.Read(datalength, 0, 4) != 0)
            {
                byte[] data = new byte[BitConverter.ToInt32(datalength, 0)];
                recvStream.Read(data, 0, data.Length);
                this.Invoke((MethodInvoker)delegate
                {
                    txtLog.Text += System.Environment.NewLine + "Client : " + Encoding.Default.GetString(data);
                });
            }
        }).Start();
    }

    public void ServerSend(string msg)
    {
        sendStream = client.GetStream();
        var data = Encoding.Default.GetBytes(msg);
        var length = data.Length;
        datalength = BitConverter.GetBytes(length);
        sendStream.Write(datalength, 0, 4);
        sendStream.Write(data, 0, data.Length);
    }

    private void btnListen_Click(object sender, EventArgs e)
    {
        Connect();
    }

    private void btnSend_Click(object sender, EventArgs e)
    {
        if (client.Connected)
        {
            ServerSend(txtSend.Text);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Connect();
    }

    private void Connect()
    {
        server.Start();
        MessageBox.Show("Waiting For Connection");
        new Thread(() =>
        {
            client = server.AcceptTcpClient();
            MessageBox.Show("Connected To Client");
            if (client.Connected)
            {
                ServerReceive();
            }
        }).Start();
    }
}


texts: Implementation of Multiparental Sorting Crossover

texts:
I implemented the Multiparental Sorting Crossover as described here in section 4.2. The (compiled) program can be run as follows:

$ java MPSX input.txt

where input.txt looks like this (the first line is the mask followed by three parents):

3 1 2 1 1 1 1 2 2

8 4 7 3 6 2 5 1 9

9 1 2 3 4 5 6 7 8

4 7 9 3 6 2 5 1 8

As for output, it merely prints the correct result as a string.

import edu.princeton.cs.algs4.In;
import java.io.InputStream;

public class MPSX {

    public static void main(String[] args) {

        String filename = args[0];
        In in = new In(filename);

        String[] Input = in.readAllLines();

        String result = solve(Input);

        System.out.println(result);

    }

    private static void swap(int[] parent_x, int[] parent_y, int index) {

        for (int i = 0; i < parent_y.length; i++) {

            if (parent_y[i] == parent_x[index]) {

                int tmp = parent_y[index];
                parent_y[index] = parent_y[i];
                parent_y[i] = tmp;

            }

        }

    }

    private static String solve(String[] Input) {

        String result = "";

        String[] parent1str = Input[1].split(" ");
        String[] parent2str = Input[2].split(" ");
        String[] parent3str = Input[3].split(" ");

        int[] parent1 = new int[parent1str.length];
        int[] parent2 = new int[parent2str.length];
        int[] parent3 = new int[parent3str.length];

        for (int i = 0; i < parent1str.length; i++) {
            parent1[i] = Integer.parseInt(parent1str[i]);
            parent2[i] = Integer.parseInt(parent2str[i]);
            parent3[i] = Integer.parseInt(parent3str[i]);
        }

        String mask = Input[0].replaceAll("\\s","");

        for (int i = 0; i < mask.length(); i++) {

            int mask_element = Character.getNumericValue(mask.charAt(i));;

            if (mask_element == 1) {
                result += parent1[i];
                swap(parent1, parent2,i);
                swap(parent1, parent3,i);
            }

            else if (mask_element == 2) {
                result += parent2[i];
                swap(parent2, parent1,i);
                swap(parent2, parent3,i);
            }

            else if (mask_element == 3) {
                result += parent3[i];
                swap(parent3, parent1,i);
                swap(parent3, parent2,i);
            }

        }

        return result;
    }

}

It is effectively the first program I wrote in Java so I know there is a lot of room for improvement and refactorization.

In particular, I am sure there is a better (more concise) way of processing the input text file. I thought of creating an array of arrays of Strings instead of 3 separate arrays but I wasn't sure how to do it.


texts: Determine added, removed and kept items between two lists

texts:
My code is determining the difference between two iterables in terms of items that have been addded, removed and kept. The items are assumed to be sortable and there are no duplicates.

def diff(before, after):
    """Return diff between iterables of sortable items `before` and `after` as
    tuple of three lists of items that have been added, removed and kept.
    """
    before_iter = iter(sorted(before))
    after_iter = iter(sorted(after))
    add_items = []
    rem_items = []
    keep_items = []
    try:
        new = old = None
        while True:
            if new == old:
                if new is not None:
                    keep_items.append(new)
                new = old = None
                new = next(after_iter)
                old = next(before_iter)
            elif new < old:
                add_items.append(new)
                new = None
                new = next(after_iter)
            elif old < new:
                rem_items.append(old)
                old = None
                old = next(before_iter)
    except StopIteration:
        if new is not None:
            add_items.append(new)
        if old is not None:
            rem_items.append(old)
        add_items += list(after_iter)
        rem_items += list(before_iter)
    return add_items, rem_items, keep_items

if __name__ == '__main__':
    assert diff([], []) == ([], [], [])
    assert diff([1, 2, 3], [4, 3, 2]) == ([4], [1], [2, 3])
    assert diff(['foo', 'bar'], ['baz', 'bar']) == (['baz'], ['foo'], ['bar'])

Main concerns:

The way I'm working with iterators seems a bit awkward and appears to unnecessarily bloat the code. I feel there must be a more elegant pattern, maybe without iterators at all?
The code should perform well on large lists. That's also why I'm not using multiple set operations instead. (add_items = set(after) - set(before), etc.) Or can I solve this efficiently with set operations? (I'm expecting both very small and very large differences between the iterables.)

Update: Unfortunately, I failed to include a key requirement into the question which therefore couldn't be considered in the answers. But I'll state it here, just for the record:

The algorithm needs to perform well when comparison between the items is expensive. Since an approach using set operations incorporates more comparisons than the algorithm above, it performs worse in my use case.


texts:
I'm having a lot of trouble in my Database program with trying to implement an effective DataGrid filtering method. After taking advice from a previous code review I'm trying to implement a DataModel method of coding. My previous method of searching my DataGrid was this;

SearchGrid (PREVIOUS)

private void SearchGrid(object sender, TextChangedEventArgs e)
    {
        DataView dv = dataGrid.ItemsSource as DataView;
        if (compNameRad.IsChecked == true)
        {
            dv.RowFilter = "CompanyName LIKE '%" + searchBox.Text + "%'";
        }
        if (compTownRad.IsChecked == true)
        {
            dv.RowFilter = "CompanyTown LIKE '%" + searchBox.Text + "%'";
        }
        if (compPcodeRad.IsChecked == true)
        {
            dv.RowFilter = "CompanyPcode LIKE '%" + searchBox.Text + "%'";
        }
    }

This worked fine with the way I bound my DataGrid before. I now bind my DataGrid using a Model class and the previous filter method does not work. I have written a new filter method which is this;

SearchGrid (NEW)

private void SearchGrid(object sender, TextChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(searchBox.Text))
            {
                ICollectionView view =      CollectionViewSource.GetDefaultView(dataGrid.ItemsSource);
                view.Filter += (obj) =>
                {
                    CompanyModel model = obj as CompanyModel;
                    if (model == null)
                        return true;

                    if (compNameRad.IsChecked == true)
                    {
                        return !string.IsNullOrEmpty(model.CompanyName) && model.CompanyName.Contains(searchBox.Text);
                    }
                    if (compTownRad.IsChecked == true)
                    {
                        return !string.IsNullOrEmpty(model.CompanyTown) && model.CompanyTown.Contains(searchBox.Text);
                     }
                    if (compPcodeRad.IsChecked == true)
                    {
                        return !string.IsNullOrEmpty(model.CompanyPcode) && model.CompanyPcode.Contains(searchBox.Text);
                    }
                    return false;
                };
            }
        }

Now this does work OK, however there are two issues:

is that it is extremely slow when I type text to search the DataGrid, and
it doesn't deal with the most simple of cases, for example if the name of the Company is "A1" then searching for "a1" will not find the company.

I have been recommended to use Entity Framework however as I am using an OleDB connection (this is a very old Database I am rewriting) I have been unable to get this to work.

Is there a more efficient search method I can use that is quicker and would also find all companies (i.e case insensitive)?


texts: Move one element before another in an associated array

texts:
I have this task where I have an associated array in PHP and I want to manipulate the order of entries. Basically I want to be able to move entry Y before entry X.

So basically if I have the following array:

['foo1' => 'bar', 'foo2' => 'buzz', 'foo3' => 'bazz']

I want to be able to say: 'put element foo3 before foo2', resulting in the following:

['foo1' => 'bar', 'foo3' => 'bazz', 'foo2' => 'buzz']

I currently have the following code:

/**
 * Change the order of an associated array, moving by key before another
 *
 * @param array $arr
 * @param string $key
 * @param string $before
 * @return array
 */
public function moveKeyBefore(array $arr, string $key, string $before)
{
    $keys = array_keys($arr);
    if (in_array($key, $keys) && in_array($before, $keys)) {
        $newArr = [];
        foreach ($arr as $idx => $value) {
            switch ($idx) {
                case $key :
                    continue;
                case $before:
                    $newArr[$key] = $arr[$key];
                    $newArr[$before] = $value;
                    break;
                default:
                    $newArr[$idx] = $value;
                    break;
            }
        }

        return $newArr;
    }

    return $arr;
}

This code basically works. However, I was wondering if there was an easier, less complex way of doing this.


texts:
I have a version of the N-Queens problem in Java. I have function that returns the column placement for each row. And another function that takes that and translates it to a board with '.' representing blanks and 'Q' representing the queens. I was hoping to get an opinion on this.

public class Solution {
    public List<List<String>> solveNQueens(int n) {
        List<Deque<Integer>> result = this.nQueens(n);
        //String[] board = new String[n];
        //Arrays.fill(board, defaultRow);
        List<List<String>> resultAsStr = new ArrayList<List<String>>();
        for (Deque<Integer> variation: result){
            String[] board = new String[n];
            Integer[] temp = variation.toArray(new Integer[0]);
            for (int row=0;row<variation.size();++row){
                char[] currRow = new char[n];
                Arrays.fill(currRow, '.');
                Integer col = temp[row];
                currRow[col] = 'Q';
                board[row] = new String(currRow);
            }
            resultAsStr.add(new ArrayList<String>(Arrays.asList(board)));
        }

        return resultAsStr;

    }

    private List<Deque<Integer>> nQueens(int n){
        List<Deque<Integer>> result = new ArrayList<Deque<Integer>>();
        Deque<Integer> colPlacement = new ArrayDeque<Integer>();
        this.nQueens(n, 0, colPlacement, result);
        return result;
    }

    private void nQueens(int n, int row, Deque<Integer> colPlacement, List<Deque<Integer>> result){
        if (n==row){
            result.add(new ArrayDeque<Integer>(colPlacement));
        } else {

            for (int col=0;col<n;++col){
                colPlacement.add(col);
                if (this.isValid(colPlacement)){
                    this.nQueens(n, row+1, colPlacement, result);
                }
                colPlacement.pollLast();
            }
        }
    }

    private boolean isValid(Deque<Integer> colPlacement){
        int row_id = colPlacement.size() -1;
        Integer[] colArray = colPlacement.toArray(new Integer[0]);
        for (int i=0;i<row_id;++i){
            int diff = Math.abs(colArray[i] - colArray[row_id]);
            if (diff == 0 || diff == row_id -i){
                return false;
            }
        }
        return true;
    }

}


texts:
I have the following codes, i want to get a list of country CODE and NAME from Locale.getISOCountries() and set it into my custom made class, i managed to do it but i somehow feel that my codes is not clean enough, especially the getCountryList() part but i not sure how to minimize it, is there any suggestion? I don't mind to use lambda if possible.

private static List<CountryPair> getCountryList()
{
    String[] locales = Locale.getISOCountries();
    List<String> countryCodes = Arrays.asList(locales);
    List<CountryPair> pairList = new ArrayList<>();
    countryCodes.forEach(code -> {
    CountryPair pair = new CountryPair();
    Locale locale = new Locale("", code);
    pair.setValue(locale.getCountry());
    pair.setDisplayName(locale.getDisplayCountry());
    pairList.add(pair);
    });
  return pairList;
}

Country pair class:

public class CountryPair {

    private String value;

    private String displayName;

    public String getValue() {
      return value;
    }

    public String getDisplayName() {
      return displayName;
    }

    public void setValue(String value) {
      this.value = value;
    }

    public void setDisplayName(String displayName) {
      this.displayName = displayName;
    }
}


texts: Making code elegant, clean and optimized

texts:
I have some piece of code that I already optimized, however I found that there is an edge case that I should handle and I am unable to make it elegant.
char* data = get_data_from_queue(data);
Album album;
get_album(data, &album);
if (get_album_vals(album) <= 0) {
    printf("Album doesn't exist, will try to create it");
    return should_create_album(album);
}
do_stuff_with_data(&data);

Now, when I don't find album vals, under certain conditions (< 0.01%), it may be a golden album.
If it is a golden album, under certain conditions (<0.01%), it may need a second chance.
This is the modified code that should keep same behavior, apart from the second chance for golden album:
char* data = get_data_from_queue(data);
Album album;
get_album(data, &album);
if (get_album_vals(album) <= 0) {
    int is_golden_album = 0;
    ret = should_create_album(album);
    if (!ret && album_might_be_golden(album)) {
        GoldenAlbum golden_album;
        if (get_golden_album(data, &golden_album)
        {
            ret = should_create_album(golden_album);
        } else {
            is_golden_album = 1;
        }
    }
    if (is_golden_album > 0)
    {
        return ret;
    }
}
do_stuff_with_data(&data);

However the new code is awful and I am not sure how to make it more elegant and optimized and I have spent way too much time on this.
Anyone have a suggestion?


texts: Backtracking solver for n queens problem and knight's tour

texts:
Playing with https://ocaml.org/learn/tutorials/99problems.html#Miscellaneous-Problems I wrote a backtracking solver for the n queens problem, then the knight's tour, and realised I could generalise the backtracking algorithm to be shared between both. How's my code? Is is F#-onic? Could any of it be simplified?

Is there a simpler alternative to the match expression in solveByBacktracking?
Can relativeMoves be described more succintly?
Can the prepend function be inlined?

Thanks for reading

// solve a problem by backtracking
let solveByBacktracking moves solved initialState =
    let rec inner state =
        // to do: backtrack immediately if arrive at state we've seen before. (This can't happen for knight's tour or n queens as below.)
        match state with
            | Some progress when (progress |> solved |> not) ->
                progress |> moves |> Seq.map (Some >> inner) |> Seq.tryFind Option.isSome |> Option.flatten
            | _ -> state
    initialState |> Some |> inner

// solve n queens problem. place n queens on an n x n board such that none threaten each other. returns row of each queen by column.
let queens n =
    let legal rows =
        // check that no queens are threatening each other
        let n = rows |> Seq.length
        let areDistinct = Seq.distinct >> Seq.length >> (=) n
        let forwardDiagonals = rows |> Seq.mapi (+)
        let backDiagonals = rows |> Seq.mapi (-)
        rows |> areDistinct && forwardDiagonals |> areDistinct && backDiagonals |> areDistinct
    let solved progress = (List.length progress) = n
    let moves progress =
        let prepend x = x::progress
        [0..n-1] |> Seq.map prepend |> Seq.filter legal
    [] |> solveByBacktracking moves solved

// search for an example of knight's tour on n by m board
let knightsTour (n,m) =
    let solved progress = (List.length progress) = n*m
    let moves progress =
        match progress with
        | [] ->
            seq {for i in [0..n-1] do for j in [0..m-1] do yield [(i, j)]}
        | (i, j)::_ ->
            let onBoard (i,j) =
                0 <= i && i < n && 0 <= j && j < m
            let relativeMoves = [(1,2); (1,-2); (2,1); (2,-1); (-1, 2); (-1, -2); (-2, 1); (-2, -1)]
            let prepend pos = pos :: progress
            let novel pos = progress |> List.contains pos |> not
            relativeMoves |> Seq.map (fun (x,y) -> (x+i, y+j)) |> Seq.filter onBoard |> Seq.filter novel |> Seq.map prepend
    [] |> solveByBacktracking moves solved


texts: Remove control and non-ASCII characters from large files

texts:
I get huge incoming files (up to 6GB) and they are littered with Control and non-ASCII characters.  I need to strip them and I made this routine (below).  The problem is that it is insanely slow.  I would love any thoughts or advice on how I can speed it up.

public void StripHighBitCharacters(string fn)
{
    string writeFile = fn + "B";
    using (var reader = new StreamReader(fn))
    using (var writer = new StreamWriter(writeFile))
    {
        while (!reader.EndOfStream)
        {
            string line = reader.ReadLine();
            if (line.Length > 0)
            {
                writer.WriteLine(BuildClearString(line));
            }
            else
            {
                writer.WriteLine(line);
            }
        }
    }
    File.Copy(writeFile, fn, true);
    File.Delete(writeFile);
}
public string BuildClearString(string line)
{

    StringBuilder sb = new StringBuilder();

    foreach (char c in line)
    {
        if (c >= 32 && c <= 175)
        {
            sb.Append(c);
        }
    }

    return (sb.ToString());
}


texts:
This program prints out a table in the console. Suggestions for improvements are welcome.

Example output

Name             Sex      Age
Klaus Ulbrecht   male     12
Dieter           male     14
Ursula           female   16

You can test and modify the program here.

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

class Main {
  private static List<List<String>> table;

  public static void main(String[] args) {
    initTable();
    int spacing = 3;
    printTable(spacing);
  }

  private static void initTable() {
    List<String> row1 = Arrays.asList("Name", "Klaus Ulbrecht", "Dieter", "Ursula");
    List<String> row2 = Arrays.asList("Sex", "male", "male", "female");
    List<String> row3 = Arrays.asList("Age", "12", "14", "16");
    table = Arrays.asList(row1, row2, row3);
  }

  private static void printTable(int spacing) {
    List<Integer> maxLengths = findMaxLengths();

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < table.get(0).size(); i++) {
      for (int j = 0; j < table.size(); j++) {
        String currentValue = table.get(j).get(i);
        sb.append(currentValue);
        for (int k = 0; k < (maxLengths.get(j) - currentValue.length() + spacing); k++) {
          sb.append(' ');
        }
      }
      sb.append('\n');
    }

    System.out.println(sb);
  }

  private static List<Integer> findMaxLengths() {
    List<Integer> maxLengths = new ArrayList<>();
    for (List<String> row : table) {
      int maxLength = 0;
      for (String value : row) {
        if (value.length() > maxLength) {
          maxLength = value.length();
        }
      }
      maxLengths.add(maxLength);
    }
    return maxLengths;
  }
}


texts:
I have this code that gets a CSV string from a list of objects where the first row in the string is the object's properties and the rows underneath are the properties values. I then create a MemoryStream of the string so it's about the same as reading from an actual .csv file into a Stream. Is there any way to cutdown on this code and perhaps do more with LINQ?
public class Lead
{
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
}
...

List<Lead> leads = new List<Lead>();
Lead lead1 = new Lead();
lead1.FirstName = "Joe";
lead1.MiddleName = "M";
lead1.LastName = "DiFabio";
leads.Add(lead1);

Lead lead2 = new Lead();
lead2.FirstName = "Dave";
lead2.MiddleName = "";
lead2.LastName = "Palacios";
leads.Add(lead2);

Lead lead3 = new Lead();
lead3.FirstName = "Andy";
lead3.MiddleName = "A";
lead3.LastName = "Nevers";
leads.Add(lead3);

List<string> headers = typeof(Lead).GetProperties().Select(x => x.Name).ToList();
string s = string.Join(",", headers);

foreach (Lead lead in leads)
{
    List<object> values = typeof(Lead).GetProperties().Select(prop => prop.GetValue(lead)).ToList();
    string ss = string.Join(",", values);
    s = $"{s}\n{ss}\n";
}

MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(s));


texts:
I have a string, for example: dashboard/12398911/overzicht and I want to check that string for 2 values. For dashboard and overzicht. If the first check is false, then the second check doesn't need to happen.

This is my current code:

private pageTypes = ['dashboard', 'klantenkaart', 'complexkaart', 'objectkaart', 'collegakaart'];
private subTypes = ['overzicht', 'tijdlijn', 'contracten', 'financieel', 'mededelingen'];

private isOnPageWithFilter(currentUrl: string): boolean {
    for (const pageType of this.pageTypes) {
        if (currentUrl.includes(pageType)) {
            for (const subType of this.subTypes) {
                if (currentUrl.includes(subType)) {
                    return true;
                }
            }
        }
    }
    return false;
}

I was wondering if there's a way of doing this where I don't need a nested for loop.

Plunkr: https://plnkr.co/edit/FXhbCr9aaXcL61g3q7Fe?p=preview


texts: Generates HTML to show current Bootstrap screen size

texts:
When I am developing in Bootstrap, I need to make sure that what is on the screen looks good. Bootstrap have various cutoff points where the flow can change. So to help with the visual debugging, I have created this tool that just shows what the current screen is according to Bootstrap.

<cfscript>
sizes = [
        { "styleClass" : "d-block d-sm-none",           "name" : "Extra small", "look" : "warning"},
        { "styleClass" : "d-none d-sm-block d-md-none",     "name" : "Small", "look" : "info"},
        { "styleClass" : "d-none d-md-block d-lg-none",     "name" : "Medium", "look" : "success"},
        { "styleClass" : "d-none d-lg-block d-xl-none",     "name" : "Large", "look" : "primary"},
        { "styleClass" : "d-none d-xl-block",           "name" : "Extra large", "look" : "dark"}
    ];

sizes.each(function(item){
    writeoutput("
#item.name#
");
})
</cfscript>

Is there additional information that can/should be shown.


texts:
I have a situation where I am receiving data from a web service and the data is in all caps.  I have to convert to HTML and format for display.  In this case, we need the string to be normalized.  The XML we receive has the possibility, and most of the time is, large, sometimes being over a MB in size.  Performance is an issue.

I have the below templates that I use for normalizing the string.  I'm limited to XSLT 1.0.

<xsl:template name="CamelCase">
    <xsl:param name="text"/>

    <xsl:variable name="checkNBSP" select="translate($text, '&nbsp;', ' ')"/>
    <xsl:variable name="check160" select="translate($checkNBSP, '&#160;', ' ')"/>

    <xsl:choose>
        <xsl:when test="contains($check160,' ')">
            <xsl:call-template name="CamelCaseWord">
                <xsl:with-param name="text" select="substring-before($check160,' ')"/>
            </xsl:call-template>
            <xsl:text> </xsl:text>
            <xsl:call-template name="CamelCase">
                <xsl:with-param name="text" select="substring-after($check160,' ')"/>
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:call-template name="CamelCaseWord">
                <xsl:with-param name="text" select="$check160"/>
            </xsl:call-template>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

<xsl:template name="CamelCaseWord">
    <xsl:param name="text"/>
    <xsl:value-of select="translate(substring($text,1,1),'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')" />
    <xsl:value-of select="translate(substring($text,2,string-length($text)-1),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')" />
</xsl:template>

I initially found the below template on Stack Overflow and made some slight modifications to it to meet my purposes.  Is this way the optimal way to format the string, or can this be cleaned up?


texts: Throwing error if settings / arguments are undefined is this a good breakout function?

texts:
var _ = require("underscore");

var checkSettingsUndefined = function(settings){
    if(_.isEmpty(settings)){
        throw new Error("settings are empty");
    }
}

var Class = function(settings){
    checkSettingsUndefined(settings);
    this.settings = settings;
}

Class.prototype.settings = function(){
    return this.settings;
}

module.exports = Class;

and here's my unit test

it("empty settings should throw error", function(){
    var Class = require("Class.js");
    expect(function(){
        return new Class();
    }).to.throwException(function (e) {
        expect(e.message).to.be("settings are empty");
    });
});


texts: Transforming arrays into the correct formats

texts:
I am still attempting to learn how to best handle arrays and iterate their values transforming them into the correct formats that are needed for my database/API.

So I have this array:

$arr = [
    0 => [
        'field' => [
            0 => [
                '@name' => 'first_name',
                '@value' => 'Jack'
            ],
            1 => [
                '@name' => 'last_name',
                '@value' => 'Lew'
            ],
            2 => [
                '@name' => 'email',
                '@value' => 'jack@gmail.com'
            ]
        ]
    ]
];

And I need it to look like this:

[0] => Array
    (
        [first_name] => Jack
        [last_name] => Lew
        [email] => jack@gmail.com
    )

To get to this I have taken the same approach I usually take:

for( $i = 0; $i < count($arr); $i++ ) {
    foreach($arr[$i] as $k => $v) {
        print_r($k . ': \r\n');
        if( is_array($v) ) {
            foreach($v as $key => $val) {
                $new[$i][$val['@name']] = $val['@value'];
            }
        }
    }
}

The problem I having here is, I believe there has to be a better way to achieve the same results without being three levels deep of loops, since they are slower and just harder to debug altogether.

I would appreciate any insights on how I can make this code better in both readability and performance.


texts: Sorting an array of positive integers including 0 much faster than Radix Sort

texts:
I was working on an Limit Order Book structure in JS and came up with this algorithm. I am pretty sure this must have already been implemented but couldn't even find a clue over the web.
The thing is, it's very fast especially when you have an array of many duplicate items. However the real beauty is, after inserting k new items into an array of already sorted n items the pseudo sort (explained below) takes only O(k) and sort takes only O(n+k). To achieve this i keep a pseudo sorted array of m items in a sparse array where m is the number of unique items.
Take for instance we need to sort [42,1,31,17,1453,5,17,0,5] where n is 9 and then we just use values as keys and construct a sparse array (Pseudo Sorted) like;
Value: 1 1 2  2  1  1    1
Index: 0 1 5 17 31 42 1453

Where Value keeps the repeat count. I think now you start to see where I am getting at. JS have a fantastic ability. In JS accessing the sparse array keys can be very fast by jumping over the non existent ones. To achieve this you either use a for in loop of Object.keys().
So you can keep your sparse (pseudo sorted) array to insert new items and they will always be kept in pseudo sorted state having all insertions and deletions done in O(1). Whenever you need a real sorted array just construct it in O(n). Now this is very important in a Limit Order Book implementation because say you have to respond to your clients with the top 100 bids and bottom 100 asks in every 500ms over a web socket connection, now you no longer need to sort the whole order book list again even if it gets updated with many new bids and asks continuously.
So here is sparseSort code which could possibly be trimmed up by employing for loops instead of .reduces etc. Still beats Radix and Array.prototype.sort().
function sparseSort(arr){
    var tmp = arr.reduce((t,r) => t[r] ? (t[r]++,t) : (t[r]=1,t),[]);
    return Object.keys(tmp)
                 .reduce((a,k) => {
                           for (var i = 0; i < tmp[k]; i++) a.push(+k);
                           return a;
                         },[]);
}

Here you can see a bench against Array.prototype.sort() and radixSort. I just would like to know if this is reasonable and what might be the handicaps involved.


texts: Creating an Array of Linked Lists from a BST

texts:
Question

  Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists)

Here is my attempt at a solution. I haven't test it, but I was trying to get feedback on whether or not this would be an appropriate approach to such solution.

public class solution {

    ArrayList<LinkedList<Node>> makeArrayList(Node n) {
        int level = 0;
        return addLists(new ArrayList<LinkedList<Node>>(), n, level);
    }

    ArrayList<LinkedList<Node>> addLists(ArrayList<LinkedList<Node>> arr, Node n, int level) {
        if (n != null) {
            if (arr.get(level) == null) {
                LinkedList<Node> newList = new LinkedList<Node>();
                arr.add(level, newList);
            }
            LinkedList<Node> nodeList = arr.get(level);
            nodeList.add(n);
            addLists(arr, n.leftChild, level + 1);
            addLists(arr, n.rightChild, level + 1);
        }
        return arr;
    }
}


texts:
I wrote this little RPG in Python. It still needs a good battle system and real enemies, but since it's my first attempt to create a rather "big" project, I'm happy with the result. Everything is under 1 single file since I dunno how to split it into multiple ones.

# By Luca Savoini

from random import randint
import time

# Player variables
playername = input("What's your name? ")
playerlevel = 1
hp = 50 + playerlevel
strenght = 10 + playerlevel + randint(1, playerlevel)
money = 100

# Enemy variables
dummyhealth = 100
playerdamage = dummyhealth - strenght

# Intro
time.sleep(1)
print(playername + ', Welcome to Lootia! Here you will fight for glory,'
               '\ncreate powerful weapons and discover ancient secrets!')
time.sleep(4)
print("You will fight many evil creatures, so kill this dummy to prove me you are worth giving a weapon")
time.sleep(3)

# Player input
print("\nEnemy health=" + str(dummyhealth))
print("1=Sword attack\n2=Run")
playerinput = input("What do you want to do? ")

# Fight!
if hp < 0:
    if playerinput == 1:
        print("You did " + playerdamage + "damage. That's a lotta damage!")
        dummyhealth - playerdamage
    elif playerinput == 2:
        moneyonrun = money - (money / 100)
    else:
        print("You are dead!")


texts:
I have written a Reddit bot in Python (code below). Open to any improvements, especially on efficiency, as I am using PythonAnywhere to run it.

The main function is to scan posts in reddit and when certain phrases are found in the text private message the reddit user. Furthermore, the reddit user shouldn't be messaged twice.

#------------------------------------------------------------------------------
def Github_text():

    print("Open textfile...")

    data = urllib.request.urlopen("####").read()
    text = re.search("<StartText>(.+?)<EndText>", str(data))

    if text:
        private_message_text = text.group(1)
        private_message_text = private_message_text.replace(r"\\n","\n")

    print("Text is ready!")

    return private_message_text

def bot_login():

    print("Login...")

    reddit = praw.Reddit(client_id="####",
                client_secret="####",
                password="####",
                user_agent="####",
                username="####")

    print("Login succesfull!")

    return reddit

def run_bot(reddit):

    now = datetime.datetime.now()
    print("Start iteration..." + now.strftime("%Y-%m-%d %H:%M:%S"))

    for submission in reddit.subreddit("all").new(limit=1000):
        if any(sentence in submission.selftext for sentence in check_sentences) \
        and submission.author not in users_messaged and not submission.stickied and submission.is_self:

          print(submission.selftext)

          if len(users_messaged) > 50:
              del users_messaged[0]
              users_messaged.append(submission.author)
          else:
              users_messaged.append(submission.author)

          reddit.redditor(str(submission.author)).message(private_message_title, private_message_text)

          print("Message send to:" + str(submission.author))

    time.sleep(120)

#------------------------------------------------------------------------------
check_sentences = ["####",
                   "####",
                   "####",
                   "####",
                   "####",
                   "####",
                   "####",
                   "####"]

users_messaged = []
private_message_title = "####"
private_message_text = Github_text()
reddit = bot_login()

print("Start loop!")

while True:
    run_bot(reddit)


texts: Best Approach for Assignment Code in Node.js (ES6 style)

texts:
Is there any way to improve this code? Using ES6 style i am using latest stable version of node.js.

const UserSchema = new mongoose.Schema({
date: string;
dateObj: {
    year: number,
    month: number,
    day: number
};
project: string;
task: string;
hours: number;
});

let data = new Data();
data.date = new Date(body.date);
    data.dateObj = {
        year: body.dateObj.year,
        month: body.dateObj.month,
        day: body.dateObj.day
    }
    data.project = body.project;
    data.task = body.task;
    data.hours = body.hours;
}


texts: Evaluate an expression binary tree - Daily Coding Challenge

texts:
Here is my solution for the Daily Coding Challenge 50

  Given an arithmetic expression in the form of a binary tree, write a function to evaluate it

Example

    *
   / \
  +    +
 / \  / \
3  2  4  5

Return >> 45

Is this the most efficient way to do this?

"""Build an operation tree and calculate the result"""

class Tree:
    def __init__(self, value, left=None, right=None):
        """Initialise values"""
        self.value = value
        self.left = left
        self.right = right

    def determine_sum(self, total):
        if self.left == None and self.right == None:
            return int(self.value)
        if self.value == "*":
            total += self.left.determine_sum(total) * self.right.determine_sum(total)
        if self.value == "+":
            total += self.left.determine_sum(total) + self.right.determine_sum(total)
        if self.value == "-":
            total += self.left.determine_sum(total) - self.right.determine_sum(total)
        if self.value == "/":
            total += self.left.determine_sum(total) / self.right.determine_sum(total)
        return total

if __name__ == "__main__":  #
    n = Tree("*")
    n.left = Tree("+")
    n.right = Tree("+")
    n.left.right = Tree("+")
    n.right.right = Tree("+")

    n.left.left = Tree("3")
    n.left.right.left = Tree("4")
    n.left.right.right = Tree("5")

    n.right.left = Tree("6")
    n.right.right.left = Tree("7")
    n.right.right.right = Tree("4")

    sum = n.determine_sum(0)
    print(sum)


texts: Sort data from a text file in descending order using quick sort

texts:
I have a text file containing the following data.

ascon1 201707011 John 77.5 11.5 11.5 11.5
ascon1 201707012 Grld 70.0 11.5 11.5 11.5
ascon1 201707013 Josh 79.5 11.5 11.5 11.5
ascon1 201707014 Jess 67.5 11.5 11.5 11.5
ascon1 201707015 Jack 97.5 11.5 11.5 11.5

I need the data to look like this.

ascon1 201707015 Jack 97.5 11.5 11.5 11.5
ascon1 201707013 Josh 79.5 11.5 11.5 11.5
ascon1 201707011 John 77.5 11.5 11.5 11.5
ascon1 201707012 Grld 70.0 11.5 11.5 11.5
ascon1 201707014 Jess 67.5 11.5 11.5 11.5

so here is my code. The above part is working using the inbuilt sorted function from python. but in ascending order instead of decending order.

with open('input.txt') as f:
    lines = [line.split(' ') for line in f]
output = open("input(sorted).txt", 'w')

for line in sorted(lines, key=itemgetter(3)):
    output.write(' '.join(line))

output.close()

I want to use the quick-sort function to solve this problem. this is my function.

def qsort(d_val):
    if len(d_val) <= 1: return d_val
    return qsort([lt for lt in d_val[1:] if lt < d_val[0]]) + d_val[0:1] + \
           qsort([ge for ge in d_val[1:] if ge >= d_val[0]])


texts:
How can I make these methods better?

Range.class_eval do
    def addto_begin(x)
        return self.begin + x..self.end
    end
    def addto_end(x)
        return self.begin..self.end+x
    end
end

Right now, I have to type:

x = 1..10
x = x.addto_begin(3)

to change the begin of the range. What I want to be able to do is:

x = 1..10
x.addto_begin(3)

How do I do this?


texts: Equalized PRNG number distribution - Part 2

texts:
A few days ago, I've made a code to equally distribute a set of numbers and retrieve them randomly. Today, I've rewritten the code (most of it, at least). I've followed most of the advice and tried to keep it clean, but also as fast as possible. The new code has a few more comments than the last one (they were needed) and the code suffered a huge simplification.

( function ( window ) {

    window.RNG = function ( min, max ) {

        var nan = function ( val ) {
                /*
                 * Checks if the value is an usable number or NaN or Infinity
                 * When dividing by 1, it will convert the value to a number or NaN
                 * NaN values return false when compared with themselves ( NaN != NaN returns true)
                 *
                 * The 2nd part of the verification will check if the value is infinite
                 * Infinity will return Infinity if you sum or subtract 1
                 * E.g.: Infinity - 1 == Infinity --> returns true
                 */
                return ( ( val / 1 ) != ( val / 1 ) ) || ( val - 1 == val );
            },
            //will contain all the available numbers
            avail = [];

        if ( nan( min ) )
        {
            throw new TypeError( 'Expecting Number or NumericString, got ' + ( min != min ? 'NaN' : ( min - 1 == min ? 'Infinity' : typeof min) ) );
        }
        if ( arguments.length > 1 )
        {
            if ( nan( max ) )
            {
                throw new TypeError( 'Expecting Number or NumericString as the second parameter, got ' + typeof max );
            }
            /*
             * converts the numbers to integers ( n>>=0 -> n = n >> 0)
             * and check if the minimum is higher than the maximum,
             * throwing an exception if that is the case
             */
            else if ( ( min >>= 0 ) >= ( max >>= 0 ) )
            {
                throw new RangeError( 'The 2nd parameter should be higher than the first' );
            }
            else if ( ( max - min ) > 268435455 )
            {
                //big numbers crash hard, so we must stop them before
                throw new RangeError( 'The difference between ' + max + ' and ' + min + ' is higher than 268435455' );
            }
        }
        else
        {
            max = min >> 0;
            min = 0;
        }

        return {
            valueOf: function ( ) {

                if( !avail.length )
                {
                    for( var i = 0; i <= max - min; i++ )
                    {
                        avail[i] = min + i;
                    }
                }

                if( avail.length > 1 )
                {
                    //returns a random element between 0 and avail.length (excluded)
                    return avail.splice( ( window.Math.random() * avail.length ) >> 0, 1)[0];
                }
                else
                {
                    return avail.splice( 0, 1 )[0];
                }

            },
            toString: function ( ) {
                return this.valueOf() + '';
            }
        };

    };

} )( Function('return this')( ) );

To use it, simply create a new object:

var random_number = new RNG( 50 ); //same as 0,50

Then, you use this to generate numbers, with direct access:

alert( random_number ); //should alert a number between 0 and 50

This also works for negative numbers but it won't work for decimal numbers.

In terms of readability and performance, what else should I improve?

If you notice, on the answer to the question, one of the pieces of advice was to avoid using:

else if( ( min = min >> 0 ) >= ( max = max >> 0 ) )

I've completely ignored it to keep my code a little DRY and to improve performance.


texts:
I have Ajax function with a callback which fetches all the Patient data however I have some perfomance issues and trying to figure out what it might be, does anyone have idea? That's my Code

var patient = new Array();
function sync(arg, callback){   //ajax result
    $('.loader').show();
    $.ajax({
        method: 'GET',
        url: 'sync/active.php',
        dataType: 'json',
        data: arg, // argument schicken und aktualisieren
        success: function(data, status, xhr){
         $('.loader').hide();
         callback(data);
        // setTimeout(sync, ajaxDelay);
        },
        error: function(xhr, ajaxOptions, thrownError){
            console.log(thrownError);
        }
   });
}
function onPatientCallback(data) {
        var res = data;
        for(var i=0; i<res.length;i++){
            for(var key in res[i]){
                var value = res[i][key];
                switch(key){
                    case "id":
                        res[i][key] = parseInt(value);
                        break;
                    case "kundennr":
                        res[i][key] = parseInt(value);
                        break;
                    case "client":
                        res[i][key] = value;
                        break;
                    case "start":
                        res[i][key] = new Date(value);
                        break;
                    case "end":
                        res[i][key] = new Date(value);
                        break;
                    case "title":
                        res[i][key] = value;
                        break;
                    case "description":
                        res[i][key] = value;
                        break;

                    case "termart":
                        res[i][key] = parseInt(value);
                        break;

                    case "userId":
                        res[i][key] = parseInt(value);
                        break;

                    default:
                        console.log("unbekannter Datentyp "+key);
                }
            }
        }
        patient = res;

}

I use the function to fill the patient variable and call it in another js file like that  sync({calling: "patient"}, onPatientCallback);


texts: Creating a time-course dependent, correlation-based directed graph with Networkx

texts:
I have a correlation matrix containing 4 time points, each with multiple samples. Each sample is identified with a time point with its name. What I am trying to accomplish here is to create a directed graph using Python's (2.7) Networkx with edges connecting nodes from the last time point to the first time point (6h --> 4h --> 2h --> 1h) given that the correlation value is above a certain threshold. On top of this I would only like to draw edges to nodes only if they have an already existing edge (with exception to the last time point). This will narrow the network the further the path gets.

Additionally since there are only 4 time points, I would like to create a sort of x-axis with each time point and with the respective nodes listed vertically above the x-axis tick marks. Ultimately I would like the graph to look something like a horizontal Christmas tree.

The code I have written works but it was written sloppy and I'm trying my best to compact it. I have listed my code below:

import networkx as nx
import matplotlib.pyplot as plt
from pandas import DataFrame

DG=nx.DiGraph()

corr=DataFrame.from_csv('Correlation_LPS-timecourse.txt', header=0, sep='\t')

timepoint1_allCols=corr.filter(regex=r'(?i)_1h_', axis=0)
timepoint2_allCols=corr.filter(regex=r'(?i)_2h_', axis=0)
timepoint3_allCols=corr.filter(regex=r'(?i)_4h_', axis=0)
timepoint4_allCols=corr.filter(regex=r'(?i)_6h_', axis=0)

timepoint_12=timepoint1_allCols.filter(regex=r'(?i)_2h_', axis=1)
timepoint_23=timepoint2_allCols.filter(regex=r'(?i)_4h_', axis=1)
timepoint_34=timepoint3_allCols.filter(regex=r'(?i)_6h_', axis=1)

threshold = 0.98

for idx, row in timepoint_34.iterrows():
    for i,entry in enumerate(row):
        if entry > threshold:
            DG.add_edge(row.index[i], idx, weight=entry)

for idx, row in timepoint_23.iterrows():
    for i,entry in enumerate(row):
            if entry > threshold and DG.degree(row.index[i]):
                DG.add_edge(row.index[i], idx, weight=entry)

for idx, row in timepoint_12.iterrows():
    for i,entry in enumerate(row):
            if entry > threshold and DG.degree(row.index[i]):
                DG.add_edge(row.index[i], idx, weight=entry)

nx.draw(DG, pos = nx.spring_layout(DG), with_labels=True)
plt.show()

If you're interested in playing with the real data that I am using I have uploaded it here.


texts: Restructuring data received from JSON call

texts:
I'm making a JSON call and receiving data and inputting the data received into some HTML. However I don't think this is the best way to return the data. It's seems like a bit of a hack as I'm injecting a bunch of HTML in my jQuery. I'm also adding an image inside of my jQuery cause I want it to appear between some of the JSON data that is getting returned. Ideally I'd like my html to loop through and generate this info into the chatInfo div. Anybody have any ideas how to better do this?

$.getJSON("/services/chatInfo.json?user=manual" + mediaTypes + locationTypes, function(data) {

         var items = [];
            $.each( data.media, function( key, val ) {
            items.push( "

" + val.displayName + "
" );
            items.push( "
" + val.hours + "

" );
            });

            $("
").html(items.join("")).appendTo( "#chatInfo" );
    });


texts: Dispatching Brainfuck commands using if-else or dictionary

texts:
Here's the first, straightforward version of BF interpreter:

def run(step_limit, memo, m_i, code):
    """ Runs valid BF code. """

    if len(code) == 0:
        return

    i = 0
    for step in range(step_limit):
        cmd = code[i]

        # Switch - case
        if cmd == '+':
            memo[m_i] += 1
        elif cmd == '-':
            memo[m_i] -= 1
        elif cmd == '>':
            m_i += 1
        elif cmd == '<':
            m_i -= 1
        elif cmd == '.':
            print (memo[m_i])
        elif cmd == ',':
            memo[m_i] = int ( input ( "Input: " ) )
        elif cmd == '[':
            if memo[m_i] == 0:
                i = code.find(']', i, len(code) )
        else: # if cmd == ']'
            if memo[m_i] != 0:
                i = code.find('[', 0, i )

        i += 1
        if i == len(code):
            break

And the second one:

""" Second version of the same method. """
# I tried to use namedtuples but I failed. Using simple, usual tuples instead.

def plus (args):
    return args[1]+1, args[2]+1, args[3]

def minus (args):
    return args[1]+1, args[2]-1, args[3]

def rigth (args):
    return args[1]+1, args[2], args[3]+1

def left (args):
    return args[1]+1, args[2], args[3]-1

def output (args):
    print (args[2])
    return args[1]+1, args[2], args[3]

def u_input (args):
    return args[1]+1, int (input ("Input: ") ), args[3]

def loop_begin (args):
    if args[2] == 0:
        return args[0].find(']', args[1], len(args[0]))+1,args[2],args[3]
    else:
        return args[1]+1, args[2], args[3]

def loop_end (args):
    if args[2] != 0:
        return args[0].find('[', 0, args[1] )+1, args[2], args[3]
    else:
        return args[1]+1, args[2], args[3]

def nothing (args): # So that memo[m_i] wouldn't go out of index
    return args[1], args[2], args[3]

commands = {
    '+' : plus,
    '-' : minus,
    '>' : rigth,
    '<' : left,
    '.' : output,
    ',' : u_input,
    '[' : loop_begin,
    ']' : loop_end,
    ' ' : nothing }

def run(step_limit, memo, m_i, code):
    """ Runs valid BF code. """

    if len(code) == 0:
        return

    code += ' ' # So that memo[m_i] wouldn't go out of index
    i = 0
    for step in range(step_limit):
        args = (code, i, memo[m_i], m_i)
        i, memo[m_i], m_i = commands[ code[i] ] ( args )
        if args[1] == len(args[0]) - 1 or code[i] == ' ':
            break

# Now we have to add space after program so that memo[m_i] wouldn't go out of index
run(1000000000, [478234, 5161845], 1, "[-<+>]<. ") # TEST, adds two numbers

Yes, I know I should have used dictionaries to increase readability because now the indexes are horrible, but this is just a quick concept.

Question: would you ever prefer second structure over the first one, and under what conditions?
Maybe you know a solution better than both of these versions?

Some of my thoughts:

Second version is 2x slower. Benchmarked with run(1000000000, [478234, 5161845], 1, "[-<+>]<. "), finishes in 73.5s while first one does the job in 36s.
In my opinion, second version is more decompositioned, thus easier to maintain and expand in very big projects, but not worthy the effort in the small ones.


texts:
In a recent interview I was asked to solve the below problem.

Problem:

  Given a string with variables in them, e.g.
  "I am a string with {{ variable }} in them"

  Create an output where the {{ variable}} is replaced with their
  actual values.

  So if given the input:

var template = {
  "sentence": "The {{ object }} {{ verb }} ",
  "object": "{{ adjective }} {{ noun }}",
  "verb": "flew",
  "adjective": "colorful",
  "noun": "bird"
};

  the function call

fillInTheBlanks(template, 'sentence')

  must produce the output:

The colorful bird flew

I came up with the following solution (which works):

var sentence = fillInTheBlanks(template, 'sentence');

//Accomplish however you'd like, additional utility functions are fine
function fillInTheBlanks(template, outputKey) {

  var val = template[outputKey];

  while (val.search(/{{/i) >=0) {
      val = splitAndMerge(val);
      val = val.replace(/,/g, " ");
  }

 return val;
}

function splitAndMerge(val) {
   var splittedSentence = val.split(' ');
    _.forEach(splittedSentence, function(item, idx) {
    if (item === '{{') {
      splittedSentence[idx+1] = resolveString(splittedSentence[idx+1]);
      splittedSentence.splice(idx+2, 1);
      splittedSentence.splice(idx, 1);
    }
  });

  return  splittedSentence.toString();

}

function resolveString(item) {
  return template[item];
}

PLNKR: http://plnkr.co/edit/4ciGzVewZRDi4RcSDsfI?p=preview

However, this solution was not considered elegant. what would have been a better way to solve this ?


texts:
Given sentence for example: ala ma kota, kot koduje w Javie kota I should to every letter occurring in the sentence I should map every string that this letter contains. So the output should be:

{a=[ala, javie, kota, ma], d=[koduje], e=[javie, koduje], i=[javie], j=[javie, koduje], k=[koduje, kot, kota], l=[ala], m=[ma], o=[koduje, kot, kota], t=[kot, kota], u=[koduje], v=[javie], w=[w]}

I have written algorithm for it, but I think that there is a better way do to this using streams (or somehow else).
Code;

String sentence = "ala ma kota, kot koduje w Javie kota .kota";

        String purifiedLowerCaseSentence = getPurifiedLowerCaseSentence(sentence);
        Set<Character> characters = getEveryCharacterOccurringInSentence(purifiedLowerCaseSentence);
        String[] splittedSentence = purifiedLowerCaseSentence.split("\\s");
        Map<Character, Set<String>> characterWithAccordingWord = new LinkedHashMap<>();

        for (char iteratedCharacter : characters) {
            for (String iteratedWord : splittedSentence) {
                if (iteratedWord.indexOf(iteratedCharacter) >= 0) {
                    characterWithAccordingWord.computeIfAbsent(iteratedCharacter, k -> new TreeSet<>());
                    characterWithAccordingWord.get(iteratedCharacter).add(iteratedWord);
                }
            }
        }

And these two methods which are placed in other class:

static String getPurifiedLowerCaseSentence(String sentence) {
        return sentence.replaceAll("\\p{P}", "").toLowerCase();
    }

    static Set<Character> getEveryCharacterOccurringInSentence(String sentence) {
        return sentence.chars()
                .mapToObj(e -> (char) e).collect(Collectors.toSet());
    }


texts:
I am running a simple Python webserver to toggle a GPIO pin
on a Raspberry Pi. All seems to work well, but I have a few
questions about my code (see below).

I am using the urlparse module to obtain the URL arguments.

The HTML file just sends out Ajax requests using buttons when clicked.

I've commented out the send_response lines, and it seems to work
both ways. Is it mandatory to send a response?
Is the code below easy to exploit? Are there improvements I can make to make it a bit more robust?

Python code:

import time
import SimpleHTTPServer
import SocketServer
from urlparse import *

ledpin=18
myport=8123
# Turn LED on  => http://ip_of_pi:port/control.html?led=on
# Turn LED off => http://ip_of_pi:port/control.html?led=off
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        urlcomp=urlparse(self.path) # Split URL in components
        query = parse_qs(urlcomp.query) # Get args as dictionary
        if len(query)==0 or query.has_key("led")==False:
            self.path=urlcomp.path
            # self.send_response(200)
        elif query["led"] == ["on"] :
            GPIO.output(ledpin,True)
            # self.send_response(200)
            return
        elif query["led"] == ["off"] :
            GPIO.output(ledpin,False)
            # self.send_response(200)
            return
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(ledpin,GPIO.OUT)

Handler = MyRequestHandler
httpd = SocketServer.TCPServer(('0.0.0.0', myport), Handler)
httpd.serve_forever()


texts:
I'm new to ruby, later I asked about ways to refactor code (Parsing GPS data), one man gave me direction, so I made class for Median filter and it will be great to read review for my work.

What guys are you thinking about it? Is it still smells?

class MedianFilter
  attr_accessor :step

  def initialize(step, keys)

    raise ArgumentError.new('Step must be odd and higher than 3') if step < 3 && step % 2 != 1
    raise ArgumentError.new('Keys must be array of symbols') unless keys.kind_of?(Array) && keys.count > 0

    @step = step
    @keys = keys

  end

  def filter(param_values)
    process_values param_values.clone
  end

  def filter!(param_values)
    process_values param_values
  end

  private

  def process_values(values)

    half_step = (@step - 1) / 2

    values.each_index do |i|

      item = values[i]

      median_points = [ values[ [0, i - half_step].max ],
                        item,
                        values[ [values.count - 1, i + half_step].min ] ]

      @keys.each do |key|
        item[key] = median_points.map { |x| x[key] || 0 }.sort[half_step]
      end

    end

    values

  end

end


texts: Implementing write sphere of values to 3D array

texts:
The code below is sort of complicated to explain...
It writes a "sphere" of data to a 3D array from the given 3D-Position outwards in a spherical shape based on the given radius and value to write.

A graphical representation of this would be:

double UbytePrism :: PrismSphereSet( uint64 Xpos , uint64 Ypos , uint64 Zpos , sint64 Radius , ubyte Byte ) {
    for( sint64 w = -Radius; w <= Radius; w ++ ) {
        for( sint64 h = -Radius; h <= Radius; h ++ ) {
            for( sint64 d = -Radius; d <= Radius; d ++ ) {
                if ( Xpos + w < ByteBuffWidth && Ypos + h < ByteBuffHeight && Zpos + d < ByteBuffDepth && Xpos + w >= 0 && Ypos + h >= 0 && Zpos + d >= 0 ) {
                    if ( ( w * w ) + ( h * h ) + ( d * d ) < Radius * Radius ) {
                        BytePrism[ ( ( ByteBuffWidth * ByteBuffHeight ) * ( Zpos + d ) ) + ( ByteBuffWidth * ( Ypos + h ) ) + ( Xpos + w ) ] = Byte;
                    };
                };
            };
        };
    };

    return 0.0;
};

The general usage of this function would be:

// On a 7x7x7 grid like the image:
// PrismSphereSet( x , y , z , radius , value );
PrismSphereSet( 3 , 3 , 3 , 4 , 5 );

As you can see there is an issue where it's not drawing an exact circular shape.
If possible I'd like to fix and or modify this to work elliptical-spheres rather
than exact spheres. However, I am not sure how to modify the if-statement if ( ( w * w ) + ( h * h ) + ( d * d ) < Radius * Radius ) { of the
function to fit my needs since I pulled it from an example code.


texts: Searching for column-indices of a multi-dimensional array that match multiple conditions (one condition per row)

texts:
I have written a script that I believe works and covers all edge-cases. I am curious about ways to improve upon speed. While the given example below covers a multi-dimensional array of 3 rows x 10 columns, my actual use case will be n rows x ~70,000 columns (where n depends upon the number of data parameters being searched).

Given individual arrays of data points, the goal is to combine them into a multi-dimensional array and find the columns in which all conditions are satisfied. If the same column of each row satisfies a given condition, the index that corresponds to that column is output; otherwise, an error is raised.

I have included a small class named MaskOps() because it has many other functions relevant in my main code, though I've only included the parts relevant to the goal in this question.

import numpy as np

class MaskOps():

    @staticmethod
    def get_base(shape, value, dtype=int):
        """ This function produces a base-mask, the values of which may be overwritten. """
        if isinstance(value, (float, int)):
            res = np.ones(shape, dtype=dtype) * value
        elif isinstance(value, str):
            res = np.array([value for idx in range(np.prod(shape))]).reshape(shape)
        return res

    @staticmethod
    def alternate_base(shape, key):
        """ This function creates base-masks that consist of one of two value; the value depends on the index input as the parameter key. """
        if key % 2 == 0:
            value = 0.25
        else:
            value = 0.5
        return MaskOps().get_base(shape, value, dtype=float)

MO = MaskOps()

Sample Data

row_a = np.linspace(1, 10, 10)
row_b = row_a * 10
row_c = row_a + 20
data = np.array([row_a, row_b, row_c])

Main Search Function

def core_algorithm(ndata, search_value):
    """
    This function prints values and indices that match the search condition.

    An index mask of non-zero values is created per row of the input data,
    and the values of the index mask are overwritten to be a zero at each
    column at which the condition is satisfied - per condition and row of data.
    Then, the columns of the index masks that sum to zero are the column-indices
    that satisfy all input conditions.
    """

    print("\nSEARCH VALUES:\n{}\n".format(search_value))
    print("NDATA:\n{}\n".format(ndata))

    bases = np.array([MO.alternate_base(len(ndata.T), idx) for idx in range(len(ndata))])
    print("ORIGINAL BASES:\n{}\n".format(bases))

    locs = np.array([np.where(ndata[idx] == search_value[idx])[0] for idx in range(len(search_value))])
    print("LOCS:\n{}\n".format(locs))

    for idx in range(len(bases)):
        bases[idx][locs[idx]] = 0
    print("UPDATED BASES:\n{}\n".format(bases))

    res_idx = np.where(np.sum(bases, axis=0) == 0)[0]
    print("RES COLUMN:\n{}\n".format(res_idx))

    if len(res_idx) == 0:
        raise ValueError("match could not be found")

    res_val = np.array([ndata[idx][res_idx] for idx in range(len(ndata))])
    print("VALUES FROM COL-INDICES\n{}\n".format(res_val))

core_algorithm(data, search_value=(3, 30, 23)) # works successfully
# core_algorithm(data, search_value=(3, 30, 24)) # throws an error

One alternative method I have yet to explore is using set intersection/unions to find the same indices, though I'm not sure if that would necessarily improve performance. I posted a similar example some time ago, though I later realized the code had bugs and could have been improved upon as an example.


texts: Merge arrays in objects in array based on property

texts:
I have the following code which takes an array that might have duplicate ids and will merge the items of those duplicate, and keep only one element per id which contains all the items of all elements with the same id.

array = [{
    id: 1,
    items: [1, 2, 3]
  },
  {
    id: 2,
    items: [1, 2]
  },
  {
    id: 1,
    items: [4]
  },
  {
    id: 3,
    items: [1]
  },
];

const mergeLines = (a) => {
  const processedIds = [];
  const finalResult = [];
  a.forEach((element) => {
    const elementId = element.id;
    if (processedIds.indexOf(elementId) === -1) {
      const occurences = a.filter((el) => el.id === elementId);
      if (occurences.length > 1) {
        const allItems = occurences.reduce((acc, curr) => {
          acc = acc.concat(curr.items);
          return acc;
        }, []);
        element = { ...element,
          items: allItems
        };
        finalResult.push(element);
      } else {
        finalResult.push(element);
      }

      processedIds.push(elementId);
    }
  });
  return finalResult;
};

console.log(mergeLines(array));

I feel this code can be optimized much further to 0(n)


texts: Returning Key Values from Stored Procedures

texts:
I wonder which is better practice when I need to return the primary key value of a newly inserted record from a SQL stored procedure. Consider the following implementations:

As Return Value

CREATE PROCEDURE [CreateRecord] ( @value NVARCHAR(128) )
AS
BEGIN
    INSERT [Records] ( [Value] ) VALUES ( @value );
    RETURN SCOPE_IDENTITY();
END

Obviously this only works for INT keys, but it takes advantage of pre-existing functionality. Also, only works when inserting a single record. I have seen this done in few places, but I generally don't like it.

As Output Parameter

CREATE PROCEDURE [CreateRecord] ( @value NVARCHAR(128), @id INT = NULL OUTPUT )
AS
BEGIN
    INSERT [Records] ( [Value] ) VALUES ( @value );
    SET @id = SCOPE_IDENTITY();
END

Works for any type of key, including multi-column keys, but still only works when inserting a single record. This is my preferred method unless I absolutely have to insert more than one record at a time.

As XML Output Parameter

CREATE PROCEDURE [CreateRecord] ( @value NVARCHAR(128), @xmldata XML = NULL OUTPUT )
AS
BEGIN
    DECLARE @inserted TABLE ( Id INT );

    INSERT [Records] ( [Value] )
    OUTPUT [inserted].[Id]
    INTO @inserted ( [Id] )
    VALUES ( @value );

    SET @xmldata = (SELECT [Id] FROM @inserted FOR XML AUTO);
END

This is similar to the previous solution, but allows multiple records to be returned. Trying to parse the output would be a huge pain, but I suppose this would be suitable for some applications. For example, if a stored procedure can insert into several different tables, a single output parameter can describe all the inserted records.

As Result Set

CREATE PROCEDURE [CreateRecord] ( @value NVARCHAR(128) )
AS
BEGIN
    DECLARE @inserted TABLE ( Id INT );

    INSERT [Records] ( [Value] )
    OUTPUT [inserted].[Id]
    INTO @inserted ( [Id] )
    VALUES ( @value );

    SELECT * FROM @inserted;
END

Superficially, this may be appealing, especially if your calling this SP from ADO, since getting the result set from the command is very straight forward. To use this SP from SQL, however, you have to write an INSERT-EXEC script, which is somewhat inelegant, in my opinion (but still a lot better than parsing XML).

Perhaps there are other methods that I'm not even aware of. What is the best method of returning the newly inserted key value from this kind of stored procedure? Are there any guidelines for deciding which is the best method?


texts:
I use the following code which is working as expected, but I want to use it in production. I'm not sure that this is clean code since I'm new to node.js. It would be great if I can get some example how can I write cleaner code.

I mean how do I use the config to read the values, there is better way?
How do I use the onListening?

/**
 * Module dependencies.
 */
var app = require('../app');
var debug = require('debug')('blog-twitter:server');
var http = require('http');
var os=require('os');
var request=require('superagent')
/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '8062');
app.set('port', port);

/**
 * Create HTTP server.
 */
//var io=require('express-socket.io');

var server = http.createServer(app);
var io=require('socket.io').listen(server);
var Twitter=require('twitter');
var cfg = require('../config.json');
//console.log(cfg.twitter);
/**
*Create a twitter client to use AUTH credentials defined
*in config.json file
*/
var client=new Twitter({
  consumer_key: cfg.twitter.consumer_key,
  consumer_secret: cfg.twitter.consumer_secret,
  access_token_key: cfg.twitter.access_token_key,
  access_token_secret: cfg.twitter.access_token_secret
});
/**
Bind to twitter public streaming API
*/
var stream=client.stream('statuses/filter',{track:"Javascript"});
/**
*Create twitter stream, when a tweet is available,
*get its embeded format and emit that to the server.
*/
stream.on("data", function(data){
  console.log(data.id_str);
  var tweet_id="https://api.twitter.com/1.1/statuses/oembed.json?id="+data.id_str;
  //console.log(data);

  //console.log("ID:",tweet_id);
  request.get(tweet_id)
  .end(function(err,res){
      if(err){
        console.log("Error: "+err);
      }else{
        //console.log(res.body);
        io.emit('tweet',res.body);
      }
  });
  //console.log("Tweet: ",data);
});
stream.on('error', function(err){
  console.log("Error retrieving tweets: "+err);
});
io.on('connection', function(client){
  client.on("join", function(data){
    console.log(data);
  });
  client.emit("join",{"message":"Welcome"});
});
/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var serverName=cfg.server;
  var runServer=`http://localhost:8060/service/tweets/${server.address().port}`;
  if(cfg.hosted){
    runServer=`http://${serverName}/service/tweets/${server.address().port}`;
  }
  console.log(" Server on:",runServer)
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
  var expose=()=>{
      request.put(blogServer,(err,res)=>{
        if(err){
          console.log("Error:",err);
        }
      });
  }
  setInterval(expose,15*1000);
}


texts:
(https://github.com/trvshrmn/slim)

This is more of an entire project review... if this is 'off topic' I apologize. I attempted to make Slim into an mvc structure. I added a few controllers, views and models to allow users to signup, login, make a couple changes to their account, and also allow admins to view the users and change their roles.

Please don't give advice like "this is terrible" but help me take steps to improve it. Also, I know full stack frameworks will do everything for me, but I want to learn myself, so don't refer me to other frameworks or other slim 'skeletons'.

Here is some of the code.

public/index.php:

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require '../vendor/autoload.php';

$settings = require '../src/settings.php';

$app = new \Slim\App($settings);

ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);

session_start();

require '../src/dependencies.php';

require '../src/middleware.php';

require '../src/routes.php';

$app->run();

src/MyApp/Controller.php:

<?php

namespace MyApp;

class Controller
{
    protected $ci;

    public function __construct($ci) {
        $this->ci = $ci;
        $this->ci->db;
        $this->flash = $ci->flash;
    }

    public function redirect($route) {
        header('Location: ' . $this->ci->router->pathFor($route), true, 302);
        die();
    }

    public function render($response, $view, $args = []) {
        return $this->ci->view->render($response, $view, $args);
    }
}

src/MyApp/Controller/HomeController.php:

<?php

namespace MyApp\Controller;

use MyApp\Controller;
use MyApp\Model\User;

class HomeController extends Controller
{
    public function home($request, $response) {
        return $this->render($response, 'index.html.twig');
    }
}

What should I do first to improve this? I am concerned with correct use of dependency injection, performance/speed, and general php/mvc best practices. I'm not concerned as much about security holes at this point, but if you see a major problem then go on and help.

Note: This app sometimes gives a twig error when I first run it, but composer remove slim/twig-view and require it again fixes it. Not sure why.