texts: Portable C++98 thread class akin to std::thread

texts:
I want a homegrown version of C++11's std::thread. My motivation is to avoid manual memory management of the arguments passed to the thread function. I'm restricted to C++98. I want better type safety than what's available in the POSIX and Win32 thread APIs.

Two notes:

I can't think of a way to avoid a heap allocation for the thunk argument. The thread instance could be deleted before the thunk has a chance to construct its arguments. I suppose I could wait on an event in the constructor signaled by thunk() once the thread is in a 'ready' state, but that seems horrible.
I'm not too concerned about exception safety as exceptions are disabled for most of this C++ codebase.

/* There is a portable thread implementation in C available already */
int portable_thread_create(portable_thread_t *)
{
    pthread_create() **OR**
    _beginthreadex()
}

#define PORTABLE_THREAD_FUNC_DECL void *
#define PORTABLE_THREAD_FUNC_DECL unsigned int __cdecl **OR**

void portable_thread_join(portable_thread_t)
{
    pthread_join() **OR**
    WaitForSingleObject()
}

template < typename TArg0 >
class thread
{
public:
    typedef void (*function_t)(TArg0);
    thread(function_t func, TArg0 arg0)
        : m_func(func)
    {
        m_arg0 = new TThunkArg(this, arg0);
        if (0 != portable_thread_create(&m_thread, thunk, m_arg0))
        {
            delete m_arg0;
            throw new std::runtime_error("Could not create a thread");
        }
    }

    void join()
    {
        portable_thread_join(m_thread);
    }

private:
    struct TThunkArg
    {
        thread<TArg0> *Self;
        TArg0 Arg0;
        TThunkArg(thread<TArg0> *self, TArg0 arg0)
            : Self(self)
            , Arg0(arg0)
        {}
    };
    static PORTABLE_THREAD_FUNC_DECL thunk(void *unsafe_args)
    {
        TThunkArg *args = reinterpret_cast<TThunkArg*>(unsafe_args);
        try
        {
            args->Self->m_func(args->Arg0);
        }
        catch(...)
        {
            delete args;
            throw;
        }

        delete args;
        return 0;
    }
    portable_thread_t m_thread;
    function_t m_func;
    TThunkArg *m_arg0;
};


texts: Links controller in MVC N-layer architecture

