texts: Cryptographic range based random number generator class

texts:
Recently had reason to design a range based random number generator that uses the RNGCryptoServiceProvider provided by the .net api.

The basic algorithm generates a random unsigned 64 bit integer and creates a floating point number between 0 and 1 by dividing it by UInt64.MaxValue+ 1.  This is then multiplied by the range and added to the minimum, to produce a 32 bit integer in the right range.

The class also includes a shuffle method.

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Linq;
public static class CryptoRandom
{
    const double MAX_RANGE = (double)UInt64.MaxValue + 1;

    /// <summary>
    /// Get a cryptographic random integer in the range from
    /// min(inclusive) to max(exclusive)
    /// </summary>
    /// <param name="min"></param>
    /// <param name="max"></param>
    /// <returns></returns>
    public static int Next(int min, int max)
    {
        if (max < min)
        {
            throw new ArgumentException("max is less than min");
        }
        if(min < 0)
        {
            throw new ArgumentException("min and max must be positive integers");
        }
        if (min == max)
        {
            return min;
        }
        using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
        {
            byte[] randomNumber = new byte[8];

            rng.GetBytes(randomNumber);
            double baseNum = BitConverter.ToUInt64(randomNumber, 0) / MAX_RANGE;

            int range = max - min;

            return (int)(baseNum * range) + min;
        }

    }
    /// <summary>
    /// Get a cryptographic random integer in the range from
    /// 0 to max(exclusive)
    /// </summary>
    /// <param name="max"></param>
    /// <returns></returns>
    public static int Next(int max)
    {
        return Next(0, max);
    }
    /// <summary>
    /// Get a cryptographic random 32-bit integer
    /// </summary>
    /// <returns></returns>
    public static int Next()
    {
        return Next(0, Int32.MaxValue);
    }
    /// <summary>
    /// A cryptographic random shuffle method
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="input"></param>
    /// <returns></returns>
    public static ICollection<T> Shuffle<T>(ICollection<T> input)
    {
        return input.OrderBy(x => Next()).ToArray();
    }
}


texts:
Here is a code example from my name, where I use a MySQL db and store players data.

In this code I'm using a DataReader when loading and saving the data in and out. Although there's only 10 fields, I have reduced the number for this example. I plan on having 50+.

The main focus of this question is to find a more efficient way of managing players' data, a way that doesn't require so much code and hard work to load / save it.

Adding new features is a pain as I have to code a whole new set of fields to load and save, not forgetting the features.

My only idea was to make a dict and load it as [columnName] = columnValue;, cache it, grab if loaded previously and save all items on save. The problem with that was I didn't like the fact I had to explicitly call by the columns name. What if I changed it?

using MySql.Data.MySqlClient;

namespace Pitaya.Game.Players.Data
{
    internal class PlayerData
    {
        public int Id;
        public string Username;
        public int Rank;
        public string Motto;
        public PlayerOutfit Outfit;
        public PlayerGender Gender;
        public long Credits;
        public long Pixels;
        public long Diamonds;
        public bool CanChange;

        public void AssignData(MySqlDataReader reader)
        {
            while (reader.Read())
            {
                Id = reader.GetInt32("id");
                Username = reader.GetString("username");
                Rank = reader.GetInt32("rank");
                Motto = reader.GetString("motto");
                Outfit = new PlayerOutfit(reader.GetString("look"));
                Gender = reader.GetString("gender").ToUpper() == "M" ? PlayerGender.Male : PlayerGender.Female;
                Credits = reader.GetInt64("credits");
                Pixels = reader.GetInt64("activity_points");
                Diamonds = reader.GetInt64("vip_points");
                CanChange = reader.GetInt32("can_change") == 1;
            }
        }

        public void SaveData()
        {
            using (var dbConnection = Program.Server.Database.Connection)
            {
                dbConnection.SetQuery("UPDATE `users` SET `username` = @username, `rank` = @rank, `motto = @motto, `look` = @look, `gender` = @gender, `credits` = @credits, `pixels` = @pixels, `diamonds` = @diamonds, `can_change` = @canChange WHERE `id` = @id");
                dbConnection.AppendParameter("id", Id);
                dbConnection.AppendParameter("username", Username);
                dbConnection.AppendParameter("rank", Rank);
                dbConnection.AppendParameter("motto", Motto);
                dbConnection.AppendParameter("look", Outfit.FigureCode);
                dbConnection.AppendParameter("gender", Gender == PlayerGender.Male ? "M" : "F");
                dbConnection.AppendParameter("credits", Credits);
                dbConnection.AppendParameter("pixels", Pixels);
                dbConnection.AppendParameter("diamonds", Diamonds);
                dbConnection.AppendParameter("canChange", CanChange ? 1 : 0);
                dbConnection.ExecuteNonQuery();
            }
        }
    }
}


texts:
What are your thoughts and comments relating to areas I could improve on?

import csv
import re
import requests
from bs4 import BeautifulSoup

class Resto:
    def __init__(self,url,filename="default"):
        self.page = 1
        url = url + "&page={0}"
        self.url = url
        self.filename = filename

    def info(self):
        linkz = []
        while True:
            content = requests.get(self.url.format(self.page)).content
            soup = BeautifulSoup(content)
            links = [i["href"] for i in soup.find_all("a",{"itemprop":"name"})]
            if not links:
                break
            linkz.extend(links)
            self.page += 1
        return linkz

    def email(self):
        names = []
        emails = []
        sites = []
        streets = []
        cities = []
        numbers = []
        for i in self.info():
            i = "http://www.yellowpages.com" + i
            content2 = requests.get(i).content
            soup2 = BeautifulSoup(content2)
            name = [i.text for i in soup2.find_all("h1",{"itemprop":"name"})]
            email = [re.sub(r'mailto:', "",i["href"]) for i in soup2.find_all("a",{"class":"email-business"})]
            if email:
                email = [email[0]]
            site = [i["href"] for i in soup2.find_all("a",{"class":"custom-link"}) if i.text == "Visit Website"]
            street = [i.text for i in soup2.find_all("p",{"class":"street-address"})]
            city = [i.text for i in soup2.find_all("p",{"class":"city-state"})]
            phone = [i.text for i in soup2.find_all("p",{"class":"phone"})]

            if not email:
                email = ["---"]
            if not site:
                site = ["---"]

            if not street:
                street = ["---"]
            if not city:
                city = ["---"]
            if not phone:
                phone = ["---"]

            names.extend(name)
            emails.extend(email)
            sites.extend(site)
            streets.extend(street)
            cities.extend(city)
            numbers.extend(phone)
        return names,streets,cities,numbers,sites,emails

    def csv(self):
        """saves csv file in root of python 3 directory"""
        items = self.email()
        items = list(zip(*items))
        with open("{0}.csv".format(self.filename), "w")as shops:
            writer = csv.writer(shops)
            writer.writerows(items)

a = Resto("http://www.yellowpages.com/search?search_terms=restaurants&geo_location_terms=tx")
a.csv()


texts: AngularJS expression redundancy in templates

texts:
I sometimes find myself using multiple expressions checking on a single flag to control the state of some template, in this example, a Facebook log in button.

On a second look, however, I noticed this pattern might bear a significant performance drawback for making Angular have to update the DOM in multiple places every time a single flag changes.

Mind you, this is a login-button directive so it's not supposed to alternate too much, it's just the latest use case I have on my hands at the moment. Other components might feature busier templates, both in condition expressions and in live updates to the DOM.

Am I just being paranoid? Or is my concern regarding performance impact here justified? Do you know of a better way to implement this (for example: a single ng-if)?

{{ isUserConnected ? 'Welcome' : 'For points' }}

  <button type="button" class="btn btn-login-fb {{isUserConnected ? 'connected' : ''}}" ng-click="facebookHandler()" unselectable="on">
    {{user.name}}
  </button>


texts:
I have a UITableview with custom cells, every cell has a button called cellButton. When the user taps the button I present an action sheet which has two buttons, buttonOne and buttonTwo. When buttonOne has been tapped I call a method with some values from the actual cell, when buttonTwo I perform a segue and prepareForSegue: method to pass data from the table view cell to another VC. I have a working solution, but I'm not sure that this is the best way because I'm passing the PFUser object from the index path to an instance variable and only use it when the user choose something in the action sheet. I never needed passing values like this, I always used directly the NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];.. way in prepareForSegue:, therefore I'm a bit confused now. Is it a correct way or can it go wrong in any case?

@property (nonatomic, strong) PFUser *userObj;

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    CustomTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"cell"];

    PFUser *user = [self.dataSourceArray objectAtIndex:indexPath.row];
    cell.usernm.text = user.username;
    cell.userId.text = user.objectId;

    cell.cellButton.tag = indexPath.row;
    [cell.cellButton addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)buttonTapped:(id)sender {

    UIButton *button = (UIButton *)sender;
    self.userObj = [self.dataSourceArray objectAtIndex:button.tag];
   [self setupActionSheet];

}

- (void) setupActionSheet {

    AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithTitle:NSLocalizedString(nil, nil)];

    [actionSheet addButtonWithTitle:NSLocalizedString(@"Button 1", nil)
                              image:[UIImage imageNamed:@"1"]
                               type:AHKActionSheetButtonTypeDefault
                            handler:^(AHKActionSheet *as) {

                                [Utilz checkUser:self.userObj.objectId with:self.userObj.username];

                            }];

    [actionSheet addButtonWithTitle:NSLocalizedString(@"Button 2", nil)
                              image:[UIImage imageNamed:@"2"]
                               type:AHKActionSheetButtonTypeDefault
                            handler:^(AHKActionSheet *as) {

                                [self performSegueWithIdentifier:@"presentNextView" sender:self];

                            }];

    [actionSheet show];

}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"presentNextView"]) {
        if ([[segue destinationViewController] isKindOfClass:[ViewControllerTwo class]]) {

            ViewControllerTwo *dataToPass = [segue destinationViewController];

            dataToPass.usrStr = self.usrObj.username;
            dataToPass.objStr = self.usrObj.objectId;

        }
    }
}


texts: Wrap a js function with a fixed this arg

texts:
If I use node.addEventListener('click',Wyg.Editor.nodeClickedEvent); then when node is clicked, nodeClickedEvent has this===node. Since nodeClickedEvent is a static function in a class, I want this to === Wyg.Editor, so I wrote a helper function to simplify it.

Helper Function:

function fixThisFunc(object,functionName){
    const fixedFunc = function(){
        object[functionName].apply(object,arguments);
    };
    return fixedFunc;
}

How it's used:

let node = document.getElementById('myFavoriteNode');
node.addEventListener('click', fixThisFunc(Wyg.Editor,'nodeClickedEvent'));

How it looked before:

node.addEventListener('click',
    function(event){
        Wyg.Editor.nodeClickedEvent(event);
    }
);

The Wyg.Editor class is like:

Wyg.Editor = class {

    static nodeClickedEvent(event){
        const clickedNode = event.target;
        console.log(this); //successfully outputs the Wyg.Editor object/class
        this.getEditableNode(clickedNode);
    }
//there are more functions, of course
};

I'm looking for a review of the Helper Function fixThisFunc

