texts: Apply arbitrary action during recursive generator function

texts:
I've got this recursive generator function. It will traverse an object looking for "leafs", any keys that don't point to sub-objects.

Then it applies one of two actions on the leaf and yields it.
Any suggestions for improvement would be appreciated. :)

const obj = {
  a: 'a',
  b: 'b',
  c: {
    d: 'd',
    e: 'e',
  }
};

const clone = toClone => JSON.parse(JSON.stringify(toClone))

function* leafIterator(object, action) {
  for (const key of Object.keys(object)) {
    if (typeof object[key] === 'object') {
      for (const inner of leafIterator(object[key], action)) {
        let oclone = clone(object);
        oclone[key] = inner;
        yield oclone;
      }
    }
    else {
      let oclone = clone(object);
      action(oclone, key);
      yield oclone;
    }
  }
}

for (let o of leafIterator(obj, (s, key) => delete s[key])) {
  console.log('result', o);
}


texts:
This is a simple class that runs a timer every 10 seconds to update the title with some information like how long the application has been up, depending on the datetime that is set in another class when the application has finished booting up and is responsive. This application is part of a game server and it just displays how long the server has been up so I know when it was last launched.

In the future it will also include the number of players connected in the title. it is important to continuously reload it as this is a console application and there isn't really much room anywhere else to display such data.

I'm really not sure about the method name CheckServer but I was feeling very unmotivated at the time, if anyone could think of a better name, be sure to post that too.

I'm looking for basic improvements in overall performance.

internal sealed class ServerProcessWorker : IDisposable
{
    private Timer _serverTimer;
    private readonly int _timerInterval;
    private DateTime _lastUpdate;
    private bool _disposing;

    public ServerProcessWorker()
    {
        _timerInterval = 10000;
    }

    public void Start()
    {
        _serverTimer = new System.Threading.Timer(e => CheckServer(), null, TimeSpan.Zero, TimeSpan.FromMilliseconds(_timerInterval));
    }

    private void CheckServer()
    {
        if ((DateTime.Now - _lastUpdate).TotalMilliseconds <= _timerInterval )
        {
            return;
        }

        var serverUptime = DateTime.Now - Sirius.GetServer().GetServerInformation().ServerStarted;

        var days = serverUptime.Days + " day" + (serverUptime.Days != 1 ? "s" : "") + ", ";
        var hours = serverUptime.Hours + " hour" + (serverUptime.Hours != 1 ? "s" : "") + ", and ";
        var minutes = serverUptime.Minutes + " minute" + (serverUptime.Minutes != 1 ? "s" : "");
        var uptimeString = days + hours + minutes;

        Console.Title = Sirius.GetServer().GetServerInformation().ServerName + " - Uptime: " + uptimeString;

        _lastUpdate = DateTime.Now;
    }

    public void Dispose()
    {
        if (_disposing)
        {
            return;
        }

        _disposing = true;

        _serverTimer.Dispose();
        _serverTimer = null;
    }
}


texts:
I have a simple implementation for a LRU cache using LinkedHashMap.

I want it to be as generic as   possible.
This is not for production use, just practice, so I don't care
if its thoroughly robust as far as it
is correct. However, I will welcome
any comments, especially the ones
which might make this better with
simple changes :)
Are there any other ways of doing this?

class LRUCache<E> {

    @SuppressWarnings("unchecked")
    LRUCache(int size)
    {
        fCacheSize = size;

        // If the cache is to be used by multiple threads,
        // the hashMap must be wrapped with code to synchronize
        fCacheMap = Collections.synchronizedMap
        (
            //true = use access order instead of insertion order
            new LinkedHashMap<Object,E>(fCacheSize, .75F, true)
            {
                @Override
                public boolean removeEldestEntry(Map.Entry eldest)
                {
                    //when to remove the eldest entry
                    return size() > 99 ;   //size exceeded the max allowed
                }
            }
        );
    }

    public void put(Object key, E elem)
    {
        fCacheMap.put(key, elem);
    }

    public E get(Object key)
    {
        return fCacheMap.get(key);
    }

    private Map<Object,E> fCacheMap;
    private int fCacheSize;
}


texts:
The question is here.

  100 people are standing in a circle with gun in their hands. 1 kills 2, 3 kills 4, 5 kills 6 and so on till we are left with only one person. Who will be the last person alive. Write code to implement this efficiently.

Here is my Java implementation:

public static void main(String[] args) throws Exception {
    int numberOfGuys = 100;
    MyObject[] objetList = new MyObject[numberOfGuys];
    for(int i=1;i<numberOfGuys+1;i++) {
        objetList[i-1] = new MyObject(i);
    }
    boolean oneElementLeft = false;
    while(!oneElementLeft) {

        for(int i=0;i<objetList.length;i++) {
            if(i != objetList.length-1 && (i+1)%2==1) {
                objetList[i+1]=null;
            }
            if(i == objetList.length-1 && objetList[i] != null) {
                objetList[0]=null;
            }
        }
        List<MyObject> newList = new ArrayList<MyObject>();
        for (MyObject myObject:objetList) {
            if(myObject != null) {
                newList.add(myObject);
            }
        }
        objetList = new MyObject[newList.size()];
        for(int i=0;i<newList.size();i++) {
            objetList[i] = newList.get(i);
        }
        if(objetList.length==1) {
            oneElementLeft = true;
        }
    }
    System.out.println(objetList[0].getIndex());
}

I am not a math guy, so I do not really understand the clever solutions with formulas, recursion etc...

Any review or better code with explanations are welcome.


texts: Security feedback sought on Perl code running command on unsafe filename in Unix env

texts:
I'm looking for security feedback on the following fully functional code.

The code is trying to safely use the Unix 'file' command to give details about the file.

A hard link is used to create a safe filename that can be used in a command line.

The paramref is a hash read from config, and considered safe. file_base_dir is a directory with only alphanumerics in the name. The 'file' command is the standard one.

What ways could my code be exploited?

sub file_details {
    my ( $self, %arg ) = @_;
    my $filename = $arg{'filename'};
    my $paramref = $arg{'paramref'};
    my $file_cmd = '/usr/bin/file';

    my $safe_filename = $$paramref{'file_base_dir'} . "/link_to_unsafe_file_file_type_build";

    # Just in case the link exists.
    unlink($safe_filename);
    if ( not link( $filename, $safe_filename ) ) {
        confess "Failed to create link $safe_filename to $filename because $!";
    }

    my $file_type = `$file_cmd '$safe_filename'`;

    # remove the link
    unlink($safe_filename);
    $file_type =~ s/\A[^:]+://x;
    chomp $file_type;

    return $file_type;
} ## end sub file_details


texts: Looking for primes with all-different digits

texts:
I recently answered a question on Mathematics Stack Exchange, where I used a small Python program to check the following :

For all 6-digit numbers, with all digits being different, choosing the digits one by one from left to right, the second last digit can always be chosen so that the number will never be a prime.

In a nutshell, I go through all the hundreds and check for each ten if there is at least one prime number. If this is true for all the tens in the hundred, then we check if the rule of all digits are different has been violated.

There is not much complicated algorithmic involved, but I look for an elegant and fast way to do this.

Here is the code :

# -*- encoding: utf-8 -*-

from math import sqrt
from _collections import defaultdict

def is_prime(n):
"""checks primality of n"""
    if n == 2:
        return True
    if n % 2 == 0 or n <= 1:
        return False
    sqr = int(sqrt(n)) + 1
    for divisor in xrange(3, sqr, 2):
        if n % divisor == 0:
            return False
    return True

def has_primes(n):
"""checks if there are any primes in [n, n+9]
with the last digit different from the others"""
    m = n / 10
    l = [int(i) for i in str(m)]
    for i in xrange(n + 1, n + 10, 2):
        if (i % 10 not in l) and is_prime(i):
            return True
    return False

if __name__ == '__main__':
    s = 100000
    e = 1000000
    res = list()
    for h in xrange(s, e, 100):  # hundreds
        for t in xrange(h, h + 100, 10):  # tens
            if not has_primes(t):
                break
        else:  # every ten has at least one prime
            l = [int(i) for i in str(h / 100)]
            d = defaultdict(int)
            for i in l:  # counting occurrences of each digit
                d[i] += 1
            print h
            for i in d:
                if d[i] > 1:
                    print '>', i
                    break
            else:
                res.append(h)
    print '\nres :'
    for n in res:
        print n

I'd like to know how I could improve it. I'm particularly not satisfied with my testing of the doublon digits; it could maybe go only through the numbers with all-different digits. I don't know how to implement this efficiently.

If you are any other suggestions, they're very welcome. Thank you.


texts: What's a better way to decrease cardinality when serializing records

texts:
I need to transfer data from one vendor's system to another.

The source vendor has a view that generates data that combines invoice and line-item data into records w/ line-item cardinality:

"Invoice","Date","Line","Description","Price"
"A","2/1/2020","1","something","100"
"A","2/1/2020","2","something else","75"
"B","1/1/2020","1","lorem ipsum","25"
"C","12/15/2020","1","foo bar","10.25"
"C","12/15/2020","2","foo bar","99.99"

The data needs to be transmitted, however, as a unit that combines the invoice and its line items:

<I>
  <Invoice>A</Invoice>
  <Date>02/01/20</Date>
  <Items>
    <Item>
      <Line>1</Line>
      <Description>something</Description>
      <Price>100</Price>
    </Item>
    <Item>
     <Line>2</Line>
     <Description>something else</Description>
     <Price>75</Price>
    </Item>
  </Items>
</I>

Towards this end, I've written the following:

# create testing data
function Get-Data
{
    [PSCustomObject]@{
        Invoice = 'A'
        Date='2/1/2020'
        Line=1
        Description = 'something'
        Price = 100.0
    }

    [PSCustomObject]@{
        Invoice = 'A'
        Date='2/1/2020'
        Line=2
        Description = 'something else'
        Price = 75.0
    }

    [PSCustomObject]@{
        Invoice = 'B'
        Date='1/1/2020'
        Line=1
        Description = 'lorem ipsum'
        Price = 25.0
    }
    [PSCustomObject]@{
        Invoice = 'C'
        Date='12/15/2020'
        Line=1
        Description = 'foo bar'
        Price = 10.25
    }
    [PSCustomObject]@{
        Invoice = 'C'
        Date='12/15/2020'
        Line=2
        Description = 'foo bar'
        Price = 99.99
    }

}

# serialize related line items
function ConvertTo-LineItemXml {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipelineByPropertyName)]
        [int]$Line,

        [Parameter(ValueFromPipelineByPropertyName)]
        [string]$Description,

        [Parameter(ValueFromPipelineByPropertyName)]
        [decimal]$Price
    )
    begin {}
    process
    {
        $xml += "<Item><Line>$Line</Line><Description>$Description</Description><Price>$Price</Price></Item>"
    }
    end
    {
        $xml
    }
}

