texts:
I am trying to make a thread test in which 4 threads are all trying to set a bool. Only one should be allowed to set it. After the first thread has set the bool (m_isRunning) to true, no other threads should set it to true because of the check isRunning().

This implementation works, but I wonder if this is the best/most efficient approach to this common situation.

#include<iostream>
#include<thread>
#include<mutex>

std::mutex mut;
bool m_running = false;

bool isRunning()
{
  return m_running;
}

void setRunning(bool running)
{
  m_running = running;
}

void func1(bool isSet)
{
  mut.lock();
  if(!isRunning())
  {
    setRunning(true);
  }
  mut.unlock();
}

int main()
{
  std::thread t1(func1,true);
  std::thread t2(func1,true);
  std::thread t3(func1,true);
  std::thread t4(func1,true);

  t1.join();
  t2.join();
  t3.join();
  t4.join();

  return 0;
}

Edit: Changed !isRunning to !isRunning() (typo)


texts:
This HostResolve procedure runs on a thread separately, to not interrupt other working functions. I would like to ask here if this procedure is correctly written or not?

Any recommendations and improvements, if any one willing to help?

Procedure HostResolve();

   const
   URL : array[1..4] of String =('facebook.com', 'google.com', 'yahoo.com', 'gmail.com');

   var
      IP:String;
      IsConnected:Boolean;
      i:integer;

   begin

      IsConnected := false;
      While true do
      begin
        if IsConnectedToInternet then
          begin
           if IsConnected = false then
             begin
        //

          for  i := Low(URL) to High(URL) do
            begin
              if  HostToIp(URL[i], IP) then
               begin
                 ShowMessage(IP);
                 IsConnected := true;
                 Break;
               end;
            end;

        //
        end;
      end else begin
          IsConnected := false;
      end;
        Sleep(1000);
    end;
 end;

 Function IsConnectedToInternet: Boolean;
 var
  dwConnectionTypes: DWORD;
   begin
    dwConnectionTypes :=
    INTERNET_CONNECTION_MODEM +
    INTERNET_CONNECTION_LAN +
    INTERNET_CONNECTION_PROXY;
    Result := InternetGetConnectedState(@dwConnectionTypes, 0);
  end;

Function HostToIP(sHost: string; var sIP: string):Boolean;
var
  aHostName: array[0..255] of Char;
  pcAddr   : PChar;
  HostEnt  : PHostEnt;
  wsData   : TWSAData;
begin
  WSAStartup($0101, wsData);
  try
    GetHostName(aHostName, SizeOf(aHostName));
    StrPCopy(aHostName, sHost);
    hostEnt := GetHostByName(aHostName);
    if Assigned(HostEnt) then
      if Assigned(HostEnt^.H_Addr_List) then begin
        pcAddr := HostEnt^.H_Addr_List^;
        if Assigned(pcAddr) then begin
          sIP := Format('%d.%d.%d.%d', [Byte(pcAddr[0]), Byte(pcAddr[1]),
            Byte(pcAddr[2]), Byte(pcAddr[3])]);
          Result := True;
        end else
          Result := False;
      end else
        Result := False
    else begin
      Result := False;
    end;
  finally
    WSACleanup;
  end;
end;


texts: Return a substring containing a certain pattern to VBA

texts:
I've written in a C++ dll the following function to return to VBA a substring containing a certain pattern, given an input string, which contains that substring:

VARIANT _stdcall ReturnT(VARIANT FileName)
{

    wstring str(FileName.bstrVal, SysStringLen(FileName.bstrVal));
    wregex ToFind(L"_[tT]\\d{2,3}(_|.)");
    wsmatch TStr;

    regex_search(str, TStr, ToFind);
    wstring TVal = TStr.str(0).erase(0, 2);
    TVal.erase(TVal.end() - 1);

    assert(!TVal.empty());
    BSTR bs = SysAllocStringLen(TVal.data(), TVal.size());

    VARIANT TValue;
    TValue.vt = VT_BSTR;
    TValue.bstrVal = bs;

    return TValue;
}

This works flawlessly, but I suspect I am doing something more complicated than it really should be.

Notice that I'm using VARIANT to avoid interop problems ( BSTR as input would return kanjis, and in output would return a string with spaces between the characters)


texts: Add or subtract two numbers depending on dropdown selection

texts:
I have a drop down list contain "Add" and "Subtract". When user select either one, it will call a function Calculate()

private int Calculate(string sAction)
{
    int iTotal = 0;

    if(sAction == "Add")
    {
        iTotal = X + Y;
    }
    else if(sAction == "Subtract")
    {
       iTotal = X-Y;
    }

    return iTotal;
}

I do not wish to hard coded it to compare the action. It seem like not fulfill Open Closed Principle. If I change the text in the drop down list, I need to change the function as well. May I know how I can improve this code?


texts:
I've been studying Reservoir sampling for a couple of days.  What I've tried here is draw a uniformly random sample of size 3 from bigger data (the 26 characters of the English alphabet) via reservoir sampling.
Below is what I've come up with.

If anyone could review my code and offer some suggestions, that'd be great.

import java.util.TreeMap;

public class test1 {
    public test1(){
        String[] data = "A B C D E F G H I J K L M O P".split(" ");
        double[] freq = new double[data.length];
        int k = 3;
        String[] sample = new String[k];

        // the tree map stores the count of appearance of each letter during
        // the total sampling procedure
        TreeMap<String, Double> dmap = new TreeMap<String, Double>();
        for (int index = 0; index < data.length; index++) {
            dmap.put(data[index], 0.0);
        }

        for (int loop = 0; loop < 1000000; loop++) {
            int i = 0;
            // initiate the sample
            while (i < k) {
                sample[i] = data[i++];
            }
            // start sampling from the reservoir
            for (; i < data.length; i++) {
                int r = (int) (Math.random() * (i + 1));
                if (r < k) {
                    sample[r] = data[i];
                }
            }
            // update the count of each entry in the map
            for (String s : sample) {
                dmap.put(s, dmap.get(s) + 1);
            }
        }
        int index = 0;
        for (Double s : dmap.values().toArray(new Double[dmap.size()])) {
            freq[index++] = s;
            // System.out.println(s);
        }
        // calculate statistics
        double mean, stddev , cov;
        mean = stats.mean(freq);
        stddev = stats.stddev(freq);
        cov = (stddev / mean) * 100;
        System.out.println(" mean                   : " + mean);
        System.out.println(" coeff of variation(%)  : " + cov);     }

    public static void main(String[] args) {
        new test1();
    }
}

Stats class:

final class stats {

    private stats() {}

    public static double sum(double[] a) {
        double sum = 0.0;
        for (int i = 0; i < a.length; i++) {
            sum += a[i];
        }
        return sum;
    }

    public static double mean(double[] a) {
        if (a.length == 0)
            return Double.NaN;
        double sum = sum(a);
        return (double) sum / a.length;
    }

    public static double stddev(double[] a) {
        return Math.sqrt(var(a));
    }

    public static double var(double[] a) {
        if (a.length == 0)
            return Double.NaN;
        double avg = mean(a);
        double sum = 0.0;
        for (int i = 0; i < a.length; i++) {
            sum += (a[i] - avg) * (a[i] - avg);
        }
        return sum / (a.length);
    }
}

My output:

 mean                   : 200000.0
 coeff of variation(%)  : 0.18734211130086761

Edit

I'v received some very helpful suggestions regarding the structure of the code .
the generic version provided by 200_success was really a nice one.
But some of the "procedural"-ness i feel that my code has , is mainly because the api for the actual code for which this was a test-case , demanded a static method which only read the input and gave a sample output. Hence to keep things visually similar , i tried putting them all in one method... The constructor ( not an ideal option many would rightly argue ).

Why the constructor? Well , it made me get away with just one small line in the main method. ( I was feeling pretty lazy back then .)

Edit 2 :
Found out about R yesterday, after a little youtube-ing for for tutorials , made a few plots . Thought i'd upload a couple of them , just for fun. (and a better view of the data)

Box-plot of the number of times each letter of the alphabet(A-Z) had come up

Bar-plot of the same data


texts:
I would like to reverse a list using cdr, car and cons. Since lists in lisp are asymmetrical (can only insert at the beginning), I am interested on how one would write a procedure to do that without using (append). Please review my code.