Are there any particular problems I should be worried about? is there a better way to achieve this functionality?


texts: Java converter from Arabic to Roman Numerals

texts:
I am learning Java and would like to get feedback on the code I wrote.

I have written an implementation of an algorithm (found here) for converting any decimal Arabic number to Roman numeral string. My concerns are:

The code seems too long for some methods.
It is not clear what is going on in the class (unless you already know what the algorithm is doing).
Correct use of OOP
Tight coupling of methods
Are there Java 8 features that I should be using but not using.

I am looking for your input, advice and feedback so that I can get better at writing clean and maintainable code.

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

import static java.util.stream.Collectors.joining;

public class RomanNumeralsConverter {

  private final Map<Integer, String> BASE_VALUES_MAP =
    new HashMap<Integer, String>() {{
      put (1, "I");
      put (4, "IV");
      put (5, "V");
      put (9, "IX");
      put (10, "X");
      put (40, "XL");
      put (50, "L");
      put (90, "XC");
      put (100, "C");
      put (400, "CD");
      put (500, "D");
      put (900, "CM");
      put (1000, "M");
    }};

  private StringBuilder romanNumeralString;

  public RomanNumeralsConverter () {
    this.romanNumeralString = new StringBuilder();
  }

  public String convert (int arabicNumberToConvert) {
    return romanNumeral(arabicNumberToConvert);
  }

  private String romanNumeral(int arabicNumberToConvert) {
    int nearestBaseValue = findNearestBaseValue(arabicNumberToConvert);
    int numberOfBasesInTheArabicNumber = arabicNumberToConvert / nearestBaseValue;
    int numberRemainingAfterLargestBaseHasBeenDeducted =
      arabicNumberToConvert % nearestBaseValue;

    this.romanNumeralString = buildRomanNumeralString (nearestBaseValue,
      numberOfBasesInTheArabicNumber);
    return numberRemainingAfterLargestBaseHasBeenDeducted != 0 ?
      convert (numberRemainingAfterLargestBaseHasBeenDeducted) :
      this.romanNumeralString.toString();
  }

  private StringBuilder buildRomanNumeralString(int nearestBaseValue,
                                         int numberOfBasesInTheArabicNumber) {
    this.romanNumeralString.append(repeatBaseValue(nearestBaseValue,
      numberOfBasesInTheArabicNumber));
    return this.romanNumeralString;
  }

  private String repeatBaseValue (int nearestBaseValue,
                                  int numberOfBasesInTheArabicNumber) {
    return Stream.generate(() -> BASE_VALUES_MAP.get(nearestBaseValue))
      .limit(numberOfBasesInTheArabicNumber)
      .collect(joining());
  }

  private int findNearestBaseValue(int arabicNumberToConvert) {
    int nearestBaseValue = 0;
    int minimumDifference = Integer.MAX_VALUE;
    if (BASE_VALUES_MAP.get (arabicNumberToConvert) != null) {
      nearestBaseValue = arabicNumberToConvert;
    } else {
      for (Integer key : BASE_VALUES_MAP.keySet ()) {
        int differenceBetweenBaseValueMapKeyAndArabicNumber = (arabicNumberToConvert - key);
        if (differenceBetweenBaseValueMapKeyAndArabicNumber < minimumDifference
          && differenceBetweenBaseValueMapKeyAndArabicNumber > 0) {
          nearestBaseValue = key;
          minimumDifference = differenceBetweenBaseValueMapKeyAndArabicNumber;
        }
      }
    }
    return nearestBaseValue;
  }
}


texts: Matrix of checkboxes - only 1 allowed in a row

texts:
Task
Create a matrix of checkboxes. The user must be able to select only 1 checkbox in a row or unselect all of them.

Solution
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
    <script type="text/javascript">
      function switch_checkbox(id_selected, id_pair)
      {
           //if the current checkbox is checked - uncheck the 2-nd checkbox in this row
          if(document.getElementById(id_selected).checked == true)
          {
              document.getElementById(id_pair).checked = false;
          }
      }
    </script>
  </head>
  <body>
    <form method="post" id="" action="send.php">
      <input type="checkbox" name="group1[]" id="1-1" value="1-1" onChange="switch_checkbox('1-1', '1-2');"/>
      <input type="checkbox" name="group2[]" id="1-2" value="1-2" onChange="switch_checkbox('1-2', '1-1');"/>
      <br />
      <input type="checkbox" name="group1[]" id="2-1" value="2-1" onChange="switch_checkbox('2-1', '2-2');"/>
      <input type="checkbox" name="group2[]" id="2-2" value="2-2" onChange="switch_checkbox('2-2', '2-1');"/>
    </form>
  </body>
</html>

As you see, the solution is very primitive. Is it possible to make it even simpler?


texts:
Task to be accomplished:

Write a function that takes two strings s and p as arguments and returns a boolean denoting whether s matches p.

p is a sequence of any number of the following:

a-z - which stands for itself
. - which matches any character
* - which matches 0 or more occurrences of the previous single character

Code:

#include <iostream>
using namespace std;

bool eval(string s, string p) {
    int j = 0;
    for(int i = 0; i < p.length(); i++) {
        // is next character is wildcard
        if((int)p[i+1] == 42)
        {
            // is it preceded by a dot
            if((int)p[i] == 46)
            {
                char charToMatch = s[j];

                // keep moving forward in string until the repetition of the 'any character' is over
                while(s[j] == charToMatch) j++;
            }
            // it's preceded by a-z
            else
            {
                // keep moving forward in string until repetition of the letter is over
                while(s[j] == p[i]) j++;
            }
        }
        // is current character a dot
        else if((int)p[i] == 46)
        {
            // move forward in string as it'll match no matter what
            j++;
        }
        // it's not '.' || '*'
        else
        {
            // is it a-z
            if((int)p[i] >= 97 && (int)p[i] <= 122) {

                // if current character in string != character mentioned in pattern
                if(s[j] != p[i])
                {
                    // pattern doesnt match
                    return false;
                }
                else
                {
                    // it matches, move forward
                    j++;
                }
            }
        }
    }

    // if pattern is ended but string is still left. pattern didnt match the whole string.
    if(j < s.length()) return false;
    // gone through whole string, pattern also finished. pattern matches.
    else return true;
}

int main() {
    cout << eval("a", "b.*"); // false
}

Constraints: Pattern is always valid and non-empty.

I have just started to learn about time complexity of algos and I believe its complexity should be \$\mathcal{O}(nm)\$ where \$n\$ and \$m\$ are the lengths of  p and the s respectively.

If it's not please correct me. Along with that, what improvements and optimizations could be made to lower the complexity?


texts: Converting [UInt32] -> [UInt8] -> [[UInt8]]

texts:
I am trying to speed up my current implementation of a function that converts [UInt32] to a [UInt8] which in turn is split up into [[UInt8]] with 6 arrays at each index.

extension Array {
    func splitBy(subSize: Int) -> [[Element]] {
        return 0.stride(to: self.count, by: subSize).map { startIndex in
        let endIndex = startIndex.advancedBy(subSize, limit: self.count)
        return Array(self[startIndex ..< endIndex])
    }
  }
}

func convertWordToBytes(fullW : [UInt32]) -> [[UInt8]] {
    var combined8 = [UInt8]()

    //Convert 17 [UInt32] to 68 [UInt8]
    for i in 0...16{
        _ = 24.stride(through: 0, by: -8).map {
            combined8.append(UInt8(truncatingBitPattern: fullW[i] >> UInt32($0)))
        }
    }

    //Split [UInt8] to [[UInt8]] with 6 values at each index.
    let combined48 = combined8.splitBy(6)

    return combined48
}

This function will be iterated millions of times in my program and its speed is a huge burden. Does anyone have any ideas?


texts:
I have developed a TCP listener to receive messages from a client machine, take that string and put it in a db, then send back a response with some data relating to that string. First attempt at a tcp network stream send and reply, just need to see if this will result in any easily avoidable "hiccups" or incorrect data being returned.

private void ReceivePortMessages()
{
    try
    {
        _TcpListener.Start();
        Debug.Print(" >> Server Started");
        _TcpClient = _TcpListener.AcceptTcpClient();
        Debug.Print(" >> Accept connection from client");
        Boolean isProcessing = true;
        using (NetworkStream networkStream = _TcpClient.GetStream())
        {
            while (isProcessing)
            {
                try
                {
                    int receivingBufferSize = (int)_TcpClient.ReceiveBufferSize;
                    byte[] bytesFrom = new byte[receivingBufferSize];
                    networkStream.Read(bytesFrom, 0, receivingBufferSize);
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));
                    if (dataFromClient != string.Empty)
                    {
                        XmlDocument xm = new XmlDocument();
                        xm.LoadXml(string.Format("<root>{0}</root>", dataFromClient));
                        XmlElement root = xm.DocumentElement;
                        string rootName = root.FirstChild.Name;
                        // Data is sent to be processed and sent back.
                        RouteInboundXML(rootName, dataFromClient, sw);
                    }
                }
                catch (ArgumentOutOfRangeException ex)
                {
                    Debug.Print("ReceivePortMessages: Remote client disconnected. " + ex.ToString());
                    _TcpClient.Close();
                    _TcpListener.Stop();
                    ErrorLog.Write("MotionIndustriesXmlProcessing", ex.ToString(), "ReceivePortMessages()");
                    return;
                }
                catch (Exception ex)
                {
                    Debug.Print("ReceivePortMessages: " + ex.ToString());
                    _TcpClient.Close();
                    _TcpListener.Stop();
                    ErrorLog.Write("MotionIndustriesXmlProcessing", ex.ToString(), "ReceivePortMessages()");
                    return;
                }
            }
            Debug.Print(" >> exit");
            isProcessing = false;
        }
    }
    catch (Exception ex)
    {
        Debug.Print("ReceivePortMessages: " + ex.ToString());
        ErrorLog.Write("MotionIndustriesXmlProcessing", ex.ToString(), "ReceivePortMessages()");
    }
    ReceivePortMessages();
}

private void RouteInboundXML(string requestType, string requestXML, Stopwatch sw)
{
    //
    // A bunch of other operations happen and then they call the SendReply() method.
    //
    SendReply();
}

private void SendReply(string reply)
{
    try
    {
        using (NetworkStream networkStream = _TcpClient.GetStream())
        {
            string serverResponse = reply;
            Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
            networkStream.Write(sendBytes, 0, sendBytes.Length);
            networkStream.Flush();
            Debug.Print(" >> " + serverResponse);
        }
    }
    catch (ArgumentOutOfRangeException ex)
    {
        Debug.Print("SendReply: Remote client disconnected. " + ex.ToString());
        _TcpClient.Close();
        _TcpListener.Stop();
        return;
    }
}


texts:
I'm not a beginner programmer as I have experience in Node and Ruby, but I'm a beginner when it comes to C++. And as C++ is quite different from these two, I figured I could use any tips, tricks, hints and pointers (hah!) to learn how to actually write C++ and to get the most out of the language. I feel a bit like I'm trying to write JS but in C++ syntax.

To get me started I've written a Bulls and cows game which works as I intended it to, but like I said above, I need help in improving the code generally as well as actually utilizing the built in C++ methods.