# convert data to required Xml message and post
function Send-Invoice {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipelineByPropertyName)]
        [string]$Invoice,

        [Parameter(ValueFromPipelineByPropertyName)]
        [datetime]$Date,

        [Parameter(ValueFromPipelineByPropertyName)]
        [pscustomobject]$Items
    )

    begin {}
    process {

        $xml = "<I><Invoice>$Invoice</Invoice><Date>$($Date.ToString('MM/dd/yy'))</Date><Items>"

        $xml += $Items | ForEach-Object {
            $_ | ConvertTo-LineItemXml
        }

        $xml += '</Items></I>'

        Invoke-WebRequest -Method Post -Uri $Uri -Body $xml -ContentType 'application/xml'
    }
    end {}
}

# controller
Get-Data |
    # group by invoice
    Group-Object {$_.Invoice} |
        # for each group
        ForEach-Object {

            # get invoice-specific information from the group's first record
            $i = $_.Group | Select-Object -First 1 Invoice, Date

            # get the line-item-specific information from the group's records
            $li = $_.Group | Select-Object Line, Description, Price

            # assign to property
            $i | Add-Member -MemberType NoteProperty -Name 'Items' -Value $li

            # return structure
            $i

        } |
Send-Invoice # format as xml and post

I should probably move ConvertTo-LineItemXml from within Send-Invoice to allow the caller to have more control over the processing.

What other improvements can I make?


texts: User Confirmation using a Userform Modeless and DoEvents

texts:
Can this be done more efficiently?

The code does the following:

Do Stuff
Show UserForm and ask user to confirm the shown data is ok
User can manipulate and controll excel as usual
As soon as user clicks the "yes" button "do some other stuff" is called

The Module

Sub ControlDataUI()
Dim Ui As New UserForm1
Dim IsConfirmed As Boolean

Debug.Print "dostuff"

Application.ScreenUpdating=True
With Ui
    .Show (0)
    While Not .IsHiden
        DoEvents
    Wend
    If .IsCancelled Then Exit Sub
    IsConfirmed = .Confirmed
End With

Debug.Print "Do some more stuff!"

If IsConfirmed Then
    Debug.Print "SaveStuff"
End If

Debug.Print "I will die!!"
End Sub

The UserForm

Private Type TView
    IsCancelled As Boolean
    Confirmed As Boolean
    IsHiden As Boolean
End Type

Private this As TView
Public Property Get IsCancelled() As Boolean
    IsCancelled = this.IsCancelled
End Property
Public Property Get Confirmed() As Boolean
    Confirmed = this.Confirmed
End Property
Public Property Get IsHiden() As Boolean
    IsHiden = this.IsHiden
End Property

Private Sub CommandButton1_Click()
Debug.Print "YES!!!!"
this.Confirmed = True
this.IsHiden = True
Me.Hide
End Sub

Private Sub CommandButton2_Click()
Debug.Print "NO?!?!"
this.Confirmed = False
this.IsHiden = True
Me.Hide
End Sub

Private Sub UserForm_Click()

End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
this.IsCancelled = True
Me.Hide
End Sub

Private Sub UserForm_Terminate()
Debug.Print "Murder! I was killed!"
End Sub

So the idea was in the right direction but the while loop had to contain a DoEvents in order to process the events comming from the user.

Summary:

1. Modeless Userform

2. While loop with DoEvents until user confirmes

This allows for the user controll of the sheet and a confirmation at any time. The code will run after the user confirms the data is ok.


texts:
Sometime ago I asked a question regarding a slow Filtering method for my DataGrid. Months later and I have a relatively quick method, though I am still looking to improve performance, especially when the user is deleting text from the SearchBox as this seems to slow down more than if the user is typing characters in.

OnTypingIntoSearchBox

private void OnSearchBoxTextChanged(object sender, TextChangedEventArgs e)
{
    ApplyFilter();
}

ApplyFilter

private void ApplyFilter()
{
    if (CurrentJobsCollectionView != null)
    {
        CurrentJobsCollectionView.Filter = FilterJobs;
    }
    UpdateJobCounter();
}

FilterJobs

    private bool FilterJobs(object o)
    {
        return FilterByCheckBox(o) && FilterByJobsSearchBox(o);
    }

FilterByJobsSearchBox

private bool FilterByJobsSearchBox(object o)
{
    try
    {
        var searchText = CharactersOnly(jobsSearchBox.Text);
        var job = o as JobModel;
        if (searchText == string.Empty)
        {
            return true;
        }
        else
        {
            if (CompanyContains(job.JobReference, searchText.ToLower()) ||
                CompanyContains(job.CaseClient, searchText.ToLower()) ||
                CompanyContains(job.JobDescription, searchText.ToLower()) ||
                CompanyContains(job.JobNotes, searchText.ToLower()) ||
                CompanyContains(job.JobID.ToString(), searchText.ToLower()))
            {
                return true;
            }
        }
        return false;
    }
    catch (System.Exception ex)
    {
        var hEs = new HandleExceptionService();
        hEs.HandleException(ex.ToString());
        return false;
    }
}

FilterByCheckBox

private bool FilterByCheckBox(object o)
{
    var today = DateTime.Today;
    criteria.Clear();

    if (yourJobsCheckBox.IsChecked == true)
    {
        criteria.Add(new Predicate<JobModel>(x => x.ITName == yourJobsCheckBox.Tag.ToString()));
    }

    if (adamJobsCheckBox.IsChecked == true)
    {
        criteria.Add(new Predicate<JobModel>(x => x.ITName == adamJobsCheckBox.Tag.ToString()));
    }

    if (chrisJobsCheckBox.IsChecked == true)
    {
        criteria.Add(new Predicate<JobModel>(x => x.ITName == chrisJobsCheckBox.Tag.ToString()));
    }

    if (danJobsCheckBox.IsChecked == true)
    {
        criteria.Add(new Predicate<JobModel>(x => x.ITName == danJobsCheckBox.Tag.ToString()));
    }

    if (emilyJobsCheckBox.IsChecked == true)
    {
        criteria.Add(new Predicate<JobModel>(x => x.ITName == emilyJobsCheckBox.Tag.ToString()));
    }

    if (kitJobsCheckBox.IsChecked == true)
    {
        criteria.Add(new Predicate<JobModel>(x => x.ITName == kitJobsCheckBox.Tag.ToString()));
    }

    if (mattJobsCheckBox.IsChecked == true)
    {
        criteria.Add(new Predicate<JobModel>(x => x.ITName == mattJobsCheckBox.Tag.ToString()));
    }

    if (unallocatedCheckBox.IsChecked == true)
    {
        criteria.Add(new Predicate<JobModel>(x => x.ITName == unallocatedCheckBox.Tag.ToString()));
    }

    if (_employees.Children.OfType<CheckBox>().All(c => Convert.ToBoolean(!c.IsChecked))) // If none are checked
    {
        currentJobsDataGrid.ItemsSource = null;
        completedJobsDataGrid.ItemsSource = null;
        archivedJobsDataGrid.ItemsSource = null;
    }

    JobModel job = o as JobModel;
    bool isIn = true;
    if (criteria.Count() == 0)
        return isIn;
    isIn = criteria.Any(x => x(job));
    return isIn;
}

I hope that isn't too much code - apologies if it is. I'm essentially looking for anyway to improve the efficiency of this filtering method, either by the user searching through typing in text or by checking specific checkboxes.


texts: Python: Combing two programs that analyze strings

texts:
I am trying to combine two programs that analyze strings into one program. The result should look at a parent string and determine if a sub-string has an exact match or a "close" match within the parent string; if it does it returns the location of this match

i.e. parent: abcdefefefef
sub cde is exact and returns 2
sub efe is exact and returns 4, 6, 8
sub deg is close and returns 3
sub z has no match and returns None

The first program I wrote locates exact matches of a sub-string within a parent string:

import string

def subStringMatchExact():
    print "This program will index the locations a given sequence"
    print "occurs within a larger sequence"
    seq = raw_input("Please input a sequence to search within: ")
    sub = raw_input("Please input a sequence to search for: ")
    n = 0
        for i in range(0,len(seq)):
        x = string.find(seq, sub, n, len(seq))
        if x == -1:
            break
        print x
        n = x + 1

The second analyzes whether or not there is an close match within a parent string and returns True if there is, and false if there isn't. Again a close match is an exact match or one that differs by only one character.

import string

def similarstrings():
    print "This program will determine whether two strings differ"
    print "by more than one character. It will return True when they"
    print "are the same or differ by one character; otherwise it will"
    print "return False"
    str1 = raw_input("Enter first string:")
    str2 = raw_input("Enter second string:")
    x = 0
    for i in range(len(str1)):
        if str1[i] == str2[i]:
            x = x + 1
        else:
            x = x
    if x >= len(str1) - 1:
        print True
    else:
        print False

Any suggestions on how to combine the two would be much appreciated.


texts: Simple but (hopefully) safe C nodes for data structures

texts:
Nodes will be for simply linked lists, circular lists, maybe later on extending them to work with graphs. I'm trying to be as defensive as possible, will this leak memory? It runs perfectly I'm just concerned about coding style and best practices. Especially regarding the allocation I'm not 100% convinced of my solution. Is it okay to allocate memory for the next component inside the constructor?

// I would have preferred to declare the typedef together with the struct,
// but this doesn't work.
typedef struct node Node;

struct node {
    int value;
    Node *next;
};

Node *create_node(int value) {

    Node *result = malloc(sizeof(Node));
    // How necessary are these checks? Under which circumstances
    // could this return NULL?
    if (result == NULL) {
        return NULL;
    }

    result->next = malloc(sizeof(Node));
    if (result->next == NULL) {
        free(result);
        return NULL;
    }

    result->value = value;

    return result;
}

void destroy_node(Node *node) {
    if (node != NULL) {
        //This seems necessary. Or is it not? Could I delete the parent
        // node and keep the children alive?
        destroy_node(node->next);
        free(node);
    }
}

int main() {

    Node *first = create_node(42);
    printf("%d\n", first->value);

    Node *second = create_node(45);
    first->next = second;
    printf("%d\n", first->next->value);

    destroy_node(first);

    return 0;
}


texts:
I want to make a graph from input from a text file in the format:

vertex1 vertex2 cost time

where vertex1 and vertex2 are strings that form an edge and cost and time are the properties of that edge. This information will be used to construct the Graph based on cost. I want to plan out the project before coding it so I have a good idea of what to do. So far I decided on the following classes:

class Edge {
private:
  int vertex1;
  int vertex1;
  int cost;
  int time;

public:
  Edge(int v1, int v2, int cost, int time) {
    this->vertex1 = v1;
    this->vertex2 = v2;
    this->cost = cost;
    this->time = time;
  }

  ~Edge();

  int getEdgeCost();

  int getEdgeTime();
};

class Graph {
private:
  vector<Edges> edge; //edges in graph

public:
  Graph() : edge(0) {}

  ~Graph(){}

  int getTotalCost();

  int getTotalTime();

  void addEdge(Edge e);

  Graph getMinSpanTree();
};

class Vertex {
private:
  string name;
  int number;
  bool visited;
  vector<Edges> connEdges;  // vector of all edges connected to this vertex

public:
  Vertex(string name, int number) {
    this->name = name;
    this->number = number;
    visited = true;
  }

  ~Vertex();

  string getName();

  int getNum();

  bool wasVisited();