texts:
I have a common issue that I face in my applications (because I don't know any better) and I want to improve.

This is my usual structure:

Project.UI (MVC Project)
Project.BLL (Class Lib)
Project.DAL (Class Lib)

LinksConfigurationController

public class LinksConfigurationController : BaseController
{
    public async Task<ActionResult> Index()
    {
        var config = new LinksConfiguration();
        var result = await config.GetLinksAsync();
        if (result == null) return View(new List<LinksViewModel>());

        var model = result.Select(item => new LinksViewModel
        {
            Id = item.Id,
            LinkEndpoint = new Uri(item.LinkEndpoint),
            LinkName = item.LinkName
        }).ToList();

        return View(model);
    }
}

LinksConfiguration (In Project.BLL)

public class LinksConfiguration
{
    public LinksConfiguration()
    {
        Repo = new LinksConfigurationRepository();
    }

    public LinksConfigurationRepository Repo { get; set; }
    public async Task<IEnumerable<LinksConfigurationDto>> GetLinksAsync()
    {
        var reuslt = await Repo.GetAllAsync();
        var dto = reuslt.Select(r => new LinksConfigurationDto
        {
            LinkEndpoint = r.LinkEndpoint,
            Id = r.Id,
            LinkName = r.LinkName
        }).ToList();

        return dto;
    }
}

LinksConfigurationRepository (In Project.DAL)

public class LinksConfigurationRepository : IRepository<LinksConfiguration>
{
    public LinksConfigurationRepository()
    {
        Db = new NZBDashContext();
    }
    private NZBDashContext Db { get; set; }
    public async Task<IEnumerable<LinksConfiguration>> GetAllAsync()
    {
        return await Db.LinksConfiguration.ToListAsync();
    }
// Rest of the implemented members from the interface
}

IRepo

public interface IRepository<T> where T : Entity
{
    T Find(int id);
    Task<T> FindAsync(int id);
    IEnumerable<T> GetAll();
    Task<IEnumerable<T>> GetAllAsync();
    T Insert(T entity);
    IEnumerable<T> Insert(IEnumerable<T> entity);
    Task<IEnumerable<T>> InsertAsync(IEnumerable<T> entity);
    Task<T> InsertAsync(T entity);
    int Remove(T entity);
    Task<int> RemoveAsync(T entity);
    Task<int> ModifyAsync(T entity);
    int Modify(T entity);
}

As you can see I have fallen into the trap of constant mapping (I could use Automapper or something similar) and it's a pain and time consuming to actually get anything done. I read through this article and while it looks like a good approach, I do not like the idea of all the layers referencing and using the same models (The model used in the view could be completely different to what is actually stored in the DB).

How can I sort this out?


texts:
I Have this class want to practice how to write a factory method pattern
and I can change the logPlace by set the app.config,
and I try to improve the performance so I use static List<string>,I want to decrease IO loading
Here is my question

This class can call factory method pattern or not?
Is my code as clear as it could be?
I think the LogBoth class can be much better, but I have no idea how to improve it.

   public enum LogLevel
    {
        Error, Debug, Info, Fatal
    }
    static class Msg
    {
        public static List<string> msgList = new List<string>();
    }
    public class LogHelper
    {
        public static ILog Create()
        {
            string logPlace = System.Web.Configuration.WebConfigurationManager.AppSettings["LogPlace"];
            switch (logPlace)
            {
                case "DB":
                    return new LogDB();
                case "File":
                    return new LogFile();
                case "Both":
                    return new LogBoth();
                default:
                    return new LogFile();
            }
            throw new NullReferenceException();
        }
    }
    public interface ILog
    {
        void WriteLog(string msg);
        void ExecWrite(LogLevel logLevel);
    }
    public class LogDB : ILog
    {
        public LogDB()
        {
            Msg.msgList.Clear();
        }
        public void WriteLog(string msg)
        {
            Msg.msgList.Add(msg);
        }
        public void ExecWrite(LogLevel logLevel)
        {
            throw new NotImplementedException();
        }
    }
    public class LogFile : ILog
    {

        private static object _lockObject = new object();

        public LogFile()
        {
            Msg.msgList.Clear();
        }

        public void WriteLog(string msg)
        {
            Msg.msgList.Add(msg);
        }
        public void ExecWrite(LogLevel logLevel)
        {
            try
            {
                Policy.Handle<Exception>().Retry(1).Execute(()=>WriteToFile(logLevel));
            }
            catch (Exception ex)
            {
                LogDB logDB = new LogDB();
                logDB.ExecWrite(logLevel);
            }
        }

        private void WriteToFile(LogLevel logLevel)
        {
            lock (_lockObject)
            {

                using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
                {
                    using (StreamWriter sw = new StreamWriter(fs))
                    {
                        foreach (string msg in Msg.msgList)
                        {
                            sw.WriteLine(string.Format("{0} [{1}] {2}", DateTime.UtcNow.AddHours(08).ToString("yyyy/MM/dd HH:mm:ss"), logLevel, msg));
                        }
                    }
                }
            }
        }

    }
    public class LogBoth : ILog
    {
        public LogBoth()
        {
            Msg.msgList.Clear();
        }
        public void ExecWrite(LogLevel logLevel)
        {
            LogDB logDB = new LogDB();
            LogFile logFile = new LogFile();

            logDB.ExecWrite(logLevel);
            logFile.ExecWrite(logLevel);
        }

        public void WriteLog(string msg)
        {
            Msg.msgList.Add(msg);
        }
    }


texts: Laravel dropdown list without empty values

texts:
I'm creating dropdown list from all possible cities in database, all cities are distincted.

$city = DB::table('contacts')->distinct('city')->lists('id', 'city');

^ Extracts all possible cities, however it also extract empty string ['' => '95].

How I can forbid retrieving empty city ?

I tried using $city = DB::table('contacts')->whereNotNull('city')->distinct('city')->lists('id', 'city'); But didn't helped. My code looks like this now.

    $city = DB::table('contacts')->distinct('city')->lists('id', 'city');
    unset($city['']);
    array_unshift($city, 'Select city');

How can I improve it ?


texts: Finding the most common character in a string with a hash map

texts:
I created a method for finding the most common character in a string (using HashMap):

public static char getMaxViaHashmap ( String s) {
         HashMap<Character, Integer> map = new HashMap<Character, Integer>();
         char maxappearchar = ' ';
         for (int i = 0; i < s.length(); i++)
         {
              if ( map.containsKey(s.charAt(i)))
              {
                    map.put (s.charAt(i), map.get(s.charAt(i)) + 1 );
              }
              else
              {
                map.put (s.charAt(i), 1);
              }
         }

          int maxValueInMap=(Collections.max(map.values()));  // This will return max value in the Hashmap
            for (Entry<Character, Integer> entry : map.entrySet())
            {
                if (entry.getValue()==maxValueInMap)
                {
                    System.out.println("the max char is : " + entry.getKey() + "  and displayed  " +maxValueInMap+ "  times");     // Print the key with max value
                    maxappearchar = entry.getKey();
                }

            }
            return maxappearchar;
    }

Questions:

What is the performance cost (in terms of \$O()\$)?
What is the memory cost (in terms of \$O()\$)?


texts: Data and vtables vs. objects and methods

texts:
I present a bunch of grids of data to the user, and want to sum certain columns in some of the grids.

// for one such grid:

rows = [{id: 0, name: "Alice", age: "23"},
        {id: 1, name: "Bob", age: "25"} /* ... */]

sum_aggregator = {
    init: function() { return 0 },
    step: function(l, r) { return l + parse(r) },
    stop: function(x) { return x }
}

columns = [{field: 'age', aggregator: sum_aggregator, filter: /* ... */}, /* ... */]

function reduce() { /* pseudocode */
    for each column c: totals[c] = columns[c].aggregator.init()
    for each row r: for each column c:
        totals[c] = columns[c].aggregator.step(totals[c], get_field(r, c))
    for each column c: totals[c] = columns[c].aggregator.stop(totals[c])
    return totals[c]
}

Using vtables---objects containing only functions---such as sum_aggregator seems unidiomatic javascript to me.  I should note that I have several other vtable'y things dealing with the rows (SQL'ish WHERE clauses in filter, etc.), and I'm sorta' jerry-rigging a sum-of-vtables class-like thingy in the columns array.

Is this good design?  Are there benefits to factoring it otherwise?  Gluing the vtable together using smaller building blocks seems like it does something good for concern separation, but using objects with methods seems more javascripty to me.  What are some good ways of thinking in this design space?


texts: Is there a better way to assign two variable to two others conditionally?

texts:
I wrote this code, but it feels like it could be a bit more elegant:

Relevant code only:

GameObject newBall;
GameObject pathBall;
if (tag.Equals(pathBallTagName))
{
    newBall = other.gameObject;
    pathBall = gameObject;
}
else
{
    newBall = gameObject;
    pathBall = other.gameObject;
}

Entire .cs file:

using UnityEngine;
using System.Collections;
using BallDelegate;

public class BallCollider : MonoBehaviour {

    public Spline mySpline;
    private SplineController mySplineController;

    public AllBallManager abm;

    public string pathBallTagName = "PathBalls";
    public string ballTagEnd = "Balls";

    public BoxCollider front;
    public BoxCollider back;
    public BoxCollider spawnArea;

    public string frontName = "BallBox Front";
    public string backName = "BallBox Back";

    public bool isInSpawn = true;

    void Start() {
        mySplineController = GetComponent<SplineController> ();
        BoxCollider[] frontBack = GetComponentsInChildren<BoxCollider> ();
        foreach (BoxCollider bc in frontBack)
            if (bc != null) {
                if (bc.name.Equals (frontName))
                    front = bc;
                else if (bc != null && bc.name.Equals (backName))
                    back = bc;
            }

    }

    void OnTriggerEnter(Collider other) {
        if (mySplineController)
        {
            mySplineController.go = true;
            if (mySpline)
                mySplineController.gravSpline = mySplineController.currentSpline = mySpline;
        }
        if (other == spawnArea) {
            isInSpawn = true;
        }
        else if (!isInSpawn) {
            BallDelegateCS bd = other.gameObject.GetComponent<BallDelegateCS>();
            if (bd) // only balls, no other game objects
            {
                GameObject newBall;
                GameObject pathBall;
                if (tag.Equals(pathBallTagName))
                {
                    newBall = other.gameObject;
                    pathBall = gameObject;
                }
                else
                {
                    newBall = gameObject;
                    pathBall = other.gameObject;
                }
                while (newBall.transform.parent)
                    newBall = newBall.transform.parent.gameObject; // make sure we don't get BallBall
                abm.MakeWayFor(newBall, pathBall);
            }
        }
    }

    void OnTriggerExit(Collider other) {
        if (other == spawnArea) {
            isInSpawn = false;
        }

    }
}


texts: Custom function to scroll spy on the jScrollPane plugin

texts:
I have an element where the jScrollPane is being used to provide custom scrollbars for an extensive text. The idea behind the code is to change the image beside the text each time the user reaches a certain amount of scroll while reading the text.

To have the code flexible, I've prepared a method to detect the number of images available and from there establish the trigger points for the image change. This is all based on the text wrapper height.

Can't this be simplified, thus reducing the amount of code, perhaps in such reduction, have it improved?

HTML structure

jQuery/JavaScript code

$imagesWrap = $('#imageWrap');

if ($imagesWrap.size()==1) {

    //target all images and count them
    var $targets = $imagesWrap.find('> img'),
        total    = $targets.size();

    //for each found, set the CSS z-index
    $targets.each(function(){

        var $this = $(this),
            index = $this.data('index');

        //revert order
        $this.css({
            'z-index': total-index
        });
    });

    var $scrollSpy   = $('.jspPane'),           //the element to spy
        height       = $scrollSpy.height(),     //its height
        stepsTrigger = parseInt(height/total),  //trigger at "every" this distance
        currentPos   = 0;                       //current position (active image)

    setInterval(function(){

        //ascertain current position (insure positive number)
        currentPos = Math.abs(parseInt($scrollSpy.css('top'), 10));

        //ascertain the target image
        var img  = Math.round(currentPos/stepsTrigger),
            id   = img==0 ? 1 : img,
            $tgt = $('img[data-index="'+id+'"]');

        //if different from the already active
        if (!$tgt.hasClass('active')) {

            $imagesWrap.find('.active').removeClass('active').hide();
            $tgt.fadeIn().addClass('active');
        }

    }, 100);
}


texts: Display Object as a node tree in HTML with clickable trace back to root node

texts:
I was given the following code and instructions for a technical test for a potential technical role I had applied for:

var input = {
    label: 'Earth',
    type: 'planet',
    children: [{
        label: 'Australia',
        type: 'country',
        children: [{
            label: 'Sydney',
            type: 'city',
            children: [{
                label: 'Nuix HQ',
                type: 'office',
                children: []
            }]
        }]
    }, {
        label: 'USA',
        type: 'country',
        children: [{
            label: 'San Franscisco',
            type: 'city',
            children: [{
                label: 'Nuix SF',
                type: 'office',
                children: []
            }]
        }, {
            label: 'Philadelphia',
            type: 'city',
            children: [{
                label: 'Nuix Philly',
                type: 'office',
                children: []
            }]
        }]
    }]
};

Task:

  Using Javascript please render HTML element that displays above JSON data.
  It should reflect parent-child relationship by appropriate element nesting and indentation.
  The structure should be right-justified, meaning the indentation should start from the right and move to the left as the nodes descend.
  Additionally, when a node is clicked, it should print (to console) all labels on a path from clicked node to the root (Earth).

  CSS visual styling is optional (nice to have).
  You can use any open-source utilities and libraries available in the fiddle, however we also value simplicity of the solution.
  The solution should be delivered in a fork of this fiddle.

I supplied the additional code as a fork of the original code:

Javascript:

let node = 1;
var result = [];
var arrNodeParent = [];
var arrNodeName = [];
tree = (lvl, parent = 0, node, data) =>
{
    let div = `<div class="node lvl${lvl}" node="${node}" parent="${parent==0?0:parent-1}">${data.label}</div>`;

    arrNodeParent[node] = parent==0?0:parent-1;
    arrNodeName[node] = data.label;

  n = node+=1;
  (data.children.length)&&data.children.forEach(e=>tree(lvl+1, node, n, e));
  result[node]=div;
}

tree(0,0,node,input)

$('.tree').append(...result);

$(".node").click(function(){
    complete = false;
        currNode = $(this);
  while(!complete){
    n = +currNode.attr("node");
    p = +currNode.attr("parent");
        console.log(arrNodeName[n]);
    currNode = $("div[node='"+arrNodeParent[n]+"']");
    complete = (p==0);
  }
});

HTML:

CSS:

.tree {
width: 100%;
}
.node {
  font-size: 12px;
  padding: 3px;
  margin-bottom: 1px;
  border: 1px solid black;
  background-color: rgb(255, 255, 128);
  width: 100px;
  margin-left: auto;
  margin-right: 0px;
}
.node:hover {
  cursor: pointer;
}
.lvl0 {
  margin-right: 0;
}
.lvl1 {
  margin-right: 20px;
}
.lvl2 {
  margin-right: 40px;
}
.lvl3 {
  margin-right: 60px;
}
.lvl4 {
  margin-right: 80px;
}
.lvl5 {
  margin-right: 100px;
}

Now, I was happy with my result, I felt I passed the brief... The client has come back saying I didn't meet the brief... I'm confused here... What specifically have I missed? And is there anything I could have done? I have asked for feedback, but I have yet to receive anything in response... Could someone possibly shed some light?


texts:
Edit: I made a new calculator after taking your input New Calculator

I made this three-function calculator. I have been learning C for a couple of months, and I learned C++ through the internet.
This is my first "real" program in C++, it started really messy but I did a lot of refining and debuging and deleting unnecessary code and this is the final result.
If you see any way to improve it or something I did wrong please tell me.

// Three numbers Calculator
#include "stdafx.h"
#include<iostream>
using namespace std;
int main()
{
    cout << "Enter action as # to exit program" << endl;
    cout << "Possible actions:+,-,*,/\n" << endl;
    while (1) //loop
    {
             long double num1, num2, num3, total;
         char action1, action2;
         cin >> num1 >> action1 >> num2 >> action2 >> num3;
         if (action1 == '/' && num2 == 0 || action2 == '/' && num3 == 0)
             cout << "You can't divide by zero" << endl;
         else if ((action2 == '*' || action2 == '/') && (action1 == '-' || action1 == '+'))  //action2 will be preformed before action1 (Order of operation)
         {
             switch (action2)  //I didn't include the options for '+' or '-' because the if statement requires action2 to be '*' or '/'.
             {
             case('/'):
                 total = num2 / num3;
                 break;
             case('*'):
                 total = num2*num3;
                 break;
             default:
                 cout << "Input not recognized";
                 break;
             }
             switch (action1)   //I didn't include the options for '*' or '/' because the if statement requires action1 to be '+' or '-'.
             {
             case('+'):
                 cout << num1 << "+" << num2 << action2 << num3 << "=" << total + num1;
                 break;
             case('-'):
                 cout << num1 << "-" << num2 << action2 << num3 << "=" << num1 - total;
                 break;
             default:
                 cout << "Input not recognized";
                 break;
             }
         }
         else //action1 will be performed before action2 (Order of operation)
         {
             switch (action1)
             {
             case('+'):
                 total = num1 + num2;
                 break;
             case('-'):
                 total = num1 - num2;
                 break;
             case('/'):
                 total = num1 / num2;
                 break;
             case('*'):
                 total = num1*num2;
                 break;
             case('#'):
                 system("PAUSE");
                 return 0;
                 break;
             default:
                 cout << "Input not recognized";
                 break;
             }
             switch (action2)
             {
             case('+'):
                 cout << num1 << action1 << num2 << "+" << num3 << "=" << total + num3;
                 break;
             case('-'):
                 cout << num1 << action1 << num2 << "-" << num3 << "=" << total - num3;
                 break;
             case('/'):
                  cout << num1 << action1 << num2 << "/" << num3 << "=" << total / num3;
                 break;
             case('*'):
                 cout << num1 << action1 << num2 << "*" << num3 << "=" << total*num3;
                 break;
             case('#'):
                 system("PAUSE");
                 return 0;
                 break;
             default:
                 cout << "Input not recognized";
                 break;
             }
         }
         cout << "\n\n";
     }
}

Update:

  Input: 7+8/2
  Output: 7+8/2=11


texts: C# Pseudo-Code improvement/peer revision

texts:
I have written this Pseudo-Code for the following program, I'm wondering if this might be descriptive enough for anyone to follow up and perform more or less the same program. The program reads and analyzes a set of data in a text file, then displays the information in a filtered way. Any improvements/ revision would be immensely appreciated.

PseudoCode:

Module main ()
//Set up format for text reading.
Declare String content
//Open and read file
Open “Data.txt”
Set contents = opened “Data.txt”

//Declare an array to store and split data

Declare string rows[] = contents split to lines
Declare string table [][] = length of rows[]

//Set loop to iterate through all values

For i is 0 less than length of rows
Table[] increments by 1
End for
//Declare arras to select and parse info
[]districts integer = integer [length of rows]
[] ages integer = integer [length of rows]
For i is 0, i is less than length of rows
i increments by 1
Set i of districts to integer parsing with position [i] in table[]
Set i of ages to integer parsing with position [i] in table[]
End for
// Analyze and pass data
Foreach integer in district
Display “district {0} has {1} resident”, district, countofdistrict.
Display “ Agegroup1 has {0} residents”, count of ages (restriction)
Display “Agegroup2 has {0} residents”, count of ages (restriction)
Display “ Agegroup3 has {0} residents”, count of ages (restriction)
Display “ Agegroup4 has {0} residents”, count of ages (restriction)
Display “ Agegroup5 has {0} residents”, count of ages (restriction)
End foreach

Program:

using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;

    namespace Project_2_practice
    {
        class Program
        {
           static void Main(string[] args)
            {

                //Parsing data into memory
                string content;
                using (StreamReader reader = new StreamReader(File.Open("Data.txt", FileMode.Open)))
                {
                    content = reader.ReadToEnd();
                }
                string[] rows = content.Split('\n'); //Each row is on a new line
                string[][] table = new string[rows.Length][];
                for (int i = 0; i < rows.Length; table[i] = rows[i].Split(','), i++) ;

         //selecting information

                int[] districts = new int[rows.Length];
                int[] ages = new int[rows.Length];

                for (int i = 0; i < rows.Length; i++)
                {
                    districts[i] = int.Parse(table[i][3]);
                    ages[i] = int.Parse(table[i][0]);
                }
                    //Analyzing selected information
                    foreach (int district in districts.Distinct().OrderBy(x => x))
                    Console.WriteLine("District {0} has {1} resident(s)", district, districts.Count(x => x == district));
                    Console.WriteLine("Ages 0-18 : {0} resident(s)", ages.Count(x => x < 18));
                    Console.WriteLine("Ages 18-30 : {0} resident(s)", ages.Count(x => x >= 18 && x <= 30));
                    Console.WriteLine("Ages 31-45 : {0} resident(s)", ages.Count(x => x >= 31 && x <= 45));
                    Console.WriteLine("Ages 46-64 : {0} resident(s)", ages.Count(x => x >= 46 && x <= 64));
                    Console.WriteLine("Ages >=65 : {0} resident(s)", ages.Count(x => x >= 65));
            }
        }
    }


texts:
`Boggle is a word game in which letters are randomly placed in a 4x4 grid
e.g:

A D Q P
N L E M
O S R T
V K J H

Words can be started from any letter and are formed by finding a sequence of connecting letters. Letters may connect diagonally, vertically or horizontally.

Example words on the above board are "son", lad" and "land". Letters may not be re-used.

Below is a recursive solution to the boggle board.
The problem with my solution is it is very slow. I had to limit word length to 8 otherwise it takes far too long.

Please can you comment on general style improvements and if you can think of another method to solve this game, a hint as to what I should do for my next attempt.

The dictionary is from here

"""Boggle game solver"""
import copy

def words_from(board, row, column, running_string="", list_words=[]):
    """Calculate all possible words from a given starting position [row, column]"""
    if row in (4, -1) or column in (4, -1):
        return
    if len(running_string) > 4:
        return
    if board[row][column] != "-":
        new_string = running_string + board[row][column]
        new_board = copy.deepcopy(board)
        new_board[row][column] = "-"
        # Add new word
        if len(new_string) >= 3:
            list_words.append(new_string.lower())

        # Find next word
        next_move = [
            (1, 1),
            (-1, -1),
            (1, -1),
            (-1, 1),
            (1, 0),
            (0, 1),
            (-1, 0),
            (0, -1),
        ]
        for dx, dy in next_move:
            words_from(new_board, row + dx, column + dy, new_string, list_words)
        return list_words

def get_permutations(board):
    """Get all permutations """
    set_permutations = set()
    counter = 0
    print("Working..", end = "")
    for row in range(4):
        for column in range(4):
            print(".", end="")
            counter += 1
            words = words_from(board, row, column, list_words=[])
            if words:
                for word in words:
                    set_permutations.add(word)
            words = None
    return sorted(list(set_permutations))

def dictionary_check(set_permuations):
    """Check set_permutations for valid English words"""
    dictionary = {}
    with open("en-dict.txt", "r", encoding="utf8") as file:
        for line in file:
            dictionary[line.strip()] = 0

    counter = 0
    for word in set_permuations:
        if word.lower() in dictionary:
            counter += 1
            print(word)
    print(f"======\n{counter} words")

def find_words(board):
    """Find words on the boggle board"""
    set_permutations = get_permutations(board)
    print("Performing dictionary check....")
    dictionary_check(set_permutations)

def build_board(string):
    """Build board from string"""
    if len(string) != 16:
        print("Error. Must enter 4*4 grid (16 characters)")
        return
    board = [[*string[0:4]], [*string[4:8]], [*string[8:12]], [*string[12:16]]]
    find_words(board)

if __name__ == "__main__":
    string_board = "playthiswordgame"
    build_board(string_board)


texts: Matching Needle & Haystack values using alternate Ontology values

texts:
I need to match values in Needle & Haystack arrays, using alternate Ontology values when relevant.

This syntax works, however I would like to know if there is a more efficient way to do this as I will be using it for several corresponding $AltNeedle arrays for each of 1000+ $needles and $haystack arrays.

In my use case, the Needle & Haystack correspond with Product and Customer attributes respectively, and matches are made and ranked by assessing thousands of attributes for each, and attributes often have an array of values. One way in which Alt. Values are used are to incorporate closely related values into certain match results.

<?php
$needles = ['John', 'Alex', 'Pam'];
$haystack = ['John','Alexander','Kim', 'Michael'];
$AltNeedle = ['Alexander', 'Alex', 'Alexi'];

foreach ($needles as $current_needle) {
    if (in_array($current_needle, $AltNeedle) ) { // Exists in $AltNeedle
        foreach ($AltNeedle as $current_AltNeedle) {
                if (in_array($current_AltNeedle, $haystack) ) { // Compares $current_AltNeedle to $haystack
                    echo $current_AltNeedle." True; ";
                }
        } // Ends $AltNeedle foreach
    }
    elseif (in_array($current_needle, $haystack) ) {
        echo $current_needle.": True; ";
    }
    else {
        echo $current_needle.": False; ";
    }
} // End foreach
?>

RESULT:

  John: True; Alexander True; Pam: False;


texts: Initializing multiple variables with different types using parallel calls

texts:
Consider the pattern below, where multiple async calls are made in parallel:

var thisTask = ThisAsync();
var thatTask = ThatAsync();

await Task.WhenAll(thisTask, thatTask);

var this = await thisTask;
var that = await thatTask;

While it works fine, I find it a bit too verbose for what it is doing.

While having some fun with tuple types, I came up with the following approach that results in the same behavior:

var (this, that) = await (ThisAsync(), ThatAsync()).ResultsAsync();

It relies on an extension method on a tuple of Tasks, like below:

static class ParallelTasksExtensions
{
    static async Task<(T1, T2)> ResultsAsync<T1, T2>(this (Task<T1>, Task<T2>) tasks)
    {
        await Task.WhenAll(tasks.Item1, tasks.Item2);

        return (await tasks.Item1, await tasks.Item2);
    }
}

With a couple overloads (wish C# supported variadic generic types like C++ does in templates) this can be extended to an arbitrary number of parallel calls, so that we can have something like this:

var (one, two, three, four) = await (OneAsync(), TwoAsync(), ThreeAsync(), FourAsync()).ResultsAsync();

I like it quite a bit because of the following reasons:

Is is dramatically shorter. Usually shorter code leads to less chance of problems (not a golden rule of course, but I feel it applies here)
It requires less state to be maintained (less variables)
It avoids people calling .Result instead of await on the original tasks (a common bad practice)

Another option that would result in the same behavior would be to create an extension class instead of coding this as an extension method.

For example:

var (this, that) = await TaskEx.WhenAll((ThisAsync(), ThatAsync()));

This approach would be more inline with existing, non-tuple based overloads of Task.WhenAll.

Thoughts?

Is it "too clever" in your opinion? I don't think there is any similar native construct that achieves this so it could be seen as clever by some I'm sure.
Do you consider this over-engineering?
Is it more readable/intuitive to you?
Do you have other suggestions for the method name?


texts:
I worried about this code in a ViewModel. ViewModel should not contain any code except binding's. But without async update the ui would freeze. How do I improve it? I'm restricted to using .net 3.5 or below.

public ShippingDocumentsRegisterViewModel()
{
    this.Columns = model.InitializeColumns();
    Action<object> Documents = new Action<object>(GetDocumentsAsync);
    IAsyncResult result = Documents.BeginInvoke(new AsyncCallback(GetDocumentsAsync),null, null);
}

public void GetDocumentsAsync(object param)
{
    this.ShippingDocuments = model.GetDocuments();
}

Model:

class ShippingDocumentsModel
    {
        public ObservableCollection<ShippingDocument> GetDocuments()
        {
            var documents = new ObservableCollection<ShippingDocument>();
            for (int i = 0; i < 100; i++)
            {
                System.Threading.Thread.Sleep(50);
                documents.Add(new ShippingDocument { Name = i.ToString() });
            }
            return documents;
        }

        public ObservableCollection<ShippingDocumentColumDescriptor> InitializeColumns()
        {
            return new ObservableCollection<ShippingDocumentColumDescriptor>
            {
                new ShippingDocumentColumDescriptor { HeaderText = "Статус", DisplayMember = "Status" },
                new ShippingDocumentColumDescriptor { HeaderText = "Підпис", DisplayMember = "Signature" }
            };
        }
    }

ViewModel:

public class ShippingDocumentsRegisterViewModel : ViewModelBase
    {
        ShippingDocumentsModel model = new ShippingDocumentsModel();

        public ShippingDocumentsRegisterViewModel()
        {
            this.Columns = model.InitializeColumns();
            Action<object> Documents = new Action<object>(GetDocumentsAsync);
            IAsyncResult result = Documents.BeginInvoke(new AsyncCallback(GetDocumentsAsync),null, null);
        }

        public void GetDocumentsAsync(object param)
        {
            this.ShippingDocuments = model.GetDocuments();
        }

        private ObservableCollection<ShippingDocument> shippingDocuments;

        public ObservableCollection<ShippingDocument> ShippingDocuments
        {
            get
            {
                return shippingDocuments;
            }

            private set
            {
                shippingDocuments = value;
                RaisePropertyChanged("ShippingDocuments");
            }
        }

        public ObservableCollection<ShippingDocumentColumDescriptor> Columns { get; private set; }

        private ICommand _addColumnCommand;

        public ICommand AddColumnCommand
        {
            get
            {
                if (_addColumnCommand == null)
                {
                    _addColumnCommand = new RelayCommand<string>(
                        s =>
                        {
                            this.Columns.Add(new ShippingDocumentColumDescriptor { HeaderText = s, DisplayMember = s });
                        });
                }
                return _addColumnCommand;
            }
        }

        private ICommand _removeColumnCommand;

        public ICommand RemoveColumnCommand
        {
            get
            {
                if (_removeColumnCommand == null)
                {
                    _removeColumnCommand = new RelayCommand<string>(
                        s =>
                        {
                            this.Columns.Remove(this.Columns.FirstOrDefault(d => d.DisplayMember == s));
                        });
                }
                return _removeColumnCommand;
            }
        }
    }

Edit:

I think maybe this solution would be better?

BackgroundWorker BW = new BackgroundWorker();
            BW.DoWork += (o, e) =>
            {
                this.ShippingDocuments = model.GetDocuments();
            };
            BW.RunWorkerAsync();


texts:
I want to count specific strings from array values

$array = array("report=D","report=D","report=D","report=I","report=I");

I am going to count the number of D,U & I, as well as their meanings.

D = Delivered
U = Undelivered
I = Invalid

I am expecting an output of:

D = 3
U = 0
I = 2

First, I replace "report=" using str_replace(), then array_filter is used to count specific values.

<?php

$array = array(
"report=D","report=D","report=D","report=I","report=I"
);

$array = str_replace("report=","",$array);

function getting_u($n) { return $n == "U"; }

function getting_d($n) { return $n == "D"; }

function getting_i($n) { return $n == "I"; }

$result_of_u = array_filter($array, "getting_u");
$result_of_d = array_filter($array, "getting_d");
$result_of_i = array_filter($array, "getting_i");

print_r($result_of_u);
print_r($result_of_d);
print_r($result_of_i);

echo "Count of U = ".count($result_of_u);
echo "\n";
echo "Count of D = ".count($result_of_d);
echo "\n";
echo "Count of I = ".count($result_of_i);
?>

See a working code here.

The code seems to work fine for me, but I'm concerned whether this is the correct/best method of procedure.

I am also unsure if my code contains any strange behaviour or present/future problems.


texts:
I've just implemented counting sort in C and would like to hear your opinions on it. As I'm usually being rather picky when rating other people's code, please go ahead and be picky, too -- I will try and justify my decisions but I'm thankful for any hints :)

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

/**
 * parses "[ a , b , c ]" into an array.
 * requirements:
 *  * first character must be a '['
 *  * subsequent characters until closing ']' must be `unsigned integer`,
 *    seperated by ','. Leading and trailing whitespace ignored.
 *
 * @return:
 *  * 0 on success
 *  * 1 if there was found an element > max
 *  * 2 if not len elements were found
 */
int parse_uint_array(size_t len, unsigned int maxval, unsigned int array[len],
        char *input)
{
    /* start at 1 to skip leading '[' */
    unsigned int pos = 1;
    for (size_t i = 0; i < len; i++)
    {
        int ccount;
        int n = sscanf(&input[pos], " %u , %n", &array[i],
                &ccount);
        if (n != 1 && i+1 < len) return 2;
        if (array[i] > maxval) return 1;
        pos += ccount;
    }
    return 0;
}

void print_uint_array(size_t len, unsigned int array[len])
{
    printf("[");
    for (size_t i = 0; i+1 < len; i++) {
        printf("%u, ", array[i]);
    }
    printf("%u]\n", array[len-1]);
}

/**
 * sorts an array of len size with maximum value maxval (can be less) which has
 * to be < UINT_MAX
 *
 * @returns
 *  * 1 if maxval+1 = 0, ie. usually maxval = UINT_MAX.
 *    This limitation is due to how counting sort works
 *  * 2 if malloc fails
 *  * 3 if an element is bigger than specified maxval
 */
int countsort_uint(size_t len, unsigned int maxval, unsigned int array[len])
{
    if (maxval+1 == 0) return 1;

    unsigned int *counts = malloc(sizeof(int)*(maxval+1));
    if (counts == NULL) {
        perror("malloc");
        return 2;
    }

    for (size_t i = 0; i < len; i++) {
        if (array[i] > maxval) return 3;
        counts[array[i]] += 1;
    }

    size_t pos = 0;
    for (size_t i = 0; i < (maxval+1); i++) {
        for (size_t j = pos; j < counts[i]+pos; j++) {
            assert(counts[i]+pos <= len);
            array[j] = i;
        }
        pos += counts[i];
    }
    assert(pos == len);

    free(counts);

    return 0;
}

int main(int argc, char *argv[])
{
    if (argc < 4) {
        fprintf(stderr, "not enough parameters supplied\n");
        return 1;
    }

    size_t len; if (sscanf(argv[1], "%zu", &len) != 1) return 2;
    if (len == 0) {
        fprintf(stderr, "length shouldn't be 0\n");
        return 4;
    }
    unsigned int max; if (sscanf(argv[2], "%u", &max) != 1) return 3;
    if (max+1 == 0) {
        fprintf(stderr, "maximum value < UINT_MAX\n");
        return 5;
    }

    unsigned int *array = malloc(sizeof(int)*len);
    if (array == NULL) {
        perror("malloc");
        return 6;
    }

    {
        int err;
        if ( (err = parse_uint_array(len, max, array, argv[3])) ) {
            fprintf(stderr, "parse_uint_array: returned %d\n", err);

            switch (err) {
            case 1:
                fprintf(stderr, "not all elements were less or equal than specified maximum\n");
                break;
            case 2:
                fprintf(stderr, "malformed array or less elements than specified\n");
                break;
            default:
                fprintf(stderr, "unknown error\n");
                break;
            }

            return 7;
        }
    }

    print_uint_array(len, array);

    {
        int err;
        if ( (err = countsort_uint(len, max, array)) ) {
            fprintf(stderr, "countsort_uint: returned %d\n", err);
            return 8;
        }
    }

    print_uint_array(len, array);

}


texts:
I have 3 simple similar event handler functions that I would like to refactor. Any suggestions?

private void btnBuildingList_Click(object sender, EventArgs e)
    {
        selectedExportType = (int)ExportType.Building;
        path = csvFilePath + String.Format("{0:yyyy-MM-dd}", datDate.DateTime) + "-BuildingList.csv";
        Export();
    }

    private void btnOwnerList_Click(object sender, EventArgs e)
    {
        selectedExportType = (int)ExportType.Persons;
        path = csvFilePath + String.Format("{0:yyyy-MM-dd}", datDate.DateTime) + "-OwnerList.csv";
        Export();
    }

    private void btnFacts_Click(object sender, EventArgs e)
    {
        selectedExportType = (int)ExportType.Facts;
        path = csvFilePath + String.Format("{0:yyyy-MM-dd}", datDate.DateTime) + "-FactsData.csv";
        Export();
    }


texts:
I'm trying to do some rudimentary DDD in validating my objects to ensure they are of a particular type. I.e. an Email object would always look like "my@example.com" and a NaturalNumber is always greater than 0.

However, I'm struggling to make it reusable. The closest I've got is a factory:

open class ConstrainedStringFactory<T>(private val creator: (String) -> T, private val validator: (String) -> Boolean) {
    operator fun invoke(value: String?): T? = value?.let { if (validator.test(it)) creator.apply(it) else null }
}

This can then be included as a companion object by any class wishing to verify it's type:

class Email private constructor(val email: String) {
    companion object Factory: ConstrainedStringFactory<Email>(::Email, { EMAIL_REGEX.matches(it) }) {
        @JvmStatic
        private val EMAIL_REGEX = "^.+@.+\\..+".toRegex()
    }
}

class NonBlankString private constructor(val value: String) {
    companion object Factory : ConstrainedStringFactory<NonBlankString>(::NonBlankString, String::isNotBlank)
}

This does exactly what I want: creating a new object is either valid or it's null (which can be checked safely):

val email = Email("invalid") ?: throw IlllegalArgumentException

Where this falls down is on generalisation. If I have a list of Spring Converter objects, for instance, I need to convert each individually:

Converter<String, NonBlankString> { value ->
    NonBlankString(value) ?: throw IllegalArgumentException("The string cannot be empty")
},
Converter<NonBlankString, String> { nonBlank->
    nonBlank.toString()
},
Converter<String, Email> { value ->
    Email(value) ?: throw IllegalArgumentException("The email is not valid")
},
Converter<Email, String> { email ->
    email.toString()
}

This seems like a lot of duplication given the objects have the same signature. And it can occur in other places. Is there some way to use an interface or a parent class to make this generalise better?

Ignoring any language limitations, something similar to the following which would reduce all the boilerplate is what I'm after:

class Email private constructor(val email: String) extends ConstrainedString(email, { EMAIL_REGEX.matches(it) }) {
}

class NonBlankString private constructor(val value: String) extends ConstrainedString(value, String::isNotBlank) {
}

Converter<ConstrainedString, String> { value ->
    value.toString()
}


texts:
Here are 3 methods which handle my ajax calls.

I loop until pass b.c. I've had problems with the Ajax Object working as expected.  This is noted here

/**
 *    Ajax
 */

var Ajax = ( function ()
{
    var Ajax = function (element)
    {
        this.object = this.create();
    };
    Ajax.prototype.create = function()
    {
        var request;
        try
        {
            request = new window.XMLHttpRequest();
        }
        catch( error )
        {
            try
            {
                request = new window.ActiveXObject( "Msxml2.XMLHTTP" );
            }
            catch( error )
            {
                try
                {
                    request = new window.ActiveXObject( "Microsoft.XMLHTTP" );
                }
                catch( error )
                {
                    request = false;
                }
            }
        }
        return request;
    };
    Ajax.prototype.use = function( param, ajax_func )
    {
        var GATEWAY = 'class.ControlEntry.php';
        var self = this;
        this.object.open( "POST", GATEWAY, true );
        this.object.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
        this.object.setRequestHeader( "Content-length", param.length );
        this.object.setRequestHeader( "Connection", "close" );
        this.object.onreadystatechange = function()
        {
            if( this.readyState === 4 )
            {
                if( this.status === 200 )
                {
                    ajax_func( this.responseText );
                    return true;
                }
                else
                {
                    self.invoke( param, ajax_func );
                    return false;
                }
            }
        };
        this.object.send( param );
        return true;
    };
    Ajax.prototype.invoke = function( param, ajax_func )
    {
        var state = false,
            count = 1;
        while( state === false && count <= 5 )
        {
            if( count !== 1 )
            {
                alert( 'Ajax Object Use Failed | Try Again ');
            }
            state = this.use( param, ajax_func );
            count++;
        }
        return state;
    };
    return Ajax;
} () );


texts:
Sum Lists: You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in
  reverse order, such that the 1 's digit is at the head of the list.
  Write a function that adds the two numbers and returns the sum as a
  linked list.

  EXAMPLE

  Input: (7-> 1 -> 6) + (5 -> 9 -> 2).That is,617 + 295

  Output: 2 -> 1 -> 9. That is, 912

Is there any way to improve the code?

def sumList(list1:List[Int], list2:List[Int], curry: Int):List[Int]= (list1.size,list2.size) match {
    case (0,0)=>List.empty
    case (0, b) =>sumList(List.empty, list2.tail, if(list2.head+curry>10)(list2.head+curry)/10 else 0):::List((list2.head+curry)%10)
    case (a,0)  =>sumList(list1.tail,List.empty , if(list1.head+curry>10)(list1.head+curry)/10 else 0):::List((list1.head+curry)%10)
    case (a,b) =>sumList(list1.tail,list2.tail, if(list1.head+list2.head+curry>10)(list1.head+list2.head+curry)/10 else 0):::List((list1.head+list2.head+curry)%10)
  }


texts:
I'm a complete neophyte to Haskell with only a smidge of FP experience – I did some Racket programming academically and have written some semi-FP JavaScript professionally, but now I'm trying to learn Haskell (and FP better). So I read Haskell Fast & Hard with no problems up until the last chapter.

Monads.

  Make a program that sums all of its arguments. Hint: use the function getArgs.

I eventually wrote a program that nominally achieves this requirement, but it felt very hacky. For reference, here is a "correct" program by the author that I think I was supposed to model after. It sums the numbers in a comma-delimited string.

import Data.Maybe

maybeRead :: Read a => String -> Maybe a
maybeRead s = case reads s of
                  [(x,"")]    -> Just x
                  _           -> Nothing
getListFromString :: String -> Maybe [Integer]
getListFromString str = maybeRead $ "[" ++ str ++ "]"
askUser :: IO [Integer]
askUser = do
  putStrLn "Enter a list of numbers (separated by comma):"
  input <- getLine
  let maybeList = getListFromString input in
      case maybeList of
          Just l  -> return l
          Nothing -> askUser
-- show
main :: IO ()
main = do
  list <- askUser
  print $ sum list

Based on the above approach, I wrote a function to convert the list of argument-strings back into a comma-delimited string so that most of the other functions could work unchanged.

import Data.Maybe
import System.Environment (getArgs)

maybeRead :: Read a => String -> Maybe a
maybeRead s = case reads s of
                  [(x,"")]    -> Just x
                  _           -> Nothing
getListFromString :: String -> Maybe [Integer]
getListFromString str = maybeRead $ "[" ++ str ++ "]"
getArgsAsString :: [String] -> String
getArgsAsString [] = "0"
getArgsAsString (x:xs) = x ++ "," ++ getArgsAsString xs
askUser :: [String] -> [Integer]
askUser input = case (getListFromString (getArgsAsString input)) of
            Just l  -> l
            Nothing -> error "failsauce"
main :: IO ()
main = do
  input <- getArgs
  print $ sum (askUser input)

I am trying to stick to the spirit of the exercise and not go too far into library functions that solve the problem for me without teaching me anything (in particular, the author says not to try too hard to understand the syntax of maybeRead), but it feels very wrong to convert a list of strings to a comma-separated string only to split it out again into a maybe-list of integers.

All advice is appreciated! (But educational guidance is appreciated more than "just use xyz lib function".)


texts:
I have a struct OPTS which contains a few chars and char[]s. I also have a file opts.cnf which can be edited in a text editor like vim. I want to read the opts.cnf and assign the values from that file to my struct.

opts.h

typedef struct OPTS {
  char opt1;
  char opt2[6];
  char opt3;
}

opts.cnf

OPT1=Y
OPT2=1234
OPT3=D

opts.c

while (fgets (work, sizeof (work), file) ) {
   if (!strncmp (work, "OPTS1=", 6) ) {
      optptr->opt1 = topper(work[6]);
   }
   if (!strncmp (work, "OPTS2=", 6) ) {
      sprintf(optptr->opt2, "%-4.4s", &work[6]);
   }
   if (!strncmp (work, "OPTS3=", 6) ) {
      optptr->opt3 = topper(work[6]);
   }
}

Is there a more efficient way to go about this? I need to be able to edit opts.cnf inside of a text editor but different formats are welcome if they make it more efficient.


texts: Does iterating through a large data set in a Map each time i click impact the performance?

texts:
I need to get values from a Map by Adapter position i get from a RecyclerView.

As you can see each time i click on an Album Art i create a new array of album objects.

final Album[] albums = new Album[albumMap.size()];
      for (Map.Entry<Integer,Album> e : albumMap.entrySet()){
      albums[i++] = e.getValue();
 }

Then i get the album like this: String selectedAlbum = albums[position].getAlbum();

But what if someone has like 10000+ albums on his device and each time an album is clicked a new array of album objects is created and i iterate through it just to get the album name.

Would this have an impact on performance if there are alot of albums present?

TL;DR Is this code bad?

Full code

@Override
    public void onClickAlbum(int position, Map<Integer,Album> albumMap) {
        if (getActivity() != null) {
            int i = 0;
            final Album[] albums = new Album[albumMap.size()];
            for (Map.Entry<Integer,Album> e : albumMap.entrySet()){
                albums[i++] = e.getValue();
            }
            String selectedAlbum = albums[position].getAlbum();
            Main.getInstance().setSongsFilteredBy(SongsLibrary.getInstance().getSongsByAlbum(selectedAlbum));
            Intent intent = new Intent(getActivity(), ListSongsActivity.class);
            intent.putExtra("title", selectedAlbum);
            startActivity(intent);
            Toast.makeText(getActivity(), "test: " + selectedAlbum, Toast.LENGTH_SHORT).show();
        }
}


texts: Processing the results of API calls and process data

texts:
I'm making use of RxJS and observables within my Angular application to process the results of API calls and process data. I've written the component and it works without any issues. However after further research into RxJS and observables I've became aware that the way in which I am using subscriptions is considered bad practice.

Essentially I have a function that subscribes to an observable, then inside the subscription a second function is called which doesn't make use of the data from the first subscription, but subscribes to a separate observable to track the state of a particular variable. Then within the same function a third method is called which does make use of data passed from the first subscription and uses it to make an API call and return some data.

What I want to do is refactor this code so that the same behaviour occurs but so that I am making use of switchMap or other RxJS functions so that the bad practice within my code is removed. However I am unsure as to how I should be employing the use of switchMap etc.

I'll post my code below with each function I have described and annotated.

initSettings(){
    this.getOrganisations$().subscribe( (res: AdminOrganisation[]) => {  //This is the first subscription that makes a get request to return an array of AdminOrganisation objects
      this.organisations = res;                                          //this results of this subscription are used to display different input options to the user in the form of
      this.serial = this.organisations[0].serialRef;                     //a mat-list.
      this.currentOrganisationName = this.organisations[0].serialName;
      this.buildSettingsForm(this.serial);
    });
  }

  buildSettingsForm(serial: string) {
    this.ipRangeFormGroup = this.formBuilder.group(
        {
          ipRanges: this.formBuilder.array([])
        }
    );

    this.numArrayElements = this.ipRangeFormArray.length;

    this.ipRangeFormArray.valueChanges.subscribe(changes => {           //This is the second subscription, this one does not require any external inputs but does rely on the
      this.numArrayElements = this.ipRangeFormArray.length;             //this.ipRangeFormArray being instantiated before it can be called, therefore it has to be create
    });                                                                 //syncronously and after the first subscription has recieved and utilised data.

    this.setSettings(serial);
  }

  setSettings(serial: string) {                                                     //This is the third subscription, this subscription utilises the this.serial variable that
    this.getSettingsFromSerial$(serial).subscribe(val => {                          //is retrieved by the first subscription and therefore relies on the data from the first
      this.savedSettingsState = val;                                                //observable to function. Like the second sub, this one also needs to occur after the first
      this.ipRestrictionEnabled = val.ipRestrictionSettings.ipRestrictionEnabled;   //has processed its data.
      for (const i of val.ipRestrictionSettings.ipRanges) {
        this.addRange(i.startRange, i.endRange, i.label);
      }
      this.displayForm = true;
    });
  }

Once I have a grasp on how I should be utilising switchMap/mergeMap/etc I'll be more confident in making this refactorings and improvements myself. But since I am relatively new to Angular I'm unsure as to what the best practice is when making use of these functions to prevent chains of subscriptions like what I have below.


texts:
I have an HTML form being populated by a table of customer requests.  The user reviews each request, sets an operation, and submits.  The operation gets set into a post arg as follow

$postArray = array_keys($_POST);

[1]=>Keep [2]=>Reject [3]=>Reject [4]=>Ignore ["item id"]=>"operation"

This is how I am parsing my Post args... it seems awkward, the unused $idx.  I am new to PHP, is there a smoother way to do this?

$postArray = array_keys($_POST);
foreach($postArray as $idx => $itemId) {
    $operation = $_POST[$itemId];
    echo "$itemId $operation </br>";
    ...perform operation...
}


texts:
I'm trying to recreate the method inject (Works like Reduce) from ruby Enumerable Module.
Using Rubocop (A Linter) I got the error:

Cyclomatic complexity for my_inject is too high. [7/6]

The code is:

module Enumerable
  def my_inject(*args)
    list = to_a if Range
    reduce = args[0] if args[0].is_a?(Integer)
    operator = args[0].is_a?(Symbol) ? args[0] : args[1]

    if operator
      list.each { |item| reduce = reduce ? reduce.send(operator, item) : item }
      return reduce
    end
    list.each { |item| reduce = reduce ? yield(reduce, item) : item }
    reduce
  end
end

I already did my best to reduce the Cyclomatic complexity,
but still have 1 above (7/6), now I stuck, any directions will be appreciate.

The code can be run on reply:
https://repl.it/@ThiagoMiranda2/INJECT


texts: jQuery script to toggle an element and handle a Close button

texts:
First of all: I am a total javascript beginner and therefore I am asking you to rate my script and tell me whether its okay or just a big mess. Note: it does work, but I guess it could be improved.

My main goal was to create a script, than can be used multiple times and does not depend on any class or id name (thats why I am using the data attribute).

$(function(){
    var toggleOpen      = $('*.[data-toggle="open"]');
    var toggleContent   = $('*.[data-toggle="content"]');
    var toggleClose     = $('*.[data-toggle="close"]');
    var toggleSpeed     = 500;
    //Set height of toggle content to avoid animation jumping
    toggleContent.css('height', toggleContent.height() + 'px');
    //Find content to toggle
    function findNextContent(target){
        var nextContent = target.parent().parent().parent().find(toggleContent);
        return nextContent;
    }
    //Toggle content
    function slideToggle(target){
        target.stop(true,true).slideToggle(toggleSpeed);
    }
    //CLose toggled content
    function closeToggle(target){
        target.slideUp(toggleSpeed);
    }
    //On Open Click
    toggleOpen.click(function(){
        var clicked     = $(this);
        var nextContent = findNextContent(clicked);
        //Check if hidden to either scroll to bottom or not
        if(nextContent.is(':hidden')){
            slideToggle(nextContent);
            smoothScrolling(toggleClose);
        }else{
            slideToggle(nextContent);
        }
        return false;
    });
    //On Close click
    toggleClose.click(function(){
        var clicked     = $(this);
        var nextContent = findNextContent(clicked);
        closeToggle(nextContent);
        return false;
    });
});

What it does: It toggles an element and it also takes care of a seperate close button.

I am glad for any feedback - be it positive or negative!


texts: Writing computer generated music to a .wav file in C

texts:
See the next iteration.

I wrote this simple C program for writing computer generated music to a WAV file over three years ago. I refactored it a little, but it does not look good to me. Any suggestions?

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

/******************************
*  Magic file format strings. *
******************************/
const char fChunkID[]     = {'R', 'I', 'F', 'F'};
const char fFormat[]      = {'W', 'A', 'V', 'E'};
const char fSubchunk1ID[] = {'f', 'm', 't', ' '};
const char fSubchunk2ID[] = {'d', 'a', 't', 'a'};

/********************************
* WriteWavePCM() configuration: *
* - 2 channels,                 *
* - frequency 44100 Hz.         *
********************************/
const unsigned short N_CHANNELS = 2;
const unsigned int SAMPLE_RATE = 44100;
const unsigned short BITS_PER_BYTE = 8;

bool WriteWavePCM(short* sound, size_t pairAmount, char* fileName){
    const static unsigned int fSubchunk1Size = 16;
    const static unsigned short fAudioFormat = 1;
    const static unsigned short fBitsPerSample = 16;

    unsigned int fByteRate = SAMPLE_RATE * N_CHANNELS *
                             fBitsPerSample / BITS_PER_BYTE;

    unsigned short fBlockAlign = N_CHANNELS * fBitsPerSample / BITS_PER_BYTE;
    unsigned int fSubchunk2Size;
    unsigned int fChunkSize;

    FILE* fout;
    size_t ws;

    if (!sound || !fileName || !(fout = fopen( fileName, "w" ))) return false;

    fSubchunk2Size = pairAmount * N_CHANNELS * fBitsPerSample / BITS_PER_BYTE;
    fChunkSize = 36 + fSubchunk2Size;

    // Writing the RIFF header:
    fwrite(&fChunkID, 1, sizeof(fChunkID),      fout);
    fwrite(&fChunkSize,  sizeof(fChunkSize), 1, fout);
    fwrite(&fFormat, 1,  sizeof(fFormat),       fout);

    // "fmt" chunk:
    fwrite(&fSubchunk1ID, 1, sizeof(fSubchunk1ID),      fout);
    fwrite(&fSubchunk1Size,  sizeof(fSubchunk1Size), 1, fout);
    fwrite(&fAudioFormat,    sizeof(fAudioFormat),   1, fout);
    fwrite(&N_CHANNELS,      sizeof(N_CHANNELS),     1, fout);
    fwrite(&SAMPLE_RATE,     sizeof(SAMPLE_RATE),    1, fout);
    fwrite(&fByteRate,       sizeof(fByteRate),      1, fout);
    fwrite(&fBlockAlign,     sizeof(fBlockAlign),    1, fout);
    fwrite(&fBitsPerSample,  sizeof(fBitsPerSample), 1, fout);

    /* "data" chunk: */
    fwrite(&fSubchunk2ID, 1, sizeof(fSubchunk2ID),      fout);
    fwrite(&fSubchunk2Size,  sizeof(fSubchunk2Size), 1, fout);

    /* sound data: */
    ws = fwrite(sound, sizeof(short), pairAmount * N_CHANNELS, fout);
    fclose(fout);
    return true;
}

/************************************
* Around 23 seconds of pure techno! *
************************************/
const unsigned int N_SAMPLE_PAIRS = 1048576;

int main(int argc, char* argv[]){
    short* sound;
    int i;
    int j;
    bool status;
    char* file_name;

    sound = (short*) malloc( sizeof(short) * N_SAMPLE_PAIRS * N_CHANNELS );

    if (!sound)
    {
        puts("Could not allocate space for the sound data.");
        return (EXIT_FAILURE);
    }

    for (i = 0, j = 0; i < N_SAMPLE_PAIRS * N_CHANNELS; i += 2, j++ )
    {
        short datum1 = 450 * ((j >> 9 | j >> 7 | j >> 2) % 128);
        short datum2 = 450 * ((j >> 11 | j >> 8 | j >> 3) % 128);

        sound[i]     = datum1; // One channel.
        sound[i + 1] = datum2; // Another channel.
    }

    file_name = argc > 1 ? argv[1] : "Default.wav";
    status = WriteWavePCM(sound, N_SAMPLE_PAIRS, file_name);
    free(sound);

    if (status)
    {
        printf("Discotheque is ready in \"%s\"\n", file_name);
    }
    else
    {
        puts( "Something seems to have gone wrong." );
        return (EXIT_FAILURE);
    }

    return 0;
}

(What comes to playing the generated file, VLC and QuickTime Player are capable to play it; not sure about other media players.)


texts:
I'm trying to set up a contact form using phpmailer. Are there any security holes in my code? I want to be sure as I feel there might be some kinda exploit I may not be aware of.

<?php

if (isset($_POST['submit'])) {

    if ($_POST['name'] != "") {
        $_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
        if ($_POST['name'] == "") {
            $errors .= 'Please enter a valid name.

';
        }
    } else {
        $errors .= 'Please enter your name.
';
    }

    if ($_POST['email'] != "") {
        $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors .= "$email is NOT a valid email address.

";
        }
    } else {
        $errors .= 'Please enter your email address.
';
    }

    if ($_POST['brand'] != "") {
        $_POST['brand'] = filter_var($_POST['brand'], FILTER_SANITIZE_STRING);
        if ($_POST['brand'] == "") {
            $errors .= 'Please enter a valid brand.

';
        }
    } else {
        $errors .= 'Please enter a brand.
';
    }

    if ($_POST['type'] != "") {
      $error .= "
You forgot to select eyeglass type!
";
    }

    if ($_POST['message'] != "") {
        $_POST['message'] = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
        if ($_POST['message'] == "") {
            $errors .= 'Please enter a message to send.
';
        }
    } else {
        $errors .= 'Please enter a message to send.
';
    }

    if (!$errors) {

        require('phpmailer/class.phpmailer.php');

        $mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
        $mail->IsSendmail(); // telling the class to use SendMail transport
        $mail->setCharset = "UTF-8";

          $mail->AddReplyTo($_POST["email"], $_POST["name"]);
          $mail->AddAddress("email@address.com");
          $mail->SetFrom($_POST["email"], $_POST["name"]);
          $mail->AddReplyTo($_POST["email"], $_POST["name"]);
          $mail->Subject = 'Home page contact form';
          $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
          $mail->IsHTML(true);
          $mail->Body = str_replace( "\n", '
', $formcontent );
          if(is_array($_FILES)) {
          $mail->AddAttachment($_FILES['file']['tmp_name'],$_FILES['file']['name']);
          }
          $mail->Send();
          header('Location: http://www.google.com');

    } else {
        echo '
' . $errors . '

';
    }
}
?>


texts: Portable (Linux, Cygwin,...) Makefile for my own Shell OpenSSL file en-/decryption scripts

texts:
Let it be clear that in this question I ask for further guidance with my current version of Makefile used for my own Shell OpenSSL file en-/decryption scripts, not those scripts themselves.

I did my best, but this is my own first Makefile, so I better give it to you for review. I may only think the work is done, there may be many issues I don't know about.

Requirements:

The implicit destination path must be easily overridden without having to edit the Makefile
The implicit target must check for integrity (hashsum) stored in the file SHA512SUMS
The file must account for non-standard Linux environments like Cygwin
I myself tested it under normal circumstances in Linux Mint 18.3 and Cygwin
All files can be simply acquired from GitHub page of this little project

The Makefile follows:

DESTDIR?=/usr/local/bin
install_path=$(DESTDIR)

script_name_1=encrypt-file-aes256
script_name_2=decrypt-file-aes256

user_id=$(shell whoami)
group_id=$(shell id -gn)

.PHONY: check
.PHONY: install
.PHONY: uninstall

check:
    [ -f $(script_name_1) ] && [ -f $(script_name_2) ] && sha512sum --check SHA512SUMS --status && echo "OK: Files are prepared. You may use make install command now." || echo "ERROR: Files are missing and / or hashsum mismatch!"

install:
    install --verbose --mode=0755 --owner=$(user_id) --group=$(group_id) --target-directory=$(install_path) $(script_name_1) $(script_name_2)

uninstall:
    rm $(install_path)/$(script_name_1) $(install_path)/$(script_name_2)


texts:
I'm trying to figure out a way to simplify implementing paged searching in sql server.

My restrictions are:

has to be in a proc.
can't use dynamic sql.

Here's my sample query:

DECLARE @TenantId int
DECLARE @MemberStatusId int
DECLARE @SearchTerm varchar(50)
DECLARE @ColumnName varchar(30)
DECLARE @PageNum int
DECLARE @RecCount int

;
WITH RowPages AS (
    SELECT TOP( @PageNum * @RecCount )
            RowNumber = ROW_NUMBER() OVER( ORDER BY
                CASE
                    WHEN @ColumnName = 'Name' THEN P.LastName
                    WHEN @ColumnName = 'PhoneNumber' THEN M.PhoneNumber
                    WHEN @ColumnName = '' THEN P.LastName
                END ASC,
                CASE
                    WHEN @ColumnName = 'DateAdded' THEN P.DateAdded
                END DESC
                ),
            TotalCount = COUNT(M.MemberId) OVER ( PARTITION BY NULL),
            M.MemberId, M.ExternalId, M.PhoneNumber, P.FirstName, P.LastName, P.EmailAddress
        FROM membership.Members M (nolock)
            INNER JOIN core.Persons P (nolock) on (P.PersonId = M.MemberId)
        WHERE (M.TenantId = @TenantId)
          AND ((@MemberStatusId = 0) or (M.MemberStatusId = @MemberStatusId))
          AND (
                (@SearchTerm = '""')
                OR (CONTAINS( (P.FirstName, P.LastName, P.EmailAddress), @SearchTerm))
            )
)
SELECT TotalCount, MemberId, ExternalId, PhoneNumber,
        FirstName, LastName, EmailAddress
    FROM RowPages
    WHERE RowNumber > ((@PageNum - 1) * @RecCount)
    ORDER BY RowNumber

What this does is perform a paged search of a couple tables.  You can pass in the page number and # records per page as well as the column to sort by and it has a full text search component.  This is one of the simpler queries of this style we have.

What I'm trying to figure out is how to optimize this.  The biggest costs in the execution plan are in regards to the full text search.  There is a table value function [FullTextMatch] which has a cost of 100%.

Ideas?


texts:
Input: Real number y and Integer number x
Output: x^y
Constraint: Must be done in O(log(y)) time.

Notice that O(log(y)) is O(length-of(y)).

public static double expon(double x, int y){
    double result = 1.0;

    double part = x;
    for (int i = 0; i < 32; i++){
        if (((y >> i) & 1) == 1){
            result *= part;
        }
        part *= part;
    }

    return result;
}


texts: Immediate Smaller Element Time Limit Exceeded

texts:
Immediate Smaller Element The code is working fine Code is here. For each element in the array, check whether the right adjacent element (on the next immediate position) of the array is smaller. If the next element is smaller, print that element. If not, then print -1. The only problem is I'm getting "Time Limit Exceeded" when I submit my answer here.
It shows

  Your program took more time than expected.Time Limit Exceeded
  Expected Time Limit < 3.496sec
  Hint: Please optimize your code and
  submit again.

How do I optimize my code to pass the time limit exceeded problem?

  Problem Statement: Given an integer array of size N. For each element
  in the array, check whether the right adjacent element (on the next
  immediate position) of the array is smaller. If next element is
  smaller, print that element. If not, then print -1.

  Input: The first line of input contains an integer T denoting the
  number of test cases. T testcases follow. Each testcase contains 2
  lines of input: The first line contains an integer N, where N is the
  size of array. The second line contains N integers(elements of the
  array) sperated with spaces.

  Output: For each test case, print the next immediate smaller elements
  for each element in the array.

  Constraints:
  1 ≤ T ≤ 200
  1 ≤ N ≤ 10E7
  1 ≤ arr[i] ≤ 1000
  Expected Time Limit < 3.496sec

  Example:

  Input:
  2
  5
  4 2 1 5 3
  6
  5 6 2 3 1 7

  Output:
  2 1 -1 3 -1
  -1 2 -1 1 -1 -1

  Explanation:
  Testcase 1: Array elements are 4, 2, 1, 5, 3. Next to 4
  is 2 which is smaller, so we print 2. Next of 2 is 1 which is smaller,
  so we print 1. Next of 1 is 5 which is greater, so we print -1. Next
  of 5 is 3 which is smaller so we print 3.  Note that for last element,
  output is always going to be -1 because there is no element on right.

Here is my code

class Program
{
    static void Main(string[] args)
    {
        int testCases = int.Parse(Console.ReadLine().Trim());

        while (testCases-- > 0)
        {
            int arrSize = int.Parse(Console.ReadLine().Trim());
            string[] arr = Console.ReadLine().Trim().Split(' ');

            for (int i = 0; i < arrSize - 1; i++)
            {
                if (int.Parse(arr[i]) > int.Parse(arr[i + 1]))
                {
                    Console.Write(arr[i + 1] + " ");
                }
                else
                    Console.Write("-1" + " ");
            }
            Console.Write("-1");
            Console.WriteLine();
        }
    }
}


texts:
I'm a developing a image processor, which reads a Base64 (compressed) image and writes its subimage to targets on threads.

(Constructors, exception handling, and resource management are omitted for brevity)

The base abstract class is AbstractImageProcessor and it implements Runnable to run on threads:

abstract class AbstractImageProcessor implements Runnable {
    protected final String base64; // input
    protected final List<Target> targetList; // list of target information

    protected abstract void read(byte[] data);
    protected abstract void write(Target t);

    @Override
    public void run() {
        byte[] data = decompress(decode()); // decode base64 and decompress
        read(data);
        for (Target t : targetList) {
            write(t)
        }
    }
}

Another abstract class, ImageIOProcessor extends AbstractImageProcessor to use ImageIO:

abstract class ImageIOProcessor extends AbstractImageProcessor {
    private BufferedImage image;

    protected abstract void writeBufferedImage(BufferedImage subimage, Target t)

    @Override
    protected void read(byte[] data) {
        image = ImageIO.read(new ByteArrayInputStream(data));
    }

    @Override
    protected void write(Target t) {
        writeBufferedImage(image.getSubimage(/* x, y, w, h from t */), t);
    }
}

There are two default implementations(concrete classes) of ImageIOProcessor, one writes to file and the other writes to base64 String:

class ImageIOFileWriter extends ImageIOProcessor {
    private File filepath;

    @Override
    protected void writeBufferedImage(BufferedImage subimage, Target t) {
        ImageIO.write(subimage, "png", filepath);
    }
}

class ImageIOBase64Writer extends ImageIOProcessor {
    @Override
    protected void writeBufferedImage(BufferedImage subimage, Target t) {
        ImageIO.write(subimage, "png", /* Base64-encoder-wrapped outputstream*/);
    }
}

The factory interface is responsible for creating appropriate image processing Runnable instance:

public interface ImageProcessorFactory {
    AbstractImageProcessor create(String base64, List<Target> t);
}

Is this the best way to implement them? Or is there better design pattern?


texts: Handling templates for a web application

texts:
I am writing up a class to handle various templates to be used in a web application. Each template contains various placeholders which will need to be replaced at the time of the build. I am wondering if the method I am using is the best solution, or if I should consider something else. At the moment I have two separate functions addPlaceholder() and addMultiplePlaceholders(). Each performs as their names suggest.

The function addPlaceholder() has two parameters one, the key $k, must be a string while the other, the value $v, can be anything. These get stored in the classes placeholder array.

The function addMultiplePlaceholders() has only one parameter, $array, and it should be an associative array. This function calls addPlaceholder() for each index of $array to store the corresponding values. The reason for the call to an existing function is to help alleviate duplicitous code, and when only a single placeholder is in use to bypass the foreach loop.

Is this the best method to accomplish this? Would it be better to forgo addPlaceholder() and just use addMultiplePlaceholders() for everything? Perhaps, overloading addPlaceholder() would be a better solution having one version which accepts the two parameters, and another which accepted the array. However, I would be in the same situation as now having to decide whether to duplicate the code for adding the placeholder to the class property, or calling the other function.

public function addPlaceholder($k,$v){
    if(empty($k)){
        throw new Exception('Class Template->addPlaceholder() '.'The placeholder string cannot be empty.');
    }

    if(isset($this->placeholders[$k])){
        throw new Exception('Class Template->addPlaceholder() '.'['.$k.'] is a duplicate entry');
    }

    $this->placeholders[$k] = $v;
}

public function addMultiplePlaceholders($array){
    if(!is_associative($array)){                    // if `$array` is not an associative array throw exception
        throw new Exception("The supplied parameter value is not an associative array");
    }

    foreach($array as $key => $value){
        try{
            addPlaceholder($key,$value);
        }catch(Exception $e){
            $msg = $e->getMessage();
            preg_replace(preg_quote('Class Template->'), '', $msg);
            throw new Exception("Class Template->addMultiplePlacerholders()->".$msg);
        }
    }
}


texts: Another Sliding Window - find each `k-size` window the maximum num. from an integer array/list

texts:
I've searched this site and find many similar questions, but not exactly the same as the one I'll post.
This attempts to solve Leetcode 239:

You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Return the max sliding window.

The subject is - given an integer array, and positive integer k, denoting the sliding window size. Each time you can only slide from left to right one position, try to find each windows maximum number and output these maximum number into an output list. [Note - the given list could be very large ~ 1 Million (nums)]
For example:  Given a nums array =  [99, 74, 48, 27, 56, 88, 66, 77, 101]; k = 3
Output should be:     [99, 74, 56, 88, 88, 88, 101]
I've tried to solve this in Python, and wonder if it could be further optimized and improved. Thanks in advance.
def maxSliding(nums: List[int], k: int) -> List[int]:
    if not k or not nums: return []

    z = len(nums)

    if z <= k:  return [max(nums, default = 0)]

    q = deque([])
    res = []

    for i, num in enumerate(nums):
        if q and q[0] == i-k:
            q.popleft()

        while q and nums[q[-1]] < num:
            q.pop()

        q.append(i)
        if i >= k-1:  res.append(nums[q[0]])
    return res

# Since every num. enters and leaves the queue at most once, the time
# complexity is O(len(A)), independent of the value of K.
if __name__ == '__main__':
    B = [99,  74, 48, 27, 56, 88, 66, 77, 101]
    print(maxSliding(B, 3))


texts: Find the longest zigzag sequence in a array of integers

texts:
I think I have a brute force solution to the problem but I can't think of a more optimal solution

A sequence of integers is called a zigzag sequence if each of its elements is either strictly less than both neighbors or strictly greater than both neighbors. For example, the sequence 4 2 3 1 5 3 is a zigzag, but 7 3 5 5 2 and 3 8 6 4 5 aren't.
For a given array of integers return the length of its longest contiguous sub-array that is a zigzag sequence.

Example

For a = [9, 8, 8, 5, 3, 5, 3, 2, 8, 6], the output should be
zigzag(a) = 4.

The longest zigzag sub-arrays are [5, 3, 5, 3] and [3, 2, 8, 6] and they both have length 4.

Input/Output
[input] array.integer a

constraints:
2 ≤ a.length ≤ 25,
0 ≤ a[i] ≤ 100.

Here is my brute force solution

def zigzag(input):
    current_longest = 0
    longest_subset  = []
    input_length    = len(input)

    for x in range(input_length):
        current_list = input[x:]

        for pos_a, num_a in enumerate(current_list):
            subset      = [num_a, ]
            prev_trend  = None

            for pos_b, num_b in enumerate(current_list[pos_a + 1:]):
                last_number = subset[-1]

                if last_number == num_b:
                    # print "[DUPE] current subset state", subset, "comparing ->", subset[-1], num_b
                    break

                if last_number > num_b:
                    cur_trending = "down"
                else:
                    cur_trending = "up"

                if prev_trend:
                    # compare trends
                    if prev_trend == cur_trending:
                        # print "[TREND] current subset state", subset, "comparing ->", subset[-1], num_b
                        break
                    else:
                        prev_trend = cur_trending
                else:
                    # initial trend set
                    prev_trend = cur_trending

                subset.append(num_b)

                if len(subset) > current_longest:
                    current_longest = len(subset)
                    longest_subset = subset

    print current_longest, longest_subset

zigzag([9, 8, 8, 5, 3, 5, 3, 2, 8, 6])
zigzag([4, 2, 3, 1, 5, 3])


texts: Return a String containing only alphabets without spaces

texts:
Scenario: Return a String that contains only alphabets without spaces.

input = "A man, a plan, a canal: Panama"

output = "AmanaplanacanalPanama"

Can you please critique my code?

private String OnlyAlphabets(final String string) {
    StringBuilder sb = new StringBuilder();
    char ch;

    for (int i = 0; i < string.length(); i++) {
        ch = string.charAt(i);
        if (!Character.isAlphabetic(ch)) {
            continue;
        }
        sb.append(ch);
    }
    return sb.toString();
}


texts: C# handling of images - is this best for memory usage?

texts:
I am working with a system that needs to consume product images uploaded by employees and resize them / add white padding to the sides to create square images to be consumed by our e-commerce site.  I'm attempting to keep things somewhat light on the memory usage because this will live in a windows service on an azure vm.  I know there are better solutions, but that's what I'm given as a platform.  I also don't want to use 3rd party libraries.

The following code is what I have so far.  Please, pick it apart and let me know if i'm making any mistakes.

public static Image ImageToFixedSize(Image originalImage, int width, int height)
{
    Graphics graphicController = null;

    try
    {
        if (originalImage != null)
        {
            int sourceWidth = originalImage.Width;
            int sourceHeight = originalImage.Height;
            int destX = 0;
            int destY = 0;

            float percent = 0;
            float percentW = 0;
            float percentH = 0;

            percentW = width / (float)sourceWidth;
            percentH = height / (float)sourceHeight;
            if (percentH < percentW)
            {
                percent = percentH;
                destX = Convert.ToInt16((width - (sourceWidth * percent)) / 2);
            }
            else
            {
                percent = percentW;
                destY = Convert.ToInt16((height - (sourceHeight * percent)) / 2);
            }

            int destWidth = (int)(sourceWidth * percent);
            int destHeight = (int)(sourceHeight * percent);

            Bitmap tempPhoto = new Bitmap(width, height, PixelFormat.Format24bppRgb);

            tempPhoto.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
            graphicController = Graphics.FromImage(tempPhoto);
            graphicController.FillRectangle(Brushes.White, 0, 0, width, height);

            // The chances of hitting this ONE SPECIFIC COLOR are very slim
            graphicController.SmoothingMode = SmoothingMode.HighQuality;
            graphicController.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphicController.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphicController.CompositingQuality = CompositingQuality.HighQuality;

            graphicController.DrawImage(
                originalImage,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(1, 1, sourceWidth - 1, sourceHeight - 1),
                GraphicsUnit.Pixel);

            return tempPhoto;
        }
        else
        {
            return null;
        }
    }
    catch
    {
        throw;
    }
    finally
    {
        graphicController.Dispose();
    }
}


texts:
I picked up python again, and I am proud with what I have without using if/elif statements throughout the whole thing. I have modified this couple of times, since I kept asking how could I make it better or more organized. My biggest complaint is using the if/elif at the bottom, for some reason when I use.

func = optionMenu.get(test, "INVALID ENTRY")

it would would return blank instead of showing "invalid entry" if I selected option that wasn't on the menu. So, I had to use if/else to band-aid it for now.

#!/usr/bin/env python

import os

def mainMenu():

    print "=" * 25
    print "Please Select An Option"
    print "=" * 25
    print ""
    print "1. option one\n"
    print "2. option two\n"
    print "3. option three\n"
    print "4. filler\n"
    menuOption = input("Select Option: ")

    optionSelect(menuOption)

class selections(object):
    def one(self):
        print "option one"

    def two(self):
        print "option two"

    def three(self):
        print "option three"

    def four(self):
        print "option four"

def optionSelect(test):
    menuSelection = selections()
    optionMenu = {
    1 : menuSelection.one,
    2 : menuSelection.two,
    3 : menuSelection.three,
    4 : menuSelection.four,
    }

    func = optionMenu.get(test)
    if test in optionMenu:
        func()
    else:
        print "ERROR INVALID ENTRY ERROR"
mainMenu()


texts:
In this problem you are given input of phone numbers and you are supposed to determine whether any number is the prefix of another. I have an addchild method that returns true or false if a given string can be inserted and is not a prefix of another string. How could I improve the efficiency of my code so that I could pass the time constraints?

http://www.spoj.com/problems/PHONELST/

import java.util.Arrays;
import java.util.Scanner;

class PhoneList {

static class Node{
    Node [] children;

    int value;

    public Node(){
        children=new Node[11];
    }

    public Node(int value){
        children=new Node[11];
        this.value=value;
    }

}

static class  Trie{
    Node root=null;

    public Trie(){
        root=new Node();
    }

    boolean addChild(String s){

        Node currentNode=root;
        int number=0;

        for(int i=0;i<s.length();i++){
            number=s.charAt(i)-'0';
            if(currentNode.children[currentNode.children.length-1]!=null){
                return false;
            }
            if(currentNode.children[number]==null){
                currentNode.children[number]=new Node(number);
            }
            currentNode=currentNode.children[number];
        }

        if(currentNode.children[currentNode.children.length-1]==null){
            currentNode.children[currentNode.children.length-1]=new Node(10);
        }else{
            return false;
        }

        return true;
    }

}

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

    int number_of_test_cases=input.nextInt();

    boolean istrue;
    for(int i=0;i<number_of_test_cases;i++){

        Trie tree=new Trie();
        int length=input.nextInt();
        String numbers[]=new String[length];

        for(int j=0;j<numbers.length;j++){
            numbers[j]=input.next();
        }

        Arrays.sort(numbers);
        istrue=true;

       for(int k=0;k<numbers.length;k++){
        if(!tree.addChild(numbers[k])){
            System.out.println("NO");
            istrue=false;
            break;
        }
        }

        if(istrue){
            System.out.println("YES");
        }
    }

}

}


texts: Asynchronous model fitting that allows termination in Python

texts:
The problem

When you work with Python interactively (e.g. in an IPython shell or notebook) and run a computationally intensive operation like fitting a machine-learning model that is implemented in a native code, you cannot interrupt the operation since the native code does not return execution control to the Python interpreter until the end of the operation. The problem is not specific to machine learning, although it is typical to run a training process for which you cannot predict the training time. In case it takes longer that you expected, to stop training you need to stop the kernel and thus lose the pre-processed features and other variables stored in the memory, i.e. you cannot interrupt only a particular operation to check a simpler model, which allegedly would be fit faster.

The solution

We propose an Asynchronous Fitter design pattern that runs fitting in a separate process and communicates the results back when they are available. It allows to stop training gracefully by killing the spawned process and then run training of a simpler model. It also allows to train several models simultaneously and work in the IPython notebook during model training. Note that multithreading is probably not an option, since we cannot stop a thread that runs an uncontrolled native code.

Here is a draft implementation:

from multiprocessing import Process, Queue
import time

class AsyncFitter(object):
    def __init__(self, model):
        self.queue = Queue()
        self.model = model
        self.proc = None
        self.start_time = None

    def fit(self, x_train, y_train):
        self.terminate()
        self.proc = Process(target=AsyncFitter.async_fit_,
            args=(self.model, x_train, y_train, self.queue))
        self.start_time = time.time()
        self.proc.start()

    def try_get_result(self):
        if self.queue.empty():
            return None

        return self.queue.get()

    def is_alive(self):
        return self.proc is not None and self.proc.is_alive()

    def terminate(self):
        if self.proc is not None and self.proc.is_alive():
            self.proc.terminate()
        self.proc = None

    def time_elapsed(self):
        if not self.start_time:
            return 0

        return time.time() - self.start_time

    @staticmethod
    def async_fit_(model, x_train, y_train, queue):
        model.fit(x_train, y_train)
        queue.put(model)

Usage

It is easy to modify a code that uses scikit-learn to adopt the pattern. Here is an example:

import numpy as np
from sklearn.svm import SVC

model = SVC(C = 1e3, kernel='linear')
fitter = AsyncFitter(model)
x_train = np.random.rand(500, 30)
y_train = np.random.randint(0, 2, size=(500,))
fitter.fit(x_train, y_train)

You can check if training is still running by calling fitter.is_alive() and check the time currently elapsed by calling fitter.time_elapsed(). Whenever you want, you can terminate() the process or just train another model that will terminate the previous one. Finally, you can obtain the model by try_get_result(), which returns None when training is in progress.

The issues

As far as I understand, the training set is being pickled and copied, which may be a problem if it is large. Is there an easy way to avoid that? Note that training needs only read-only access to the training set.

What happens if someone loses a reference to an AsyncFitter instance that wraps a running process? Is there a way to implement an asynchronous delayed resource cleanup?


texts:
I developed a QuickIndex class which serves to index arrays of stringafiable objects using a tree structure. The purpose is to then primarily to allow for fast index or include? method calls directed to the quick_index object as a proxy for the original array, as the index tree can be traversed much more efficiently than a linear array.

There is a gist containing the whole class, but the main functionality comes from the two methods included below.

class QuickIndex
  def initialize ary, stop_char = "!"
    @stop_char = stop_char
    @size = ary.size
    @index = Hash.new
    ary.each_with_index do |num, i|
      num = num.to_s.split("") << @stop_char
      index = @index
      until num.empty?
        n = num.shift
        index = index[n] ||= (n == @stop_char ? [] : {})
      end
      index << i
    end
  end

  def index item
    index = @index
    (item.to_s.split("") << @stop_char).each { |n| next unless index = (index[n] or nil rescue nil) }
    index
  end
end

The stop_char is a single character which serves to indicate the end of a string in the index.

The class is specifically intended for locating specific values in very large (NArray) arrays of ints or floats, but it's nice for it to work with other objects too.

It works reasonably well, but I'd like to know of any optimisations or alternative strategies to this problem which would make the class quicker at either building or querying the index and/or reduce the memory footprint. Or if there's some standard library alternative I've overlooked...


texts:
I'm developing a webapp in ASP.Net MVC. One of the requirements of the project is that users follow a "workflow". The workflow has a number of steps, and a conditional branch. The workflow is long running (week+) and most steps rely on one or more API calls to a 3rd party.

I have previously wondered about application "flow" in a typical webapp. Say for instance that every workflow step has a corrisponding URL eg: /Workflow/Step1, /Workflow/Step2. In this particular workflow, Step1 is not valid once you reach Step2.

I read about Application Controller patterns and decided to try and make a basic workflow object, where the viewstate is managed by the workflow, rather than the particular endpoint.

This would mean that for instance, visiting /Workflow/Process would return the current stage of the workflow, rather than a single view. There's a custom model binder which can take a namespace and bind to a model as long as there's a name for it in the form collection.

This is a template of the controller. It's a work in progress, but the idea is that additional workflows would be pluggable from the business layer, rather then relying on links between views. Is this a terrible idea, and can anyone see any fundamental problems with this approach?

public class CaseController : Controller
{
    public ActionResult New()
    {
        var store = new InMemoryCaseStore<ExampleCase>();
        var workflow = new ExampleCaseWorkflow(store);
        var result = workflow.New();

        return View(result.ViewName, result.ViewModel);
    }

    public ActionResult Load(string Id)
    {
        var store = new InMemoryCaseStore<ExampleCase>();
        var workflow = new ExampleCaseWorkflow(store);
        var result = workflow.Load(Id);

        return View(result.ViewName, result.ViewModel);
    }

    public ActionResult Process([NamespaceModelBinder("Business.Models")]dynamic model)
    {
        var temp = model.Id;

        var store = new InMemoryCaseStore<ExampleCase>();
        var workflow = new ExampleCaseWorkflow(store);
        var stage = workflow.Next(model);

        return View(stage.ViewName, stage.ViewModel);
    }

    public ActionResult Back(string Id)
    {
        throw new NotImplementedException();
    }
}

public class NamespaceModelBinder : DefaultModelBinder
{
    public NamespaceModelBinder(string location)
    {
        //todo: this is going to be slow - test and see how bad it is.
        var q = from t in AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes())
                where t.IsClass && t.Namespace == location
                select t;
        modelMap = q.ToDictionary(x => x.Name, x => x);
    }

    Dictionary<string, Type> modelMap;

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {

        var type = controllerContext.HttpContext.Request.Form["ModelType"];
        bindingContext.ModelName = type;
        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, modelMap[type]);

        return base.BindModel(controllerContext, bindingContext);
    }
}