I'm wondering if it's worthwhile to write a separate function for say the random number generation, or would that be a waste of memory?

I've also seen that many in the C++ community seem to favour comments instead of descriptive variable/function names.
Example:

int a = 3.14159265359; // pi with 11 decimal numbers

instead of:

int pi_eleven_decimals = 3.14159265359;

Is that merely a question of taste or is it simply how it's done in C++?

The bulls and cows game code:

#include "pch.h"
#include <iostream>
#include <time.h>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main() {
    int bull;
    int cow;
    int find_count;
    int value1;
    int value2;
    int value3;
    int value4;
    int calculate_cows;
    string secret_number = "";
    string guess = "";
    bool run_game = true;
    char again;
    bool win;
    cout << "Welcome to the Bulls and Cows game!" << endl;
    while (run_game == true) {
        bull = 0;
        cow = 0;
        find_count = 0;
        calculate_cows = 0;
        //random number generation begin
        srand(time(NULL));
        value1 = rand() % 10;
        value2 = rand() % 10;
        value3 = rand() % 10;
        value4 = rand() % 10;
        // random number generation stop
        stringstream ss;
        ss << value1 << value2 << value3 << value4;
        secret_number = ss.str();
        win = false;
        while (win == false) {
            cout << "Make a guess: (XXXX)" << endl;
            cin >> guess;

            for (int i = 0; i < secret_number.length(); i++) {
                if (guess.at(i) == secret_number.at(i)) {
                    bull++;
                }
            }

            for (int i = 0; i < guess.length(); i++) {
                int secret = secret_number.at(i);
                if (guess.find(secret)) {
                    find_count++;
                }
            }

            calculate_cows = find_count - bull;
            cow = (calculate_cows < 0) ? 0 : calculate_cows;

            cout << "Bulls: " << bull << endl << "Cows: " << cow << endl;
            if (bull == 4) {
                cout << "You win!" << endl;
                win = true;
            }
            else {
                bull = 0;
                cow = 0;
                find_count = 0;
            }
        }
        cout << "Play again? (y/n)" << endl;
        cin >> again;
        run_game = (again == 'y') ? true : false;
    }
    cout << "Thanks for playing! :)" << endl;
    return 0;
}


texts:
Basically, I have a list, newtry of blocks, and I want to find a value of catchtype that makes them all return true for block.isCatchExtendable(newhandler, catchtype) or report an error if this can't be done. block.isCatchExtendable returns two values, success and a new type to try on failure.

My current code works, but the control flow is very convoluted, with numerous breaks and elses. I was wondering if anyone could think of a better way to arrange things. Also, these are all my own functions, so I am free to change the interfaces, etc.

while 1:
    ct_changed = False

    for block in newtry:
        success, newcatchtype = block.isCatchExtendable(newhandler, catchtype)
        if not success:
            if catchtype == newcatchtype: #no success and no other types to try, so just break and fail
                break
            catchtype, ct_changed = newcatchtype, True
    else:
        if ct_changed:
            continue
        else:
            break
    error('Unable to extend try block completely')

isCatchExtendible:

def isCatchExtendable(self, newhandler, catchtype):
    return self.catchset.extendible(newhandler, catchtype, self.currentHandlers)

This then calls:

#If not extendible with current catchtype, returns suggested type as second arg
def extendible(self, newhandler, catchtype, outerhs):
    if catchtype is None:
        temp = self.catchsets.get(newhandler)
        if temp is None:
            return True, None
        return False, temp.getSingleTType()[0]

    proposed = ExceptionSet.fromTops(self.env, catchtype)
    inner = [h for h in self.handlers if h != newhandler and h not in outerhs]
    outer = [h for h in self.handlers if h in outerhs]

    sofar = ExceptionSet.fromTops(self.env)
    for h in inner:
        sofar = sofar | self.catchsets[h]
    if (proposed - sofar) != self.catchsets[newhandler]:

        #Get a suggsted catch type to try instead
        suggested = (self.catchsets[newhandler] | sofar).getSingleTType()
        suggested = objtypes.commonSupertype(self.env, suggested, (catchtype, 0))
        assert(self.env.isSubClass(suggested[0], 'java/lang/Throwable'))
        return False, suggested[0]
    for h in outer:
        if not proposed.isdisjoint(self.catchsets[h]):
            return False, catchtype
    return True, catchtype


texts: A simple error messaging and logging system via macro(s) in C++

texts:
I'm just trying to build a quick and crude error messaging system. It currently looks like this:
#include <exception>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <map>

enum MsgTy {
    OK = 0,
    WARNING,
    ERROR,
    CRITICAL,
};

class FileWriter {
    std::string filename_;
    std::ostringstream msg_;
public:
    FileWriter(const std::string& filename, std::ostringstream& msg)
      : filename_{ filename } {
        operator()(msg);
    }

    void operator()(std::ostringstream& msg) {
        std::ofstream out("log.txt", std::ios::app);
        out << msg.str();
    }
};

static std::map<MsgTy, std::string> msg_id{
    {MsgTy::OK, {"OK: "}},
    {MsgTy::WARNING, {"WARNING: "}},
    {MsgTy::ERROR, {"ERROR: "}},
    {MsgTy::CRITICAL, {"CRITICAL: "}}
};

#define messaging(MsgTy, msg, log2file) do { \
    std::ostringstream strm; \
    if ((MsgTy) == OK) { \
        strm << msg_id[(MsgTy)] << (msg) << '\n'; \
        std::cout << strm.str(); \
        if((log2file) == true) \
            FileWriter fw("log.txt", strm); \
    } \
    if ((MsgTy) == WARNING) { \
        strm << msg_id[(MsgTy)] << (msg) << '\n'; \
        std::cout << strm.str(); \
        if((log2file) == true) \
            FileWriter fw("log.txt", strm);\
    } \
    if ((MsgTy) == ERROR) { \
        strm << msg_id[(MsgTy)] << (msg) << '\n'; \
        std::cerr << strm.str(); \
        if((log2file) == true) \
            FileWriter fw("log.txt", strm); \
        throw strm.str(); \
    } \
    if ((MsgTy) == CRITICAL) { \
        strm << msg_id[(MsgTy)] << (msg) << '\n'; \
        std::cerr << strm.str(); \
        if((log2file) == true) \
            FileWriter fw("log.txt", strm); \
        throw strm.str(); \
    } \
} while(0)