  Graph getShortestPath();
};

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

  std::string ifileName = std::string(argv[1]);

  ifstream ifile;
  if(ifile)
    ifile.open(ifileName);

  Edge edge;
  Graph* p_graph;
  Vertex v;

  string vert1, vert2;
  int cost, time;

  int i = 1; // numbers each vertex

  while(ifile.good()) {
  // read in input, put it in vars above, skipped for brevity

  // make the vertices
  v1 = new Vertex(vert1, i);
  i++; // increments vertex number
  v2 = new Vertex(vert2, i);
  i++;

  // make the edge
  edge = new Edge(v1.getNum(), v2.getNum(), cost, time);

  // add it to graph
  p_graph->addEdge(edge);

}

Is my design correct or is it lacking something? Can it be improved?


texts: Avoid while(true) in task scheduling code

texts:
I am writing a task scheduler (that will one day grow up to be a windows service when I look into them) that should pretty much loop infinitely until I tell the program to stop. But having while(true) seems incorrect. What is the correct way to implement the loop? Use a dummy boolean variable that the code doesn't actually set to false ever (or should it set to false in a catch whose try encompasses the whole inside of the loop?)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataPump
{
    class TaskManager
    {
        // Tasks added externally on an instance of TaskManager
        public Dictionary<DatapumpTask, Task> Tasks = new Dictionary<DatapumpTask, Task>();

        public void Go()
        {
            Func<Task, bool> isBusy = task => task.Status == TaskStatus.Running ||
                                              task.Status == TaskStatus.WaitingToRun ||
                                              task.Status == TaskStatus.WaitingForActivation;

            //Run Loop  --- To Do move off the main thread
            while (true)
            {
                for (int t = 0; t < Tasks.Count; t++)
                {
                    KeyValuePair<DatapumpTask, Task> task = Tasks.ElementAt(t);

                    if (task.Key.NextRun < DateTime.Now && (task.Value == null || !isBusy(task.Value)))
                    {
                        Tasks[task.Key] = Task.Factory.StartNew(() => task.Key.Run());
                    }

                    if (task.Value != null && task.Value.IsFaulted)
                    {
                        task.Key.Log("Task faulted - something is wrong!" , LogType.Error);
                        Tasks[task.Key] = null;
                    }
                }
            }
        }

    }

Note DatapumpTask has a public void Run() method, a public void Log() method that logs to a text file and Run() will set its DateTime NextRun property correctly...


texts:
Project Euler #4 asks:

  Find the largest palindrome made from the product of two 3-digit numbers.

The code is as follows:

module Main where

import Data.List (sortBy)
import Data.Ord (comparing)

palindromes :: [Integer]
palindromes = [calcPalindrome a b c | a <- [1..9], b <- [0..9], c <- [0..9]]
    where
        calcPalindrome a b c = 100001 * a + 10010 * b + 1100 * c

is3Digit :: Integer -> Bool
is3Digit n = n >= 100 && n <= 999

isDiv :: Integer -> Integer -> Bool
isDiv n d = n `mod` d == 0

-- returns all multiples of 2 3-digit numbers
-- for palindromes
isMultiple :: Integer -> Bool
isMultiple n = not $ null threeMultiples
    where
        multiples :: [(Integer, Integer)]
        multiples = do
            d <- [10..99]
            if n `isDiv` (d * 11)
            then return (d * 11, n `div` (d * 11))
            else []
        threeMultiples :: [(Integer, Integer)]
        threeMultiples = filter (\ (m, n) -> is3Digit m && is3Digit n) multiples

problem4 :: Integer -> Integer
problem4 n =
    head $ filter isMultiple $ sortBy (flip compare) $ filter (< n) palindromes

main :: IO ()
main = do
    _ <- getLine
    contents <- getContents
    let cases = map read $ lines contents
    let results = map problem4 cases
    mapM_ print results

I'd appreciate comments on isMultiple and problem4 as they seem rather messy. Any other general comments are welcome too.


texts: Is this a good way to construct the class for a C++ template partial specialisation of a member function?

texts:
I am teaching myself c++ by doing a series of exercises.
I liked the idea of working out how hash tables could be done using just the language
and no std calls. I discovered that you cant do
"class member function partial template specialisation" and so worked on options for
how this would be achieved.
The code below is a stripped down version of the useful parts of a hash table.
Leaving just enough to show the structure of what is needed.
Is there a better way to construct the class - IE a better idiom to solve partial specialisation?
I have tried full class specialisation and struct partial template specialisation
but this seems the best so far.
I would be interested in comments about other ways to call the members and fuctions.
I have thought of:

A 'using' line for all the members/function in the fuctions.
One 'using' line to create a typedef that can be used as the prefix.
Putting the full cast at each use.

#include "stdio.h"

template <typename K, typename H>
class hash_table_common {
public:
    H& hash_type()                          // Standard CRTP helper function
    {
        return static_cast<H&>(*this);
    }
    int& operator[](K key)
    {
        return hash_type().get_value(key);
    }
    size_t hash(int key)
    {
        return key % 10;
    }
    int m_storage[10]{ 0 };
};

template <typename K>
class hash_table : public hash_table_common<K, hash_table<K>> {
public:
    class hash_table_common<K, hash_table<K>>& hash_type()
    {
        return static_cast<hash_table_common<K, hash_table<K>>&>(*this);
    }
    int& get_value(K key)
    {
        int hashable = 3; // value_to_int(); Real code will go here, for this demo it works for one value!
        int index1 = hash_type().hash(hashable);
        return hash_type().m_storage[index1];
    }
};

template <>
class hash_table<const char*> : public hash_table_common<const char*, hash_table<const char*>> {
public:
    class hash_table_common<const char*, hash_table<const char*>>& hash_type()
    {
        return static_cast<hash_table_common<const char*, hash_table<const char*>>&>(*this);
    }
    int& get_value(const char* key)
    {
        int hash_as_int = (int)key[0];
        int index = hash_type().hash(hash_as_int);
        return hash_type().m_storage[index];
    }
};
#endif

int main() {
    class hash_table<const char*> a;
    class hash_table<float> b;
    a["word"] = 3;
    b[4.5f] = 14;
    printf("%d %d", a["word"], b[4.5f]);
    return 0;
}


texts:
I rarely write multithreaded code, and am on shaky ground when doing so.  I make mistakes.  I would like a sanity check of something I am going to introduce in one of my apps.

There will be exactly one running instance of the Thread class below in my application.  (It will be stored in a servlet context attribute.)  "Clients" will call one of three methods on the instance, getRunList() to get data from it, signalFreshRunListCreation() to tell the thread to generate new data, and stopThread() to signal the thread to exit.  On its own, the thread creates new data every 30 seconds.

Have I made any errors?

public class ThreadRunListDefault extends Thread {

    // This set to true signals that the thread should exit.
    private boolean _boStop = false;
    // The thread sets this to true just before it sleeps.
    private boolean _boIsSleeping = false;
    // An external client sets this to true to signal that a new run list should  be created.
    private boolean _boFreshRunListRequested = false;
    // This is a mutex to lock the run list while a fresh one is being created.
    private Object _lockRunList = new Object();
    // This is the actual data that will be returned.
    private List<BeanRunOutput> _runList;
    // This is the time the thread will sleep between refreshing the data on its own
    private long _iSleepMilliseconds = 30000;

    @Override
    public void run() {

        // Loop as long as no client has indicated the thread should stop.
        while (!_boStop) {
            // Create the data.
            this.createFreshRunList();

            // Only sleep if a refresh of the data wasn't requested while we were
            // creating a fresh run list.
            if (!_boFreshRunListRequested) {
                try {
                    // We set the sleeping flag to true so that signalFreshRunListCreation() will
                    // know whether or not to call interrupt() on the thread and wake it up.
                    _boIsSleeping = true;
                    Thread.sleep(_iSleepMilliseconds);
                } catch (InterruptedException e) { }
                _boIsSleeping = false;
            }
        }
    }

    /*
     * This is the method that will be called by run() to create new data in the _runList member variable.
     */
    private void createFreshRunList() {
        synchronized(this._lockRunList) {
            // Here we put the code that creates the run list.
            // Typically it will take 5 to 10 seconds.
            _runList = new ArrayList<BeanRunOutput>();
        }
    }

    /*
     * This is the method a client will call to get the data in _runList.
     */
    public List<BeanRunOutput> getRunList() {
        synchronized(this._lockRunList) {
            return _runList;
        }
    }

    /*
     * This is the method a client will call to signal the thread that a new run list should be created.
     * If run() is currently gathering data (_boIsSleeping is false), a flag will be set to tell run()
     * to run again immediately after it is finished, without sleeping first.  If the thread is currently
     * sleeping, it will be interrupted.
     */
    public void signalFreshRunListCreation() {
        if (_boIsSleeping) {
            // Thread is sleeping so interrupt it.
            this.interrupt();
        } else {
            // The thread is running so signal it should just run again when
            // complete (in other words not sleep).
            _boFreshRunListRequested = true;
        }
    }

    /*
     * This method allows a client to signal the thread to exit.
    */
    public void stopThread() {
        _boStop = true;
    }
}


texts: PHP creating username with random number

texts:
Trying to complete an add user script. Nothing out of the ordinary, however I have transitioned over to using prepared statements, and I am trying to get better at creating my own functions.

<?php
include("../include/sessions.php");

if(isset($_POST['criteria']))
{
  $value = $_POST['criteria'];
  $firstname = htmlspecialchars(trim($value['firstname']));
  $lastname = htmlspecialchars(trim($value['lastname']));
  // few more

  // set blank variable to be passed into function
  $dbusername = '';

  // pass necessary variables into the function
  // $dbc is the database connection needed for the prepared statement
  function createUsername($firstname, $lastname, $dbusername, $dbc)
  {
    // check if $user ever matches $dbusername, if so, rerun loop
    while($user == $dbusername)
    {
      $digits = 4;
      $randomNumber = rand(pow(10, $digits-1), pow(10, $digits)-1);
      // get first 3 letters of firstname
      $first3 = substr($firstname, 0, 3);
      // get first 3 letters of lastname
      $last3 = substr($lastname, 0, 3);
      // set user to $first3, $last3, and $randomNumber
      $user = $first3 . '' . $last3 . '' . $randomNumber;

      // prepare statement
      $select = "SELECT username FROM users WHERE username = ?;";
      $stmt = $dbc->prepare($select);

      // pass in the new $user
      $stmt->bind_param("s", $user);
      $stmt->execute();
      $result = $stmt->get_result();
      $row = $result->fetch_assoc();

      // if the created user happens to exist in the database, set it to $dbusername
      $dbusername = $row['username'];
      // rerun the loop if this happens
    }
    // if no matches, return the new username
    return $user;
  }
}

$user = createUsername($firstname, $lastname, $dbusername, $dbc);

echo 'username is ' . $user; // username should look like this: johbea3647
?>

I tried to notate the code as much as possible. But just in case, I'll break it down here...

The idea is to take create a brand new username that begins with the first 3 letters of the first and last name, then add a random 4 digit number to the end.

Hopefully, as long as the seemingly random username does not exist in the database, then return the new username. However, in the event the random username happens to exist, then run the loop again until there is no match.

I hope this all makes sense. Please review my code and see if there are any problems, or if there is a way to possibly simplify it all.

So far, everything seems to work. I'm just not too sure about that while loop.


texts:
I'm sick of writing negative code statements like String.IsNullOrEmpty(value) and so I'm writing a function that checks for availability. It should answer the question, "Is this value usable?" without validating the data.

This function has been exceptionally difficult to write but I have a solution I feel comfortable with using. I'm hoping someone can poke holes in it and give me constructive feedback.

public static bool IsAvailable<T>(T value)
{
    if (value == null)
        return false;

    var type = typeof(T);
    if (type.IsValueType)
        return true;

    if (typeof(IEnumerable).IsAssignableFrom(type))
    {
        var enumerator = (value as IEnumerable).Cast<object>();
        return enumerator.Any(a => IsAvailable(a));
    }

    var valueString = Convert.ToString(value);
    return !String.IsNullOrWhiteSpace(valueString);
}


texts: Machine independent C library for printing the binary representation of data types to stdout

texts:
I'm curious as to peoples thoughts on this small library I have made. I noticed there are no functions in the C standard library to accomplish this task.

I have tried to make the code machine independent. If anyone has access to machines where short != 2 byte, int != 4 byte, long != 8 byte or where bytes themselves are not 8 bits. I would be curious as to the test results.

GitHub

The current functions for printing the binary representations are all slight modifications of the below:

#include <limits.h>
#include <stdio.h>

void printcb(char n)
{
    int i;
    int type_bits = CHAR_BIT;
    int mask = 1 << type_bits - 1;

    for (i = 0; i < type_bits; ++i) {
        if (n & mask)
            putc('1', stdout);
        else
            putc('0', stdout);
        n <<= 1;
    }
    putc('\n', stdout);
}


texts: Repeatedly fetching a URL until the response contains "state: INIT"

texts:
I am working on a project in which I need to make a URL call to one of my servers from a bash shell script.

 http://hostname.domain.com:8080/beat

After hitting the above URL, I will be getting the below response, from which I need to parse and extract the value of state:

num_retries_allowed: 3 count: 30 count_behind: 100 state: INIT num_rounds: 60 hour_col: 2 day_col: 0

Now I will keep on hitting the above URL every 10 seconds until the value of the state variable is equal to INIT:

state = INIT

If the state is equal to INIT then I will exit successfully out of the shell script, otherwise I will keep on trying until the state becomes INIT.

Also, if the state: string is missing in the $DATA variable by any chance, then I want to assign 0 to the state variable. So if state is equal to 0, then I will also exit out of the shell script successfully.

I am hitting the above URL and checking whether I got a successful response or not. If I got a successful response, then I am breaking out (which means server is running fine), but if I didn't got successful response, then I am checking whether my server is running or not on port 8080. If it is not running, then I will start the server. And I am retrying this for a period of 15 times, and after 15 tries if the server hasn't come back up, then exit out of the shell script with a non-zero status code.

Is the below shell script correct?

#!/bin/bash

HOSTNAME=$hostname
DATA=""
RETRY=15

echo $HOSTNAME

sleep 1m

while true; do

    while [ $RETRY -gt 0 ]
    do
        DATA=$(wget -O - -q -t 1 http://$HOSTNAME:8080/beat)
        if [ $? -eq 0 ]
        then
            break
        else
            if lsof -Pi :8080 -sTCP:LISTEN -t >/dev/null ;
            then
                echo "Server is running"
            else
                echo "Server is not running so re-starting the server here"
                # starting server here
            fi
            let RETRY-=1
            sleep 30
        fi
    done

    if [ $RETRY -eq 0 ]
    then
        echo "Server is still down. Exiting out now." >&2
        exit 2
    fi

    echo "Server is up. Now parsing the data out of the beat."

    #grep $DATA for state
    state=$(grep -oP 'state: \K\S+' <<< "$DATA")
    [[ -z "$state" ]] && state=0

    echo $state

    #verify the condiitons
    if [[ $state -eq "INIT" || $state -eq "0" ]]; then exit 0; fi

    #wait another 10 seconds
    sleep 10

done

Is there any better way of doing this if I am doing anything wrong?


texts: Find-grep-sed for project-wide search & replace

texts:
I always forget how to do this efficiently with Vim's arglist. Drawing inspiration from a post over at Stack Overflow, I wrote a Bash function to perform a project-wide search & replace.

It does the following:

find files matching a file-pattern
narrow down to those files containing a search-pattern
within those files, replace all occurrences of the search-pattern

Example usage: greplace **.rb old_method new_method

greplace() {
  if [ "${#}" != 3 ]; then
    echo "Usage: greplace file_pattern search_pattern replacement"
    return 1
  else
    file_pattern=$1
    search_pattern=$2
    replacement=$3

    find . -name "${file_pattern}" |
    xargs grep -rwl "${search_pattern}" |
    xargs sed -i '' "s/[[:<:]]${search_pattern}[[:>:]]/${replacement}/g"
  fi
}

I'm on OSX, so unfortunately I had to use the ugly (and I assume non-portable) [[:<:]] word-boundaries for sed. I tried \b and \<, with and without -E (for extended regular expressions), but still no dice.

I also debated whether to bake the word-boundaries in or leave them up to the caller (my poor little fingers). But I can't imagine wanting use this without word boundaries. I'd much rather miss a replacement because it's a variation on the search term than accidentally mangle a word happens to contain the search term.

Another potential issue is the fact that I'm using sed -i '' to perform the in-place replacements without making any backup files. This seems fine for my use, since I'm invariably using Git for version control. I'm curious how big a risk this is though.

Update Props to janos for his pointers and improvements. Here's an updated version:

greplace() {
  if [ "$#" != 3 ]; then
    echo "Usage: greplace file_pattern search_pattern replacement"
    return 1
  else
    file_pattern=$1
    search_pattern=$2
    replacement=$3

    # This works with BSD grep and the sed bundled with OS X.
    # GNU grep takes `-Z` instead of `--null`.
    # Other versions of sed may not support the `-i ''` syntax.

    find . -name "$file_pattern" -exec grep -lw --null "$search_pattern" {} + |
    xargs -0 sed -i '' "s/[[:<:]]$search_pattern[[:>:]]/$replacement/g"
  fi
}


texts:
Here is problem:
There is string (domain) divided by dots (like www.part1.partN.com)
Need to build reversed by dot string (like com.partN.part1.www)
Both strings are utf-8 encoded

My solution:

std::string reverseHost(const std::string& host)
{
    std::string ret;
    ret.reserve(host.size());

    size_t tail = host.size();
    size_t head = host.find_last_of('.');

    while (head != std::string::npos)
    {
        ret.append(host.c_str() + head + 1, tail - head - 1);
        ret += '.';

        tail = head;
        head = host.find_last_of('.', tail - 1);
    }

    ret.append(host.c_str(), tail);

    return ret;
}

Need to improve speed (or advice how to improve), raw memory and other tricks allowed. ty.


texts: Obtaining prediction bands for regression model

texts:
I'm trying to generate prediction bands for an exponential fit to some 2-dimensional data (available here).

The data (blue points), best fit found by scipy.optimize.curve_fit (red curve), and lower & upper 95% prediction bands (green curves) can be seen in the image below.

I'd love some confirmation that the code is actually doing things correctly and I haven't missed some step or simply used the wrong statistical tools.

The references I used are basically this post, and this video, both adapted to work with a general function, rather than being hardcoded to work with a linear function of the form \$y = a*x+b\$.

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import stats

def make_plot(x, xd, yd, popt, upb, lpb):
    # Plot data.
    plt.scatter(xd, yd)
    # Plot best fit curve.
    plt.plot(x, func(x, *popt), c='r')
    # Prediction band (upper)
    plt.plot(x, upb, c='g')
    # Prediction band (lower)
    plt.plot(x, lpb, c='g')
    plt.show()

def func(x, a, b, c):
    '''Exponential 3-param function.'''
    return a * np.exp(b * x) + c

def predband(x, xd, yd, f_vars, conf=0.95):
    """
    Code adapted from Rodrigo Nemmen's post:
    http://astropython.blogspot.com.ar/2011/12/calculating-prediction-band-
    of-linear.html

    Calculates the prediction band of the regression model at the
    desired confidence level.

    Clarification of the difference between confidence and prediction bands:

    "The prediction bands are further from the best-fit line than the
    confidence bands, a lot further if you have many data points. The 95%
    prediction band is the area in which you expect 95% of all data points
    to fall. In contrast, the 95% confidence band is the area that has a
    95% chance of containing the true regression line."
    (from http://www.graphpad.com/guides/prism/6/curve-fitting/index.htm?
    reg_graphing_tips_linear_regressio.htm)

    Arguments:
    - x: array with x values to calculate the confidence band.
    - xd, yd: data arrays.
    - a, b, c: linear fit parameters.
    - conf: desired confidence level, by default 0.95 (2 sigma)

    References:
    1. http://www.JerryDallal.com/LHSP/slr.htm, Introduction to Simple Linear
    Regression, Gerard E. Dallal, Ph.D.
    """

    alpha = 1. - conf    # Significance
    N = xd.size          # data sample size
    var_n = len(f_vars)  # Number of variables used by the fitted function.

    # Quantile of Student's t distribution for p=(1 - alpha/2)
    q = stats.t.ppf(1. - alpha / 2., N - var_n)

    # Std. deviation of an individual measurement (Bevington, eq. 6.15)
    se = np.sqrt(1. / (N - var_n) * np.sum((yd - func(xd, *f_vars)) ** 2))

    # Auxiliary definitions
    sx = (x - xd.mean()) ** 2
    sxd = np.sum((xd - xd.mean()) ** 2)

    # Predicted values (best-fit model)
    yp = func(x, *f_vars)
    # Prediction band
    dy = q * se * np.sqrt(1. + (1. / N) + (sx / sxd))

    # Upper & lower prediction bands.
    lpb, upb = yp - dy, yp + dy

    return lpb, upb

# Read data from file.
xd, yd = np.loadtxt('exponential_data.dat', unpack=True)

# Find best fit of data with 3-parameters exponential function.
popt, pcov = curve_fit(func, xd, yd)

# Generate equi-spaced x values.
x = np.linspace(xd.min(), xd.max(), 100)

# Call function to generate lower an upper prediction bands.
lpb, upb = predband(x, xd, yd, popt, conf=0.95)

# Plot.
make_plot(x, xd, yd, popt, upb, lpb)


texts: Python Code for List of Month Names starting with current month

texts:
I am looking for a cleaner, more pythonic way to get a list of the name of the months starting with the current month and ending 12 months later.

For example, it's December so my list should be

['Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov']

Here is how I'm currently doing it:

from datetime import datetime

currentMonth = datetime.now().month

if (currentMonth == 1):
    theList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
elif (currentMonth == 2):
    theList = ['Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan']
elif (currentMonth == 3):
    theList = ['Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb']
elif (currentMonth == 4):
    theList = ['Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar']
elif (currentMonth == 5):
    theList = ['May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr']
elif (currentMonth == 6):
    theList = ['Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May']
elif (currentMonth == 7):
    theList = ['Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
elif (currentMonth == 8):
    theList = ['Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul']
elif (currentMonth == 9):
    theList = ['Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug']
elif (currentMonth == 10):
    theList = ['Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep']
elif (currentMonth == 11):
    theList = ['Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct']
elif (currentMonth == 12):
    theList = ['Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov']

print(theList)

Ideas?


texts: Finding pairs of numbers within A that add up to N

texts:
I am working on an interview question from Amazon Software Interview:

  Given an integer N and an array of unsorted integers A find all pairs of numbers within A which add up to N

I have a working solution in Java:

static void allPairsAddToN(int[] array, int n) {
    for(int c=0;c<array.length; c ++) {
        for(int j=c+1; j<array.length; j++) {
            if(array[c] + array[j] == n)
                System.out.println("(" + array[c] +", " + array[j] +")" );
        }
    }
}

Is this the most efficient solution? To me, this is the brute force approach that runs in \$O(n^2)\$. But for this problem, wouldn't you have to try every possibility (unsorted)? Is there some trick where you don't?


texts:
the Encoding scheme is given below:

  Don't replace the characters in the even places. Replace the characters in the odd places by their place numbers . and if they exceed 'z', then again they will start from 'a'.

  example: for a message "hello" would be "ieolt" and for message "maya" would be "naba"

  how many lines of code [minimum] do we have to write in order to encode a lengthy string in python in the above format.?

mycode is given below:

def encode(msg):
    encoded_message = ""
    letters = "abcdefghijklmnopqrstuvwxyz"
    index_of_msg = 0
    for char in msg.lower():
        if char.isalpha():
            if index_of_msg%2 == 0 :
                encoded_message += letters[((letters.rfind(char) )+ (index_of_msg+1))%26]  # changed msg.rfind(char) to index_of_msg
            else:
                encoded_message += char
        else:
            encoded_message += char
        index_of_msg +=1
    return encoded_message


texts: Ensure that all `h2` tags have a `span` inserted

texts:
I'm running these on page load to ensure that all h2 tags have a span inserted (it's a large WordPress site that needs to have this done to get the right styles)

$('.bottomLine').each(function() {
    $(this).insertAfter($(this).parent().find('.price'));
});
$('.prod-desc > h2').each(function() {
    $(this).wrapInner('');
})
$('h2.review_text').each(function() {
    $(this).wrapInner('');
})
$('.related > h2').each(function() {
    $(this).wrapInner('');
})
$('.up-sells > h2').each(function() {
    $(this).wrapInner('');
})

EDIT

I'm kinda getting the message that this is a bad idea so I will expand upon why I think I need to.

I need to create this out of h2 tags.

Which I currently make using:

  Join us on instgram

and SCSS

.seporator {
  text-align: center;
  text-transform: uppercase;
  padding: 40px 40px 46px;
  width: 100%;

  span {
    padding-bottom: 10px;
    border-bottom: 1px solid $red;
    line-height: 48px;
    margin-bottom: 10px;
  }
}

Throughout the WordPress site I see that the previous theme has been using a CSS hook to style h2 elements within the page as breaks. Therefore when I perform the insertion of a  and add h2 to my scss I get the design.

  h2 {
    @extend .seporator;
    font-size: 1.5rem;
  }

If this underlined, correctly spaced design can be achieved using purely h2 tags then I would love to hear about it.


texts:
This is my implementation of 1024bit(can be changed) RSA. Is there anything I'm doing wrong?

public class Rsa:IEncryption
{
    public AsymmetricCipherKeyPair Keys { get;private set; }

    private readonly Pkcs1Encoding _engine;

    public Rsa()
    {
        Keys = GenerateKeys();
        _engine = new Pkcs1Encoding(new RsaEngine());
    }

    public byte[] Encrypt(byte[] buffer)
    {
        return Encrypt(buffer, 0, buffer.Length);
    }

    public byte[] Decrypt(byte[] buffer)
    {
        return Decrypt(buffer, 0, buffer.Length);
    }

    public byte[] Encrypt(byte[] buffer, int offSet, int length)
    {
        return RsaProcessor(buffer, offSet, length, Keys.Public);
    }

    public byte[] Decrypt(byte[] buffer, int offSet, int length)
    {
        return RsaProcessor(buffer, offSet, length,Keys.Private);
    }

    private byte[] RsaProcessor(byte[] data,int offset,int length, AsymmetricKeyParameter key)
    {
        _engine.Init(!key.IsPrivate, key);

        var blockSize = _engine.GetInputBlockSize();

        var result = new List<byte>();
        for (var i = offset; i < offset+length; i += blockSize)
        {
            var currentSize = Math.Min(blockSize, offset + length - i);
            result.AddRange(_engine.ProcessBlock(data, i, currentSize));
        }
        return result.ToArray();
    }

    public static AsymmetricCipherKeyPair GenerateKeys()
    {
        var rsaKeyParams = new RsaKeyGenerationParameters(BigInteger.ProbablePrime(512, new Random()),
                                                          new SecureRandom(), 1024, 25); //Unsure about the certinaty parameter
        var keyGen = new RsaKeyPairGenerator();
        keyGen.Init(rsaKeyParams);

        return keyGen.GenerateKeyPair();
    }
}


texts:
I recently submitted an implementation of a singly linked list and tried to apply some of the suggestions on this implementation. I decided not to implement the List interface as I only wanted to practice what I believed to be the most important methods. I'm wondering how I could tidy this up some more and improve upon it.

Singly Linked List: Java Singly Linked List Implementation

DoublyLinkedList.java

public class DoublyLinkedList<T> {

    private class Node {

        private T data;
        Node next, prev;

        public Node() {
        }

        public Node(T data) {
            this.data = data;
        }
    }

    private Node head, last;
    private int size;

    public DoublyLinkedList() {
        this.size = 0;
    }

    public void addToBeginning(T data) {
        Node temp = new Node(data);
        if (head == null) {
            head = temp;
            last = head;
        } else {
            temp.next = head;
            head.prev = temp;
            head = temp;
        }
        size++;
    }

    public void add(T data) {
        Node temp = new Node(data);
        if (head == null) {
            head = temp;
            last = head;
        } else {
            last.next = temp;
            temp.prev = last;
            last = temp;
        }
        size++;
    }

    public void add(T data, int index) {
        Node temp = new Node(data);
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException();
        } else if (index == 0) {
            addToBeginning(data);
        } else if (index == size) {
            add(data);
        } else {
            Node current = head;
            for (int i = 0; i < index; i++) {
                current = current.next;
            }
            Node previous = current.prev;
            previous.next = temp;
            temp.prev = previous;
            temp.next = current;
            current.prev = temp;
            size++;
        }
    }

    public T get(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException();
        } else {
            Node current = head;
            for (int i = 0; i < index; i++) {
                current = current.next;
            }
            return current.data;
        }
    }

    public void delete(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException();
        } else if (index == 0) {
            head = head.next;
            head.prev = null;
            size--;
        } else if (index == size - 1) {
            last = last.prev;
            last.next = null;
            size--;
        } else {
            Node current = head;
            for (int i = 0; i < index; i++) {
                current = current.next;
            }
            Node previous = current.prev;
            Node next = current.next;
            previous.next = current.next;
            next.prev = previous;
            size--;
        }
    }

    public int getSize() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }
}