(define (reverse l)
    (define (aux orig result)
        (if (null? orig) result
                (aux (cdr orig) (cons (car orig) result))))
    (aux l '()))

Is this good enough? Are there better or more efficient ways to do this?


texts:
I found this method kinda tough to get for a beginner like me, but I tried to do my best, and here's what I came up with.

Is this good code regarding performance? Is there anything wrong with it?

var notPrime = [] ;
var prime = [] ;

var n = prompt("Enter n: ");

for(var i = 2 ; i < n ; i++ ){

    if(notPrime.indexOf(i) != -1){
        continue;
    }

    for(var j = i ; i <= j ; j++){
        if((i * j) < n){
            notPrime.push(i*j);
        } else {
            break;
        }
    }
    prime.push(i);
}

for(var f in prime){
    console.log(prime[f]);
}


texts: Compute all the permutations for a given vector of integers

texts:
The task is to compute all the permutations for a given vector of integers (but of course the specific integer type is not relevant for the solution)

The strategy is based on recursion + iterations

At each recursion, the state consists of

the root sequence a which is the set of elements already placed
the remaining elements set b which is the set of elements still to be placed

Inside the recursion, a loop places the N(i) (with i recursion index and) remaining elements producing the same amount of new root sequences and a new recursion is started so that N(i+1)=N(i)-1 hence meaning the overall complexity is O(N!) as expected

The recursion ends when there are no more elements to place hence b.empty() is true

Each recursion set ends with a valid sequence hence they are all merged together in a final list of sequences

Here is my CPP solution

#include <iostream>
#include <vector>
using namespace std;

vector<int> remove_item (const vector<int>& a, const unsigned int id)
{
    vector<int> res;
    for(unsigned int i=0; i<a.size(); ++i) if(i!=id) res.push_back(a[i]);
    return res;
}

vector<int> add_item(const vector<int>& a, const int b)
{
    vector<int> res=a;
    res.push_back(b);
    return res;
}

vector< vector<int> > merge(const vector< vector<int> >& a, const vector< vector<int> >& b)
{
    vector< vector<int> > res=a;
    for(const auto& e : b) res.push_back(e);
    return res;
}

vector< vector<int> > permutations(const vector<int>& b, const vector<int>& a={})
{

    if(b.empty()) return { a };

    vector< vector<int> > res;
    for(unsigned int i=0; i<b.size(); ++i) res=merge(res, permutations(remove_item(b,i), add_item(a, b[i])));
    return res;
}

int main() {
    // your code goes here

    auto res = permutations({1,2,3,4,5});
    cout << "Sol Num = " << res.size() << endl;
    for(const auto& a : res)
    {
        for(const auto& b : a) cout << to_string(b) << " ";
        cout << endl;
    }
    return 0;
}


texts: A program for fun to see how red and blue appears blended to purple due to resolution

texts:
I do some art both analog and digital. This time I did some color test digitally. To work on my programming skill so that it's shareable I'm asking for help to get some code review.

How's the readability?
Is it easy to follow line of thought?
Suggestion as to how to improve?

I'm using John Zelles graphics.py for this

#A program for fun to see how red, blue and purple appears at resolution

from math import *
from graphics import *

def hole(win, centerx, centery, radius): #draws an inverted sphere
    for circle in range(radius, 0, -1):
        c = Circle(Point(centerx, centery), circle)
        c.setWidth(0)
        coloratangle = int(sin(circle/radius*pi/2)*255) #max resolution from black to white is 255 steps
        c.setFill(color_rgb(coloratangle * (circle % 2), 0, coloratangle * ((circle + 1) % 2))) # Modulus instead of Boolean? Modulus in c.setFill or in another line?
        c.draw(win)

windowheight = 1350
windowwidth = 730
win = GraphWin("My Circle", windowheight, windowwidth)
win.setBackground(color_rgb(255, 100, 100))

centerx = int(windowheight / 2)
centery = int(windowwidth / 2) #intetger
radius = int(sqrt(centerx**2 + centery**2)) #pythagoras

hole(win, centerx, centery, radius)

win.getMouse() # Pause to view result
win.close()    # Close window when done


texts: Shift elements left by n indices in a list

texts:
For the following question, the function
• should mutate the original list
• should NOT create any new lists
• should NOT return anything
Functions that do not create new lists are said to be ”in place.” Such functions are often desirable because they do not require extra memory to operate.
Define shift_left, a function that takes a list and shifts each element in the list to the left by n indices. If elements start ”falling off” on the left, they are placed back on the right. NOTE: you may assume that n is a non-negative integer.
def shift_left(lst, n):
"""Shifts the elements of lst over by n indices.
>>> lst = [1, 2, 3, 4, 5]
>>> shift_left(lst, 2)
>>> lst
[3, 4, 5, 1, 2]
"""

Below is the solution:
def shift_left(lst, n):
    """Shifts the lst over by n indices

    >>> lst = [1, 2, 3, 4, 5]
    >>> shift_left(lst, 2)
    >>> lst
    [3, 4, 5, 1, 2]
    """
    assert (n > 0), "n should be non-negative integer"
    def shift(ntimes):
        if ntimes == 0:
            return
        else:
            temp = lst[0]
            for index in range(len(lst) - 1):
                lst[index] = lst[index + 1]
            lst[index + 1] = temp
            return shift(ntimes-1)
    return shift(n)

I have yet to learn about raising exceptions in Python.
Can this code be more elegant by following a recursive approach? As of now, space (stack frame) usage can be considered secondary.


texts: Close to the metal C++ Palindrome Program

texts:
I am attempting to reinvent the wheel by writing my own palindrome checking program in C++, using only basic loops and mathematical operations. I have arrived at a solution, but was wondering if it's the best solution and if it could be improved. I'm doing this primarily as a learning exercise. My code:

#include <iostream> // cout
#include <stdio.h>  // printf
#include <string>

using namespace std;

bool is_palidrome(string inputString) {
  int num_to_parse = inputString.size();

  /* immediately return on single letter string as all single letter strings are palindromes -- saves CPU time as programme does not need to enter the loop */
  if(num_to_parse == 1) {
      return true;
  }

  for(int i=0; num_to_parse; i++) {
      int point_end = num_to_parse - i - 1;
    if(inputString[i] == inputString[point_end]) {
      continue;
    } else if (i == num_to_parse) {
      return true;
    } else {
      return false;
    }
}}

int main() {
    // Change the value of inputString to test different palindromes
    string inputString = "caabaac";
    printf("%s", is_palidrome(inputString)?"This is a palindrome.":"Not a palindrome."); // ternary: test condition ? return this if true : return this if false
    return 0;
}

I think at the moment I'm doing about 2x the number of loops I need to do, and so wasting CPU time. Also, there may be further optimizations. Any help really appreciated as I really want to understand this stuff properly and contribute to code-bases, rather than just doing everything with other people's higher-level code.


texts:
I tried implementing a queue using std::vector, using some properties of vector class. Is there scope for further improvement in my code, to make it more efficient?

#include<bits/stdc++.h>
using namespace std;
vector<int> q;

 void push(int d){
   q.insert(q.end(),d);
 }

 void pop(){
 q.erase(q.begin());
 }

 int front(){
 return *q.begin();
 }

 int main(){
    push(1);
    push(2);
    push(3);
    push(4);
    pop();
    cout<<front()<<endl;
     for(int i=0;i<q.size();i++) cout<<q[i]<<" ";
  }


texts: Copying a file hash to clipboard without PowerShell

texts:
… isn't easy.

@echo off&(for /f "tokens=*" %%a in ('certutil -hashfile "%1" MD5') do echo %%a&for /f "delims=" %%b in ('echo %%a^|findstr /r /i /x [0-9A-F]*') do if "%%b" neq "" echo %%b|clip&pause&exit)&pause

PowerShell is slow to load so I used batch instead. I use this command to extend the context menu of windows explorer, hence a single line.

There is one minor issue; certutil doesn't support empty files.

Bonus registry entries: https://paste.ee/p/sgSJY


texts:
What I tried to do is compare arbitrary structures independent of the == operator implementation.

template<typename T>
bool bitWiseCompare(T a, T b)
{
  size_t size = sizeof(T) / sizeof(char);
  char* array_a = (char*)(&a);
  char* array_b = (char*)(&b);
  for(size_t i = 0; i<size; i++)
  {
    if(array_a[i] != array_b[i])
    {
      return false;
    }
  }
  return true;
}


texts: Null replacement - Is this LINQ readable?

texts:
This is the original version of code written by my coworker that replaces every null cells with an empty string.

for (int i = 0; i < dGV_factory.Rows.Count; i++)
{

       this.dGV_factory["dGV_factory_groupID", i].Value
             = this.dGV_factory["dGV_factory_groupID", i].Value ?? "";
       this.dGV_factory["dGV_factory_groupID", i].Value
             = this.dGV_factory["dGV_factory_groupID", i].Value ?? "";
       this.dGV_factory["dGV_factory_groupID", i].Value
             = this.dGV_factory["dGV_factory_groupID", i].Value ?? "";
       this.dGV_factory["UE", i].Value
             = this.dGV_factory["UE", i].Value ?? "";
                ...
}

My instant reaction: Ugh.

Being a shameless fanatic of LINQ, I decided to rewrite the code using LINQ.

foreach(DataGridViewRow row in dGV_factory.Rows)
{
      //Replace every null cells with an empty string
      row.Cells.Cast<DataGridViewCell>().ToList().ForEach(cell => cell.Value = cell.Value ?? "");
}

However, I'm wondering if this code is less readable than the above version, even though it is definitely compact.

In my eyes, it's definitely readable as I'm comfortable with LINQ but my coworkers have not even heard of LINQ.

Which is a better change? Should I keep my LINQ version or unroll LINQ to two foreach loops?


texts: Using a for-loop to fill 20 picturebox number 'i' with image

texts:
I implemented as follows and it works (I got the solution here), but I really wonder if I can do that without having to define an array. For 20 it's a hassle but can be done, but what if you have an hundred to do? Is there a more "aesthetic" way to do that?

public void afficheuneimagecombo()
    {
 for (int i = 0; i <= 20; i++)
       {
            Item imguse = new Item();
            pictureBoxs[i].Load(imguse.getImage());
            pictureBoxs[i].SizeMode = PictureBoxSizeMode.StretchImage
        }

      }

PictureBox[] pictureBoxs = new PictureBox[20];

public Form1()
        {
            InitializeComponent();

            pictureBoxs[0] = pictureBox1;
            pictureBoxs[1] = pictureBox2;
            pictureBoxs[2] = pictureBox3;
            pictureBoxs[3] = pictureBox4;
            pictureBoxs[4] = pictureBox5;
              [...]
            pictureBoxs[20] = pictureBox20;

            afficheuneimagecombo()
        }


texts:
I'm a beginner in programming and I would like to have feedback and tips to improve. He's a simple command line program. It's a Rock, Paper, Scissors game.

I guess I could use an enum for the "Attack", but I don't know how to use it with cout after that...

Thanks!

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

enum class Result
{
    win = 1,
    loss = -1,
    tie = 0
};

string ResultToString(Result result)
{
    switch (result)
    {
    case Result::win:
        return "WIN!";
    case Result::loss:
        return "LOSS!";
    default:
        return "TIE!";
    }
}

string DeterminePlay(char playAbbreviation)
{
    if (playAbbreviation == 'r')
    {
        return "Rock";
    }
    else if (playAbbreviation == 'p')
    {
        return "Paper";
    }
    else
    {
        return "Scissors";
    }
}

Result DetermineResult(char playerPlay, char computerPlay)
{
    if (playerPlay == 'r' && computerPlay == 's')
    {
        return Result::win;
    }
    else if (playerPlay == 'p' && computerPlay == 'r')
    {
        return Result::win;
    }
    else if (playerPlay == 's' && computerPlay == 'p')
    {
        return Result::win;
    }
    else if (playerPlay == 's' && computerPlay == 'r')
    {
        return Result::loss;
    }
    else if (playerPlay == 'r' && computerPlay == 'p')
    {
        return Result::loss;
    }
    else if (playerPlay == 'p' && computerPlay == 's')
    {
        return Result::loss;
    }
    else
    {
        return Result::tie;
    }
}

int GenerateRandomNumber(int min, int max)
{
    srand((int)time(0));
    int number{(rand() % max) + min};
    return number;
}

char GenerateComputerPlay()
{
    char computerPlay{};
    int number{GenerateRandomNumber(1, 3)};
    switch (number)
    {
    case 1:
        computerPlay = 'r';
        break;
    case 2:
        computerPlay = 'p';
        break;
    default:
        computerPlay = 's';
    }
    return computerPlay;
}

int main()
{
    setlocale(LC_ALL, "");
    char play{'y'};
    while (play == 'y')
    {
        char computerPlay{};
        char playerPlay{};

        cout << "--- Rock, Paper, Scissors ---" << endl << endl;

        while (playerPlay != 'r' && playerPlay != 'p' && playerPlay != 's')
        {
            cout << "Enter a choice : (R)ock, (P)aper, (S)cissors : ";
            cin >> playerPlay;
            playerPlay = tolower(playerPlay);
        }

        cout << endl << "You played " << DeterminePlay(playerPlay) << endl;

        computerPlay = GenerateComputerPlay();
        cout << "The computer played " << DeterminePlay(computerPlay) << endl;

        Result result{DetermineResult(playerPlay, computerPlay)};
        cout << "It's a " << ResultToString(result) << endl << endl;

        cout << "Play again?" << endl << "(Y)es" << endl << "(N)o" << endl;
        cin >> play;
        play = tolower(play);
    }
    return 0;
}


texts: Tracking 1400+ client codes, multi-threading nightmare

texts:
I am looking for a bit of help. I am having to cycle through 1400 clients code on my server, I have to check what Version of the software they are on and check for customization's to the code so when we apply updates, those aren't lost. I tried to do it serialized, as you might have guessed, that took forever. I then Tried running it parallel, as you might have expected, I am getting "Os Error, too many open files" I tried to resolve this by throwing in "sleep(random())" Which Works,  But this seems convoluted and slows down the process considerably, and it could also be my code is complete garbage, any insight would be great.
I am using git in CLI to get version, this seems to be heavy? Is there a better way to pull tags?
Here, I get a list of the clients, I do some editing to get the pathing
def full_check(client_list, cur_vers):
    for c in client_list:
        if sc.venue_check(c):
            url = sc.surl(c[0])
            if url is not None:
                path = f'/home/ubuntu/site-files/{url}'
                # Maximizing output, this cut run time by 90%
                # Hard to log though...

                nschools.append({
                    'path': path,
                    'cur_vers': cur_vers,
                    'client': c[0],
                    'schema_version': c[2]
                })
# Here, I am then looping through the paths I get, I put a sleep to stop it from bugging out
# about OS File open Limits
    for s in nschools:
        print(s['path'])
        sleep(random())
        t = threading.Thread(target=vers_check, args=(s['path'], s['cur_vers'], s['client'], s['schema_version']))
        t.start()

Here I am going through doing some version checking
def vers_check(path, cur_vers, client, schema_version):
    """
    This Checks the Schools Release.
    TODO Add logging and Return Functionality.
    :param client:
    :param schema_version:
    :param path:
    :param school:
    :param cur_vers:
    :return:
    """
    os.chdir(path)
    try:
        vers = subprocess.check_output(["git", "describe", "--tags"]).strip().decode('utf-8')

        raw = str(vers).strip('-')
        rawsplit = raw.split('-')
        st = rawsplit[0]

        if str(st) != cur_vers:
            cschools.append({
                'client': client,
                'schema_version': schema_version,
                'sw_version': st,
                'path': path,
                'is_update': False
            })
            log.log('warn', 'Version Check', f'The School {client} is on Software Version {st} and Schema Version {schema_version} Which is Out Of Date. Current Version is {cur_vers}')
        else:
            cschools.append({
                'client': client,
                'schema_version': schema_version,
                'sw_version': st,
                'path': path,
                'is_update': True
            })
            log.log('info', 'Version Check', f'The School is on Software Version {st} and Schema Version {schema_version} Which is Up To Date. Current Version is {cur_vers}')
    except subprocess.CalledProcessError as e:
        log.log('err', 'Failed Version Check', f'We were unable to get the version for {client}', e)
```


texts:
This function checks if the cell of a Scrabble board is a double letter bonus. It has a 23 cyclomatic complexity, which is higher than the threshold of 20. I don't know how to do it another way, I think that this is the only way to do it. Here is my function :

checkDoubleLetterCell(row: number, column: number): boolean
{
if((row === middle- 1 || row === middle + 1)
&& (column === middle - 1 || column === middle + 1)
|| (row === 0 || row == SCRABBLE_SIZE - 1 || row === middle)
&& (column === middle + Math.round(middle/2) || column === middle - Math.round(middle/2))
|| (column === 0 || column === SCRABBLE_SIZE - 1 || column === middle)
&& (row === middle + Math.round(middle/2) || row === middle - Math.round(middle/2))
|| (column === middle + 1 || column === middle - 1)
&& (row === middle + Math.round(middle/2) + 1 || row === middle - Math.round(middle/2) - 1)
|| (row === middle + 1 || row === middle - 1)
&& (column === middle + Math.round(middle/2) + 1 || column === middle - Math.round(middle/2) - 1))
{
    return true;
}
return false;
}


texts:
This program is used to solve Challenge #140 [Intermediate] on /r/dailyprogrammer. The challenge is, given a input set of directed edges, print the corresponding adjacency matrix.

Here is a sample input:

5 5
0 3 -> 1
1 -> 2
2 -> 4
3 -> 4
0 -> 0 3

and the corresponding solution:

11010
00100
00001
01001
00000

Note that there can be more than one edge per line - the set of edges generated is then the Cartesian product of those nodes. For instance, 0 3 -> 1 would generate the edges [(0, 1), (3, 1)].

Here is my solution:

import Data.Function
import Data.Ix
import Data.List
import qualified Data.Set as Set

type Edge = (Integer, Integer)

genGrid :: Integer -> Set.Set Edge -> [[Bool]]
genGrid n edges = (map . map) (`Set.member` edges) coordGrid
  where
    coordGrid = groupBy ((==) `on` fst) coords
    coords = range ((0, 0), (n - 1, n - 1))

parseEdge :: String -> [Edge]
parseEdge s = [(from, to) | from <- outgoing, to <- incoming]
  where
    outgoing = map read (takeWhile (/= "->") split)
    incoming = map read (tail $ dropWhile (/= "->") split)
    split = words s

doChallenge :: [String] -> [String]
doChallenge s = (map . map) pprint (genGrid n edges)
 where
    n = read (head $ words $ head s)
    edges = Set.fromList $ concatMap parseEdge (drop 1 s)
    pprint True = '1'
    pprint _ = '0'

input :: [String]
input = ["5 5", "0 3 -> 1", "1 -> 2", "2 -> 4", "3 -> 4", "0 -> 0 3"]

output :: [String]
output = ["11010", "00100", "00001", "01001", "00000"]

main :: IO ()
main = print $ output == doChallenge input

My main points of focus

Readability of the code
How idiomatic the program is

Assume that the input is well-formed - it's okay if the IO stuff crashes on a bad input.


texts: Convert a list of sets into the minimum list of non-intersecting sets

texts:
I have a list of sets. The same items may appear in multiple sets.

I want to transform this into a new list of sets where:

Each item only appears once in the entire list of sets.
For each set in this new list, on every set in the old list, the new set will either be a subset or will not intersect at all.

I want this new list of sets to contain the minimum number of sets it can while still satisfying the above two requirements.

For example, this list

abcd
befg
cehi

Would turn into

ad
b
c
e
fg
hi

This seems like a pretty generic problem. Is there a name for it?

Here's my implementation. It requires the comparison of each set with each other set, so I guess this has a performance \$O(k \cdot n^2)\$ where \$n\$ is the count of lists, and \$k\$ is the average length of each set.

Are there any efficiency issues that could be fixed easily?

public static class SetUtilities
{
    public static IEnumerable<IEnumerable<T>> MinimumNonIntersectingSets<T>(this IEnumerable<IEnumerable<T>> sets)
    {
        List<List<T>> disjointSets = new List<List<T>>();
        // Special case: if there is a null set we have to add it first
        if (sets.Any(s => !(s.Any())))
        {
            disjointSets.Add(new List<T>());
            sets = sets.Where(s => s.Any());
        }

        foreach (IEnumerable<T> newSet in sets)
        {
            List<T> disjointCopy = newSet.ToList();
            int i = 0;
            while(i < disjointSets.Count())
            {
                var intersection = disjointSets[i].Intersect(disjointCopy).ToList();

                if ((intersection.Count() == disjointCopy.Count()) && (intersection.Count() == disjointSets[i].Count())) // They are equal
                {
                    disjointCopy.Clear();
                    break;
                }
                if (intersection.Any())
                {
                    disjointSets[i] = disjointSets[i].Except(intersection).ToList();
                    disjointSets.Insert(++i, intersection);
                    disjointCopy = disjointCopy.Except(intersection).ToList();
                }
                ++i;
            }
            if(disjointCopy.Any())
            {
                disjointSets.Add(disjointCopy);
            }
        }
        return disjointSets;
    }
}


texts:
I am going to have multiple APIs in routes folder should I put them in in the same file API or separate them?

├── app.js
├── src/
│   ├── contants/
│   ├── helpers/
│   ├── models/
│   ├── routes/
|   |         |___index.js
              |___api.js
│   └── libs/
│       ├── backbone/
│       ├── underscore/
│       └── ...

api.js file contains all the APIs
    const jwt = require("jsonwebtoken")
    const axios = require("axios")
    require("express-async-errors")
    const bodyParser = require("body-parser")
    const fs = require("fs")

    const LOLTrackingSystem = require("../methods/onlineGamesTracking/LOLTracking")
    const getUserData = require("../methods/leagueOfLegends/getUserData")
    const isAuthenticated = require("../helpers/authenticated")

    const apiRoute = (api) => {
      api.use(bodyParser.json())
      api.use(bodyParser.urlencoded({
        extended: false
      }));

      api.post("/api/auth", (req, res) => {
        //API Functions
      })

      api.post("/api/gizmo/memberProfile", isAuthenticated, (req, res) => {
        //API Functions
      })

      api.post("/api/gizmo/memberState/:userId/:host/:state", async (req, res) => {
        //API Functions
      })
    }

    module.exports = apiRoute

Is what I am doing is right?

If it's wrong what is the right way to do it?


texts:
I'm new to ASP.Net and up until now my code has worked but has been a mish mash all over the place with no real structure. I'm trying to teach myself how to keep the presentation/BLL/DAL separate so I have built a simple page to try and work with.

Page has 3 text boxes: clock number, first name and last name. On inputting a clock number in the clock number text box, I want to go off to my database and fetch the first name and last name of the person that clock number belongs to.

My DAL consists of 3 classes as below:

Public Class EmployeeName
Private _FirstName As String
Private _Lastname As String

Public Property FirstName() As String
    Get
        Return _FirstName
    End Get
    Set(value As String)
        _FirstName = value
    End Set
End Property

Public Property LastName() As String
    Get
        Return _Lastname
    End Get
    Set(value As String)
        _Lastname = value
    End Set
End Property
End Class

Public Class EmployeeNameDBAccess

Public Function GetEmployeeName(clockNo As Integer) As EmployeeName

    Dim employeeName As EmployeeName = Nothing
    Dim params As SqlParameter() = New SqlParameter() {New SqlParameter("@clockNo", clockNo)}

    Using tbl As DataTable = SMARTDBHelper.ExecuteParameterisedSelectCommand("getEmployeeName", CommandType.StoredProcedure, params)
        If tbl.Rows.Count = 1 Then
            Dim row As DataRow = tbl.Rows(0)
            employeeName = New EmployeeName
            employeeName.FirstName = row("INITIALS").ToString()
            employeeName.LastName = row("SURNAME").ToString()
        End If
    End Using
    Return employeeName
End Function
End Class

Public Class SMARTDBHelper
Const constr As String = "connection string goes here"

Friend Shared Function ExecuteParameterisedSelectCommand(cmdName As String, cmdType As CommandType, param As SqlParameter()) As DataTable

    Dim tbl As New DataTable()

    Using con As New SqlConnection(constr)
        Using cmd As SqlCommand = con.CreateCommand()
            cmd.CommandType = cmdType
            cmd.CommandText = cmdName
            cmd.Parameters.AddRange(param)

            Try
                If con.State <> ConnectionState.Open Then
                    con.Open()
                End If

                Using da As New SqlDataAdapter(cmd)
                    da.Fill(tbl)
                End Using
            Catch ex As Exception
                Throw
            End Try
        End Using
    End Using

    Return tbl

End Function

End Class

My BLL consists of the following class

Public Class EmployeeNameHandler

Private employee As EmployeeNameDBAccess

Public Sub New()
    employee = New EmployeeNameDBAccess()
End Sub

Public Function GetFirstname(clockNo As Integer) As String

    Dim emp = employee.GetEmployeeName(clockNo)
    Return emp.FirstName

End Function

Public Function GetLastname(clockNo As Integer) As String

    Dim emp = employee.GetEmployeeName(clockNo)
    Return emp.LastName

End Function
End Class

Then on my page I have the following code to populate the text boxes

Protected Sub txtCLock_TextChanged(sender As Object, e As EventArgs) Handles txtCLock.TextChanged

    Dim emp As New EmployeeNameHandler
    Dim cn As Integer = CInt(txtCLock.Text)
    Dim firstname = emp.GetFirstname(cn)
    Dim lastname = emp.GetLastname(cn)

    txtFirstName.Text = firstname
    txtLastName.Text = lastname

End Sub

I appreciate this is basic however I would be interested to gather opinion of if I am going down the correct route here? Could this be done in a better way? Also, there is next to no error handling here, this is a topic I'm very weak on so would appreciate any advice etc. Thanks


texts: C++ algorithm to implement multiple operators in one

texts:
I have a class called IntMatrix which has 2 fields:
Dimensions dimensions;//To save height and width of my matrix
int *data;//For saving data

and I need to override the operators >,>=,<,<=,==,!= which take a scalar and compare each single value in my matrix with that scalar accordingly, and returns a new matrix with the same size that contains 1 if the comparison returned true and 0 else.
For example:
mat: {1,2,3;4,5,6}
mat_2 = mat > 3;//Should return {0,0,0;1,1,1}
So, you may notice that all my functions have the exact lines of code except whenever I wrote != it should be > or < or == or etc....
So, in order to remove duplication here's how I implemented them:
IntMatrix IntMatrix::operator<(int num) const {
    return filter(*this,Between(INT_MIN,num-1));
}

IntMatrix IntMatrix::operator>(int num) const {
    return filter(*this,Between(num+1,INT_MAX));
}

IntMatrix IntMatrix::operator!=(int num) const {
    return filter(*this,Between(num,num), true);
}

where Between is a functor (to replace a pointer to a function).
So, when I reviewed my code I strongly believe this is not the best solution to give to this kind of problem, since filter() won't be well understandable by other programmers.
From your experience is there anyway to improve this code?
(I know that macros would be perfect here but don't want to use them either since they are a bad practice)
Note: I am working with C++11 and want only to use standard libraries.


texts: Parse a simple key=value config file in C

texts:
Write a program that should read a file formatted strictly like
  this below:

$ cat sample

bingo=2
bingo2=939
bingo3=text

  The left and right side of = are consecutively parameter name and
  its respective value. The values can be integer or strings. Each parameter is
  separated by a newline. The parameter name and its value will not be more than
  127 bytes.

This program is fed an input search token, and if found, parse_param_file() will fill the input arguments with string or integer value.

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

#define TEXT "sample"

/*
 * Function: parse_param_file
 * Arguments:
 * token    - param name that needs to be looked up
 * buf      - buffer for string value. Pass NULL if unwanted
 * buf_int  - buffer for integer value. Pass NULL if unwanted
 * filename - string formatted path to the file
 */
int parse_param_file(const char *token, char **buf, int *buf_int,
        const char *filename) {
    if (!token || (!buf && !buf_int)) {
        printf("%s: invalid args\n", __FUNCTION__);
        return 1;
    }
    FILE *f = fopen(filename, "r");
    if (f == NULL) {
        printf("%s: %s not found\n", __FUNCTION__, filename);
        return 1;
    }
    char *left = malloc(128);
    char *right = malloc(128);
    char *dlim_ptr, *end_ptr;
    char fbuf[256];
    while (fgets(fbuf, 256, f)) {
        dlim_ptr = strstr(fbuf, "=");
        end_ptr = strstr(dlim_ptr, "\n");
        strncpy(left, fbuf, dlim_ptr - fbuf);
        strncpy(right, dlim_ptr + 1, end_ptr - dlim_ptr - 1);
        if (strcmp(left, token) == 0) {
            /* Param found */
            if (buf != NULL)
                *buf = strdup(right);
            if (buf_int != NULL)
                *buf_int = atoi(right);
            fclose(f);
            free(left);
            free(right);
            return 0;
        }
    }
    fclose(f);
    printf("%s: Param not found in %s\n", __FUNCTION__, filename);
    free(left);
    free(right);
    return 1;
}

/* How to use parse_param_file() */
int main(void) {
    char *buf = malloc(128);
    int val = 0;

    /* Test 1 */
    if (parse_param_file("bingo2", NULL, NULL, TEXT))
        fprintf(stderr, "parse_param_file() failed\n");
    printf("buf : %s\n", buf);
    printf("int : %d\n", val);
    /* Test 2 */
    if (parse_param_file("bingo3242", NULL, &val, TEXT))
        fprintf(stderr, "parse_param_file() failed\n");
    printf("buf : %s\n", buf);
    printf("int : %d\n", val);
    /* You must clear *buf and val if you want to reuse them as args again */
    /* Test 3 */
    if (parse_param_file("bingo3", &buf, &val, TEXT))
        fprintf(stderr, "parse_param_file() failed\n");
    printf("buf : %s\n", buf);
    printf("int : %d\n", val);

    free(buf);
    return 0;
}


texts:
Is there any other way to shorten this code without sacrificing readability?  I am fairly new to C#, let alone programming, and I wanted to know if this is as short as this code can possibly become.  Feedback would be greatly welcomed.

Side note: was Questions.Questask used properly here, or could there have been a better way?

 class Program
 {
    static void Main(string[] args)
    {
        string name = "";
        while (name.ToLower() != "none")
        {
            Console.WriteLine("Are you Kydd,Leo,Jay,Sha, or Zigg");
            name = Console.ReadLine();

            if (name.ToLower() == "kydd")
                Question.Questask("Input question here", "Kquestion","Link");
            else if (name.ToLower() == "leo")
                Question.Questask("Input question here", "Lquestion", "Link");
            else if (name.ToLower() == "jay")
                Question.Questask("Input question here", "Jquestion", "Link");
            else if (name.ToLower() == "sha")
                Question.Questask("Input question here", "Squestion", "Link");
            if (name.ToLower() == "zigg")
                Question.Questask("Input question here", "Zquestion", "Link");
       }
    }

    class Question
    {
        public static void Questask(string question, string questAnswer, string url)
        {
            Console.WriteLine(question);
            questAnswer = Console.ReadLine();
            if (questAnswer.ToLower() == "yes")
            {
                Console.WriteLine("You are right!");
                Console.ReadKey();
            }
            else
            {
                System.Diagnostics.Process.Start(url);
            }
        }
    }
}


texts:
This converts from character representation of integers to their decimal value:

def chrtodec(str):
    dec = 0
    base = ord('0')
    for chr in str:
        dec = dec * 10 + ord(chr) - base
    return dec

For example: "123" -> 123


texts: How can I modify my graph traversal algorithm to increase efficiency?

texts:
I have an adjacency matrix "A" which I am using to represent a graph for a social network. Each node of the graph represents a person's name, and I am storing people's names in an 2-d array (the index of the person's name in the array is the same as the node's row index in the adjacency matrix). I wrote an algorithm to return the neighbors of node in the graph that are at most x nodes away from the node (the indices of the neighbor nodes will be stored in a binary tree and the root of the tree will be returned) but the algorithm is inefficient and takes 1-2 minutes or so to return the output, albeit a correct one. I would appreciate some advice on how to optimize this algorithm.

b_tree *get_friends(b_tree *root, int x, int y, char a_name[50] int dim) {
    /* root is root if b-tree containing pointers to the neighbors */
    /* a_name is the name of a person in the graph (want to get the neighbors of this node)*/
    /* x is maximum distance the neighbor can be from the node */
    /* y is used to keep track of x and is always 0 and dim is the length/width of matrix */
    /* M is a global variable for the matrix */
    /* name_search searches the tree and returns NULL if the index is already in the tree (to prevent duplicates) */
    /* friend_list is a global array containing the names of all the nodes in the graph (including a_name) */
    /* retrieve_ind returns the index of the user name in the the friend_list array */
    if (x == y - 1) return root;
    int r = retrieve_ind(a_name);
    for (int a = 0; a < dim; a++) {
        if (M[r][a] > 0) {
            if (name_search(root, a) == NULL) root = insert_in_tree(root, a);
            root = get_friends(root, x, y + 1, friend_list[a], dim);
        }
    }
    return root;
}


texts: Deserializing a byte array from Java in C++

texts:
I am writing a byte array value into a file, consisting of up to three of these arrays, using Java with big Endian byte order format. Now I need to read that file from a C++ program.

short employeeId = 32767;
long lastModifiedDate = "1379811105109L";
byte[] attributeValue = os.toByteArray();

I am writing employeeId, lastModifiedDate and attributeValue together into a single byte array. I am writing that resulting byte array into a file and then I will have my C++ program retrieve that byte array data from the file and then deserialize it to extract employeeId, lastModifiedDate and attributeValue from it.

This writes the byte array value into a file with big Endian format:

public class ByteBufferTest {

    public static void main(String[] args) {

        String text = "Byte Array Test For Big Endian";
        byte[] attributeValue = text.getBytes();

        long lastModifiedDate = 1289811105109L;
        short employeeId = 32767;

        int size = 2 + 8 + 4 + attributeValue.length; // short is 2 bytes, long 8 and int 4

        ByteBuffer bbuf = ByteBuffer.allocate(size);
        bbuf.order(ByteOrder.BIG_ENDIAN);

        bbuf.putShort(employeeId);
        bbuf.putLong(lastModifiedDate);
        bbuf.putInt(attributeValue.length);
        bbuf.put(attributeValue);

        bbuf.rewind();

        // best approach is copy the internal buffer
        byte[] bytesToStore = new byte[size];
        bbuf.get(bytesToStore);

        writeFile(bytesToStore);

    }

    /**
     * Write the file in Java
     * @param byteArray
     */
    public static void writeFile(byte[] byteArray) {

        try{
            File file = new File("bytebuffertest");

            FileOutputStream output = new FileOutputStream(file);
            IOUtils.write(byteArray, output);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Now I need to retrieve the byte array from that same file using this C++ program and deserialize it to extract employeeId, lastModifiedDate and attributeValue from it. I am not sure what the best way is on the C++ side.

int main() {

    string line;

    std::ifstream myfile("bytebuffertest", std::ios::binary);

    if (myfile.is_open()) {

        uint16_t employeeId;
        uint64_t lastModifiedDate;
        uint32_t attributeLength;

        char buffer[8]; // sized for the biggest read we want to do

        // read two bytes (will be in the wrong order)
        myfile.read(buffer, 2);

        // swap the bytes
        std::swap(buffer[0], buffer[1]);

        // only now convert bytes to an integer
        employeeId = *reinterpret_cast<uint16_t*>(buffer);

        cout<< employeeId <<endl;

        // read eight bytes (will be in the wrong order)
        myfile.read(buffer, 8);

        // swap the bytes
        std::swap(buffer[0], buffer[7]);
        std::swap(buffer[1], buffer[6]);
        std::swap(buffer[2], buffer[5]);
        std::swap(buffer[3], buffer[4]);

        // only now convert bytes to an integer
        lastModifiedDate = *reinterpret_cast<uint64_t*>(buffer);

        cout<< lastModifiedDate <<endl;

        // read 4 bytes (will be in the wrong order)
        myfile.read(buffer, 4);

        // swap the bytes
        std::swap(buffer[0], buffer[3]);
        std::swap(buffer[1], buffer[2]);

        // only now convert bytes to an integer
        attributeLength = *reinterpret_cast<uint32_t*>(buffer);

        cout<< attributeLength <<endl;

        myfile.read(buffer, attributeLength);

        // now I am not sure how should I get the actual attribute value here?

        //close the stream:
        myfile.close();
    }

    else
        cout << "Unable to open file";

    return 0;
}

Can anybody take a look on C++ code and see what I can do to improve it, as I don't think it is looking much efficient? Any better way to deserialize the byte array and extract relevant information on the C++ side?


texts: N-Layer using MEF dependency injection on MVC project

texts:
I'm trying to create a "perfect" generic solution structure for MVC (5.2.3.0) projects using MEF.

Currently my solution looks like this.

Core layer contains generic classes that could be used in any project
Data layer contains a ApplicationContext (: DbContext) and models
Repositories layer contains Repository classes to access data
Service layer contains business rules
TreeOfMana is the presentation (MVC)
Dependencies is where I'm adding all interfaces (IUser, IRepository, IApplicationContext...)

They don't know each other

The layers "export" their DLLs on the Post Build event to the presentation bin folder.

copy "$(TargetFileName)" "$(SolutionDir)$(SolutionName)\bin"

This allows me to load assemblies and add to MEF

public static class MefConfig
{
    public static CompositionContainer Container { get; private set; }

    public static void Register()
    {
        var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "TreeOfMana*.dll", SearchOption.AllDirectories)
            .Where(o => !o.Replace(AppDomain.CurrentDomain.BaseDirectory, "").Contains("obj\\"));

        var catalogAggregator = new AggregateCatalog();

        foreach (var file in files)
        {
            catalogAggregator.Catalogs.Add(new AssemblyCatalog(Assembly.LoadFrom(file)));
        }

        Container = new CompositionContainer(catalogAggregator);
    }
}

To wire-up with MVC I'm using a custom controller factory. For that first I need to export the controller:

public class ControllerExportAttribute : ExportAttribute
{
    public ControllerExportAttribute(Type concreteType)
        : base(concreteType.FullName, typeof(IController))
    {

    }
}

[ControllerExportAttribute(typeof(HomeController))]
[PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.NonShared)]
public class HomeController : Controller { }

By exporting as IController and having the contract name I can find it on the exports list.

My ControllerFactory is:

public class MefControllerFactory : DefaultControllerFactory
{
    private readonly CompositionContainer compositionContainer;

    public MefControllerFactory(CompositionContainer compositionContainer)
    {
        this.compositionContainer = compositionContainer;
    }

    protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
    {
        IController result = null;

        var export = compositionContainer.GetExports(typeof(IController), null, controllerType.FullName).SingleOrDefault();

        if (null != export)
            result = export.Value as IController;

        if (null != result)
            compositionContainer.SatisfyImportsOnce(result);

        return result;
    }
}

The controller factory finds the exported controller where the contract name ends with the controller name requested.

Question

I'm looking for advice on how to separate the layers, how to properly use MEF on an architecture like this.

Does this structure I created look decent?
Does it make sense?
Should I change something?
Am I going mad?


texts:
This is the function which I wrote and am currently using in my project.  I want to know if there is a better way to write it:

function pageLoader(pageIndex){

            $(".ServicesSectionWrapper,.ServicesSectionWrapper .Selector,.ServicesSection,.JournalSectionWrapper,.JournalSectionWrapper .Selector,.JournalSection,.AboutSectionWrapper,.AboutSectionWrapper .Selector,.AboutSection").hide();

        switch(pageIndex){

        case 1:
        $(".AboutSectionWrapper").fadeIn(400,function(){$("#AboutWrapper").fadeIn(400,function(){$("#ManagerWrapper").fadeIn(400,function(){$("#DeveloperWrapper").fadeIn(400,function(){$("#DesignerWrapper").fadeIn(400,function(){$(".AboutSection").fadeIn(400,function(){$(".AboutSection").addClass("PreLoadRotate")})})})})})});
        break;

        case 2:
        $(".JournalSectionWrapper").fadeIn(400,function(){$("#DateOne").fadeIn(400,function(){$("#DateTwo").fadeIn(400,function(){$("#DateThree").fadeIn(400,function(){$("#DateFour").fadeIn(400,function(){$("#DateFive").fadeIn(400,function(){$("#DateSix").fadeIn(400,function(){$("#DateSeven").fadeIn(400,function(){$("#DateEight").fadeIn(400,function(){$(".JournalSection").fadeIn(400,function(){$(".JournalSection").addClass("PreLoadRotate")})})})})})})})})})});
        break;

        case 3:
        $(".ServicesSectionWrapper").fadeIn(400,function(){$("#AppsWrapper").fadeIn(400,function(){$("#ResponsiveWrapper").fadeIn(400,function(){$("#DigitalWrapper").fadeIn(400,function(){$("#PTRWrapper").fadeIn(400,function(){$(".ServicesSection").fadeIn(400,function(){$(".ServicesSection").addClass("PreLoadRotate")})})})})})});
        break;

        }
    }

And here is the HTML:

This is a menu (AboutSectionWrapper) which has selectors as you can see.  I want to load the menu first and then sequentially load the selectors and finally fade in the menu indicator and add a CSS class which has a transition in it.

It is the same for other cases but for example in CASE 2, there are more selectors!


texts: Method for validating properties based on passed conditions

texts:
I wrote a method for validating properties based on passed conditions. It works well, but declaration takes more space than the actual condition. Is there any way to make it shorter?

public virtual string Validate(string propertyName, params Tuple<Expression<Func<bool>>, string>[] predicates)
{
    if (!ValidationProperties.ContainsKey(propertyName))
        throw new ArgumentException($"No property found with name '{propertyName}'. Make sure you register it first.");

    foreach (var predicate in predicates)
    {
        if (predicate.Item1.Compile().Invoke())
        {
            ValidationProperties[propertyName] = false;
            ValidationChangedEvent?.Invoke(this, false);
            return predicate.Item2;
        }
    }

    ValidationProperties[propertyName] = true;

    if (ValidationProperties.All(pair => pair.Value))
        ValidationChangedEvent?.Invoke(this, true);

    return null;
}

And here's example of call which I want to be shorter:

 var result = Validate(nameof(FilePath),
                        new Tuple<Expression<Func<bool>>, string>(() => string.IsNullOrEmpty(FilePath), "Select a file to load"));

Basically I want to get rid of: new Tuple<Expression<Func<bool>>, string>


texts: Shell POSIX OpenSSL file decryption script follow-up #1

texts:
This question is the first follow-up of: Shell POSIX OpenSSL file decryption script

Please read it before you continue reading this. Thank you.

I only have one new problem solved and I would like you to have a look.

That problem being accepting one option -o output_directory.

I have little idea if I did this the best way, but it works.

The code follows:

#!/bin/sh

bold=$(tput bold)
red=$(tput setaf 1)
yellow=$(tput setaf 3)
nocolor=$(tput sgr0)

bold_red=${bold}${red}
bold_yellow=${bold}${yellow}

print_usage_and_exit()
{
    echo "Usage: $0 [-o output_directory] filename_to_decrypt"
    exit 1
}

print_error_and_exit()
{
    echo "${bold_red}$1 Exit code = $2.${nocolor}" 1>&2
    exit "$2"
}

while getopts ":o:" option
do
    case "${option}" in
        o)
          given_output_directory=${OPTARG}
          ;;
        h | *)
          print_usage_and_exit
          ;;
    esac
done

shift $((OPTIND - 1))

[ "$#" -eq 0 ] &&
print_usage_and_exit

[ "$#" -gt 1 ] &&
print_error_and_exit "Multiple files are not supported." 2

[ ! -f "$1" ] &&
print_error_and_exit "The given argument is not an existing file." 3

input_filename="$1"

[ ! -r "$input_filename" ] &&
print_error_and_exit "Input file is not readable by you." 4

input_filepath=$(dirname "$input_filename")

if [ -z ${given_output_directory} ]
then
    output_directory="$input_filepath"
else
    output_directory="$given_output_directory"
fi

[ ! -w "$output_directory" ] &&
print_error_and_exit "Destination directory is not writable by you." 5

filename_extracted_from_path=$(basename "$input_filename")
filename_without_enc_extension="${filename_extracted_from_path%.enc}"

if [ "$filename_extracted_from_path" = "$filename_without_enc_extension" ]
then
    # the file has a different than .enc extension or no extension at all
    # what we do now, is that we append .dec extention to the file name
    output_filename="$output_directory/$filename_extracted_from_path".dec
else
    # the file has the .enc extension
    # what we do now, is that we use the file name without .enc extension
    output_filename="$output_directory/$filename_without_enc_extension"
fi

[ -f "$output_filename" ] &&
print_error_and_exit "Destination file exists." 6

if ! pv -W "$input_filename" | openssl enc -aes-256-cbc -md sha256 -salt -out "$output_filename" -d 2> /dev/null
then
    [ -f "$output_filename" ] && rm "$output_filename"

    print_error_and_exit "Decryption failed." 7
else
    echo "${bold_yellow}Decryption successful.${nocolor}"

    exit 0
fi

Uploaded on GitHub: https://git.io/fxslm


texts: Implementing IDisposable correctly to return TCP connection back to pool

texts:
I'm trying to implement TCP connection pooling and return a connection back to the pool using IDisposable. I'm wondering if my implementation is correct. It seems to be working but I think because the base class also implements IDisposable and finalize, my code might be leaky.

public class BaseClass : IDisposable
{
    internal bool IsDisposed { get; set; }
    private object someResource;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~BaseClass()
    {
        Dispose(false);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (someResource != null)
        {
            // some clearn up
            return;
        }

        if (disposing)
        {
            //dispose un managed resources

        }
    }
}

public class ChildClass : BaseClass
{
    // adds some functionality
}

public class MyClass : ChildClass, IDisposable
{
    MyPoolManager manager = null;

    public MyClass(MyPoolManager manager)
    {
        this.manager = manager;

    }
    void IDisposable.Dispose()
    {
        manager.ReturnPooledConnection(this);
    }
}

public class MyPoolManager
{
    private static MyPoolManager instance = new MyPoolManager();
    private static object objLock = new object();

    private static Queue<MyClass> que = null;
    private string name;

    static MyPoolManager()
    {
        que = new Queue<MyClass>();
        // enqueue some instances of MyClass here
        MyClass client = new MyClass(instance);
        que.Enqueue(client);
    }

    private MyPoolManager() { }

    public MyPoolManager(string name)
    {
        this.name = name;
    }

    public MyClass GetPooledConnection()
    {
        lock (objLock)
        {
            while (que.Count == 0)
            {
                if (!Monitor.Wait(objLock, 1000))
                    throw new TimeoutException("Connection timeout");
            }
            return que.Dequeue();
        }
    }

    public void ReturnPooledConnection(MyClass client)
    {
        lock (objLock)
        {
            que.Enqueue(client);
            Monitor.Pulse(objLock);
        }
    }
}

Use it like this in your program:

MyPoolManager pool = new MyPoolManager();
using (var conn = pool.GetPooledConnection())
{
    // use the conn here
}

// when you reach here the conn should have returned back to the pool


texts:
I have a block of Jinja2 (used in Sceptre/CloudFormation). It is not readable in my opinion, but I can't find any way to clean it up to improve it.

{% set args = "--kubelet-extra-args '--node-labels=nodegroup=" + sceptre_user_data.node_group_name %}

{% if sceptre_user_data.node_labels != "None" %}
  {% set args = args + "," + sceptre_user_data.node_labels %}
{% endif %}

zone=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)

{% if sceptre_user_data.cni_custom_network == "Yes" %}
  {% set args = args + ",k8s.amazonaws.com/eniConfig=pod-netconfig-$zone" %}
{% endif %}

{% if sceptre_user_data.taints != "None" %}
  {% set args = args + " --register-with-taints=" + sceptre_user_data.taints %}
{% endif %}

{% set args = args + "'" %}

eval "/etc/eks/bootstrap.sh ${EKSClusterName} {{ args }}"

I tried using join filters although that seemed to make it worse.

(This has nothing to do with Flask, but is all about Jinja2 obviously. But there appears to be no Jinja2 tag.)


texts: Showing popup according to the header nav link

texts:
I am showing templates in popups according to the user navigation links. It works for me, but, is this the correct way to do it?

var app = angular.module('plunker', []);

app.service('modalService', function( $rootScope ) {

  this.hide = function () {

    this.show = false;

  }

  this.showIt = function () {

    this.show = true;

  }

  this.setCategory = function ( category ) {

     return this.showPath = category+'.html'

  }

  this.showCategory = function (category) {

    this.setCategory( category )
    $rootScope.$apply();
  }

})

app.controller('header', function($scope) {

  $scope.view = "home view";

});

app.controller('home', function($scope, modalService) {

  $scope.name = 'World';
  $scope.service = modalService;

});

//header directive

app.directive('headerDir', function( modalService) {

  return {
      restrict : "E",
      replace:true,
      templateUrl:'header.html',
      scope:{},
      link : function (scope, element, attrs) {

         element.on('click', '.edit', function () {
            modalService.showIt();
            modalService.showCategory('edit');
         });

         element.on('click', '.service', function () {
           modalService.showIt();
           modalService.showCategory('service');

         })

      }
  }

});

app.directive('popUpDir', function () {

  return {
    replace:true,
    restrict:"E",
    templateUrl : "popup.html"
  }

})

Click on the top link to show the popup, and click on the screen to hide the popup.

Live Demo


texts: Different implementation of an Interface along with additional parameters

texts:
I am designing an interface for 2 distinct implementations as follows:

Perform operations without client credentials ( for my local applications)
Perform operations using security token. (for web applications)

Interfaces are as follows :

interface IContactService
{
    void Add(Contact c);
    void Update(Contact c);
}

interface IProxy
{
     string Token { get; set; }
     void SetToken(string token);
}

and below are the implementations :

public class ContactBusinessImpl : IContactService
{

    private IContactService _contactService;

    public ContactBusinessImpl(IContactService contactService) {
        _contactService = contactService;
    }

    public void Add(Contact c)
    {
        _contactService.Add(c);
    }

    public void Update(Contact c)
    {
        _contactService.Update(c);
    }
}

public class ContactBusinessProxyImpl : IContactService , IProxy
{
    public string Token { get; set; }

    public void SetToken(string token)
    {
        Token = token;
    }
    public void Add(Contact c)
    {
        var client = new HttpClient();
        client.SetBearerToken(Token);
        var stringContent = new StringContent(JsonConvert.SerializeObject(c), Encoding.UTF8, "application/json");
        client.PostAsync("api/add", stringContent);
    }

    public void Update(Contact c)
    {
        var client = new HttpClient();
        client.SetBearerToken(Token);
        var stringContent = new StringContent(JsonConvert.SerializeObject(c), Encoding.UTF8, "application/json");
        client.PostAsync("api/update", stringContent);
    }
}

Earlier I was using token as a parameter for each method (Add(Contact c,string token)) which was not acceptable.

Now I am okay with above approach, but it seems like without SetToken I cant do anything in proxy implementation.

Since I am using DI to instantiate classes for can't go for Adapter pattern like ContactBusinessProxyImpl(string token).

Is there any better approach or pattern can be used here?


texts:
I'm still in the process of learning Python and am doing some of the Project Euler problems.

I have made a factorisation algorithm that works; however, it runs really slowly, and I'm not too well-versed on coding for performance. If someone could give me some pointers on how to improve the algorithm's efficiency it would be a huge help.

def factorise(num_to_factorize):
    """This method returns a list of factors for a particular number passed in to the parameters."""
    factors = []
    for i in range(1,math.floor(num_to_factorize/2)+1):  # Loops from 1 to half the number, floors for odd numbers.
        if num_to_factorize % i == 0:  # Factor check.
            factors.append(i)  # Append on to an array to be checked.
    factors.append(num_to_factorize)  # Append the number itself as it is a factor.
    return factors

def prime_factorise(num_to_prime_factorize):
    """This method returns the prime factors of the number passed in to the method as a parameter."""
    prime_factors = []
    for factor in factorise(num_to_prime_factorize):  # Loop through each factor.
        if factorise(factor) == [1, factor] or factorise(factor) == [1]:  # if prime factors
            prime_factors.append(factor)
    return prime_factors


texts: Generating and sending new password to user

texts:
Generate new password and send to user, if user is registered.

Two TextBox on page, txtUserName & txtEamil.
User can provide either UserName or Email to get new password.
If UserName is provided then find User on username, if exists then
generate new password and Email.
If user provided email then check if any user exists with provided
email then generate new password and Email.

protected void btnSubmit_Click(object sender, EventArgs e)
{
    string userName = txtUserName.Text.Trim();
    string email = txtEmail.Text.Trim();

    //
    if (string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(email))
    {
        lblMessage.Text = "Please provide at least either of the one, User Name or Email.";
    }
    else
    {
        SendNewPasswordToUser(userName, email);
    }
}

private void SendNewPasswordToUser(string userName, string email)
{
    if (!string.IsNullOrEmpty(userName))
    {
        MembershipUser mu = Membership.GetUser(userName);
        if (mu != null)
        {
            string password = mu.ResetPassword();
            EmailPassword(password, mu.Email);
        }
    }
    else if (!string.IsNullOrEmpty(email))
    {
        userName = Membership.GetUserNameByEmail(email);
        if (!string.IsNullOrEmpty(userName))
        {
            MembershipUser mu = Membership.GetUser(userName);
            string password = mu.ResetPassword();
            EmailPassword(password, mu.Email);
        }
    }
}

private void EmailPassword(string password, string toEmail)
{
    string mailBody = string.Format("Your new password is {0}", password);
    Mail.SendMail("admin@abc.com", toEmail, "New Password", mailBody);
}

Is there a better approach to avoid so many ifs?


texts:
I coded this simple protocol but I'm sure that it can be better, this is the process:

Reads incoming data
Waits until payload size can be read
Reads the full message
Checks if there are mixed messages
Reads incoming data again

Code:

private async void ReadPackets(StreamSocket socket, SocketInformation socketInformation)
{
    byte[] data = new byte[BufferSize];

    IInputStream inputStream = socket.InputStream;
    IBuffer buffer = data.AsBuffer();

    while (socketInformation.open)
    {
        IBuffer bytesRead;

        try
        {
            bytesRead = await inputStream.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);

            if (bytesRead.Length > 0)
            {
                PrintByteArray("Data", data);
            }
        }
        catch (Exception)
        {
            break;
        }

        // Wait for payload size
        if (buffer.Length >= 4)
        {
            int commandType = (int)BitConverter.ToInt16(data, 0);
            int payloadSize = (int)BitConverter.ToInt16(data, 2);
            int packetSize = PacketHeaderSize + payloadSize;

            // Wait for full packet
            if (buffer.Length >= packetSize)
            {
                byte[] packet = new byte[packetSize];
                System.Buffer.BlockCopy(data, 0, packet, 0, packetSize);

                Debug.WriteLine("Packet received.");

                ConcurrentQueue<byte[]> packetReceiveQueue = socketInformation.GetPacketReceiveQueue();

                packetReceiveQueue.Enqueue(packet);

                if (buffer.Length > packetSize)
                {
                    int bufferLength = (int)buffer.Length - packetSize;

                    byte[] newData = new byte[BufferSize];
                    System.Buffer.BlockCopy(data, packetSize, newData, 0, bufferLength);
                    data = newData;

                    buffer.Length = (uint)bufferLength;
                }
            }
        }
    }

    Debug.WriteLine("Socket closed.");
    inputStream.Dispose();
    socket.Dispose();
}


texts: Aliasing utility class method in extended class

texts:
Consider this setup:

class UtilityClass
{
    public function formatNumber($input) {
        return number_format($input, 0, '', ' ');
    }

    public function trimText($input) {
        return substr(trim($input), 0, 100);
    }

    // bunch of other methods
}

class SessionClass
{
    public $utils;
    private $permissions = array();

    function __construct() {
        $this->utils = new UtilityClass();
        $this->setPermissions();
    }

    public function getPermissions($type) {
        return $this->permissions[$type];
    }

    public function getSettings() {
        // do stuff
    }

    private function setPermissions() {
        // do stuff to set $this->permissions
    }

    // bunch of other methods
}

class BaseClass
{
    public $session;

    function __construct($session) {
        $this->session = $session;
    }

    // bunch of methods
}

class ExtendedClass extends BaseClass
{
    // bunch of methods
}

$session = new SessionClass();
$extClass = new ExtendedClass($session);

When I want to use the formatNumber method of UtilityClass in my ExtendedClass, I can do it from within ExtendedClass like so:

$this->session->utils->formatNumber('some input');

...because the $session object, containing the $utils object, was injected into the $extClass object. However, if I use the formatNumber method from UtilityClass very often in ExtendedClass, it means quite a lot of (long) calls like written above. I could shorten it by using 'traits', changing:

trait Utilities
{
    function formatNumber($input) {
        // do something and return
    }
}

...and:

class ExtendedClass extends BaseClass
{
    use Utilities;

   // bunch of methods
}

I could then do the same call like this:

$this->formatNumber('some input');

I could put use Utilities in BaseClass so all extended classes could use it. But I would have to put an extra use Utilities in SessionClass, because that needs it as well. So then I end up with a $session object and an $extClass object which both contain the methods from the Utilities trait, and one is injected into the other. That seems wrong.

Another solution is 'aliasing' the formatNumber method from the UtilityClass class. To that end, I could change BaseClass:

class BaseClass
{
    function __construct($session) {
        $this->session = $session;
    }

    function get($input) {
        return $this->session->utils->formatNumber($input);
    }

    // more methods
}

This also seems not quite right. Is there a better solution? What would give the best performance/least redundancy?

Could PHP 5.6 offer the best solution? Using namespaces: Aliasing/Importing

Using use you can now 'alias' a function like this:

// aliasing a function (PHP 5.6+)
use function My\Full\functionName as func;


texts:
I made a simple Blackjack/21 game in C++. It does not use any fancy graphics, just the console output. It is as simple as it can get.

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>

void printData(int pTotal, int dCard) {

    std::cout << "\nYour total is " << pTotal;
    std::cout << "\nDealer has a " << dCard << " showing.\n";

}

int getCard() {

    return std::rand() % 11 + 2;

}

void turn(int& pTotal, char choice, bool& stay) {

    // If the user wants to hit
    if (choice == 'H' || choice == 'h') {

        // If the user hits 21 or above
        if ((pTotal += getCard()) >= 21) {

            std::cout << "Your total is " << pTotal;
            stay = true;

        }

        return;
    }

    // Since the only other option can be to stay, then stay
    stay = true;

}

int main() {

    bool stay;
    char choice = NULL;

    while (true) {

        std::cout << "================================";
        stay = false;

        // Initialize srand and get random card numbers
        std::srand(std::time(0));
        int dCard = getCard();
        int pTotal = getCard() + getCard();
        int dTotal = dCard + getCard();

        // Player's turn
        while (!stay) {

            printData(pTotal, dCard);
            std::cout << "[H]it or [S]tay?\n";
            std::cin >> choice;
            turn(pTotal, choice, stay);

        }

        stay = false;
        std::cout << "\n\nIt is now the dealer's turn!\n";

        // Dealer's turn
        while (dTotal <= 21 && !stay) {

            if (dTotal >= 17)
                stay = true;
            else
                dTotal += getCard();

        }

        // Display winner
        std::cout << "\n\nThe player has " << pTotal << ".\nThe dealer has " << dTotal << ".\n\n";
        if ((std::abs(21 - pTotal)) < (std::abs(21 - dTotal))) std::cout << "The player wins!\n";
        else std::cout << "The dealer wins!\n";

    }

}

Is this code efficient?
Is the code easy to read/understand and to follow?
Are variable names appropriate?


texts: Unit test for a maximum-finding function

texts:
A while ago, I got this question as a part of an interview test which asked to write a function to find the biggest number in a vector and write all the unit tests required to show that the code works under any circumstance using any language or pseudo-code.
To the best of my knowledge, one would need a testing framework in order to do that, so I wrote this and I got a rejection email a couple of hours later.
#include <cassert>
#include <vector>

int largest (std::vector<int> vec ) {

int max = vec[0];
for (int i=1; i<vec.size(); i++)
   if (vec[i] > max)
      max = vec[i];
return max;
}

void test (std::vector<int> vec, int i) {
assert (largest (vec) == i);
}

int main() {
std::vector<int> vec = { 7, 50, 16, 8, 25, 9, 12,112 };
test (vec, 112);
test (vec, 7);

return 0;
}

I have zero experience in professional software development and I used C++ since I find it easy to compile and run.
What did I do wrong? What should I have written? Any input would be great.


texts:
I got a proposed exercise from a Java2 book. This one wants me to find out the numeric centers.

A numeric center splits two list of numbers that make the same result when you add the numbers in each list. For example, 6 is the first numeric center because 1+2+3+4+5=15 and 7+8=15 too. The second numeric center is 35 because 1+2+3..+34=595 and 36+37+38+39=595 too.

 //I'll call the Numeric Center cn from here.
public class cnumerico {
    public static void main(String args[]){
        int n, index, fsum, ssum;
        n=204; //The higher number we would get.
        index=1; //No explanation need I guess.
        fsum=0; //Stands for first sum.
        ssum=1; //Stands for second sum.
        do{
            for (int i=1;i<index;i++){
                fsum=fsum+i; //We make the first sum from 1 until it reaches the index.
                }
            for (int j=index+1;j<index*2;j++){
                if (ssum==fsum){
                    System.out.println(index+" es un centro numerico.");
                    break;
                    //In this if I check if the numbers are equal, if it is we found our cn so I stop the loop.
                    }else{
                        ssum=ssum+j;
                        }
                //If we still didn't find our cn this else does the sum from index(+1 because the cn musn't be in the sum).
                }
            index++;
            fsum=0;ssum=0; //Resetting the sums to start again.
        }while (index<n+1);
    }
}

It works, but I have a feeling that I could do it much simpler.


texts: I want to see if there is anything I don't need in my CSS file for my current layout

texts:
Here is my link to the JSFiddle and the full screen description.

Note on the full mode screen: the footer is not sticking, but it actually sticks if I check on my browser.

So that is exactly what I want for my layout. I want someone to see if there's anything in my CSS I don't need, or if I am using improperly without affecting the layout that is displayed.

For example:

Under the Header ID I have a element called top:0; what is this used for and do I actually need it?
Under the Main ID I have margin: 0 auto -50px; I found help from someone, but quite don't understand the theory on it.
Under the Footer ID I have bottom:0; what is this used for as well and do I need it?

HTML:

CSS:

/*THIS IS THE CSS CODE FOR WNG WEBSITE*/
html, body
{
        padding:0;
        margin:0;
        height:100%;
        font-size:0.8em;
}
#page
{
        height:100%;
        min-width:960px;
}
#header
{
        position:relative;
        background-color:#115EA2;
        height:100px;
        width:100%;
        top:0;
}
#main
{
        width:1300px;
        background-color:#F1F2F3;
        margin: 0 auto -50px;
        vertical-align:bottom;
        padding: 20px 20px 40px 20px;
        color:#115EA2;
        text-decoration:none;
        height:2000px;
}
#footer
{
        position:fixed;
        width:100%;
        bottom:0;
        height: 35px;
        background-color:#115EA2;
}


texts:
I have a line residing in some n-dimensional space, that needs to be discretized into a set of points. Given the start, end points, and some the number of points r that  are needed, I can accomplish this as follows:

import numpy as np

start, end = (0, 0, 0), (10, 10, 10)
r = 3
dl = zip(*[np.linspace(s_i, e_i, r) for s_i, e_i in zip(start, end)])

This seems to work well enough, but I'd rather the entire thing work as a generator, and right now now the linspace has to be computed for the whole thing. How could I accomplish this?


texts: Advent of Code 2016: Day 1 "No Time for a Taxicab"

texts:
Here I'm talking about Part 2 of the puzzle, where we need to find "How many blocks away is the first location you visit twice?".

At first I solved it as everybody else using a set of all visited points.
Peter Norvig employed that approach, you can check his solution on GitHub.

My code was not that elegant, but Peter's notebook reminded me of existence of complex type, so I modified my function and ended up here:

def solve_set(instructions):
    direction, loc, visited = 1j, 0, {0}
    for i in instructions.split(', '):
        direction *= {'R': -1j, 'L': 1j}[i[0]]
        for _ in range(int(i[1:])):
            loc += direction
            if loc in visited:
                return abs(loc.real) + abs(loc.imag)
            visited.add(loc)

Now let's try to optimize it.

The puzzle uses Taxicab geometry,
and if we assume that all instructions have a positive number of steps (greater than zero),
we can split segments into two subsets, parallel and orthogonal,
and for each new segment check only orthogonal segments for an intersection.
No matter what, on a new instruction (i.e. new segment) those two sets interchange,
so parallel segments become orthogonal and orthogonal become parallel.
To update subsets (represented as lists) we use insort function from bisect module
which inserts an element into a list keeping it sorted.
Then we get a list of candidates from orthogonal set of segments using bisect function
and iterate over it in the direction of current segment to get the first intersection:

from bisect import bisect, insort

def solve_bisect(instructions):
    N, E, S = 1j, 1, -1j
    direction, cur, prev, prev_s = N, 0, 0, None
    parallel, orthogonal = [], []  # segments
    for i in instructions.split(', '):
        direction *= {'R': -1j, 'L': 1j}[i[0]]
        cur += direction * int(i[1:])
        if direction in (N, S): s = prev.real, prev.imag, cur.imag
        else:                   s = prev.imag, prev.real, cur.real
        insort(parallel, s)
        candidates = orthogonal[bisect(orthogonal, s[1:2]) : bisect(orthogonal, s[2:])]
        for c in candidates if direction in (N, E) else candidates[::-1]:
            if prev_s != c and (c[1] <= s[0] <= c[2] or c[2] <= s[0] <= c[1]):
                return abs(s[0]) + abs(c[0])
        prev, prev_s, parallel, orthogonal = cur, s, orthogonal, parallel

Now we need to generate a large input for comparison:

from random import choice, randrange
instructions = ', '.join(f'{choice("LR")}{randrange(1, 1000000)}' for _ in range(100000))

I don't know what you will end up with, but I get these results:

In [15]: %timeit solve_bisect(instructions)
5.91 ms ± 144 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [16]: %timeit solve_set(instructions)
465 ms ± 8.75 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So in this case solve_bisect is roughly 100x times faster than the naive approach.

But I'd like to know if there's an even better way to solve the problem.


texts: Is there a way to make reshaping arrays shorter and cleaner?

texts:
I'm trying to reshape my input arrays in a way that's described below to be able to fit a  curve on the data points, plot it, etc.
It works fine, but I'm afraid it's not the most efficient way of doing it, and also it's hard to understand and read. It's part of a bigger function, but I only post here the critical part and not the whole function. I also added little comments to help you understand what's going on. I know it's ugly.

import numpy as np
from itertools import chain

#example inputs
delay = np.array([10,20,30,40,50,60,70,None])
omega = [[1,2,3,4],[1.1,2.2,3.3,None],[1.4,2.4,3.4,None],[1.5,2.8,None,None],
         [1.8,2.9,None,None],[1.9,None,None,None],[2.0,None,None,None],[None,None,None,None]]

"""
desired output explained:
with delay's first component 10 I want to assign 1, 2, 3 and 4
so the outputs starts like this: [10,10,10,10] , [1,2,3,4]
then with delay's second component 20 I want to assign 1.1, 2.2, 3.3 and drop the None value.
at the moment the outputs should look like this: [10,10,10,10,20,20,20] , [1,2,3,4,1.1,2.2,3.3]
and so on.
"""

def spp_method(omegas, delays):

    #dropping all None values from delays
    delays = delays[delays != np.array(None)]
    #dropping all the None values from omegas
    omegas_ext = []
    for element in omegas:
        item = [x for x in element if x is not None]
        omegas_ext.append(item)

    #expand delays with the number of values in omegas_ext appropriate component
    delays_exp = []
    for idx in range(len(omegas_ext)):
        if len(omegas_ext[idx])>1:
            value = delays[idx]
            item_to_add = [value]*(len(omegas_ext[idx]))
            delays_exp.append(item_to_add)
        elif len(omegas_ext[idx]) == 1:
            value = delays[idx]
            delays_exp.append([value])
    #put the values into simple array to plot and to fit curve.
    delays_unpacked = []
    omegas_unpacked = []
    for element in omegas_ext:
        for item in element:
            omegas_unpacked.append(item)
    delays_unpacked = list(chain.from_iterable(delays_exp))
    return np.array(delays_unpacked), np.array(omegas_unpacked)

y, x = spp_method(omega, delay)

print(x)
#outputs to: [1.  2.  3.  4.  1.1 2.2 3.3 1.4 2.4 3.4 1.5 2.8 1.8 2.9 1.9 2. ]
print(y)
#outputs to: [10 10 10 10 20 20 20 30 30 30 40 40 50 50 60 70]

which are correct.

Any improvements in the code are well-appreciated.


texts: Mixing Async and Sync in same HTTP request ASP.NET Core C#

texts:
Is it bad practice to mix async and sync call in same ASP.NET core API call?

For example, in following code method CropBlackBroderOfAnImageAsync is an async method.

On the other hand SaveImageForProcessing(file, sourceFolderPath); is a sync method.

The reason I am calling SaveImageForProcessing synchronously is
that I want use the result of it to execute the code in CropBlackBroderOfAnImageAsync.

public async Task<(string sourceFolderPath, string destinationFolderPath)> CropBlackBorderOfAnImage(IFormFile file)
{
    var extension = Path.GetExtension(file.FileName);
    var newFileName = Guid.NewGuid().ToString();//Create a new Name for the file due to security reasons.
    var fileNameSource = newFileName + extension;
    var sourceFolderPath = Path.Combine(Directory.GetCurrentDirectory(), "Images\\Source", fileNameSource);

    var fileNameDestination = newFileName + "Result" + extension;
    var destinationFolderPath = Path.Combine(Directory.GetCurrentDirectory(), "Images\\Destination", fileNameDestination);

    SaveImageForProcessing(file, sourceFolderPath);

    await _imageCropBlackBroderService.CropBlackBroderOfAnImageAsync(sourceFolderPath, destinationFolderPath);

    return (sourceFolderPath, destinationFolderPath);
}

private void SaveImageForProcessing(IFormFile file, string path)
{
    using (var bits = new FileStream(path, FileMode.Create))
    {
        file.CopyTo(bits);
    }
}


texts:
First string includes 4 integers: N, M, A, B (1 ≤ N, M ≤ 300, A, B ≤ 1000).
Each next line include M-symbols. Symbol . is a clean cell, * and ** are dirty.

I need to find the sum for cleaning if A its sum of ** cell, B is sum of *.

What I can do better?

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

using std::cin;
using std::cout;
using std::string;
using std::vector;

int main() {
  int n, m, a, b;
  cin >> n >> m >> a >> b;

  vector<string> parquet;

  int itr = 0;

  while (itr < n) {
    string cell;
    cin >> cell;
    parquet.push_back(cell);
    itr++;
  }

  int sum = 0;

  itr = 0;

  while (itr < parquet.size()) {
    for (int i = 0; i < parquet[itr].size(); i++) {
      if (parquet[itr][i] == '*') {
        if (parquet[itr][i + 1] == '*') {
          i++;
          sum += a;
        } else {
          sum += b;
        }
      }
    }

    itr++;
  }

  cout << sum;
}


texts: Performance issue “not enough memory” Macro vba Excel - Parsing data

texts:
I have built some code that should parse the data according to a unique value and then create a new Worksheet for each unique value. My initial table has 10 Columns and around 25K rows. The code works well for up to ca. 8500 rows. Above, I get the error message
not enough memory, etc...
Excel 64bits can not be installed on our work machines... Any ideas for a workaround? I just need this code to run in less than 3 hours and it will be a big win! Thanks!
Sub Split_data()
Dim lr As Long
Dim ws As Worksheet
Dim vcol, i As Integer
Dim icol As Long
Dim myarr As Variant
Dim title As String
Dim titlerow As Integer
Dim OutPut As Integer

 'This macro splits data into multiple worksheets based on the variables on a column found in Excel.
 'An InputBox asks you which columns you'd like to filter by, and it just creates these worksheets.

Application.ScreenUpdating = False
vcol = Application.InputBox(prompt:="Which column would you like to filter by?", title:="Filter column", Default:="10", Type:=1)
Set ws = Worksheets("Import") 'change worhseet name when necessary
lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
title = "A1:J14"
titlerow = ws.Range(title).Cells(1).Row
icol = ws.Columns.Count
ws.Cells(1, icol) = "Unique"
For i = 3 To lr
    On Error Resume Next
    If ws.Cells(i, vcol) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, vcol), ws.Columns(icol), 0) = 0 Then
        ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol)
    End If
Next
Application.ScreenUpdating = False
myarr = Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
ws.Columns(icol).Clear

For i = 3 To UBound(myarr)
    ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) & ""
    If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then
        Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
    Else
        Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
    End If
    ws.Range("A" & titlerow & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Range("A1")
    Sheets(myarr(i) & "").Columns.AutoFit

Next

ws.AutoFilterMode = False
ws.Activate
Sheets("Instructions").Select

OutPut = MsgBox("Data successfully parsed", vbInformation, "Confirmation")
End Sub


texts:
I'm solving Project Euler problem 7, which says:

  By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number?

Here's the code I've written:

def primes(n):
    primes = []
    attempt = 3
    while len(primes) < (n-1):
        for i in range(len(primes)):
            if attempt % primes[i] == 0:
                attempt += 2
                break
        else:
            primes.append(attempt)
            print (primes)
    return (primes)

While testing a number, if it finds that the number is divisible by one of the primes in the list, the for loop breaks, and starts again with a larger number. If it isn't divisible, it's added to the list of primes. This keeps going until the list is as large as desired (in this case 10000, and I've omitted 2 so the last member of the list is the 10001st prime)

The problem is that this is extremely slow. I've seen other solutions that can apparently solve this in seconds, if not less. What are some ways I could make this run faster?


texts: Mutative Heap's algorithm (permutations generator) in Clojure

texts:
For a side project I'm working on, I need to be able to generate permutations. Instead of relying on an existing library like math.combinatorics, I decided to write my own implementation, and arbitrarily decided on Heap's Algorithm.

Example:

(permutations [1 2 3])
=> [[1 2 3] [2 1 3] [3 1 2] [1 3 2] [2 3 1] [3 2 1]]

I realized pretty quickly though that this algorithm relies heavily on the mutation of an array, and ended up giving up trying to adapt it to proper FP style.

I went to the dark side and made an implementation that relies on two atoms to function.

Now, the mutable array part seems pretty necessary to the algorithm, but I ended up needing a second atom to accumulate the permutations. I tried adapting the doseq part to a reduction or just using loop, but the recursive calls are such that it's very difficult to see how I'd pass data along back up the stack.

Mainly, I'd like advice on how I can get rid of the need for result-atom, but I'd welcome any critique here.

I'm fully aware that this is going strongly against the FP grain here, but I seemed forced into this corner trying to implement this algorithm. I'd also, if possible, like to see a fully FP implementation of this, but I'd wager that that would be quite difficult.

I'm also aware that Heap's algorithm may not be suited for FP, but that's ok. After like half an hour of fiddling, I became more focused on producing a working implementation of this algorithm, and less whether or not this was the right algorithm to be using in the first place.

(ns wof-guesser.logic.permutations)

(defn- swap-v [v i1 i2]
  (let [x (get v i1)]
    (-> v
        (assoc i1 (get v i2))
        (assoc i2 x))))

(defn- mutative-permutate [coll-atom result-atom]
  ((fn rec [n]
     (when (> n 1)
       (let [n-even? (zero? (rem n 2))
             swap-pos #(if n-even? % 0)]

         (doseq [i (range (dec n))]
           (rec (dec n))
           (swap! coll-atom swap-v (swap-pos i) (dec n))
           (swap! result-atom conj @coll-atom))

         (rec (dec n)))))

   (count @coll-atom)))

(defn permutations [coll]
  (let [v-coll (vec coll)
        col-a  (atom v-coll)
        res-a  (atom [v-coll])]
    (mutative-permutate col-a res-a)
    @res-a))


texts:
After watching Herb Sutter describe single-linked lists in terms of unique_ptr I decided to implement my own. In particular I want to know if my move semantics are correct and if any unnecessary copies are made. It passes my simple cases with int and I plan to add insertion/deleting later.

#include <iostream>
#include <memory>
#include <cstddef>
#include <utility>

template<typename Type>
class Node {
public:
  Node(const Type& data) : data {data} {}
  std::unique_ptr<Node<Type>> next = nullptr;
  Type data;
};

template<typename Type>
class LinkedList {
public:
  void push_back(const Type& data) {
    if (!head) {
      head = std::make_unique<Node<Type>>(data);
      return;
    }

    Node<Type>* end = head.get();

    while (end->next) {
      end = end->next.get();
    }

    end->next = std::make_unique<Node<Type>>(data);
  }

  Type pop_back() {
    if (!head) {
      throw;
    }

    Node<Type>* end = head.get();
    Node<Type>* previous = nullptr;

    while (end->next) {
      previous = end;
      end = end->next.get();
    }

    const Type data = end->data;

    if (previous) {
      previous->next = nullptr;
    }

    return data;
  }

  void push_front(const Type& data) {
    if (!head) {
      head = std::make_unique<Node<Type>>(data);
      return;
    }

    std::unique_ptr<Node<Type>> new_head = std::make_unique<Node<Type>>(data);
    new_head->next = std::move(head);
    head = std::move(new_head);
  }

  Type pop_front() {
    if (!head) {
      throw;
    }

    const Type data = head->data;
    head = std::move(head->next);
    return data;
  }

  std::size_t size() const {
    if (!head) {
      return 0;
    }

    std::size_t size = 1;
    Node<Type>* traverse = head.get();

    while (traverse->next) {
      traverse = traverse->next.get();
      size++;
    }

    return size;
  }

  /* iterative destroy to avoid recursive deletes */
  void destroy() {
    if (!head) {
      return;
    }

    while (head->next) {
      head = std::move(head->next);
    }

    head = nullptr;
  }

private:
  std::unique_ptr<Node<Type>> head = nullptr;
};

Edit: With Deduplicator's response I ended up with this code

#include <iostream>
#include <memory>
#include <cstddef>
#include <utility>

template<typename Type>
class Node {
public:
  Node(const Type& data) : data {data} {}
  std::unique_ptr<Node<Type>> next = nullptr;
  Type data;
};

template<typename Type>
class LinkedList {
public:
  void push_back(const Type& data) {
    auto end = &head;

    while (*end) {
      end = &(*end)->next;
    }

    *end = std::make_unique<Node<Type>>(data);
  }

  Type pop_back() {
    auto end = &head;
    auto previous = &head;

    while (*end) {
      previous = end;
      end = &(*end)->next;
    }

    const Type data = (*previous)->data;
    *previous = nullptr;
    return data;
  }

  void push_front(const Type& data) {
    auto new_head = std::make_unique<Node<Type>>(data);
    new_head->next = std::move(head);
    head = std::move(new_head);
  }

  Type pop_front() {
    const Type data = head->data;
    head = std::move(head->next);
    return data;
  }

  ~LinkedList() {
    auto end = &head;

    while (*end) {
      *end = std::move((*end)->next);
    }
  }

private:
  std::unique_ptr<Node<Type>> head = nullptr;
};


texts:
Here is my next Numpy practice, I am not sure is it more accurate to call it "Stroke Algorithm" or "Draw edge stuff", xD.

Anyway I did in steps:

calculate each pixel's RGB absolute distance to pixels on its right and down side, the distance is simple measured by absolute different in each color value and sum them up.
if the absolute distance on both directions all larger than some particular value, then it is an edge pixel, and color it black, else white

Suggestions I am looking for

Any suggestions in Numpy, I have some duplicate code this time, and didn't find good way to remove them.

Full code:

# -*- coding: utf-8 -*-
import numpy as np
from PIL import Image

def stroke(image_path, output, level=80, edge_color=[255,255,255], blackground_color=[0,0,0]):
    img = Image.open(image_path)
    data = np.asarray(img, dtype="int32")

    w, h, k = data.shape
    dirright_data = np.concatenate((data[:, 1:], data[:,-1:]), axis=1)
    dirdown_data = np.concatenate((data[1:,:], data[-1:,:]), axis=0)

    disRight = np.absolute(np.sum(data - dirright_data, axis=2))
    disDown = np.absolute(np.sum(data - dirdown_data, axis=2))

    level = min(max(1,level), 255)
    D_right = np.asarray(disRight<=level, dtype="int32")
    D_down = np.asarray(disDown<=level, dtype="int32")

    D = (D_right+D_down) > 1
    neg_D = (D_right+D_down) <= 1
    data[D] = edge_color
    data[neg_D] = blackground_color

    img = Image.fromarray(np.asarray(np.clip(data, 0, 255), dtype="uint8"), "RGB")
    img.save(output)

if __name__ == "__main__":
    stroke("images/bob.png", "new_test.jpg")


texts: Creating a page number array for pagination

texts:
I have written a small function to generate an array of page numbers for displaying a pagination. The inputs to the function is an active page number p, and the max page number. The function will return an array of 5 possible page numbers available near the active page.

Example input, output:

pages(1,10): [1,2,3,4,5]

pages(10,10): [6,7,8,9,10]

pages(5,10): [3,4,5,6,7]

The function is:

def pages(p,max):
    a=[p]
    while len(a)<5 and not (a[0]==1 and a[-1]==max):
        if a[0]>1:
            a.insert(0,a[0]-1)
        if a[-1]<max:
            a.append(a[-1]+1)
    return a

Is there anything to do to improve this code, or is there any other simpler methods to achieve this?