int main() {
    try {
        messaging(MsgTy::OK, "Everything is good!", true);
        messaging(MsgTy::WARNING, "Something isn't quite right!", false);
        messaging(MsgTy::ERROR, "Something went wrong!", true);
        messaging(MsgTy::CRITICAL, "Something horribly went wrong!", true);
    }
    catch (const std::exception& e) {
        std::cerr << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

I'm using a combination of several techniques... I'm using a class as a functor object for writing to basic text files, currently, it will only append to the file if it already exists or tries to create one. The file writer will only be invoked if the condition flag is true within the messaging system.
I'm using an enumeration and a static map to hold the basic strings for the different types of errors, warnings, or messages that my application or library might use. Then I'm using macro expansion to act as a function. Specific Error Message Types will also throw an exception and halt the program, while others, will just log to the console and let execution continue.
Yes I know I could have just written a function, class, functor, etc. and I know that macros can be tricky to get correct and are harder to debug, but this was also an exercise to refresh my skills at writing good solid macros.
What I would like to know:

Are there any apparent issues with how I implemented the macro?
Can there be any improvements made to it?
Is the intent clear on its usage?
I'm also interested in any other feedback.

Note -This is not production code: it's for a personal project, however, I would still like it to be critiqued as if it were to be production code!-


texts:
I have a piece of code that has to deal with some nested promises and shared variables between them. This code is complicated by itself and because of promises syntax is even more difficult to read for those that haven't written it.

The code right now is something like this:

const _deleteOneToOneRooms = function(userId, teamMembers) {
  return function() {
    return User.findOne({ _id: userId })
    .then((userDeleted) => {
      return Promise.all(teamMembers.map((member) => {
        return User.findOne({ _id: member }).then((user) => {
          return {
            id: user._id,
            commonTeams: Utils.arrayIntersect(user.teams, userDeleted.teams).length !== 0
          };
        });
      }))
      .then((usersNoCommonTeam) => {
        return Promise.all(usersNoCommonTeam.map((user) => {
          if(user.commonTeams) {
            return Promise.resolve();
          }
          return Room.findOneAndRemove(
            {
              $and: [
                { type: 'one-to-one' },
                { owners: { $all: [user.id, userDeleted] } }
              ]
            });
        }));
      });
    })
    .then((roomsToDelete) => {
      return Promise.all(roomsToDelete.map((room) => {
        if(room) {
          return Membership.remove({ room: room._id });
        }
        return Promise.resolve();
      }));
    });
  };
};

someDatabaseLookups.then(_deleteOneToOneRooms(userId, teamMembers))

I have considered to split each then into functions so the overall code is simpler to read:

const _deleteOneToOneRooms = function(userId, teamMembers) {
  return function() {
     return User.findOne({ _id: userId })
     .then((deletedUser) => {
       return _getUsersWithNoCommonTeams(deletedUser, teamMembers);
     })
     .then((usersNoCommonTeam) => {
       return _getOneToOneRooms(userId, usersNoCommonTeam);
     })
     .then(_removeRooms);
  };
};

But I don't like having one-line functions only to give them names and at the end if you are reading the code for the first time, you will have to scroll up and down to know what is being done, which from my point of view makes it harder to understand.

So my question is, is there a convention on how to write the cleanest code when dealing with complicated nested promises that use shared variables?


texts: Ruby: possible Poker holds for a hand of length n

texts:
Hello everyone and thanks in advance for taking the time to read my post!!
In the process of learning Ruby, I'm writing a video poker machine that analyzes hands represented by arrays of Cards, like so: [ card, card, card, card, card ]
You may know that in draw poker, one can hold certain cards and toss the rest to the dealer, to be replaced by drawing new cards from the deck in the hopes of improving one's hand (hence the name). It's natural to figure that holds would be represented by an array of boolean values. To wit: [ true, true, false, false, false ] would mean holding the first two cards in a five-card hand and discarding the rest. What I'm trying to write is a method that will give me an array of all possible holds (an array of arrays) for a given hand size.
I've found that Ruby is terrific (though a bit slow) for permutations and combinations, i.e., all possible unique hands from a 52-card deck. All I have to do for that is call deck.combination( hand_size ).to_a. But unfortunately neither .permutation nor .combination is really giving me what I need for a method to produce possible holds.
High school math (which I'm terrible at, by the way) tells me that when determining possible unique n-combinations of two possible values, the size of the universe of all possible n-combinations will be two to the power of n - meaning there are 32 possible holds for a five-card poker hand.
After slaughtering a snow-white bull for the gods at midnight under a full moon, I've come up with the following solution using binary numbers. This method loops through a range from 0...2 ** hand_size, turns each element of the range into a binary number string with a hand_size number of leading zeroes using .rjust, then .maps each character in the string to an array of hand_size elements using a conditional and ternary; if the character is "1" it maps a true to the array, otherwise the character is a "0" and it maps false to the array.
def possible_holds( hand_size )
   result = []
   for each_hold in 0...2 ** hand_size do
      as_binary = each_hold.to_s( 2 ).rjust( hand_size, "0" )
      result << ( 0...hand_size ).to_a.map{ | card | as_binary[ card ] == "1" ? true : false }
   end
   result
end

This clunky little method actually works very well, but... it just doesn't seem very rubinic. I would love to hear clever suggestions as to how to improve it. I have this nagging feeling that this can all be done with a neat, simple method/enumerable or two... but no matter how many virgins I sacrifice I just can't seem to come up with anything better.
Thanks in advance for your help and happy coding!!


texts: Thread-safe Phoenix Singleton class template with Boost

texts:
I've implemented the phoenix-singleton as a class template with boost inspired by Modern C++ Design. The code compiles fine with MSVC 2013 - and it seems to work, but I'm new
to multi-threaded programming and Boost. Are there any pitfalls in the code? Improvements?

TSingleton.h

#ifndef TSINGLETON_H
#define TSINGLETON_H

#include <cstdlib>
#include <boost/atomic.hpp>
#include <boost/thread/mutex.hpp>

template<typename T>
class TSingleton{
public:
    static T& getInstance();

protected:
    inline explicit TSingleton();
    TSingleton(const TSingleton&);
    TSingleton& operator=(const TSingleton&);
    virtual ~TSingleton();
    static void _CreateInstance();
    static void _Phoenix();
    static void _KillPhoenix();

    static boost::atomic<T*> _instance;
    static boost::atomic<bool> _destroyed;
    static boost::mutex _instantiation_mutex;
};

template<typename T>
boost::atomic<bool> TSingleton<T>::_destroyed = (boost::atomic<bool>) false;

template<typename T>
boost::atomic<T*> TSingleton<T>::_instance = (boost::atomic<T*>) nullptr;

template<typename T>
boost::mutex TSingleton<T>::_instantiation_mutex;

template<typename T>
TSingleton<T>::~TSingleton(){
    TSingleton::_destroyed = true;
    TSingleton::_instance = nullptr;
}

template<typename T>
T& TSingleton<T>::getInstance(){
    T* tmp = TSingleton::_instance.load(boost::memory_order_consume);
    if (!tmp){
        boost::mutex::scoped_lock guard(TSingleton::_instantiation_mutex);
        tmp = TSingleton::_instance.load(boost::memory_order_consume);
        if (!tmp){
            if (TSingleton::_destroyed){
                TSingleton::_Phoenix();
            }else{
                TSingleton::_CreateInstance();
            }
            tmp = TSingleton::_instance.load(boost::memory_order_consume);
        }
    }
    return *tmp;
}

template<typename T>
void TSingleton<T>::_CreateInstance(){
    static T instance;
    TSingleton::_instance.store(&instance, boost::memory_order_release);
}

template<typename T>
void TSingleton<T>::_Phoenix(){
    TSingleton::_CreateInstance();
    new(TSingleton::_instance) T;
    std::atexit(TSingleton::_KillPhoenix);
    TSingleton::_destroyed = false;
}

template<typename T>
void TSingleton<T>::_KillPhoenix(){
    T* tmp = TSingleton::_instance.load(boost::memory_order_consume);
    tmp->~T();
    TSingleton::_destroyed = true;
    TSingleton::_instance = nullptr;
}

#endif // TSINGLETON_H

Simple usage example:

#include <iostream>
#include "TSingleton.h"

class Foo{
public:
    void bar(){ std::cout << "bar" << std::endl; }
};

int main(int argc, char **argv){
    Foo& myfoo = TSingleton<Foo>::getInstance();
    myfoo.bar();
    return 0;
}


texts: String formatting for uint64_t that represents a fixed-point decimal

texts:
My goal is to take a uint64_t that represents a fixed-point decimal, and output a string representation of the decimal. The fixed-point representation always has eight decimal places, so for example 1.12345678 is represented as 112345678.

How can I make the following code cleaner and/or faster? Obviously all the character insertions/deletions are very slow, but what's the best way to get rid of those?

std::string uint64_to_string(uint64_t n) {
  auto retval = std::to_string(n);  // Initial conversion to string

  if(retval.size() <= 8) {
    // Add leading zeros if necessary, so for example n=1 becomes 000000001
    size_t num_leading_zeros = 9 - retval.size();
    retval.insert(0, num_leading_zeros, '0');
  }

  // Insert decimal, so 000000001 becomes 0.00000001
  retval.insert(retval.size() - 8, 1, '.');

  // Trim trailing zeros, and trim '.' if it is the last character
  boost::trim_right_if(retval, [](char c) { return (c == '0' || c == '.'); });
  return retval;
}


texts:
I have two scripts written by my co-workers for auto-filling a form with information from the Facebook graph-api. I am trying to figure out which has been coded in a more efficient style?

This is the first one. http://jsfiddle.net/TcGGZ/30/

$('#account_get').click(function(){
    $.getJSON('http://graph.facebook.com/'+$('#facebook').val(), function(fd) {
        $('#id').val(fd.id);
        $('#name').val(fd.name);
        $('#first_name').val(fd.first_name);
        $('#last_name').val(fd.last_name);
        $('#link').val(fd.link);
        $('#username').val(fd.username);
        $('#gender').val(fd.gender);
        $('#locale').val(fd.locale);
    });
});

This is the second one I am trying to decide about. http://jsfiddle.net/VuY2b/46/

var facebook_account = '';

function fillForm() {
    facebook_account = $('#facebook').val();

    $.getJSON('http://graph.facebook.com/' + facebook_account, function(data) {
        var facebook_data = data;
        console.log(facebook_data);
        var inputs = $('form > input');
        for (var key in facebook_data) {
            for (var l = 0; l < inputs.length; l++) {
                if (inputs[l].getAttribute('name') === key) {
                    inputs[l].value = facebook_data[key];
                }
            }
        }
    });

}

var x = document.getElementById('account_get');
x.addEventListener("click", fillForm, false);


texts: Solving Project Euler problem #48 in Scala

texts:
I'm trying to learn some Scala and decided to try to tackle some Project Euler problems.

For problem #48, coming from a Python background, my solution is the following one-liner:

print ( (1 to 1000).map(i => BigInt(i).pow(i)).sum % BigInt(10).pow(10) )

Is this idiomatic? Is there a simpler/more readable solution?


texts: W3 automatic slideshow converted to React (gatsbyjs)

texts:
The original Javascript slider is on W3 schools. I modified it to work as a slider for my homepage. The goal is to call it into index.js (which works) and use it at the top of the page (which works) and if I want to swap out an image, I could load slideshow.js, add a new static image or remove an old one (also works).
But I bet it isn't really "React ready" as many tutorials have multiple components and GraphQL calls in them.
How can I make this better?
Oh yeah, Gatsby version 3.0.0 and gatsby-starter-default is the base.
import * as React from "react";
import { slideshow_wrapper } from "./slideshow.module.css";
import { StaticImage } from "gatsby-plugin-image";

const SlideShow = () => {
    let myIndex = 0;
    const showNextSlide = () => {
    let i;
    let x = document.getElementsByClassName("mySlides");
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    myIndex++;
    if (myIndex > x.length) {
        myIndex = 1;
    }
    x[myIndex - 1].style.display = "block";
};
React.useEffect(() => {
    showNextSlide()
    const i = setInterval(showNextSlide, 4000);
    return () => clearInterval(i)
}, [])
return (
<div className={slideshow_wrapper}>
    <StaticImage
        src="../../images/slides/home_slider_1.jpg"
        width={1920}
        quality={100}
        formats={["AUTO", "WEBP", "AVIF"]}
        alt="A Gatsby astronaut"
        className="mySlides"
    />
    <StaticImage
        src="../../images/slides/home_slider_2.jpg"
        width={1920}
        quality={100}
        formats={["AUTO", "WEBP", "AVIF"]}
        alt="A Gatsby astronaut"
        className="mySlides"
    />
    </div>
    );
};

export default SlideShow;


texts:
I have a two directories, input and output.
input is a flat directory containing, among others, some .jpg files.
output has
nested subdirectories and contains .jpg files with same names as these in input.
There can be some names in input missing in output.
Names in output can be duplicated in different subdirectories.

An example structure:

$ tree input/
input/
├── a
├── b
├── c
├── d
├── e.jpg
├── f.jpg
├── h
├── i
├── j.jpg
└── z.jpg

0 directories, 10 files
$ tree output
output
├── 1
│   └── 2
│       └── 3
│           └── e.jpg
├── A
│   └── B
│       └── f.jpg
├── O
│   └── j.jpg
└── X
    └── Y
        └── Z
            └── j.jpg

9 directories, 4 files

The task is to overwrite all .jpg files in output directory with these from input based on their names.

Python version:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import collections
import os
import shutil
import sys

def get_paths(root):
    paths = collections.defaultdict(list)
    for path, subdirs, files in os.walk(root):
        for f in files:
            if os.path.splitext(f)[1] == '.jpg':
                paths[os.path.basename(f)].append(os.path.join(path, f))
    return paths

def main():
    if len(sys.argv) != 3:
        msg = 'python {} path/to/input/dir path/to/output/dir'
        print(msg.format(sys.argv[0]))
        sys.exit(1)

    input_dir, output_dir = sys.argv[1], sys.argv[2]
    input_paths, output_paths = get_paths(input_dir), get_paths(output_dir)

    for filename, input_path in input_paths.items():
        for output_path in output_paths.get(filename, []):
            shutil.copy(input_path[0], output_path)

if __name__ == '__main__':
    main()

Usage:

$ cat input/e.jpg input/f.jpg input/j.jpg
e
f
j
$ cat output/1/2/3/e.jpg output/A/B/f.jpg output/X/Y/Z/j.jpg output/O/j.jpg
X
X
X
X
$ python test.py input/ output/
$ cat output/1/2/3/e.jpg output/A/B/f.jpg output/X/Y/Z/j.jpg output/O/j.jpg
e
f
j
j

C++14 version:

#include <map>
#include <list>
#include <iostream>
#include <boost/filesystem.hpp>

auto get_paths(boost::filesystem::path root) {
    std::map<
        const boost::filesystem::path,
        std::list<boost::filesystem::path>
    > paths;

    boost::filesystem::recursive_directory_iterator it(root);
    const boost::filesystem::path jpg(".jpg");
    for(; it != boost::filesystem::recursive_directory_iterator(); ++it) {
        if(boost::filesystem::is_regular_file(*it) && boost::filesystem::extension(*it) == jpg){
            paths[it->path().filename()].push_back(it->path());
        }
    }
    return paths;
}

int main(int argc, char** argv) {
    if(argc != 3) {
        std::cerr << argv[0] << " path/to/input/dir path/to/output/dir" << std::endl;
        return 1;
    }

    boost::filesystem::path input_dir(argv[1]);
    boost::filesystem::path output_dir(argv[2]);

    auto input_paths = get_paths(input_dir);
    auto output_paths = get_paths(output_dir);

    for(auto const& input_pair: input_paths) {
        const auto output_pair = output_paths.find(input_pair.first);
        if(output_pair != output_paths.end()) {
            for(auto const& output_path: output_pair->second) {
                boost::filesystem::copy_file(
                    input_pair.second.front(),
                    output_path,
                    boost::filesystem::copy_option::overwrite_if_exists
                );
            }
        }
    }
}

Usage:

$ cat input/e.jpg input/f.jpg input/j.jpg
e
f
j
$ g++ test.cpp -o test -lboost_system -lboost_filesystem -std=c++14
$ cat output/1/2/3/e.jpg output/A/B/f.jpg output/X/Y/Z/j.jpg output/O/j.jpg
X
X
X
X
$ ./test input/ output/
$ cat output/1/2/3/e.jpg output/A/B/f.jpg output/X/Y/Z/j.jpg output/O/j.jpg
e
f
j
j


texts:
I have a valid code in C-style
int arr[10][10] = {0}; // all elements of array are 0

What is the optimal way to do the same for C++ style array?
My idea is
#include <array>

std::array<std::array<int, 10>, 10> arr = {0}; // is it correct?


texts:
I have a method to upload a file using the Net::SFTP gem:

class Uploader

 def initialize(host,user,password)
   @host = host
   @user = user
   @password = password
 end

 def upload(local_file_path,remote_file_path)
  Net::SFTP.start(@host,@user,:password => @password) do |sftp|
   sftp.upload!(local_file_path,remote_file_path) do |event,uploader,*args|
     case event
     when :open
       Rails.logger("Starting upload...")
     when :finished
       Rails.logger("Finishing upload...")
     end
   end
  end
 end
end

The upload method seems rather large to me. Any suggestions on how I could split it up into smaller components?


texts: Strategy for avoiding threadpool starvation while performing cpu bound jobs in a queued fashion

texts:
My aim is to avoid using threadpool threads for CPU bound work, thus avoiding a situation where IIS stops responding to new requests.

Can you see any problems with the code below? Is this a safe/clean approach? Can you offer any improvements?

    private static ConcurrentQueue<Job> Jobs = new ConcurrentQueue<Job>();
    static int threadCount = 0;

    private void QueueJob(Job job)
    {

        bool startQueue=false;

        lock(Jobs)
        {
            if (threadCount == 0)
            {
                Interlocked.Increment(ref threadCount);
                startQueue = true;
            }
        }

        Jobs.Enqueue(job);

        if (startQueue)
        {
           var t= new Thread(new ThreadStart(ConsumeQueue));
           t.Start();
        }

    }
    private void ConsumeQueue()
    {
        while (true)
        {
            lock (Jobs)
            {
                if (!Jobs.Any())
                {
                    Interlocked.Decrement(ref threadCount);
                    return;
                }
            }

            Job j;

            var jobToDo = Jobs.TryDequeue(out j);

            if (jobToDo)
            {
                DoCPUBoundWork(j);
            }
        }

    }


texts:
This just adds fractions. For example, if we have a text file with:

1/3
1/2

It will print:

5/6

I would love to hear some remarks on how I can make this more Scala-like.

class Fraction(c: BigInt, d: BigInt) {
  val divisor = c.gcd(d);
  def counter = c / divisor;
  def denominator = d / divisor;

  def lcm(a: BigInt, b: BigInt):BigInt = (a * b).abs / a.gcd(b)

  def + (f: Fraction): Fraction = {
    val lcmVal = lcm(f.denominator, denominator)
    val apply = (count: BigInt, div: BigInt) => lcmVal / div * count
    new Fraction(
      apply(f.counter, f.denominator)
        + apply(counter, denominator)
      , lcmVal)
  }

  override def toString(): String = {
    return String.format("%s / %s", counter, denominator)
  }
}

object AddingFractions {

  def sumFractions(fractions: Array[Fraction]): Fraction = {
    val sum = fractions(0) + fractions(1)
    if (fractions.length > 2) {
      return sumFractions(sum +: fractions.slice(2, fractions.length))
    }
    sum
  }

  def main(args: Array[String]): Unit = {
    val lines = scala.io.Source.fromFile(args(0)).getLines()
    val linesArray = lines.toArray

    val fractions = linesArray
      .map((s: String) => s.split("/"))
      .map((ar: Array[String]) => Array(Integer.parseInt(ar(0)), Integer.parseInt(ar(1))))
      .map((iar: Array[Int]) => new Fraction(iar(0), iar(1)))

    println(sumFractions(fractions))
  }
}


texts:
I was asked the following question:

  Given a data stream input of non-negative integers a1, a2, ..., an,
  ..., summarize the numbers seen so far as a list of disjoint
  intervals.

  For example, suppose the integers from the data stream are 1, 3, 7, 2,
  6, ..., then the summary will be:

[1, 1]
[1, 1], [3, 3]
[1, 1], [3, 3], [7, 7]
[1, 3], [7, 7]
[1, 3], [6, 7]

My approach to this problem was to keep adding the numbers to a structure such as a TreeSet which will help with the in-order iteration. While iterating I can check whether the values are consecutive and if they are, I add them to the existing interval, otherwise I create a new interval. Here's the code I have to accomplish it:

public class SummaryRanges {
    private TreeSet<Integer> streamNums;
    /** Initialize your data structure here. */
    public SummaryRanges() {
        streamNums= new TreeSet<Integer>();
    }

    public void addNum(int val) {
        if(!streamNums.contains(val)) {
            streamNums.add(val);
        }
    }

    public List<Interval> getIntervals() {
        ArrayList<Interval> buffer = new ArrayList<Interval>();
        if(!streamNums.isEmpty()) {
            int start = streamNums.first();
            int end = start;
            Iterator<Integer> streamIter = streamNums.iterator();
            if(streamIter.hasNext()) streamIter.next();
            while(streamIter.hasNext()) {
                int i = streamIter.next();
                if(i == end + 1) {
                    end = i;
                } else {
                    buffer.add(new Interval(start,end));
                    start = i;
                    end = i;
                }
            }
          buffer.add(new Interval(start,end));
        }
        return buffer;
    }
}

It will be great to get some pointers on how to do this better.


texts: LeetCode: Delete Nodes And Return Forest C#

texts:
https://leetcode.com/problems/delete-nodes-and-return-forest/

Given the root of a binary tree, each node in the tree has a distinct value.

After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).

Return the roots of the trees in the remaining forest.  You may return the result in any order.

  Input: root = [1,2,3,4,5,6,7], to_delete = [3,5] Output:
  [[1,2,null,4],[6],[7]]

  Constraints:

  The number of nodes in the given tree is at most 1000. Each node has a
  distinct value between 1 and 1000. to_delete.length <= 1000 to_delete
  contains distinct values between 1 and 1000.

Please review for performance and style.

using System.Collections.Generic;
using System.Linq;
using GraphsQuestions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TreeQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/delete-nodes-and-return-forest/
    /// </summary>
    [TestClass]
    public class DeleteNodesAndReturnForestTest
    {
        [TestMethod]
        public void ExampleTest()
        {
            var root = new TreeNode(1);
            root.left = new TreeNode(2);
            root.left.left = new TreeNode(4);
            root.left.right = new TreeNode(5);
            root.right = new TreeNode(3);
            root.right.left = new TreeNode(6);
            root.right.right=new TreeNode(7);
            var deleteNodes=new DeleteNodesAndReturnForest();
            var res = deleteNodes.DelNodes(root, new[] {3, 5});
            Assert.AreEqual(6,res[0].val);
            Assert.AreEqual(7,res[1].val);
            Assert.AreEqual(1,res[2].val);
            Assert.AreEqual(2,res[2].left.val);
            Assert.AreEqual(4,res[2].left.left.val);
            Assert.IsNull(res[2].left.right);

        }
    }

    public class DeleteNodesAndReturnForest
    {
        List<TreeNode> _forest;
        public IList<TreeNode> DelNodes(TreeNode root, int[] to_delete)
        {
            if (root == null || to_delete == null || to_delete.Length == 0)
            {
                return _forest;
            }
            _forest = new List<TreeNode>();
            Helper(root, to_delete);
            if (!to_delete.Contains(root.val))
            {
                _forest.Add(root);
            }
            return _forest;
        }

        private TreeNode Helper(TreeNode root, int[] to_delete)
        {
            if (root == null)
            {
                return null;
            }
            //first do the recursion
            root.left = Helper(root.left, to_delete);
            root.right = Helper(root.right, to_delete);
            //when coming back from recursion(post-order). all the subtrees is already deleted
            //delete root and add to the forest the left and right leaves
            if (to_delete.Contains(root.val))
            {
                if (root.left != null)
                {
                    _forest.Add(root.left);
                }
                if (root.right != null)
                {
                    _forest.Add(root.right);
                }

                return null;
            }

            return root;
        }
    }
}


texts:
I have been trying to get better at functional programming, which includes understanding map/reduce. I wrote a function intended to fill an autocomplete with values. The challenge I was encountering was my Mongo records, which had a category array that needed to be flattened for the autocomplete to work. Being a novice, I somehow came up with this code, and it works. But I know there must be a better way to do it using map/reduce.

You will see cats stores a call that uses .map, but it's the code from the package example and I have no idea what it does.

      categoryTypeAheadVals: function() {
    cats = Todos.find({}, {categories: 1}).fetch().map(function(it){ return it.categories; });
    y = [];
    var x = cats.forEach(function(it) {
      it.forEach(function(it){
        y.push(it);
      });
    });
    return y;
  }

});