texts:
We all know that math notation is idiosyncratic. Canonical representation of math objects often have irregular grammar rules to improve readability. For example we write a polynomial \$3x^3 + x^2\$ instead of more uniform but more verbose \$3x^3 + 1x^2 + 0x^1 + 0x^0\$. When a coefficient equals 0, you don't write the term, if the power equals \$1\$, you simply write \$x\$, and so on. So I wrote a simple program that outputs a string representation of a polynomial, given a list of coefficients:

def enumerate2(xs, start=0, step=1):
    for x in xs:
        yield (start, x)
        start += step

def poly(xs):
    """Return string representation of a polynomial.

    >>> poly([2,1,0])
    "2x^2 + x"
    """
    res = []
    for e, x in enumerate2(xs, len(xs)-1, -1):

        variable = 'x'

        if x == 1:
            coefficient = ''
        elif x == -1:
            coefficient = '-'
        else:
            coefficient = str(x)

        if e == 1:
            power = ''
        elif e == 0:
            power = ''
            variable = ''
        else:
            power = '^' + str(e)

        if x < 0:
            coefficient = '(' + coefficient
            power = power + ')'

        if x != 0:
            res.append(coefficient + variable + power)

    return ' + '.join(res)

enumerate2 is a custom version of enumerate that supports variable step. The result looks like this:

>>> poly([2,0,3,-4,-3,2,0,1,10])
'2x^8 + 3x^6 + (-4x^5) + (-3x^4) + 2x^3 + x + 10'

How do I make this code more elegant and probably more generic? Oh, and the result is sub-optimal, as negative terms are enclosed in brackets, instead of changing the preceding plus sign to minus.


texts: Does the class have unnecessary and violating Single responsibility principle method?

texts:
I encountered with the following code in the work. The MyItemCoordinator should receive MyItem objects, process them, add them to MyItemList collection and then pass them to the listeners.

My questions are:

When I saw NewMyItem method I thought that MyItemCoordinator is a factory but when I saw NewMyItem's implementation I found out that it creates, sorts, calling to listeners and it's not static. So MyItemCoordinator is not a factory and NewMyItem method does way more things that it should to do according to its name, right?
If it's not a factory so why NewMyItem method receives so many params, creates an object, adds to the collection? Why not to do:

example:

var coordinator = new MyItemCoordinator();
var myItem = new MyItem(...PARAMS..)
coordinator.AddMyItemToList(myItem)

Inside AddMyItemToList we can sort and call the listeners. This is more clear way to do, isn't it?
So, is this implementation correct? Doesn't it have something wrong?

public class MyItemCoordinator
{
    ...

    public IList<MyItem> MyItemList = new List<MyItem>();

    public void NewMyItem(int id, ...15_MORE_PARAMS)
    {
        MyItem myItem = new MyItem(id,...ONLY_5_PARAMS_WITHIN_15_ARE_USED);
        AddMyItemToList(myItem);
        SortMyItemList();
        if (MyItemDetectedHandler != null)
            MyItemDetectedHandler(this);
    }

    public void AddMyItemToList(MyItem myItem)
    {
        //makes some checking and adds myItem to MyItemList
    }

    ...
}


texts:
Which of these three methods is better?

import java.util.* ;
public class anycode{

  public static void print_digits3(int num){
    //this method converts integer to string and parses it
    int digit = 0 ;
    String num_str = new Integer(num).toString() ;
    int counter = 0  ;
    while(counter != num_str.length()){
       System.out.println("digit: " + num_str.charAt(counter)  + "| real integer digit: " + Integer.parseInt(num_str.substring(counter,counter+1))) ;
      counter++ ;
    }

  }