texts: Passing an object to the view in CodeIgniter

texts:
I'm trying to use an object and persist it into the data base.

I created a class in the library's folder.

<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Solicitud {

    private $categoria;
    private $consecutivo;
    private $id;
    private $mensaje;
    private $solicitante;

    function __construct(){
        $this->categoria = 1;
        $this->consecutivo = 1;
        $this->mensaje = "Mensaje por defecto";
    }

    public function escalarSolicitud( User $actual, User $nuevo){
        $this->setSolicitante($nuevo);
    }

    # Getters and Setters

    public function setCategoria( $categoria ){
        $this->categoria = $categoria;
    }

    public function getCategoria(){
        return $this->categoria;
    }

Here is the Controller:

<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');

class Administrador extends Ci_Controller {

    function __construct(){
        parent::__construct();
    }

    public function crearSolicitud(){

        $session_data = $this->session->userdata('session_user');
        $usuario      = $session_data['usuario'];
        $categoria    = $this->input->post('category');
        $mensaje      = $this->input->post('description');

        $solicitud = new solicitud;

        $solicitud->setSolicitante($user);
        $solicitud->setCategoria($categoria);
        $solicitud->setMensaje($mensaje);

        $this->helpdesk_model->createSupport( $solicitud );
    }

And in the Model how can I use the object properties:

public function createSupport( $soporte ){

    $this->db->trans_start();

        $data = array(
            'id' => null,
            'id_user' => $soporte[usuario], ???
            'id_category' => $soporte[categoria], ???
            'message' => $soporte[mensaje] ???
        );

        $this->db->insert('supports', $data);

    $this->db->trans_complete();

    return $this->db->trans_status();

}

I need to know if I'm in the right direction or if the use of the 'Solicitud' class is not necessary.  If I'm right, how should I call in the model the object attributes?


texts: Project Euler Problem #50 Consecutive Prime Sums

texts:
Problem: Which prime, below one-million, can be written as the sum of the most consecutive primes?

At the moment my code runs for over 200 seconds and was wondering how I can find a way to bring that down by a large amount. I have tried optimising it as much as I can and added an extra if statement, if(subSum < 1000000): to reduce the need to see if subSum is a prime. Here is my code at the moment:

def sieve(num):
    primes = []
    import math
    for i in range(num):
        primes.append(True)
    j = 1
    while(j<(math.sqrt(num)+1)):
        k = (j+1)*2
        while(k<(num+1)):
            primes[k-1] = False
            k+=(j+1)
        j+=1
    primes[0] = False
    prime = []
    for a in range(num):
        if(primes[a] == True):
            prime.append(a+1)
    return prime

primes = sieve(1000000)
count = 1
high = 0
length = len(primes)
while count <= length:
    i = 0
    while(i<(length-count)):
        sub = primes[i:i+count]
        subSum = sum(sub)
        if(subSum < 1000000):
            if(subSum in primes):
                if(subSum>high):
                    high = subSum
                break
            else:
                i+=1
        else:
            break
    count += 1
print(high)

Thanks for any help.


texts:
This code is supposed to count each character in a given string and account for error handling and type casting as well, and it should do it in the most efficient manner possible, with O(n) being an upper limit for both time and memory. I have gone through my process for problem solving which involves explaining the problem in my own words, looking at the inputs, the outputs, if the answer is even possible given the I/O, and then refactoring my code. Please, if anyone sees a better way to accomplish this then let me know.

function characterCounter(str) {
    // Error Handling
    // No input
    if (!str) {
        return "String input required";
    }

    // attempt to type cast non strings
    if (typeof str !== "string") {
        str = str.toString();
        // input could not be successfully type casted
        if (typeof str !== "string") {
            return "Invalid input";
        }
    }

    const stringLen = str.length;
    const result = {};
    let i = 0;

    // loop through each character for O(n) time complexity and O(n) space complexity
    // since the object grows based on input size
    for (; i < stringLen; i++) {
        // If string not in object as a key then add it and set value to 1
        if (result[str[i]] === undefined && str[i] !== " ") {
            result[str[i].toLowerCase()] = 1;
        } else {
            if (str[i] !== " ") {
                // add one to value at current key
                result[str[i]]++;
            }
        }
    }
    return result;
}

// Returns an object which allows O(1) for insert, deletion, access, and O(n) for searching...
console.log(characterCounter("Hello, World!"));


texts: Working with group of checkboxes in MS Excel

texts:
I have the following checkbox as depicted by the image below:

The checkboxes are in 3 groups. Confidentiality, Integrity ad Availability. When the first in is clicked, the Confidentiality turns Red for High, Orange for Medium and Green for Low.

This is a lot of work to be done as you need to create a subroutine for each checkbox control. Below is a sample code for 2 checkboxes in the first line in the image above.

Private Sub CheckBox21_Change()

With Me.CheckBox21
If .Value Then ClearGroup .GroupName, .Name
End With

End Sub

Private Sub CheckBox22_Change()

With Me.CheckBox22
If .Value Then ClearGroup .GroupName, .Name
End With

End Sub

Private Sub ClearGroup(sGroup As String, sName As String)
    Dim ole As OLEObject

        For Each ole In Me.OLEObjects
            If TypeName(ole.Object) = "CheckBox" Then
                If ole.Object.GroupName = sGroup And ole.Name <> sName Then
                    ole.Object.Value = False
                End If
            End If
        Next ole
End Sub

Private Sub CheckBox21_Click()
    If CheckBox21.Value = True Then
    Range("i6", "m6").Value = "High"
    Range("r3").Value = "H"
    Range("i6", "m6").Interior.Color = RGB(217, 0, 0)
    Range("r3").Interior.Color = RGB(217, 0, 0)

    Else
    CheckBox21.Value = False
    Range("i6", "m6").Value = "Low"
    Range("r3").Value = "L"
    Range("i6", "m6").Interior.Color = RGB(153, 204, 0)
    Range("r3").Interior.Color = RGB(153, 204, 0)
    End If

End Sub
Private Sub CheckBox22_Click()
    If CheckBox22.Value = True Then
    Range("i6", "m6").Value = "Medium"
    Range("r3").Value = "M"
    Range("i6", "m6").Interior.Color = RGB(255, 204, 0)
    Range("r3").Interior.Color = RGB(255, 204, 0)

    Else
    CheckBox22.Value = False
    Range("i6", "m6").Value = "Low"
    Range("r3").Value = "L"
    Range("i6", "m6").Interior.Color = RGB(153, 204, 0)
    Range("r3").Interior.Color = RGB(153, 204, 0)
    End If
End Sub

Is there any other way I can write the VBA code such that the overall line of code will be reduced?


texts: Securely upload multiple image files with PHP

texts:
I am working on script to a upload image files Securely. can anyone please review my code and suggest improvements on security.
<input type="file" name="images[]" id="image" multiple="multiple">
check if request method is POST and request was made from same domain and form was submitted with submit btn
if (is_post_request() && is_request_same_domain() && isset($_POST['add-list-submit'])) {

Convert the $_FILES array to a cleaner version
$images = rearrange_files_array($_FILES['images']);

function rearrange_files_array($file)
{

    $file_array = [];
    $file_count = count($file['name']);
    $file_keys = array_keys($file);

    for ($i = 0; $i < $file_count; $i++) {
        foreach ($file_keys as $key) {
            $file_array[$i][$key] = $file[$key][$i];
        }
    }
    return $file_array;
}

Loop through the images
foreach ($images as $image) {

Check if image was upload, image mime type, extension, and size
if (!isset($image) || $image['error'] !== UPLOAD_ERR_OK) {
    $errors['form'] = 'Please upload the images.';
} else {
    if (!is_file_valid_image($image) || !has_valid_file_extension($image, ['jpeg', 'png', 'jpg'])) {
        $errors['form'] = 'Only PNG and JPG file formats are allowed.';
    }

    if (has_max_file_size($image)) {
        $errors['form'] = 'Max file size is 2.5 MB.';
    }
}

function has_valid_file_extension($file, $allowed_file_extensions)
{
  $file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);
  return in_array($file_extension, $allowed_file_extensions);
}

function is_file_valid_image($file)
{
  $imageTypes = [IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_SWF, IMAGETYPE_PSD, IMAGETYPE_BMP, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM, IMAGETYPE_JPC, IMAGETYPE_JP2, IMAGETYPE_JPX, IMAGETYPE_JB2, IMAGETYPE_SWC, IMAGETYPE_IFF, IMAGETYPE_WBMP, IMAGETYPE_XBM, IMAGETYPE_ICO];
  $info = getimagesize($file['tmp_name']);
  $width = $info[0];
  $height = $info[1];
  $type = $info[2];
  $bits = $info['bits'];
  $mime = $info['mime'];

  if (!in_array($type, $imageTypes)) {
    return false; // Invalid Image Type
  } else if ($width <= 1 && $height <= 1) {
    return false; // Invalid Image Size
  } else if ($bits === 1) {
    return false; // One Bit Image
  } else if ($mime !== 'image/gif' || $mime !== 'image/jpg' || $mime !== 'image/jpeg' || $mime !== 'image/png') {
    return false; // Invalid Image Type
  } else {
    return true;
  }
}

function has_max_file_size($file)
{
  return $file['size'] > 2500000; // 2.5 MB
}

If there are no errors move the image to the uploads directory
$filename = bin2hex(random_bytes(12));
$file_ext = pathinfo($image['name'])['extension'];
$upload_path = UPLOAD_DIRECTORY . '/' . $filename . '.' . $file_ext;
move_uploaded_file($image['tmp_name'], $upload_path);


texts: Filter out comments in Delphi source code

texts:
Today I am working on refactoring and documenting some ancient Delphi code.  In that language, which is derived from Pascal, there are three forms of comments:
(* This is the original Pascal style comment, which is never used in my files *)
{ this is TurboPascal-style comment which I want to remove }
// This is a Delphi-style comment which  I want to remove

As noted in this small sample, I want to strip out the last two styles of comments.  The first kind of comment is never used in the code files I'm using, so there is no special processing done if they are encountered.  I decided to do this using a std::streambuf.  The code and some sample input is below.  I'm interested in any comments for improvement.
commentfilterbuf.h
#ifndef COMMENTFILTER_H
#define COMMENTFILTER_H
#include <streambuf>

class commentfilterbuf : public std::streambuf {
    std::streambuf* sbuf;
    char buffer = EOF;
public:
    commentfilterbuf(std::streambuf* sbuf);
    int underflow();
};
#endif // COMMENTFILTER_H

commentfilterbuf.cpp
#include "commentfilterbuf.h"

commentfilterbuf::commentfilterbuf(std::streambuf* sbuf)
    : sbuf(sbuf)
{
}

int commentfilterbuf::underflow() {
    traits_type::int_type i;
    // skip comments which are delimited with { and }
    for (i = sbuf->sbumpc(); i == '{'; i = sbuf->sbumpc()) {
        while ((i = sbuf->sbumpc()) != '}');
    }
    if (traits_type::not_eof(i)) {
        // check for single line comments like this one
        if (i == sbuf->sgetc() && i == '/') {
            while ((i = sbuf->sbumpc()) != '\n');
        }
        buffer = traits_type::to_char_type(i);
        setg(&buffer, &buffer, &buffer+1);
    }
    return i;
}

testfilter.cpp
#include "commentfilterbuf.h"
#include <iostream>
#include <fstream>
#include <string>

int main(int argc, char* argv[])
{
    if (argc != 2) {
        std::cerr << "Usage: testfilter inputfile\n";
        return 0;
    }
    std::ifstream fin{argv[1]};
    if (!fin) {
        std::cerr << "Error: could not open " << argv[1] << "\n";
        return 1;
    }
    commentfilterbuf sbuf(fin.rdbuf());
    std::istream in(&sbuf);
    std::string line;
    for (std::string line; std::getline(in, line); ) {
        std::cout << line << '\n';
    }
}

sample.in
program HelloWorld;

{$APPTYPE CONSOLE}
{ This is a comment. }
{
    this is a multiline comment.
}
{  This is a Turbo Pascal comment }
// This is a Delphi comment. All is ignored till the end of the line.
// let's try to confuse the parser
{ comment 1 // Comment 2 }begin
// comment 1 { comment 2 }foo

  // Here's a comment
  WriteLn('Hello World');  { and another }
end.


texts: Decrypting a form always returns the previous authentication ticket values

texts:
I have an MVC application that uses Active Directory membership for user authentication.

After the user logs in, a FormsAuthenticatedTicket is created and encrypted. Then, in Application_PostAuthenticateRequest the ticket is decrypted and the deserialized user data is stored in a custom principal object.

My problem is that when a user logs in after their cookie has expired, the ticket is encrypted with the current login data, but in global.asax the previous login's ticket is still decrypted. When debugging, I have seen the ticket data of the previous login of the same user with version 2.

What mistake did I make?

Web.config:

<authentication mode="Forms">
  <forms name=".ADAuthCookie" loginUrl="~/Account/Login">
  </forms>
</authentication>

<membership defaultProvider="ADMembershipProvider">
<providers>
<clear/>
<add name="ADMembershipProvider"
  type="System.Web.Security.ActiveDirectoryMembershipProvider"
  connectionStringName ="ADconnectionString"
  attributeMapUsername="sAMAccountName" />

</providers>
</membership>

my post action login method

  [HttpPost]
  [AllowAnonymous]
  public ActionResult Login(string userName, string password, bool rememberMe, string returnUrl)
  {

    if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
    {
        ViewBag.Message = FormattedMessage.GetFormattedMessage("Veuillez Entrer l'utilisateur et/ou mot passe", TypeMessage.Danger, true);
        return this.View();
    }

    if (Membership.ValidateUser(userName, password))
    {
        FormsAuthentication.SetAuthCookie(userName, rememberMe);
        //JavaScriptSerializer js = new JavaScriptSerializer();
        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
        var userAD = UserPrincipal.FindByIdentity(principalContext, userName);
        var intervenant = unitOfWorkBll.UserBLL.GetAllFiltered(u => u.Matricule == userAD.EmployeeId, includes: "IntervenantRoles.Role, IntervenantStructures.Structure").SingleOrDefault();
        //string userData = js.Serialize(intervenant);
        string userData = JsonConvert.SerializeObject(intervenant, Formatting.Indented, new JsonSerializerSettings {
            PreserveReferencesHandling = PreserveReferencesHandling.Objects
        });
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(10),rememberMe, userData);

        string encryptedTicket = FormsAuthentication.Encrypt(ticket);
        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

        Response.Cookies.Add(cookie);
        if (!string.IsNullOrWhiteSpace(returnUrl) )
        {
            return this.Redirect(returnUrl);
        }

        return this.RedirectToAction("Index", "Home");
    }

    ViewBag.Message= FormattedMessage.GetFormattedMessage("l'utilisateur et /ou le mot passe incorrect.", TypeMessage.Danger, true);

    return this.View();
}

global.asax

protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
    HttpCookie autoCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

    if (autoCookie != null)
    {
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(autoCookie.Value);
        Intervenant user = JsonConvert.DeserializeObject<Intervenant>(ticket.UserData/*, new JsonSerializerSettings {
            PreserveReferencesHandling = PreserveReferencesHandling.Objects
        }*/);

        CustomADPrincipal customADPrincipal = new CustomADPrincipal(user); ;

        HttpContext.Current.User = customADPrincipal;
    }

}


texts: Find neighboring PINs on a numeric keypad

texts:
I am new to coding and to apply for an internship I need to solve several tasks. This is one of them. I wrote working code, but the program says it takes too long to complete. Help me speed up my code please.

Requirements:

Time limit - 1s
Memory Limit - 64mb
Input- standard input
Output- standard output

There is a task:

  Hi, your colleague forgot the pin code from the door to the office.
  The keyboard is:

        ┌───┬───┬───┐
        │ 1 │ 2 │ 3 │
        ├───┼───┼───┤
        │ 4 │ 5 │ 6 │
        ├───┼───┼───┤
        │ 7 │ 8 │ 9 │
        └───┼───┼───┘
            │ 0 │
            └───┘

  A colleague recalls that it seems that the pin code was 1357, but
  perhaps each digit should be shifted horizontally or vertically, but
  not diagonally.

  For example, instead of 1 it can be 2 or 4, and instead of 5 it can be
  2, 4, 6 or 8.

  Help a colleague get into the office.

  Input:
  A string with a pin code. The length of the string is from
  1 to 8 digits, for example, 1357.

  Output:
  The source pin code and possible pin codes with regard to
  shifts, sorted and separated by a comma.

  Do not forget that the pin codes must be strings, as they can begin
  with 0, and must be sorted like strings.

  Examples

  Input: 11
  Output: 11,12,14,21,22,24,41,42,44

  Input: 8
  Output: 0.5,7,8,9

  Input: 46
  Output: 13,15,16,19,43,45,46,49,53,55,56,59,73,75,76,79

Formalization:

var readline = require("readline");
           var rl = readline.createInterface(process.stdin, process.stdout);
           rl.on("line", function(line) {
             console.log("0,5,7,8,9")
             rl.close();
           }).on("close",function(){
             process.exit(0);
           });

MY code

const readline = require('readline');

const rl = readline.createInterface({
 input: process.stdin,
 output: process.stdout
});

function drawMatrix(InArray) {
   let matrix= [];
   for (let z = 0; z < InArray.length; z++) {
       switch (InArray[z]) {
           case '1':
               row = [1, 2, 4];
               break;
           case '2':
               row = [1, 2, 3, 5];
               break;
           case '3':
               row = [2, 3, 6];
               break;
           case '4':
               row = [1, 4, 5, 7];
               break;
           case '5':
               row = [2, 4, 5, 6, 8];
               break;
           case '6':
               row = [3, 5, 6, 9];
               break;
           case '7':
               row = [4, 7, 8];
               break;
           case '8':
               row = [0, 5, 7, 8, 9];
               break;
           case '9':
               row = [6, 8, 9];
               break;
           case '0':
               row = [0, 8];
               break;
       };
      // console.log(row);
       matrix.push(row);
   };
  //console.log(matrix);
  return matrix;
};

function keyVars(matrix) {
   let positions = [];
   let someVar = [];
   let allVars = [];
   let totalCount = matrix.length;

   for (let  i = 0; i < totalCount; i++) {
       positions[i] = 0;
   };

   let next = totalCount - 1;

   while (next >= 0) {
       for (let i=0; i < totalCount; i++) {
           someVar.push(matrix[i][positions[i]]);
       };

       next = totalCount - 1;

       let Var = someVar.join('');
       someVar = [];

       while (next >=0 && (positions[next] + 1) >= matrix[next].length) {
       next--;
       };

       positions[next]++;

       for (let i = next + 1; i < totalCount; i++) {
           positions[i] = 0;
       };

       allVars.push(Var);
   };

   let allVarsStr = allVars.join();
   return allVarsStr;
};

rl.on('line', (input) => {
   console.log(`Входные данные: ${input}`);
   console.log(`Выходные данные: ${keyVars(drawMatrix(input))}`);
   rl.close();
 }).on("close",function(){
   process.exit(0);
 });

```


texts: Fetch StackOverflow questions and save them to a markdown table

texts:
I'm trying to write a script that would (a) fetch StackOverflow questions and (b) update a markdown table with new entries.
With github actions I automated this script to run daily.
Idea borrowed from simonw
Code:
import re
import requests
from pathlib import Path
from datetime import datetime

URL = "https://api.stackexchange.com/2.2/questions"
DATE = datetime.utcnow().date()
ROOT = Path(__file__).parent.resolve()

def get_epochs(date):
    """ Get epoch dates for the start and end of the (current) day. """

    start = datetime(
        year=date.year, month=date.month, day=date.day,
        hour=0, minute=0, second=0
    )
    end = datetime(
        year=date.year, month=date.month, day=date.day,
        hour=23, minute=59, second=59
    )
    return int(start.timestamp()), int(end.timestamp())

def fetch_questions(start, end, tag, site="stackoverflow"):
    """ Fetch questions from stackoverflowAPI. """

    _params = {
        "fromdate": start,
        "todate": end,
        "order": "desc",
        "sort": "votes",
        "tagged": tag,
        "site": site,
    }
    return requests.get(URL, params=_params).json()

def build_table(*args, **kwargs):
    """ Build a markdown table from a list of entries. """

    columns = [
        "\n".join(
            "* [{title}]({url}) - {score} votes".format(
                # to prevent code from breaking if special characters are present
                title=re.sub(r'[^\w\s]', '', item["title"]),
                url=item["link"],
                score=item["score"]
            )
            for item in chunk["items"][:8]
        )
        for chunk in args
    ]
    return columns

def replace_chunk(content, marker, chunk, inline=False):
    """ Replace chunks of README.md """

    r = re.compile(
        r"<!\-\- {} starts \-\->.*<!\-\- {} ends \-\->".format(marker, marker),
        re.DOTALL,
    )
    if not inline:
        chunk = "\n{}\n".format(chunk)
    chunk = "{}".format(marker, chunk, marker)
    return r.sub(chunk, content)

if __name__ == "__main__":

    readme = ROOT / "README.md"
    start, end = get_epochs(DATE)

    pandas, beautifulsoup, code_review = build_table(
        fetch_questions(start, end, tag="pandas"),
        fetch_questions(start, end, tag="beautifulsoup"),
        fetch_questions(start, end, tag="python", site="codereview")
    )

    readme_contents = readme.open().read()
    rewritten = replace_chunk(readme_contents, "date", DATE.strftime("%Y-%m-%d"), inline=True)
    rewritten = replace_chunk(rewritten, "pandas", pandas)
    rewritten = replace_chunk(rewritten, "bs", beautifulsoup)
    rewritten = replace_chunk(rewritten, "code_review", code_review)

    with open(readme, "w") as output:
        output.write(rewritten)

Markdown file:
# Stackoverflow daily top questions:  date

### Pandas

pandas content

### BeautifulSoup

bs4 content

### Python code review submissions

code review content

Sample output:


texts: A small app-crawler created using python

texts:
I've written some code using python having tried to comply with OOP design for the purpose of collecting name of the app, price and developer name from i-tune site by going deeper until there is a limit [which can be toggled within my script] to stop as it has millions of links to go. It is working impeccably at this moment. I tried my best to make this scraper pythonic. However, suggestions to bring about any change to make this crawler more robust will be highly appreciable. Thanks in advance.

from lxml import html
import requests

class app_scraper:

    start_url = "https://itunes.apple.com/us/app/candy-crush-saga/id553834731?mt=8"

    def __init__(self):

        self.links = [self.start_url]
        self.vault = []

    def crawler(self):

        for url in self.links:
            self.get_app(url)

    def get_app(self, url):

        print("Scraping now "+ url)
        page = requests.get(url)
        tree = html.fromstring(page.text)

        name = tree.xpath('//h1[@itemprop="name"]/text()')[0]
        developer = tree.xpath('//div[@class="left"]/h2/text()')[0]
        price = tree.xpath('//div[@itemprop="price"]/text()')[0]

        item = processor(name, developer, price)
        self.vault.append(item)

        p_links = tree.xpath('//div[@class="lockup-info"]//li/a[@class="name"]/@href')
        for p_link in p_links:
            if not len(self.links)>=5:  # It'll stop crawling until it meets the limit whatever it is
                self.links += [p_link]

class processor:

    def __init__(self, name, developer, price):

        self.name = name
        self.developer = developer
        self.price = price

    def __str__(self):
        return (self.name+" "+self.price+" "+self.developer)

crawl = app_scraper()
crawl.crawler()

for info in crawl.vault:
    print(info)


texts:
Using Chris Adamson's book Learning Core Audio I'm getting familiar with Core Audio for Mac/iOS. The code examples are 100% Objective-C. I'm trying to follow along using Swift 3.

This small piece of software is used to find usable AudioStreamBasicDescriptions for a given file type and format.

import Foundation
import AudioToolbox

// Create ID for specific fileType and fileFormat
var fileTypeAndFormat = AudioFileTypeAndFormatID()
fileTypeAndFormat.mFileType = kAudioFileCAFType
fileTypeAndFormat.mFormatID = kAudioFormatLinearPCM

// Target: Gather possible AudioStreamBasicDescriptions for given fileType and fileFormat
// Get size of array containing all available AudioStreamBasicDescriptions
var possibleError = noErr
var infoSize: UInt32 = 0

possibleError = AudioFileGetGlobalInfoSize(kAudioFileGlobalInfo_AvailableStreamDescriptionsForFormat,
                                           UInt32(MemoryLayout<AudioFileTypeAndFormatID>.stride),
                                           &fileTypeAndFormat,
                                           &infoSize)
assert(possibleError == noErr)

// Get number of AudioStreamBasicDescription stored in array
let asbdCount = Int(infoSize) / MemoryLayout<AudioStreamBasicDescription>.stride

// Allocate memory for array to store AudioStreamBasicDescriptions in
var asbds = [AudioStreamBasicDescription](repeating: AudioStreamBasicDescription(), count: asbdCount)

// Fill array with all available AudioStreamBasicDescriptions
possibleError = AudioFileGetGlobalInfo(kAudioFileGlobalInfo_AvailableStreamDescriptionsForFormat,
                                       UInt32(MemoryLayout<AudioFileTypeAndFormatID>.stride),
                                       &fileTypeAndFormat,
                                       &infoSize,
                                       &asbds)
assert(possibleError == noErr)

// Print each AudioStreamBasicDescription of array
for n in 0..<asbdCount {
    var reformattedID = asbds[n].mFormatID.bigEndian

    // TODO: This seems too ugly to be true
    withUnsafePointer(to: &reformattedID) { stringIDPtr in
        print(String(format: "%d: mFormatID: %s, mFormatFlags: %d, mBitsPerChannel: %d", n, stringIDPtr,
                     asbds[n].mFormatFlags, asbds[n].mBitsPerChannel))
    }
}

In an production environment the asserts should be replaced with better error handling, but correct error handling was not the purpose of this script.

Specific parts I'd like to get a review on:

The memory allocation to store available StreamDescriptions for format in. Is the allocation via array Swift-style-conform?
Getting the mFormatID of an AudioStreamBasicDescription via withUnsafePointer(to: &reformattedID) seems utterly unpleasant. Can this be realized in a more elegant way?


texts: SQL query that extracts a topic keyword from article titles

texts:
I have a query like this to select the only row with title contains specific programming topics.

SELECT
    posted_date,
CASE
    WHEN LOWER(title) LIKE "%c#%" THEN "c#"
    WHEN LOWER(title) LIKE "%c++%" THEN "c++"
    .
    .
    .
    WHEN LOWER(title) LIKE "%sql%" THEN "sql"
    ELSE ""
END AS single_topics
FROM
    article_data
WHERE
    EXTRACT(YEAR FROM posted_date) = 2018

It's working fine but I wonder that can WHEN in CASE part be shortened in case of a lot of topics to choose?

Sample data in title column (they are like article title).

The fastest way to do x in C++.
Things most people get wrong about JavaScript.
How to send android push notification using cURL.
macOS Mojave - Features, Specifications and more.
What is map, filter and reduce function in Python and how to use them?


texts: Merging (not removing) duplicated elements in a vector

texts:
There's a struct named Player containing name and stat:

struct Player {
    name: String,
    stat: Stat,
}

struct Stat {
    points: u32,
    fouls: u32,
}

And I have a Vec<Player>. What is interesting is that there can be multiple players with same name and different stats like the following:

let players = vec![
    Player {
        name: String::from("player1"),
        stat: Stat {
            points: 10,
            fouls: 1,
        },
    },
    Player {
        name: String::from("player2"),
        stat: Stat {
            points: 30,
            fouls: 3,
        },
    },
    Player {
        name: String::from("player1"),
        stat: Stat {
            points: 5,
            fouls: 1,
        },
    },
];

The first and the third elements have same name, but with different stat values. What I want to do is merging those elements into one by adding all stat values. After the merging process, the output vector will have 2 elements like the following:

[
    Player {
        name: String::from("player2"),
        stat: Stat {
            points: 30,
            fouls: 3,
        },
    },
    Player {
        name: String::from("player1"),
        stat: Stat {
            points: 15,
            fouls: 2,
        },
    },
]

(The order of output vector is not important in this case.)

And the code below is my solution:

let dup_merged: Vec<_> = players
    .into_iter()
    .fold(
        HashMap::new(),
        |mut acc: HashMap<String, Player>, curr: Player| {
            match acc.get(&curr.name) {
                Some(prev) => {
                    // Is it better to modify prev.stat
                    // instead of inserting new Player instance?
                    // HashMap<String, &Player> required to modification?
                    acc.insert(
                        curr.name.clone(),
                        Player {
                            name: curr.name,
                            stat: Stat {
                                points: prev.stat.points + curr.stat.points,
                                fouls: prev.stat.fouls + curr.stat.fouls,
                            },
                        },
                    );
                }
                None => {
                    acc.insert(curr.name.clone(), curr);
                }
            }
            acc
        },
    )
    .into_iter() // Hope there's better way to get a vector of a hash map
    .map(|(_, v)| v)
    .collect();

Playground link

I used HashMap (key: player.name: String, value: player: Player) to accumulate stat values for players with same name, then  converted the HashMap to Vec<Player> again. I think my solution can be simpler, more idiomatic and refined better.


texts: React custom hooks using refs as index counters

texts:
My custom hook useTyper.js ended up as a bit of a mess and hard to read.
It's mimicking a nested for-loop but using React.useRefs to hold on to the indexes between renders. The indexes are the current positions of the outer and inner loop, those often named i and j in traditional nested for loops.
Here's a fancy code sandbox for the mess below.
One thing I'm particularly unhappy with is the naming of stringIdx and stringsIdx. Any suggestion for a change?
useTyper.js
import React from "react";
import useInterval from "./useInterval.js";

/**
 * A simple typewriter that prints strings, one character after another
 * @param {Array<string>} strings - Array of strings to type
 * @param {function<string>} set - A useState setter to update the current string value
 * @param {number} defaultDelay - Delay between updates
 */
const useTyper = (strings, set, defaultDelay = 100) => {
  const [delay, setDelay] = React.useState(defaultDelay);
  // index counters, normally named i and j if this were an imperative loop
  const stringIdx = React.useRef(0);
  const stringsIdx = React.useRef(0);

  const textTyper = () => {
    const currentString = strings[stringsIdx.current];

    set(currentString.substr(0, stringIdx.current + 1));

    if (stringIdx.current > currentString.length) {
      // Done with string
      stringsIdx.current += 1;
      stringIdx.current = 0;
      if (stringsIdx.current > strings.length - 1) {
        setDelay(null); // Ended.
      }
    }
    stringIdx.current += 1;
  };

  useInterval(textTyper, delay);
};

export default useTyper;

For completion, this is the useInterval hook being used by useTyper.
It can be referenced from one of Dan Abramovs blog posts.
useInterval.js
import React from 'react';

const useInterval = (callback, delay) => {
  const savedCallback = React.useRef();

  // Remember the latest callback.
  React.useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  React.useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => {
        clearInterval(id);
      };
    }
  }, [delay]);
};

export default useInterval;

Here is how the useTyper hook can be used.
import React, { useState } from "react";
import "./styles.css";
import useTyper from "./hooks/useTyper.js";
export default function App() {
  const [placeHolder, setPlaceHolder] = useState("");

  const placeHolders = [
    "First input suggestion",
    "Second input suggeston",
    "Creativity flows...   ",
    "Alright, lets leave it here."
  ];

  useTyper(placeHolders, setPlaceHolder);

  return (

        <input
          id="formElement"
          autoComplete="off"
          autoFocus
          size="20"
          type="text"
          placeholder={placeHolder}
        />

  );
}

Again, here's the link to the code sandbox.


texts:
I made code for signing in users and storing data about them. Everything is fully encrypted and secure also, it is meant to be imported into other code. I'm looking for ways to improve it and to fix any bugs people might find.

import pickle
import base64

class user():
    def __init__(self, username, password, user_data):
        self.username = username
        self.password = password
        self.user_data = user_data

def get_user():
    try:
        user_saves = open("users", 'rb')
        users = dict(pickle.load(user_saves))
        user_saves.close
        name, password, users = sign_in(users)
    except:
        name, password, users = new_user(True)

    name = base64.b64decode(name.decode('utf-8'))
    password = base64.b64decode(password.decode('utf-8'))
    return name, password, users

def new_user(is_first = False, users=None):
    print('Creating account... ')
    if users != None:
        loop = True
        while loop:
            name = input('What is your username: ')
            name = base64.b64encode(name.encode('utf-8'))
            if name in users:
                print('Already taken.')
            else:
                loop = False
                password = input('What is your password: ')
                password = base64.b64encode(password.encode('utf-8'))
    else:
        name = input('What is your username: ')
        name = base64.b64encode(name.encode('utf-8'))
        password = input('What is your password: ')
        password = base64.b64encode(password.encode('utf-8'))
    if is_first == True:
        user = {name:password}
        user_saves = open("users", 'wb')
        pickle.dump(user, user_saves)
        add_user_data('', password, True)
        return name, password, user
    else:
        add_user_data('', password)
        users.update({name:password})
        user_saves = open("users", 'wb')
        pickle.dump(users, user_saves)
        return name, password, users
    user_saves.close

def sign_in(users):
    nsi = True #not signed in
    while nsi == True:
        username = input('What is your username: ')
        username = base64.b64encode(username.encode('utf-8'))
        if username in users:
            password = input('What is your password: ')
            password = base64.b64encode(password.encode('utf-8'))
            if password == users.get(username):
                print('working')
                nsi = False
                return username, password
            else:
                print('Wrong password.')
        else:
            yn = y_or_n('y or n, are you a new user: ')
            if yn == True:
                nsi = False
                name, password = new_user(users=users)
                return name, password

def y_or_n(promt):
    ni = True #no input
    while ni:
        yn = input(promt).lower()
        if yn == 'y':
            return True
        elif yn == 'n':
            return False
        else:
            print('y or n')

def add_user_data(data, password, is_first=False):
    password = base64.b64encode(password.encode('utf-8'))
    data = base64.b64encode(data.encode('utf-8'))
    if is_first == True:
        user_data = {password:data}
        users_data = open("users_data", 'wb')
        pickle.dump(user_data, users_data)
    else:
        user_data.update({password:data})
        users_data = open("users_data", 'wb')
        pickle.dump(user_data, users_data)
    users_data.close

def get_user_data(password):
    password = base64.b64encode(password.encode('utf-8'))
    user_data = pickle.load('user_data')
    user_data = base64.b64decode(user_data.decode('utf-8'))
    return user_data

def delete_user(name, data, ):
    data.pop('name', None)

name, password, users = get_user()
data = get_user_data(password)
print(data)
user_stats = user(name, password, data)