  public static void print_digits4(int num){
    //this method converts integer to array of chars and parses it
     char[]num_sequence_of_chars = new Integer(num).toString().toCharArray() ;
     for(int i = 0 ; i < num_sequence_of_chars.length ; i++){
       System.out.println("digit :" + num_sequence_of_chars[i] ) ;
     }
  }
  public static void print_digits2(int num){
    //this is the MATH method of parsing number - take every first digit div by
    // 1000,100,10,1 and update num - num% to get the rest

    //it s clunky, hard to read
    int digit = 0 ;

    Integer res_int = new Integer(num) ;

    int num_len = res_int.toString().length();// need to know if the number is 3-digit,4-digit etc
    //so we can know the power of 10 - 10^3, 10^2, 10^1 etc
    System.out.println("len of num : " + num_len) ;
    num_len-- ;
    double base = 0 ;
    int temp ;
    while( num_len >= 0){
      temp = num ;
      base = Math.pow(10,num_len) ;
      num = num / (int)base ;// type recasting to int is a must, it does not work without it - no idea why
      System.out.println("num :"  + num) ;
      num = (int) temp % (int)base ;
      num_len-- ;
  }

  }
  public static void print_digits(int num){
    int digit = 0 ;
    while(num != 0 ){
    digit = num%10 ;
    System.out.print(digit + "\t") ;
      num = num/ 10 ;
    }
  }

  public static void main(String args[]){
              print_digits2(7658) ;
              System.out.println("--------------------------") ;
              print_digits3(7658) ;
  }

}

How can I rewrite the print_digits2?  I want a more efficient MATH method of doing - no converting to string \ char[].


texts: Custom exception handling function or logging library?

texts:
I want to document every exception handled in my code and some states of the code when it works properly.
What I've done is two functions, one that creates an 'error report' (function: error) and one that creates a 'state report'(function: state), and they work by being called in functions where there's stuff I'd like to have documented, they have a code parameter which I use to select the message of the report (apart from the exception, in the case of it being an error report) and then they call another function which takes this information and loads it to a JSON file(function: writeReport). If I'm being clear so far, you can skip all the code examples, my question is at the end.

Here I show you the functions I mentioned before (messages are in spanish because its my main language):

# Exception mesagges (this is the one that records exceptions)
def error(code, exception, extra=None):
    if code == 0:
        stateReport.message = ('Error indefinido')
    elif code == 1:
        stateReport.message = ('Error en la conexion o creacion de la base de datos')
    elif code == 2:
        stateReport.message = ('No se pudieron crear las tablas o ya existen')
    elif code == 3:
        stateReport.message = (f'No se pudo recuperar la tabla {extra}')
    elif code == 4:
        stateReport.message = (f'Error indefinido que no afecta al funcionamiento')
    elif code == 5:
        stateReport.message = (f'Error en manipulacion de GUI que no afecta al funcionamiento')
    elif code == 100:
        stateReport.message = (f'Error desconocido al presionar una tecla')
    stateReport.function = (inspect.stack()[1].function)
    stateReport.date_time = date_time
    stateReport.error = str(exception)
    writeReport()
    return

# State messages (this I use when some special case goes right)
def state(code, extra=None):
    if code == 0:
        stateReport.message = (f'El programa funciono correctamente')
    elif code == 1:
        stateReport.message = (f'Se accedio a la base de datos')
    elif code == 2:
        stateReport.message = (f'Se creo exitosamente la nueva tabla')
    elif code == 3:
        stateReport.message = (f'Valores ingresados incorrectos. Valor incorrecto: {extra}')
    stateReport.function = (inspect.stack()[1].function)
    stateReport.date_time = date_time
    stateReport.error = '---------->Sin errores<----------' #This means "No errors"
    writeReport()

def writeReport():
    report = {'date': stateReport.date_time,
               'function': stateReport.function,
               'message': stateReport.message,
               'error': stateReport.error}
    if not os.path.exists(reportsFile):
        with open(reportsFile, 'w', newline='') as file:
            json.dump(report, file, indent=4)
    else:
        with open(reportsFile, 'a', newline='') as file:
            json.dump(report, file, indent=4)
    return

Now, heres a function where I use this feature on, just so you see how I actually implemented it:

table = 'clientes'
    ## This is the creation of a <new> table in an sqlite database
try:
    c.execute(f'''CREATE TABLE {table} (
    id integer,
    nombre text,
    apellido text,
    valoracion real)''')
    state(2)
    ##If the table is successfully created a state report is saved with this info
except Exception as e:
    error(2, e, table)
    ##On the contrary, if an exception occurs, en error report is recorded

This works great, but today I ran into the logging library (im kinda new in python) and it made me think. Is it better to use loggings in all of this cases? It would create a file with everything, it's allready a python library and I would avoid having three separate functions just for recording stuf, but I dont know if it's logging proper way of using it.


texts: AngularJS services for APIs in large applications

texts:
I've been reading about AngularJS services and factories, and how you should strive for a thin controller, but as the project I've been working on grows it seems more and more impractical with as interconnected as the app is.  For a little background, I am using UI-Grid to display most data in the app (20+ grids) and MVC5.  At the moment, I've placed all of my API calls to SQL within the main controller, along with all of my grid definitions:

app.controller('MainController', ['$scope', '$http', '$filter', 'logger', function ($scope, $http, $filter, logger) {

    $scope.project = {};

    /*
    * Grid Listing Definition
    */
    $scope.gridListing = { enableRowSelection: true, enableRowHeaderSelection: false, multiSelect: false, enableColumnMenus: false, enableSorting: false };
    $scope.gridListing.onRegisterApi = function (gridApi) {
        // Set api on scope
        $scope.gridListing.Api = gridApi;
        gridApi.selection.on.rowSelectionChanged($scope, function (row) {
            $scope.gridListing.selectedRow = false; // Used for visibility on the view
            if (row.isSelected) {
                $scope.gridListing.selectedRow = row.entity;
            };
        });
    };
    $scope.gridListing.columnDefs = [
        { field: 'ListingNumber', displayName: 'Number', type: 'number', width: '10%' }
        , { field: 'CreatedOn', displayName: 'CreatedOn', type: 'date', cellFilter: 'date:"yyyy-MM-dd"', width: '10%' }
        , { field: 'CreatedBy', displayName: 'CreatedBy', width: '10%' }
        , { field: 'Description', displayName: 'Description' }
        , { field: 'FunctionState', displayName: 'State', width: '10%' }
    ];

    $scope.load_gridListing = function () { // Update when new Listing is selected
        $scope.gridListing.data = []; // Clear grid for new data
        $http.get('/api/qryListingAPI/?project=' + $scope.project.ProjectID)
        .then(function (response) {
            $scope.gridListing.data = response.data;
        })
        .catch(function (response) {
            // Custom logger for error tracking
            logger.log(usrName, 'app', response.status + " - " + response.statusText, logger.Error);
        });
    };
}]);

As the user interacts with objects in the view, like selecting a new project etc. various grids need to be updated to reflect the users selection.  I had tied these "load" functions on the view to update grids as needed.  I had originally thought of creating services for each of the views that I use to populate these grids, but with so many, and needing to share between controllers, I elected not to to avoid massive controller definitions and added complexity making sure each controller was on the same page.  I may be misunderstanding how to implement AngularJS the way many say AngularJS should be implemented and making it more complicated than it needs to be.  Any suggestions for implementing an app with 20+ grids and 30+ APIs?


texts: Try every username and password from a list on a website

texts:
This code will be brute force specific site using http POST method.

 def BruteForce(url, username, password):
        userfile = open(username, "r")
        userlist = userfile.read()
        userlist = userlist.split("\n")

        passfile = open(password, "r")
        passlist = passfile.read()
        passlist = passlist.split("\n")

        for i in userlist:
            for j in passlist:
                data = {"username":i, "password": j}
                data2 = {"username":i, "password": j}
                data = urllib.urlencode(data)
                request = urllib2.Request(url, data)

                response = urllib2.urlopen(request)
                payload = response.read()

                isconnect = "True"
                if(payload.find(isconnect)>=0):
                    print "Found, the password is: " + data2["password"] + " and the username is: " + data2["username"]
                    return

                else:
                    pass

Is this code efficient?
How I can improve my code?
Should I use multithreading mechanism to speed up my script?


texts: Use a context manager to save an object on exit

texts:
The following code uses a context manager to store and load variables into files.
However, it's very annoying to have to set the value property of what is yielded by the context manager (loaded.value).
I would like to

Not have to define a new class like LoadedValue
Set the yielded value of the context manager (loaded) to be the value that is saved.

Any way of doing either of those two (as well as other helpful improvements) would be greatly appreciated.

import os
import pickle
from contextlib import contextmanager

class LoadedValue:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return "<LoadedValue: {}>".format(self.value)

@contextmanager
def load_manager(load_file="file.pkl"):
    with open(load_file, "rb") as f:
        loaded_object = LoadedValue(pickle.load(f))
    try:
        yield loaded_object
    finally:
        with open(load_file, "wb+") as f:
            pickle.dump(loaded_object.value, f)

if __name__ == "__main__":
    filename = "test.pkl"
    with open(filename, "wb+") as f:
        pickle.dump(7, f)

    with load_manager(filename) as loaded:
        print(loaded) # >>> <LoadedValue: 7>
        loaded.value = 5 # this is what I have to do
        # loaded = 5  # this is what I want to do

    with load_manager(filename) as loaded:
        print(loaded) # >>> <LoadedValue: 5>


texts:
I'm trying to create a light system, with the midpoint algorithm and Bresenham Line Algorithm. I'm trying to redraw all the time (1 option) or redraw when I need to.  When the circles are too big it becomes a bit laggy.

Example

function Light(x, y, range)
{
    this.CordX = x;
    this.CordY = y;
    this.LuminosityRange = range;
}
   setInterval(function(){
        stats.begin(); // Begin to count FPS
        ctx.clearRect(0, 0, Width, Height); // Clear Canvas

        // STEP 1 -- DRAW THE BACKGROUND (BLACK)
        for(var y = 0; y < Height; y++)
        {
            for(var x = 0; x < Width; x++)
            {
                var index = x + (y * Width),
                    indexColor = index * 4;

                shadowBitMapData[indexColor + 0] = shadowBitMapData[indexColor + 1] = shadowBitMapData[indexColor + 2] = 0;
                shadowBitMapData[indexColor + 3] = 255;
            }
        }

        // SETEP 2 -- DRAW THE LIGHT
        for(var light = 0; light < lamps.length; light++)
        {
            var currentLight = lamps[light];
            var xCL = ~~currentLight.CordX,
                yCL = ~~currentLight.CordY,
                iCL = xCL + (yCL * Width),
                rCL = ~~currentLight.LuminosityRange;

            // MidPoint Algorithm
            var xMP = rCL,
                yMP = 0,
                rEMP = 1 - xMP;

            while(xMP >= yMP)
            {

                var x1 = xMP + xCL,
                    x2 = yMP + xCL,
                    x3 = -xMP + xCL,
                    x4 = -yMP + xCL;

                var y1 = yMP + yCL,
                    y2 = xMP + yCL,
                    y3 = -yMP + yCL,
                    y4 = -xMP + yCL;

                var index1 = x1 + (y1 * Width);
                var index2 = x2 + (y2 * Width);

                var index3 = x3 + (y1 * Width);
                var index4 = x4 + (y2 * Width);

                var index5 = x3 + (y3 * Width);
                var index6 = x4 + (y4 * Width);

                var index7 = x1 + (y3 * Width);
                var index8 = x2 + (y4 * Width);

                // Fill Top
                //shadowBitMapData[index6 * 4 + 3] = 0;
                //shadowBitMapData[index8 * 4 + 3] = 0;
                BresenhamLine(x4, y4, x2, y4, shadowBitMapData, Width);

                // Fill Mid Top
                //shadowBitMapData[index5 * 4 + 3] = 0;
                //shadowBitMapData[index7 * 4 + 3] = 0;
                BresenhamLine(x3, y3, x1, y3, shadowBitMapData, Width);

                // Fill Mid Bottom
                //shadowBitMapData[index1 * 4 + 3] = 0;
                //shadowBitMapData[index3 * 4 + 3] = 0;
                BresenhamLine(x1, y1, x3, y1, shadowBitMapData, Width);

                // Fill Bottom
                //shadowBitMapData[index2 * 4 + 3] = 0;
                //shadowBitMapData[index4 * 4 + 3] = 0;
                BresenhamLine(x2, y2, x4, y2, shadowBitMapData, Width);

                yMP++;

                if (rEMP < 0)
                {
                    rEMP += 2 * yMP + 1;
                }
                else
                {
                    xMP--;
                    rEMP += 2 * (yMP - xMP + 1);
                }
            }
        }

        ctx.putImageData(shadowBitMap, 0, 0); // Draw Shadow
        stats.end(); // End to count FPS
    }, 1000 / 60);

function BresenhamLine(x0, y0, x1, y1, bitmap, Width)
{
    var dx = Math.abs(x0 - x1);
    var dy = Math.abs(y0 - y1);

    var sx = x1 < x0 ? 1 : -1;
    var sy = y1 < y0 ? 1 : -1;

    var err = dx - dy;
    var e2;

    var lm = 0;
    while (true)
    {
        bitmap[(x1 + y1 * Width) * 4 + 3] = 0;

        if (x1 == x0 && y1 == y0) break;

        e2 = 2 * err;
        if (e2 > -dy)
        {
            err = err - dy;
            x1 = x1 + sx;
        }

        if (e2 < dx)
        {
            err = err + dx;
            y1 = y1 + sy;
        }
    }
}


texts: Sieve of Eratosthenes implementation is running slowly

texts:
I have written this code to find prime numbers, and it works well, but the calculation speeds are incredibly slow.  Am I doing this wrong? I know that I might be really doing this the wrong way, but please help me!

using System;
using System.Collections.Generic;

namespace Primenumbers
{
class MainClass
{
    public static void Main (string[] args)
    {

        List<int> NoPrime = new List<int>();

        for(int x = 2; x < 10000;x++)
        {
            for(int y = x * 2;y < 10000;y = y + x)
            {

            if(!NoPrime.Contains(y))
                {
                    NoPrime.Add(y);
                }

            }

        }

        for(int z = 2; z < 10000;z++)
        {
            if(!NoPrime.Contains(z))
            {
                Console.WriteLine(z);
            }
        }

    }
}
}


texts:
I am wondering if someone can review my code and tell me if there is a way to enhance it and make it more efficient.

import java.util.Scanner;

public class apples {
    public static void main (String[] args){
        Scanner input = new Scanner(System.in);

        int selection;

        for (int i=0; i<4;i++){
            System.out.println("Please enter the selection you would like");
            System.out.println("Enter 1 for Coffee");
            System.out.println("Enter 2 for Tea");
            System.out.println("Enter 3 for Juice");
            System.out.println("Enter 4 for Fizzy Drink");
            selection = input.nextInt();
            if(selection==1){
                System.out.println("You have chosen coffee");
            }
            if(selection==2){
                System.out.println("You have chosen tea");
            }
            if(selection==3){
                System.out.println("You have chosen juice");
            }
            if(selection==4){
                System.out.println("You have chosen fizzy drink");
            }
            if(selection<1 || selection>4){
                System.out.println("You have made a wrong selection, please re-select");
            }
        }
    }
}


texts:
For legacy reason (guys here LOVE immutable object), I need a struct that contain an IpV4.

I can't use System.Net.IPAddress because it's not a struct.

So far here what I got:

public struct IpV4Address
{
    readonly byte[] address;

    public IpV4Address(byte[] address)
    {
        Throw.IfArgumentIsNull("address", address);

        if (address.Length != 4)
        {
            throw new ArgumentException("Wrong address length", "address");
        }

        this.address = new byte[4];
        Array.Copy(address, this.address, 4);
    }

    public override string ToString()
    {
        return string.Join(".", address);
    }

    /// <summary>
    ///     Parse a string representing an IPV4.
    ///     <example>xxx.yyy.zzz.www</example>
    /// </summary>
    /// <param name="quadDotted">The string to parse.</param>
    /// <returns>The IPV4</returns>
    public static IpV4Address Parse(string quadDotted)
    {
        Throw.IfArgumentIsNull("quadDotted", quadDotted);

        var bytes = quadDotted.Split('.').Select(byte.Parse).ToArray();

        return new IpV4Address(bytes);
    }

    /// <summary>
    ///     Try parse a string representing an IPV4.
    ///     <example>xxx.yyy.zzz.www</example>
    /// </summary>
    /// <param name="quadDotted">The string to parse.</param>
    /// <param name="result">The IPV4</param>
    /// <returns>A value indicating whether the parse succeed.</returns>
    public static bool TryParse(string quadDotted, out IpV4Address result)
    {
        if (quadDotted == null)
        {
            goto Fail;
        }

        var elements = quadDotted.Split('.');
        if (elements.Length != 4)
        {
            goto Fail;
        }

        var address = new byte[4];
        for (var i = 0; i < 4; i++)
        {
            if (!byte.TryParse(elements[i], out address[i]))
            {
                goto Fail;
            }
        }

        result = new IpV4Address(address);
        return true;

        Fail:
        result = default(IpV4Address);
        return false;
    }

It's the first time I use a goto in a C# code. And I don't feel ashamed !


texts: Best practise way to handle array of pairs

texts:
I am trying to randomly select 4 items out of an array, each item has an index, a name and a price attached to it. Currently I have the following code segment to select 4 at random:

function SelectItems()
{
     $arrayItems = array(
          1 => "Name of Item 1",
          2 => "Name of Item 2",
          3 => "Name of Item 3",
          4 => "Name of Item 4",
     );

     $arrayItemPrices = array(
          1 => "$6.00",
          2 => "$4.00",
          3 => "$5.00",
          4 => "$15.00",
     );

     $randomKeys = array_rand( $arrayItems, 4 );
     foreach( $randomKeys as $key )
     {
          $name = $arrayItems[$key];
          $price = $arrayItemPrices[$key];

          /* Process item... */
     }
}

However, this is not how I would approach it in C++, I would only use a std::map<int, std::pair<std::string, std::string>>, this would map directly in PHP to an array where the value consisted of a pair of strings, however as there is no pair class in PHP I have done it with two arrays. Is this best practise in PHP?


texts: Process 2 lists concurrently with the first list adding to the second

texts:
I'm new to multi-threading and concurrency. I've got 2 lists that I want to process concurrently. Processing both lists requires a lot of time.sleep() and waiting for other servers to finish, so I figured rather than do one at a time I could process them simultaneously.

The first list is un-validated items and I try to validate them and if successful add them to the second list for processing. I want to start validating items in the first list and then while that is going start on the processing of the 2nd list. I've since found out I wanted a Queue for the 2nd list and that has helped but I can't help but feel that even though this works I'm missing something.

def process_sr(jira, tuple, args, log):
    ... # does some pretty straight forward stuff but lots of waiting
    return "done"

def waiting_for_build(tuple, validqueue, log):
    sr, pr = tuple
    iter = 0
    log.info("Waiting for {} to re-build".format(pr))
    while iter < 30:  # don't add. It's been more than 10 minutes and we need to finish
        log.debug("%s still waiting for Jenkins", pr)
        sleep(20)
        status = pr.build_status()
        if status is None:
            break  # don't add. Build finished "FAILURE" or didn't build in 10 min
        elif status == "Wait":
            iter += 1
        elif status == "Done":
            validqueue.put((sr,pr))

def build_lists(jira, log):
    validqueue = Queue()
    waiting_for_jenkins = []
    ...  # this builds the two lists
    return validqueue, waiting_for_jenkins

def main():
    args, log = cli_args()
    jira = JiraWrapper()

    validqueue, waiting_for_jenkins = build_lists(jira, log)

    workers = len(waiting_for_jenkins) + validqueue.qsize()

    threads = []
    for item in waiting_for_jenkins:
        name = str(item[1])
        threads.append(threading.Thread(target=waiting_for_build, name=name, args=(item, validqueue, log)))
        threads[-1].start()

    def worker(i):
        log.debug("started")
        results = []
        while True:
            log.debug("blocking on queue")
            item = validqueue.get()
            if item is None:
                log.debug("done")
                return results
            log.debug("got item %s", item)
            result = process_sr(jira, item, args, log)
            results.append({result:item})
            log.debug("task %s done", item)
            validqueue.task_done()

    log.debug("%d workers will be spawned", workers)
    if not workers:
        log.info("Nothing to do here")
    else:
        with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:  # can't use thread_name_prefix until python 3.6
            futures = executor.map(worker, range(workers))

            for thread in threads:
                thread.join()
            validqueue.join()

            for i in range(workers):
                validqueue.put(None)
            for future in futures:
                log.debug(future)

    exit(0)

if __name__ == '__main__':
    main()

I've included as much as I think is needed. The main() method and specifically the two multi-threaded bits are where I'm looking for feedback.


texts: Admin method in CakePHP to add a venue to the database

texts:
I have a VenuesController and an EventsController. My venues controller has an admin_add method that, well, allows an administrator to add a venue to the database. It looks like this:

public function admin_add() {
    if ($this->request->is('post')) {
        if ($this->Venue->save($this->request->data)) {
            $message = 'Venue has been created.';
            $this->response->statusCode(201);
            if ($this->request->params['ext'] == 'json') {
                $this->set('id', $this->Venue->id);
                $this->set('_serialize', array('id'));
            }
            else {
                $this->Session->setFlash($message, 'flash', array('class' => 'success'));
                $this->redirect(array('action' => 'index'));
            }
        }
        else {
            if ($this->request->params['ext'] == 'json') {
                $this->set('validationErrors', $this->Venue->validationErrors);
                $this->set('_serialize', array('validationErrors'));
                $this->response->statusCode(400);
            }
        }
    }
}

As you can see, there are a lot of if () statements which seem like code smells to me. But they’re there because in my CMS’s events section, you can add a venue inline via a modal, which sents the request to this function via AJAX.

So my question is: can I improve the above VenuesController::admin_add() method, make it more intelligent without the need for the if () statements, and just generally make it more CakePHP-ier?


texts:
Caeser's cipher code where there are a converter and a game part with user input. The code includes keys (settable and not settable).

import random

def change_letter(original, new_message, key_number, alpha):
    for letter in original:
        if letter in alpha.lower():
            new_message += alpha[(alpha.lower().index(letter) + key_number) % 26].lower()
        elif letter in alpha:
            new_message += alpha[(alpha.index(letter) + key_number) % 26]
        else:
            new_message += letter

    return new_message

def encipher(the_key, message, inp=True):
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    output_message = ""

    if inp:
        try:
            the_key = int(input('Key?  ・  '))
        except ValueError:
            the_key = input('\nNot valid input  ・  ')
            while not the_key.isnumeric():
                the_key = input('Not valid input  ・  ')

    output_message = change_letter(message, output_message, int(the_key), alphabet)

    return output_message

def convert():
    while True:
        key = None
        type_word = input('\nType your word  ・  ')
        print('\n{}  ::  {}'.format(type_word, encipher(key, type_word)))
        convert_again = input('\nWould you like to convert again? | Y/N  ・  ').upper()

        if convert_again == 'Y' or convert_again == 'YES':
            continue
        break

def play():
    while True:
        key = random.randint(1, 25)
        words = ('WWE', 'Javascript', 'Pythonista', 'Computer Science', 'Eighty-three', 'Event Log', '5K Freestyle')
        word = random.choice(words)
        question = input('\nWhat is {} of key {}  ・  '.format(word, key)).lower()
        changed_word = encipher(key, word, inp=False)

        if question == changed_word.lower():
            print(f'Congratulations! You guessed {changed_word} from {word}')
        else:
            print(f'Oops! Wrong answer. The word is {changed_word} from {word}')

        play_again = input('\nWould you like to play again? | Y/N  ・  ')

        if play_again.upper() == 'YES' or play_again.upper() == 'Y':
            continue
        break

def main():
    while True:
        convert_or_play = input('C to convert, P to play  ・  ')
        if convert_or_play.upper() == 'C':
            convert()
        elif convert_or_play.upper() == 'P':
            play()
        else:
            break
        print()

if __name__ == '__main__':
    main()


texts: Flux: async communication with websockets

texts:
I want to arrange async server-client communication with websockets and vanilla flux architecture. There is an excellent article about "Async Server-Side Communication with the Flux Architecture". I gonna implement it analogue with SockJS and ES6 promises:

ActionCreator.js     - it's the same but moved to ES6

import * as constants from ('../constants/constants'),
import TodoService = require('../services/todo-service');

class ActionCreator {

  addTodo(text) {
    var that = this;
    service.addTodo({text: text}).then(function(todo) {
        that.dispatch(constants.ADD_TODO, todo);
    });
  }
}

export default new ActionCreator();

services/todo-service.js - even shorter

import WebSocketWrapper from 'WebSocketWrapper';

class TodoService {

    addTodo(todo) {
        //maybe do something with todos before send them to the server
        return WebSocketWrapper.send(todo);
    }
}

export default new TodoService();

WebSocketWrapper.js

/**
 * Due fact that SockJS provide raw websocket API and do not implement pub/sub, we need to do wrapper, which will corellate request/response
 */

import SockJS from 'sockjs';
import selectn from 'selectn';

var reqId = 1;
const responseDeffers = {};

class WebSocketWrapper {

    constructor(url) {
        this.ws = new SockJS(url);
        this.ws.onopen = this.onOpen;
        this.ws.onmessage = this.onMessage;
        this.ws.onclose = this.onClose;
        this.ws.onerror = this.onError;
    },

    onMessage(message) {
        let requestId = selectn('message.data.request_id');
        if (!requestId) return;
        //resolve or reject the promise which is kept in ActionCreator
        if (message.data.result === 'Ok') resolveRequest(requestId, message);
        else rejectRequest(requestId, message.error);
    },

    /**
     * Return Promise, which will be resolved/rejected on server response with the same requestId
     */
    send(request) {
        return new Promise(function(resolve, reject) {
            //cache resolve/reject function to be able to invoke themn on server response
            responseDeffers[reqId++] = {
                resolve: res,
                reject: rej
            };
            //send message via websockets
            if (this.ws.readyState == this.ws.OPEN) {
                this.ws.send(JSON.stringify(request));
            } else {
                reject('Websocket connection is closed');
            }
        });
    },

    resolveRequest(requestId, message) {
        let response = JSON.parse(message.data);
        responseDeffers[request_id].resolve(response);
    },

    rejectRequest(requestId, message) {
        responseDeffers[requestId].reject(message);
    }

    onOpen() {},

    oClose() {},

    onError(e) {}
}

export default new WebSocketStore(ENV.props.url);


texts: Reducing allocations in arbitrary precision calculations with Julia

texts:
I am new to Julia and have only written in python before which is most likely also reflected by my coding style.
Unfortunately, my applications require very high numerical precision which is why I am resorting to BigFloat and BigInt in Julia. For some reason, this leads to a major increase in allocations besides the obvious increase in computational time.
I am wondering where my code can be improved.
I have attached the current version of my code below with example parameters that allow for execution under 1s.
using Combinatorics

function gamma_mpnq(m::Int, p::Int, n::Int, q::Int)::BigFloat
    return sqrt(factorial(big(m)) * factorial(big(n))) / (big(2)^(p + q) * factorial(big(m - 2 * p)) * factorial(big(n - 2 * q)) * factorial(big(q)) * factorial(big(p)))
end

function general_binomial(alpha::Float64, k::Int)
    """
    Implementation of the generalized binomial.
    """
    _prod = BigFloat(1.0)
    for kk in 1:k
        _prod *= (alpha - kk + 1.)
    end
    return _prod / factorial(big(k))
end

function construct_M(nmax::Int, mmax::Int)::Array
    """
    Construct the matrix M containing all moments <C^n * C*^m> up to nmax and mmax.
    """
    _M = zeros(BigFloat, nmax, mmax)
    for mm in 1:nmax
        for nn in 1:mmax
            if nn == 1
                _M[nn, mm] = 1. / doublefactorial(BigInt(2*mm - 1))
            elseif mm == 1
                _M[nn, mm] = 1. / doublefactorial(BigInt(2*nn - 1))
            else
                _M[nn, mm] = (((nn-1) * _M[nn-1, mm] + (mm-1) * _M[nn, mm-1]) / (2. * (nn-mm)^2 + (nn-1) + (mm-1)))
            end
        end
    end
    return _M
end

function maclaurin_exp(n::Int, m::Int, p::Int, q::Int, M::Array, cutoff::Int)::BigFloat
    """
    Calculate the expectation value of ((1+C)/(1+C*))^((n-m)/2) * C^p * C*^q
    using the Maclaurin expansion and the matrix containing all moments M.
    """
    inner::BigFloat = 0.0
    @views for nn in 1:cutoff
        for mm in 1:cutoff
            inner += (general_binomial((n-m)/2., mm-1) * general_binomial((m-n)/2., nn-1) * M[q+nn, p+mm])
        end
    end
    return inner
end

function Hmn(m::Int, n::Int, M::Array, cutoff::Int)::Float64
    """
    Calculates a single entry of the Hmn matrix.
    """
    ppmax = div(m, 2)
    qqmax = div(n, 2)
    outer = 0.0
    for pp in 0:ppmax
        for qq in 0:qqmax
            outer += (gamma_mpnq(m, pp, n, qq) * maclaurin_exp(n, m, pp, qq, M, cutoff))
            # println(pp, " ", qq, " ", outer)
        end
    end
    return outer
end

dim = 128
cutoff = 64
M = construct_M(dim+cutoff, dim+cutoff)
@btime Hmn(12, 2, M, cutoff)

```


texts: Count groups of open cells around a cell on a grid

texts:
Consider a 3x3 square surrounding a cell (marked @) on a grid:

0 1 1
1 @ 0
1 1 1

I need to find the number of groups of open cells (ones) surrounding the center cell. In the above example, there are two groups of open cells. All cells have the value 0, closed, or 1, open.
Here's what I have:

{
    // x and y coordinates for offsets corresponding
    // to the eight neighboring cells
    const xDir = [0, 1, 1, 1, 0,-1,-1,-1];
    const yDir = [1, 1, 0,-1,-1,-1, 0, 1];

    // generate a randomly open (1) or closed (0) 3 by 3 square of cells
    const generateSquare = _ => {
        const square = [];
        for (let x = 0; x < 3; x++) {
            square[x] = [];
            for (let y = 0; y < 3; y++) {
                square[x][y] = Number(Math.random() < 0.5);
            }
        }
        return square;
    };

    // count the number of contiguous groups of open (1) cells
    const countGroups = square => {
        let groups = 0;
        // loop clockwise through neighbors and count transitions from 0 to 1
        let prev = square[0][2];
        for (let i = 0; i < 8; i++) {
            let curr = square[1 + xDir[i]][1 + yDir[i]];
            groups += Number(!prev && curr);
            prev = curr;
        }
        // if there aren't any transitions, check if all neighbors are 1
        return !groups && prev ? 1 : groups;
    };

    const square = generateSquare();
    console.table(square);
    console.log(countGroups(square));
}

Is there anything I can improve?


texts: Iterating through 128-byte records in a file

texts:
I need to read records from a flat file, where each 128 bytes constitutes a logical record. The calling module of this below reader does just the following.

while(iterator.hasNext()){
    iterator.next();
    //do Something
 }

Means there will be a next() call after every hasNext() invocation.

Now here goes the reader.

public class FlatFileiteratorReader implements Iterable<String> {

    FileChannel fileChannel;

public FlatFileiteratorReader(FileInputStream fileInputStream) {
    fileChannel = fileInputStream.getChannel();
}

private class SampleFileIterator implements Iterator<String> {
    Charset charset = Charset.forName("ISO-8859-1");
    ByteBuffer byteBuffer = MappedByteBuffer.allocateDirect(128 * 100);
    LinkedList<String> recordCollection = new LinkedList<String>();
    String record = null;

    @Override
    public boolean hasNext() {
        if (!recordCollection.isEmpty()) {
            record = recordCollection.poll();
            return true;
        } else {
            try {
                int numberOfBytes = fileChannel.read(byteBuffer);
                if (numberOfBytes > 0) {
                    byteBuffer.rewind();
                    loadRecordsIntoCollection(charset.decode(byteBuffer)
                            .toString().substring(0, numberOfBytes),
                            numberOfBytes);
                    byteBuffer.flip();
                    record = recordCollection.poll();
                    return true;
                }
            } catch (IOException e) {
                // Report Exception. Real exception logging code in place
            }
        }
        try {
            fileChannel.close();
        } catch (IOException e) {
            // TODO Report Exception. Logging
        }
        return false;

    }

    @Override
    public String next() {
        return record;
    }

    @Override
    public void remove() {
        // NOT required

    }

    /**
     *
     * @param records
     * @param length
     */
    private void loadRecordsIntoCollection(String records, int length) {
        int numberOfRecords = length / 128;
        for (int i = 0; i < numberOfRecords; i++) {
            recordCollection.add(records.substring(i * 128, (i + 1) * 128));
        }
    }

}

    @Override
    public Iterator<String> iterator() {
        return new SampleFileIterator();
    }
}

The code reads 80 mb of data in 1.2 seconds on a machine with 7200 RPM HDD, with Sun JVM and running Windows XP OS. But I'm not that satisfied with the code I have written. Is there any other way to write this in a better way (especially the decoding to character set and taking only the bytes that has been read, I mean the charset.decode(byteBuffer) .toString().substring(0, numberOfBytes) part)?