texts: Get missing sequential numbers from array

texts:
I have an array like Original = {1, 2, 3, 6, 7, 8, 9, 10, 12}. After removing some elements like Delete = {6, 7} from it, I want to get n sequential numbers which are not in the array, like IDs = {4, 5, 6, 7, 11, 13, 14, ..., n}.

After getting the numbers I want the original array to be changed to the updated array.

public static ushort GetNextID(ref List<ushort> Updating)
{
    for (var i = 0; i < Updating.Count; i++)
    {
        if (Updating[i] != i + 1)
        {
            Updating.Insert(i, Convert.ToUInt16(i + 1));
            return Convert.ToUInt16(i + 1);
        }
    }
    Updating.Add(Convert.ToUInt16(Updating.Last() + 1));
    return Convert.ToUInt16(Updating.Last() + 1);
}
public static ushort[] GetNextIDs(ref List<ushort> Updating, ushort Count)
{
    List<ushort> IDs = new List<ushort>();
    for (var t = 0; t < Count; t++) IDs.Add(GetNextID(ref Updating));
    return IDs.ToArray();
}
static void Main(string[] args)
{
    IEnumerable<ushort> Original = new ushort[] { 1, 2, 3, 4, 5, 6, 7, 9, 10 };
    IEnumerable<ushort> Delete = new ushort[] { 4, 5, 6 };
    var Updating = Original.Except(Delete).ToList();

    // Expected: 4, 5, 6, 8, 11, 12, 13, 14
    // Outputs:  4, 5, 6, 8, 12, 13, 14, 15
    foreach (var id in GetNextIDs(ref Updating, 8)) Console.WriteLine(id);

    Console.WriteLine();

    // 1, 2, 3, (4, 5, 6), 7, (8), 9, 10, (11, 12, 13, 14)
    foreach (var i in Updating) Console.WriteLine(i);

    Original = Updating;
    Console.ReadKey();
}

I'm using refs for performance but I'm not sure if it does any good.


texts: Factory pattern for image or shape marker

texts:
I'm making a photo marker application and need to make a factory pattern for marker. I think it is not very flexible and overall not good.

Would you check my code and suggest what could be improved?

import Foundation

enum MarkerType: String {
    case Shape, Image
}

enum MarkerError: ErrorType {
    case ImageNoExist
    case ShapeNoExist
}

struct ImageMarker {
    static func make(type: String) -> UIImageView {
        var imageStr: String = ""
        switch type {
        case "X":
            imageStr = "close.png"
            break
        default: break
        }

        let image = UIImage(named: imageStr)
        let tintedImage = image?.imageWithRenderingMode(.AlwaysTemplate)
        let imageView = UIImageView(image: tintedImage)
        imageView.tintColor = UIColor.redColor()
        return imageView
    }
}

struct ShapeMarker {
    static func make(type: String) -> UIView {
        var shape: UIView = UIView()
        switch type {
        case "CIRCLE":
            //shape = CircleView()
            break
        default: break
        }

        return shape
    }
}

typealias Factory = (String) -> AnyObject

class MarkerHelper {
    class func factoryFor(type: MarkerType) -> Factory {
        switch type {
        case .Shape:
            return ShapeMarker.make
        case .Image:
            return ImageMarker.make
        }
    }
}


texts:
I have implemented an nth prime algorithm in Rust that uses value lookup for n < 6, trial division for n < 1000, and a sieve function for n > 999. How can it be better optimized?

pub fn nth(x: u32) -> Result<u64, String> {

match x > 0 {
    true => match x {
        1 => Ok(2),
        2 => Ok(3),
        3 => Ok(5),
        4 => Ok(7),
        5 => Ok(11),
        x if x < 1000 => Ok(trial_div(x)),
        _ => Ok(sieve(x)),
    },
    false => Err(String::from("invalid input")),
  }
}

fn trial_div(x: u32) -> u64 {
  let mut primes: Vec<u64> = Vec::with_capacity(x as usize);

  primes.push(2);

  if x > 1 {
    primes.push(3);
  }

  let mut next_checked = *primes.last().unwrap() + 2;

  while primes.len() < x as usize {
        if primes.iter().all(|&i| next_checked % i != 0) {
            primes.push(next_checked)
        }
        next_checked += 2;
  }
  *primes.last().unwrap()
}

fn sieve(x: u32) -> u64 {
  let x = x as f64;

  let upper_limit = (x * ((x*x.ln()).ln())).floor() as usize;
  let mut prime_indices = vec![true; upper_limit];

  for i in 2..upper_limit {
    if prime_indices[i] {
        let mut counter = 0;
        while (i.pow(2) + (counter * i)) < upper_limit {
            prime_indices[(i.pow(2) + (counter * i)) as usize] = false;
            counter += 1
        }
    }
  }

  let mut prime_x = 1;
  let mut prime_count = 0;
  for i in 2..upper_limit {
    if prime_indices[i] {
        prime_count += 1;
        prime_x = i
    }
    if prime_count == x as u64 {
        break
    }
  }
  prime_x as u64
}


texts:
I'm using the cosine function in C++ to simulate flashing for a sprite in my game. The method looks like this:

(anything in the sf namespace is part of the SFML graphics library)

void Player::update(const float& deltaTime)
{
    mAccumulatedTime += deltaTime;
    float opacity = abs(cosf(5*mAccumulatedTime)) * 255;
    static int numFlashes = 0;
    if (opacity == 255) {
        cout << ++numFlashes << endl;
    }
    mSprite.setFillColor(sf::Color(255, 255, 255, opacity));
}

So every time opacity is equal to 255 (basically the passing of one full period),  numFlashes should be incremented. The problem is, cos() isn't perfect, meaning it doesn't exactly reach 1 and 0, so the if condition is rarely met. If I use rough checking like if (opacity > 255*0.9999), then numFlashes becomes really high, really fast.

Does anyone know a way to accurately check when a full period has passed? Or is that just not possible?


texts: Reverse a word using string manipulation

texts:
#include<stdafx.h>
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<iostream>
using namespace std;
string temp[10];
void extract(char * c)
{
    int ind = 0;

    //char *temp = (char *)malloc(sizeof(char));
    while(*c!= NULL)
    {
        if(*c!= ' ') // read all chars in a word and store in temp.
        {
        temp[ind]= temp[ind] + *c;
        c++;

        }
        else if(*c== ' ') // reached end of word
        {
        c++;
        ind++;
        }
    }
    int length = sizeof(temp)/sizeof(temp[0]);
    printf("The reversed string is");
    for(int i=length;i>=0;i--)
    {
    cout<<temp[i];// not able to print it with printf statement
    }

}

void main()
{
char *c = "seattle is good";
extract(c);

}

This should print the sentence in reverse order . Input is "seattle is good"
Output for the above will be "good is seattle"
I have 2 questions ,
1. I am using string array here with size of 10. How can I make it dynamic?
2. For some reason the printf("%s",temp[i]) was not giving me correct results(At the very end of extract method). I then used cout and it was fine. Any ideas why? Am I doing something silly?

Algorithm Description:

Take the input string as char array.
Extract words from the string by looking for empty space.
Store each word in a temp string array.
temp[0] = seattle
temp[1] = is
temp[2] = good
Then loop backwards through this temp array and print contents.


texts:
So, I've tried to make a simple math library in Rust. What do you think about it?

const PRECISION: f64=512.; //Balance between speed and precision here.

fn ln(x:f64) -> f64 {
    let mut sum=0.;
    let epsilon=(x-1.)/(5.*PRECISION);
    let mut i=1.;
    while (epsilon>0. && i<x) || (epsilon<0. && i>x) {
        sum+=epsilon/i;
        i+=epsilon;
    }
    sum
}

fn exp(x:f64) -> f64 {
    let mut i=0.;
    let mut y=1.;
    let epsilon=x/PRECISION;
    while (epsilon>0. && i<x) || (epsilon<0. && i>x) {
        y+=epsilon*y;
        i+=epsilon;
    }
    y
}

fn arctan(x:f64) -> f64 {
    let mut sum=0.;
    let epsilon=x/PRECISION;
    let mut i=0.;
    while i<x {
        sum+=epsilon/(1.+i*i);
        i+=epsilon;
    }
    sum*(180./pi())
}

fn tan(degrees:f64) -> f64 {
    sin(degrees)/cos(degrees)
}

fn sin(degrees:f64) -> f64 {
    if degrees<0. {
        return -sin(-degrees);
    }
    if degrees>90. {
        return cos(degrees-90.);
    }
    let radians=degrees/(180./pi());
    let mut tmpsin=0.;
    let mut tmpcos=1.;
    let epsilon=radians/PRECISION;
    let mut i=0.;
    while (epsilon>0. && i<radians) || (epsilon<0. && i>radians) {
        tmpsin+=epsilon*tmpcos;
        tmpcos-=epsilon*tmpsin;
        i+=epsilon;
    }
    tmpsin
}

fn arcsin(x:f64) -> f64 {
    arctan(x/sqrt(1.-x*x))
}

fn arccos(x:f64) -> f64 {
    90.-arcsin(x)
}

fn cos(degrees:f64) -> f64 {
    sin(90.-degrees)
}

fn sqrt(x:f64) -> f64 {
    let mut max=1000.;
    let mut min=0.;
    let mut i=(min+max)/2.;
    while (max-min)>1./PRECISION {
        if i*i>x {
            max=i;
        }
        else {
            min=i;
        }
        i=(max+min)/2.;
    }
    i
}

fn pi() -> f64 {
    let mut sum=0.;
    let mut i=-1.;
    let epsilon=1./PRECISION;
    while i<1. {
        sum+=epsilon/(1.+i*i);
        i+=epsilon;
    }
    2.*sum
}

fn main() {
    println!("x\tsin(x)\tcos(x)\ttan(x)\tln(x)\tsqrt(x)\tasin\tacos\tatan");
    for i in 0..101 {
        print!("{:.4}\t",i);
        print!("{:.4}\t",sin(i as f64));
        print!("{:.4}\t",cos(i as f64));
        if tan(i as f64)<100. && tan(i as f64)> -10. {
            print!("{:.4}\t",tan(i as f64));
        }
        else if tan(i as f64)< -10. {
            print!("{:.3}\t",tan(i as f64));
        }
        else {
            print!("inf\t");
        }
        if ln(i as f64)> -100. {
            print!("{:.4}\t",ln(i as f64));
        }
        else {
            print!("-inf\t");
        }
        print!("{:.4}\t",sqrt(i as f64));
        if arcsin((i as f64)/100.)<90. {
            print!("{:.4}\t",arcsin((i as f64)/100.));
        }
        else {
            print!("90\t");
        }
        if arccos((i as f64)/100.)<90. && arccos((i as f64)/100.)>0. {
            print!("{:.4}\t",arccos((i as f64)/100.));
        }
        else if arccos((i as f64)/100.)>0. {
            print!("90\t");
        }
        else {
            print!("0\t");
        }
        print!("{:.4}\n",arctan((i as f64)/100.));
    }
    println!("pi={:.4}",pi());
    println!("rad={:.4}",180./pi());
    println!("ln(1/pi)={:.4}",ln(1./pi()));
    println!("e={:.4}",exp(1 as f64));
    println!("1/e={:.4}",exp(-1 as f64));
}


texts:
I have created a basic login system that asks the user for a password. Here's a list of what it does:

When you run the code it will open an Inputbox asking you for a password.
There is one criteria: You have to enter a password of 8 characters. If you enter a password with less or more, it will give you an error message.
If you leave the Inputbox blank or press Cancel, it will switch over to a Yes or No msgbox asking you if you want to quit the macro. Yes will close and No, will bring you back to the Inputbox.

I believe that there are many ways to optimize the code. Are there any suggestions?

Sub Userlogin(Password, ExitApplication)

Dim Confirm
Dim PasswordLength As Integer

' Password System
If Password = "" Then

    ' Loop until Password is correct.
    Do While Password = ""
        Password = InputBox("Enter your Password:", "Login")
        PasswordLength = Len(Password)

        ' Asks the user if they want to close the application.
        If Password = "" Then
            Confirm = MsgBox("Are you sure you want to close this application?", vbYesNo, "Confirm")
        End If

            If Confirm = vbYes Then
                ExitApplication = True
                Exit Do
                Exit Sub
            End If

            If Confirm = vbNo Then
                Password = ""
                PasswordLength = 8
                Confirm = ""
            End If

        ' Checks if the Password is 8 characters.
        If Not PasswordLength = 8 Then
            MsgBox "The Password must be 8 characters long." & vbNewLine & vbNewLine & "Please Try again.", vbCritical, "Password Incorrect"
            Password = ""
        End If

    Loop

End If

End Sub

Main Sub is here:

Sub MainSub()

' Standard Dim's
Dim Username As String
Dim Password As String

Dim ExitApplication As Boolean

'_______________________________________________________________________________

' Set Values

ExitApplication = False
Username = CreateObject("WScript.Network").Username

'_______________________________________________________________________________

Call Userlogin(Password, ExitApplication)
    If ExitApplication = True Then
        Exit Sub
    End If

End Sub


texts:
Here's a Tic-Tac-Toe program I wrote in Python. How can I improve it (.eg. make it more readable)?

class Gameboard():

    def __init__(self):
        self.gameboard = {1:' ' , 2: ' ', 3: ' ', 4:' ',  5:' ',  6:' ',  7:' ',  8:' ',  9:' '}

    def setPeice(self, user, position, gameboard):
        gameboard[position] = user
        return gameboard
    @property
    def gameBoard(self):
        '''
        need to learn more about properties. They seem to be used primarily as
        getters and setters. ??
        '''
        return self.gameboard

    def clearboard(self):
        self.gameboard = {1:' ' , 2: ' ', 3: ' ', 4:' ',  5:' ',  6:' ',  7:' ',  8:' ',  9:' '}

    def is_place_taken(self, gameboard, index):
        if gameboard[index] != ' ' :
            return True

    def is_board_full(self, gameboard):
        for index in range(1, 10):
            if gameboard[index] == ' ':
                return False
        return True

    def is_game_won(self, gameboard):
        win_conds = ((1,2,3), (4,5,6), (7,8,9), (1,4,7), (2,5,8), (3,6,9), (1,5,9), (3,5,7))
        for win_cond in win_conds:
            if gameboard[win_cond[0]] == gameboard[win_cond[1]] and gameboard[win_cond[1]] == gameboard[win_cond[2]] and gameboard[win_cond[0]]!= ' ':
                return True

    def printBoard(self,gameboard):
        index = 0
        for row in range(1,4):
            for column in range(1,4):
                index += 1
                if column != 3:
                    print(gameboard[index], end='')
                    print('|', end='')
                else:
                    print(gameboard[index])

class Game():

    def on_start(self):
        '''
        Called on initial start and in subsequent restarts
        '''
        self.controlBoard = Gameboard()
        self.gameboard = self.controlBoard.gameBoard
        self.playerOne ='o'
        self.playerTwo = 'x'
        print('Welcome to tic-tac-toe')
        print("What is player one's name?")
        self.player_one = input(' : ')
        print("What is player two's name?")
        self.player_two = input(' : ')
        print('Here is your game board, each place is represented by 1-9, starting from left column each time and movng along the row')
        self.controlBoard.printBoard(self.gameboard)
        self.turn = 1

    def on_end(self):
        #check if a player wants to end the game
        if self.running == False:
            replay = input('Press 0 to quit or 1 to play again: ')
            try:
                if int(replay):
                    self.running = True
                    self.on_start()
            except:
                print("A number must be entered.")
                self.on_end()

    def takeTurn(self, user, peice):
        print(user + ' choose a place, 1-9')
        try:
            position = int(input(': '))
            if position > 9 or position < 1:
                raise Exception

        except:
            print('Pick a number between 1-9')
            return self.takeTurn(user, peice)

        if self.controlBoard.is_place_taken(self.gameboard, position):
            print("That place is taken")
            self.takeTurn(user,peice)
        else:
            self.controlBoard.setPeice(peice, position, self.gameboard)
            self.controlBoard.printBoard(self.gameboard)
            if self.controlBoard.is_game_won(self.gameboard):
                print(user +  " wins.")
                self.running = False

    def main(self,):
        self.running = True
        self.on_start()
        while self.running:
            if self.turn%2 != 0:
                self.takeTurn(self.player_one, 'o')
            else:
                self.takeTurn(self.player_two, 'x')

            if self.controlBoard.is_board_full(self.gameboard):
                print("Its a draw!! You both lose!")
                self.running = False
            self.turn += 1

            if not self.running:
                self.on_end()

if __name__ == '__main__':
    Game().main()


texts:
I have to implement WMSAuth in C#: http://wmsauth.org/examples

// The following function was copied from http://wmsauth.org/examples
public static string BuildProtectedURLWithValidity(string password, string media_url, string ip, int valid)
{
    string result = null;
    DateTime cur_date = DateTime.Now;
    TimeZone localzone = TimeZone.CurrentTimeZone;

    DateTime localTime = localzone.ToUniversalTime(cur_date);

    string date_time = localTime.ToString(new CultureInfo("en-us"));

    Int32 Valid = valid;
    string to_be_hashed = ip + password + date_time + Valid.ToString();

    byte[] to_be_hashed_byte_array = new byte[to_be_hashed.Length];

    int i = 0;
    foreach (char cur_char in to_be_hashed)
    {
        to_be_hashed_byte_array[i++] = (byte)cur_char;
    }

    byte[] hash = (new MD5CryptoServiceProvider()).ComputeHash(to_be_hashed_byte_array);

    string md5_signature = Convert.ToBase64String(hash);

    result = media_url + "?server_time=" + date_time + "&hash_value=" + md5_signature + "&validminutes=" + Valid.ToString();
    return (result);
}

The problem is that, although I believe the code above might work for every possible input, it seems to be done without much knowledge of C#, and I have a big concern with the Encoding in the byte to char casting.

So I changed the code to this:

private static string BuildProtectedURLWithValidity(string wmsAuthPassword, string mediaUrl, string clientIp, int validMinutes)
{
    string dateTimeString = DateTime.UtcNow.ToString(new CultureInfo("en-us"));
    string validMinutesString = validMinutes.ToString();

    string stringToBeHashed = clientIp + wmsAuthPassword + dateTimeString + validMinutesString;
    string hashValue;
    using (MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider())
    {
        byte[] bytesToBeHashed = Encoding.UTF8.GetBytes(stringToBeHashed);
        byte[] hashBytes = md5Provider.ComputeHash(bytesToBeHashed);
        hashValue = Convert.ToBase64String(hashBytes);
    }

    string result = mediaUrl + "?server_time=" + dateTimeString + "&hash_value=" + hashValue + "&validminutes=" + validMinutesString;
    return result;
}

But my real concern is that with my attempt to follow the company's naming standards and improve the code readability I might be introducing a bug in already tested code. Would you use the version posted in the the WMSAuth page?

Note: It has to work with the .NET Framework 1.1


texts:
I solved this problem.

  Problem Statement

  Given a string, sort it in decreasing order based on the frequency of
  characters.

  Example 1

  Input: "tree"

  Output: "eert"

  Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a
  valid answer.

  Example 2:

  Input: "cccaaa"

  Output: "cccaaa"

  Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also
  a valid answer. Note that "cacaca" is incorrect, as the same
  characters must be together. Example 3:

  Input: "Aabb"

  Output: "bbAa"

  Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
  Note that 'A' and 'a' are treated as two different characters.

I solved this problem using heaps(since it was tagged under this category). I feel my solution is a bit verbose which includes building a vector from a map and so on.

Can you think of any redundancies that can be removed from this solution or any better way of doing it.

class CompareHeap
    {
        public:
            bool operator()(const std::pair< char, int> &A, const std::pair< char , int > &B )
            {
                return (A.second < B.second);
            }
    };
    class Solution {
    public:
        string frequencySort(string input) {
        std::string answer = "";
        std::map<char, int> freq;
        for(auto it = input.begin(); it!= input.end(); ++it)
        {
            if(freq.find(*it) != freq.end())
            {
                freq[*it] += 1;
            }
            else
            {
                freq[*it] = 1;
            }
        }
        std::vector<std::pair<char, int >> v;
        std::transform(freq.begin(), freq.end(), std::back_inserter(v), [](std::pair<char , int > kv) {return kv;});
        std::make_heap(v.begin(), v.end(), CompareHeap());
        while(v.size() > 0)
        {
            std::pop_heap(v.begin(), v.end(), CompareHeap());
            answer += std::string(v.back().second,v.back().first);
            v.pop_back();
        }
        return answer;
        }
    };


texts:
I want to give users help in which format they have to enter a date. The label content is:

  Date (YYYY-MM-DD)

I used the following markup:

Date (YYYY-MM-DD)

Note: the new HTML5 input-type values (like date) might be used, but this label is a fallback for users with older browsers. Most of them use screenreaders and I try to give the most nitty-gritty markup.

I wonder:

Should I use the code element?
Is my use of the kbd element correct in this context? The "YYYY-MM-DD" represents something that users should enter, but it isn't something they should enter exactly as given, of course. It's more some kind of variable, I guess.
So maybe the var element might be appropiate?
Is my use of the abbr element correct?
Should I use the dfn element around each abbr element? So "YYYY" would be defined as year, because strictly spoken it is not an abbreviation for "four-digit year" but for "Year Year Year Year".


texts:
Motivation

I came across an interesting question on SO: determine-if-string-has-all-unique-characters and thought about providing an extension method to enable duplicate removal given some kind of normalization.

Description

  The goals:

  Remove any duplicate characters (keep the first occurence) and return the updated string.
  The method should be able to handle diacritics and extended unicode characters.
  The method should allow the consumer to control normalization to find duplicates (for instance, case-sensitivity).

Questions

Looking for general feedback on C# conventions
Performance feedback
Am I reinventing the wheel?

Code

public static class StringExtension
{
    public static string RemoveDuplicateChars(
        this string text, Func<string, string> normalizer = null)
    {
        var output = new StringBuilder();
        var entropy = new HashSet<string>();
        var iterator = StringInfo.GetTextElementEnumerator(text);

        if (normalizer == null)
        {
            normalizer = x => x.Normalize();
        }

        while (iterator.MoveNext())
        {
            var character = iterator.GetTextElement();
            if (entropy.Add(normalizer(character)))
            {
                output.Append(character);
            }
        }

        return output.ToString();
    }
}

Unit Tests

Let's test a string that contains variations on the letter A, including the Angstrom sign Å. The Angstrom sign has unicode codepoint u212B, but can also be constructed as the letter A with the diacritic u030A. Both represent the same character.

[TestClass]
public class Fixtures
{
    [TestMethod]
    public void Fixture()
    {
        // ÅÅAaA -> ÅAa
        Assert.AreEqual("ÅAa", "\u212BA\u030AAaA"
            .RemoveDuplicateChars());

        // ÅÅAaA -> ÅA
        // Note that the ToLowerInvariant is used to normalize characters
        // when searching for duplicates, it does not mean the output gets
        // transformed to lower case.
        Assert.AreEqual("ÅA", "\u212BA\u030AAaA"
            .RemoveDuplicateChars(x => x.Normalize().ToLowerInvariant()));
    }
}


texts: Need feedback for a anglar 8 simple calendar appplication with the abilily to show to dos

texts:
I just built a simple calendar app using angular 8. I would like to get some suggestions for improvements in the project. any feedback will be appreciated. I would like to know what I could have done better in the application in terms of both typescript code and overall app design. this is the github link for my project https://github.com/SagarMajumdar/calapparepo

This is a custom calendar and i am using a JSON structure similar to this to show the calendar as well as the to do items for each day

calendar application screenshot

the way calendar JSON is being contructed is as follows . The subscription is for when a new month and year is selected.

  for (let i = 1; i <= this.modays[this.yrmo.mo - 1].days; i++) {
        if (flg === 1) {
          this.dayStructure.days.push (
            {cols: [
              {
                day : i,
                dayname: this.weekdays[(new Date(this.yrmo.yr, this.yrmo.mo - 1, i - 1) ).getDay()].day,
                dayofweek :  (new Date(this.yrmo.yr, this.yrmo.mo - 1, i - 1) ).getDay() + 1
                , todos : this.getotodos(this.yrmo.yr, this.yrmo.mo, i)
              }
            ]} );
          flg = 0;
          this.flagGotMoTodos = true;
        } else {
          this.dayStructure.days[rownum].cols.push(
            {
              day : i,
              dayname: this.weekdays[(new Date(this.yrmo.yr, this.yrmo.mo - 1, i - 1) ).getDay()].day,
              dayofweek :  (new Date(this.yrmo.yr, this.yrmo.mo - 1, i - 1) ).getDay() + 1
              , todos : this.getotodos(this.yrmo.yr, this.yrmo.mo, i)
            }
          );
        }
        if ( (new Date(this.yrmo.yr, this.yrmo.mo - 1, i - 1) ).getDay() === 6 ) {
          flg = 1;
          rownum = rownum + 1;
        }
      }

      console.log('\n---------------------------------------------------------------\n');
      this.dayStructure = this.fillblanks(this.dayStructure);

thanks


texts: PHP - Saving inbound email and its attachment

texts:
I have below code, which is basically handling inbound emails in my application, save the actual email content (text + attachments) to my database, and further save the actual attachment file on my server.

In my Email.php model, I have below function that handles the incoming email. The $token is the first string of the email. For example, my To: email can look like this: avdksokiell@myapp.com where avdksokiell is my token.

So as you can see, I fire off the Email model as below:

Mailbox::to('{token}@myapp.com', Email::class);

When above condition is met, below will be run:

public function __invoke(InboundEmail $email, $token)
{
    //Get the correct stream.
    $stream = Stream::where('token', $token)->firstOrFail();

    //Persist the token to the database. {token}@in.myapp.com
    $email->stream_id = $stream->id;

    //Save the email.
    $email->save();

    //If any attachments, persist them to the database.
    $this->storeAttachments($stream, $email);

}

Above works, because I have a relationship set up between Stream and Email:

Stream.php:

/**
 * A stream can have many e-mails
 */
public function emails()
{
    return $this->hasMany(Email::class);
}

Email.php:

/**
 * An email belongs to a Stream.
 */
public function stream()
{
    return $this->belongsTo(Stream::class);
}

Furthermore, in order to save the actual attachment from the mail, I have created a method called storeAttachments(Stream $stream, InboundEmail $email) function in Email that looks like below:

/**
 * A method to store incoming attachments from email.
 *
 */
public function storeAttachments(Stream $stream, InboundEmail $email)
{
    $attributes = [];
    foreach ($email->attachments() as $attachment) {
        //Set an unique filename
        $filename = uniqid() . '.' . File::extension($attachment->getFilename());
        //Store the file on the server
        $store = Storage::put($stream->token . '/' . $filename, $attachment->getContent());
        //Add file information, so we can persist it to the database.
        $attributes['name'] = $attachment->getFilename();
        $attributes['path'] = $stream->token . '/' . $filename;

        //Persist it to the database.
        $stream->addDocuments($attributes);
    }
}

Because my users can choose to:

Upload files from a web frontend
Send files by email into my app

I also have a Document model, that stores all the files:

I also have a relationship set up here:

Stream.php:

/**
 * A stream can have many documents
 */
public function documents()
{
    return $this->hasMany(Document::class);
}

Document.php:

//A document belongs to a Stream.
public function stream()
{
    return $this->belongsTo(Stream::class);
}

Now, for handling the saving files to the database, I have below method in my Stream model:

/**
 * Add document(s) to the stream
 *
 * @return Illuminate\Database\Eloquent\Model
 */
public function addDocuments(array $attributes)
{
    return $this->documents()->create($attributes);
}

I am a bit unsure if above design/methodology is correct and seen as "best practice".

One thing I notice is, that whenever I handle an incoming mail in the __invoke function, I run a query to get the stream_id by looking up the token, because the relationships is using stream_id.

Hope someone can help me shed some light if above is OK or if anything can be improved.

I'll be happy to share more code if needed.


texts:
The following code finds the max depth of nested parentheses in the given string - for example, for {}{}{{}} it outputs 2. If the given string doesn't contain correct sequence of parentheses (like {{}), it outputs "NIE". User enters the length of the string and the string.

My concerns: the algorithm is somewhat slow, and I don't think it's really the best way to solve this problem.

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int maxDepth(string S)
{
    int current_max = 0;
    int max = 0;
    int n = S.length();

    for (int i = 0; i< n; i++)
    {
        if ((S[i] == '(') || (S[i] == '{') || (S[i] == '['))
        {
            current_max++;

            if (current_max> max)
                max = current_max;
        }
        else if ((S[i] == ')') || (S[i] == '}') || (S[i] == ']'))
        {
            if (current_max>0)
                current_max--;
            else
                return -1;
        }
    }

    if (current_max != 0)
        return -1;

    return max;
}

int main()
{
    int n, i;
    cin >> n;
    string s;
    cin >> s;
    for (i=0; i<n; i++)
    {

        if (count(s.begin(), s.end(), '(')!=count(s.begin(), s.end(), ')'))
        {

            cout << "NIE\n";

            return 0;

        };

        if (count(s.begin(), s.end(), '{')!=count(s.begin(), s.end(), '}'))
        {

            cout << "NIE\n";

            return 0;

        };

            if (count(s.begin(), s.end(), '[')!=count(s.begin(), s.end(), ']'))
        {

            cout << "NIE\n";

            return 0;

        };

    };
    cout << maxDepth(s) << "\n";
    return 0;
}


texts:
Is it bad design if I create repostory with methods that returns generic types. For example in AccountsRepository if I have:

public class Repository<T> : IRepository<T>
where T : class
{
}

public class AccountsRepository<TUser> :
Repository<User>,IAccountsRepository
    where TUser : class,IUser,new()
    {
      public TUser GetUserByUserName(string username)
      {
       return this.context.User.Where(s =>
       s.UserName.Equals(username)).Select(c=>new TUser(){ Password =c.Password }).FirstOrDefault();
      }
    }

Is this the proper way of doing that. So It's something like I return DTO object but it is generic type. So my classes using repository doesn't have to know what types are the objects in database.


texts:
I just recently began going over number systems again, granted I didn't pay very much attention to it the first time for lack of understanding its importance (I've only been coding for a year and some change). Below this paragraph of text I have a simple Binary to Decimal converter, and I was wondering if there's a better way to do this, or if my algorithm is okay:

import java.util.Scanner;

public class BinaryToDecimal {

public static void main(String[] args) {
    Scanner scan1 = new Scanner(System.in);
    System.out.println("Enter a binary number: ");
    String Binary = scan1.next(); // 11011
    double power = 0;
    double sum = 0;

    for (int i = Binary.length() - 1; i >= 0; i--) {
        char TempHold = Binary.charAt(i);
        double num = Character.getNumericValue(TempHold);
        sum = (sum + (num * (Math.pow(2, power))));
        power++;
    }

    System.out.println(sum + "(10)");

}

}

My process:

The first step was to, of course, allow the user to input their own binary number for testing purposes with a scanner and a variable of String called Binary for the initialization of this input (I chose to make this a String vs an Integer for looping purposes).
Next I created a variable of type double called power that will start off at 0 and be utilized in the for loop later.
Lastly, as far as preliminary variable declarations go, I created a sum variable to hold the sum of the binary-decimal conversion.
Within the for loop I ensured that my iterator traversed the String backwards in respect to my method of conversion.
After setting up the for loop, I created a variable of type Character called TempHold to seize and store the character of the Binary variable that corresponds to the current iteration of the loop.
My next step was to parse the TempHold Character variable into a String so that I could utilize it arithmetically in my conversion method.
At the end of this for loop I incremented the power variable so that I could increase the value of the exponent being used in the conversion method.


texts:
For a homework assignment, I made a web page that has a text area. The user inputs some text, hits the analyse button, and the output is supposed to be a list of the frequency of words of a given number of characters.

For example, "one two three" would be two words of three characters and one word of five characters.

It works, but is there room for improvement?

HTML:

Text Input

<textarea id="text" placeholder="type something..." rows="20" cols="80"></textarea>
<button id="analyse">Click to analyze</button>

Results

JavaScript:

function getWordInfo() {
    var text1 = document.getElementById("text").value;
    var text2 = text1.replace(/[^\d\w ]+/g," ");
    var text3 = text2.split(/[ ]+/);
    return text3;
}

function firstLoop() {
    var text = getWordInfo();
    var wordMap = [];
    var i =0;
    var looplength = text.length;
    for ( i ;i < looplength; i++) {
        wordMap.push(text[i].length)
    }
    return wordMap;
}

function objCon(name,count) { //object constructor
    this.name = name;
    this.count = count;
}

function maxNum() {
    var array1 = firstLoop();
    var num = Math.max.apply(Math, array1);
    return num;
}

function objArrCon() { //object array constructor
    var num = maxNum();
    var array1 = [];
    var i = 2;
    for ( i ; i <= num; i++) {
        var myObj = new objCon(i,0);
        array1.push(myObj);
    }
    return array1;
}

function objArrParse() { //updates the object with word info
    var array1 = firstLoop();
    var array2 = objArrCon();
    var loopLength1 = array1.length;
    var loopLength2 = array2.length;
    for (var i = 0; i < loopLength1; i++) {
        for (var m = 0; m < loopLength2; m++) {
            if (array2[m].name === array1[i]) {
                array2[m].count++;
                }
        }
    }
    return array2;
}

function objArrTrun() { //object array truncation
    var array1 = objArrParse();
    var len = array1.length;
    for (var i = 0;i < len; i++) {
        if (array1[i].count === 0) {
            array1.splice(i, 1);
            len--;
            }
        }
    return array1;
}

function formatter() {
    var strAr = objArrTrun();
    var arrayLength = strAr.length;
    var formatStr = [];
    for (var i = 0; i < arrayLength; i++) {
        var str = "Number of characters: " + strAr[i].name + ", Number of words with this length: " + strAr[i].count;
        formatStr.push(str);
    }
    return formatStr;
}

function clearBox(elementID) {
    document.getElementById(elementID).innerHTML = "";
}

function analyseButtonClick() {
    clearBox("results");
    var html = " ";
    var str = formatter();
    var len = str.length;
    for (var i = 0; i < len; i++) {
        html += "
" + str[i] + "
";
}
    document.getElementById("results").innerHTML += html;
}

function init() {
    var button = document.getElementById("analyse");
    button.onclick = analyseButtonClick;
}

window.onload = init;


texts: Constructing expressions that produce integers by only using digits in string '2017' and high school level operators and functions

texts:
At school, we have a competition where the winner is determined by the length of their unbroken sequence of expressions that evaluate to integers 0 to n.
You must use the next year's number in the correct order, every digit exactly once.

example:

0 = 2*0*17
1 = 2-01^7
2 = 2-0*17
...

The competition doesn't have a section for computer-aided results, but I thought I would try it for fun.

The problem is, I don't know how to do this efficiently.
In Python 3.5, I am using
itertools.product('2017()*/+-',repetitions=a)
where a is an integer 4 to n to gather different lengths of expressions,
and picking the results that evaluate to integers and fit the criteria.
This takes more than O(10^n) time.

Is there a way to do this more efficiently in Python?
If I should change language, what would be relatively easy to write but efficient?

Here is my whole code:

import itertools
import timeit

max_length = 8
min_val = 0
max_val = 100

start_time = timeit.default_timer()

year = '2017'
special_chars = '()*/+-'
these_chars = year + special_chars

def perm(seq, n):
    for p in itertools.product(seq, repeat=n):
        yield p

# Does every character in str_a occur in str_b
# in the right order and exactly once, with arbitrary in-betweens
def right_order(str_a, str_b):
    list_a = list(str_a)
    list_result = []
    for c in str_b:
        if c in str_a:
            list_result.append(c)
    if list_result == list_a:
        return True
    else:
        return False

def strs(length, dictionary):
    for a in perm(these_chars, length):
        cand = 0
        a = ''.join(a)
        try:
            cand = eval(a)
            if int(cand) != cand:
                continue
        except:
            pass

        if right_order(year, a) == True:
            if not any(c in '()' for c in str(cand)) and min_val <= cand <= max_val and '//' not in a: # To remove tuples and non-standard operators
                if cand in dictionary:
                    if len(dictionary[cand]) < 10:
                        dictionary[cand].append(a)
                else:
                    dictionary[cand] = [a]
    return dictionary

result_dict = {}
for i in range(len(year),max_length + 1):
    result_dict = strs(i, result_dict)

for k,v in sorted(result_dict.items()):
    key = str(k) + ': '
    values = "   ".join(v[0:4])

    print('{:<8} {}'.format(key, values),end=' ')

    print('...' * (len(v) > 4))

print()
stop_time = timeit.default_timer()
print('execution time: ' + str(stop_time - start_time))

input('EXIT')


texts: Pandas Groupby operation on a large dataset

texts:
I am working with a large dataset expanding > 50 years. Each year has ~10 million lines of records with multiple variables/columns. I need to perform groupby operations by location and time. My code runs extremely slow - it takes 2-5 hours to process 1 year's data depending on the number of stations in the year. I looked at a few posts on multiprocessing, but since I have no experiences with it, I am not sure if that method applies to my problem. I'd appreciate it if someone can point out how I can make the code more efficient.

#!/usr/bin/env python
# encoding: utf-8
import numpy as np
import pandas as pd
import datetime
import argparse
from scipy.stats.mstats import hmean

def Nstat(df):
    duMW = [6,7,8,9,30,31,32,33,34,35,98]
    d = {}
    d['NMW']  = df['MW'].count()
    d['NPW']  = df['PW'].count()
    d['NDU']  = df.loc[ isd['RH']<=90,'MW'].isin(duMW).sum()
    d['NDU6']  = (df.loc[ df['RH']<=90,'MW']==6 ).sum()
    d['NDU7']  = (df.loc[ df['RH']<=90,'MW']==7 ).sum()
    d['NDU8']  = (df.loc[ df['RH']<=90,'MW']==8 ).sum()
    d['NDU9']  = (df.loc[ df['RH']<=90,'MW']==9 ).sum()
    d['NDU30'] = (df.loc[ df['RH']<=90,'MW']==30).sum()
    d['NDU31'] = (df.loc[ df['RH']<=90,'MW']==31).sum()
    d['NDU32'] = (df.loc[ df['RH']<=90,'MW']==32).sum()
    d['NDU33'] = (df.loc[ df['RH']<=90,'MW']==33).sum()
    d['NDU34'] = (df.loc[ df['RH']<=90,'MW']==34).sum()
    d['NDU35'] = (df.loc[ df['RH']<=90,'MW']==35).sum()
    d['NDU98'] = (df.loc[ df['RH']<=90,'MW']==98).sum()
    d['NDUpw'] = (df.loc[ df['RH']<=90,'PW']==3).sum()
    d['VIS_Hvg'] = hmean(df.loc[df['VIS']>0,'VIS'])
    d['Vi_Avg'] = df['Vi'].mean()

    return pd.Series(d,index=['NMW','NPW',\
'NDU','NDU6','NDU7','NDU8','NDU9','NDU30','NDU31','NDU32',\
'NDU33','NDU34','NDU35','NDU98','NDUpw','VIS_Hvg','Vi_Avg'])

if __name__ =='__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("start_year",type=int,help='4-digit start year')
    parser.add_argument("end_year",type=int,help='4-digit end year')
    args = parser.parse_args()
    years = np.arange(args.start_year,args.end_year)

    dTypes = {
        'NMW':'Int32',\
        'NPW':'Int32',\
        'NDU':'Int32',\
        'NDU6':'Int32',\
        'NDU7':'Int32',\
        'NDU8':'Int32',\
        'NDU9':'Int32',\
        'NDU30':'Int32',\
        'NDU31':'Int32',\
        'NDU32':'Int32',\
        'NDU33':'Int32',\
        'NDU34':'Int32',\
        'NDU35':'Int32',\
        'NDU98':'Int32',\
        'NDUpw':'Int32'\
    }

    for iyr,yr in enumerate(years):
        print('process year {:d} at {:s}'.format(yr,datetime.datetime.now().strftime('%m-%d %H:%M:%S')))
        isd = pd.read_hdf('isd_lite_'+str(yr)+'.h5',dtype={'STATION':'str'})

        isd['YYYYMM'] = pd.to_datetime(isd['YYYYMMDDHH'],format='%Y%m%d%H').dt.strftime('%Y%m')
        isd['VIS'] = isd['VIS']/1000.
        isd['Vi'] = isd['VIS'].apply(lambda x: 1/x if x>0 else np.nan)

        print('>> groupby and output at {:s}'.format(datetime.datetime.now().strftime('%m-%d %H:%M:%S')))

        stn_month = isd.groupby(['STATION','YYYYMM']).apply(Nstat).reset_index().astype(dTypes)
        stn_month.to_csv('stn_month_'+str(yr)+'.csv',index=False,float_format='%.3f')

The last groupby (by STATION and YYYYMM) operation is most time consuming.
I have a fairly good work station (256 cores) and want to maximize the use of it.

A sample file is provided here. It takes 7 min to process this file. Not horribly long due to a small number of stations.


texts:
I have wrote a code to approximate the solution of a boundary value problem:

  x'' = p(t)x'(t)+q(t)x(t)+r(t)
  x(b) = beta in [a,b]

by using Runge-Kutta method of order N = 4.

Do you have any idea to make it short? I don't know how to call a subroutine as an argument in another subroutine. I had to copy the rk4 subroutine for each equation of U and V.

program test_linsht
!
! Linear Shooting method
! To approximate the solution of boundary value problem
!           x'' = p(t)x'(t)+q(t)x(t)+r(t)
!'          x(b) = beta in [a,b]
! and using Runge-Kutta method of order N = 4
!
!
!
implicit none
integer,parameter :: n = 2
integer,parameter :: nstep = 20
real(8) :: U(nstep)             ! U contains the solutions at each step
real(8) :: V(nstep),out(nstep)  ! V just like U for another equation
real(8) :: a,b,h,alph,beta,w
real(8) :: x(0:n)
integer :: i
a = 0.d0
b = 4.0
alph = 125.d-2
beta  = -95.d-2
h = (b-a)/nstep
! x = t0 x0 x'0
x = (/0.d0, alph, 0.d0/)

call rks4U(n,h,x,nstep,U)
a = 0.d0
b = 4.0
x = (/0.d0, 0.d0, 1.d0 /)
h = (b-a)/nstep

call rks4V(n,h,x,nstep,V)

! calculate the solution to the boundary value broblem
w = (beta - U(nstep))/V(nstep)
write (*,*) w,U(nstep),V(nstep)
!w = 0.485884
out = U + w * V
do i = 1,nstep
    write(*,100) i,i*h,U(i), w*V(i), out(i)
enddo
100 format (1x,I5,f10.2,f15.6,f15.6,f15.6)
end program

subroutine xprsysU(n,x,f)
! x prime of system of equations

    real(8), dimension(0:n) :: x,f
    integer :: n
    ! time is introduced as a new differential equation
    f(0) = 1.d0
    f(1) = x(2)
    f(2) = 2.*x(0)/(1+x(0)*x(0))*x(2)- 2./(1.+x(0)*x(0))*x(1) + 1.0
end subroutine

subroutine xprsysV(n,x,f)
! x prime of system of equations

    real(8), dimension(0:n) :: x,f
    integer :: n
    ! time is introduced as a new differential equation
    f(0) = 1.d0
    f(1) = x(2)
    f(2) = 2.*x(0)/(1+x(0)*x(0))*x(2)- 2./(1.+x(0)*x(0))*x(1)
end subroutine

subroutine rks4U(n,h,x,nstep,xout)

implicit none
      real(8) :: x(0:n)
      real(8) :: y(0:n), f(0:n,4)
      real(8) :: xout(nstep)
      integer :: i,k,n,nstep
      real(8) :: h
      !write(*,200) "k","t","x","y"
      !write(*,100) 0,x
      f = 0.
out:  do k = 1,nstep
          call xprsysU(n,x,f(0,1))
in1:      do i = 0,n
              y(i) = x(i) + 0.5*h*f(i,1)
              !print *, f(i,1)
          end do in1
          call xprsysU(n,y,f(0:n,2))
in2:      do i = 0,n
              y(i) = x(i) + 0.5*h*f(i,2)
          end do in2
          call xprsysU(n,y,f(0:n,3))
in3:      do i = 0,n
              y(i) = x(i) + h*f(i,3)
          end do in3
          call xprsysU(n,y,f(0:n,4))
in4:      do i = 0,n
              x(i) = x(i) + (h/6.0)* (f(i,1) + 2.0*(f(i,2) + f(i,3)) + f(i,4))
          end do in4
          xout(k) = x(1)
      end do out
      !100 format (1x,I5,f10.2,f15.8,f15.8)
      !200 format (1x,A4,2A10,A16)
end subroutine rks4U

subroutine rks4V(n,h,x,nstep,xout)

implicit none
      real(8) :: x(0:n)
      real(8) :: y(0:n), f(0:n,4)
      real(8) :: xout(nstep)
      integer :: i,k,n,nstep
      real(8) :: h
      !write(*,200) "k","t","x","y"
      !write(*,100) 0,x
      f = 0.
out:  do k = 1,nstep
          call xprsysV(n,x,f(0,1))
in1:      do i = 0,n
              y(i) = x(i) + 0.5*h*f(i,1)
              !print *, f(i,1)
          end do in1
          call xprsysV(n,y,f(0:n,2))
in2:      do i = 0,n
              y(i) = x(i) + 0.5*h*f(i,2)
          end do in2
          call xprsysV(n,y,f(0:n,3))
in3:      do i = 0,n
              y(i) = x(i) + h*f(i,3)
          end do in3
          call xprsysV(n,y,f(0:n,4))
in4:      do i = 0,n
              x(i) = x(i) + (h/6.0)* (f(i,1) + 2.0*(f(i,2) + f(i,3)) + f(i,4))
          end do in4
          xout(k) = x(1)
      end do out
      !100 format (1x,I5,f10.2,f15.8,f15.8)
      !200 format (1x,A4,2A10,A16)
end subroutine rks4V


texts: Effective way to remove white spaces from string

texts:
I have come up with this approach but I'm not convinced about its effectiveness. Is there any effective approach?

#include <string>
#include <iostream>

template <typename Container,  typename UnaryPredicate>
auto remove_if(Container& c, UnaryPredicate pred)
    -> decltype(c.begin())
{
    auto it = std::begin(c);
    while (it != std::end(c))
    {
        if(pred(*it))
        {
            it = c.erase(it);
        }
        else
        {
            ++it;
        }
    }
    return it;
}

template <typename Container, typename T>
auto remove(Container& c,  T const& value)
    -> decltype(c.begin())
{
    return remove_if(c,  [&](T const& t) { return t == value; });
}

int main()
{
    std::string str = " Text with some spaces ";
    remove(str, ' ');
    std::cout << str ;
}


texts:
My TableView consists of four cells (for blacklisting categories) with a boolean property (indicated with a checkmark) and another cell with a UISwitch embedded in it. My current controller is as follows:

class TableViewController: UITableViewController {
    var blacklisted = Set<Category>()
    var flags = Set<String>()

    @IBAction func toggle(_ sender: UISwitch) {
        if (sender.isOn) {
            print("if")
        } else {
            print("else")
        }
    }

    @IBAction func cancel(_ sender: UIBarButtonItem) {
        self.dismiss(animated: true)
    }

    @IBAction func done(_ sender: UIBarButtonItem) {
        ViewController.allowed = ViewController.allowed.subtracting(blacklisted)
        ViewController.flags = ViewController.flags.union(flags)

        print(ViewController.allowed)
        print(ViewController.flags)
        self.dismiss(animated: true)
    }

    var states = [PastState.UNSELECTED, PastState.UNSELECTED, PastState.UNSELECTED, PastState.UNSELECTED]

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if (indexPath.section != 0) {
            return
        }

        tableView.cellForRow(at: indexPath)?.accessoryType
                = (states[indexPath.row] == PastState.SELECTED)
                ? .none
                : .checkmark

        switch (indexPath.row) {
            case 0:
                TableViewController.toggleItem(if: states[0], set: &flags, with: "nsfw")
                break

            case 1:
                TableViewController.toggleItem(if: states[1], set: &flags, with: "religious", "political")
                break

            case 2:
                TableViewController.toggleItem(if: states[2], set: &blacklisted, with: Category.Programming)
                break

            case 3:
                TableViewController.toggleItem(if: states[3], set: &blacklisted, with: Category.Dark)
                break

            default: break
        }

        states[indexPath.row] = (states[indexPath.row] == PastState.SELECTED)
                ? PastState.UNSELECTED
                : PastState.SELECTED
    }

    static func toggleItem<T: Hashable>(`if` state: PastState, set: inout Set<T>, with items: T...) {
        if (state == PastState.UNSELECTED) {
            for item in items {
                set.insert(item)
            }
        } else {
            for item in items {
                set.remove(item)
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

I've been told the code is spaghetti code and to separate the model, but I'm not quite too sure how.


texts:
What I want to achieve is the following:

#include "tree.h"

#include <iostream>

int main() {

  Tree<std::string>* tA = new Tree<std::string>("A");
  Tree<std::string>* tB = new Tree<std::string>("B", tA);
  Tree<std::string>* tC = new Tree<std::string>("C", tA);
  Tree<std::string>* tD = new Tree<std::string>("D", tB);
  Tree<std::string>* tE = new Tree<std::string>("E", tB);
  Tree<std::string>* tF = new Tree<std::string>("F", tB);

  for (auto cur : *tA) {
    std::cout << "traversed from " << (cur->parent ? cur->parent->val : "NULL") << " to " << cur->val <<  std::endl;
  }

  // std::next(std::next(tF->begin()));

  return 0;
}

And here is my implementation.

#ifndef TREE_H
#define TREE_H

#include <iterator>
#include <stack>
#include <vector>

#include <iostream>

template <typename T>
class Tree {
 public:
  class iterator {
   public:
    using iterator_category = std::forward_iterator_tag;
    using value_type = T;
    using difference_type = std::ptrdiff_t;
    using pointer = T*;
    using reference = T&;

   public:
    iterator() = default;

    iterator(Tree<T>* const root);

    Tree<T>* operator*() const;

    iterator& operator++();

    bool operator!=(iterator const& other) const;

    Tree<T>* cur;

   private:
    std::stack<Tree<T>*> s_;
  };

 public:
  Tree() = default;

  Tree(T const& val, Tree<T>* parent = NULL);

  void* operator new(size_t size);

  iterator begin();

  iterator end();

  T val;

  Tree<T>* const parent = NULL;

 private:
  std::vector<Tree<T>*> children_;
};

template <typename T>
Tree<T>::iterator::iterator(Tree<T>* const root)
    : cur(root) {}

template <typename T>
Tree<T>* Tree<T>::iterator::operator*() const {
  return cur;
}

template <typename T>
typename Tree<T>::iterator& Tree<T>::iterator::operator++() {
  if (cur == NULL) {
    throw std::out_of_range("No more nodes for traversal");
  }

  for (auto& child : cur->children_) {
    s_.push(child);
  }

  if (s_.empty()) {
    cur = NULL;
  } else {
    cur = s_.top(); s_.pop();
  }

  return *this;
}

template <typename T>
bool Tree<T>::iterator::operator!=(Tree<T>::iterator const& other) const {
  return cur != other.cur;
}

template <typename T>
Tree<T>::Tree(T const& val, Tree<T>* const parent)
    : val(val), parent(parent) {
  if (parent) {
    parent->children_.push_back(this);
  }
}

template <typename T>
void* Tree<T>::operator new(size_t size) {
  void* p = ::new Tree<T>();
  return p;
}

template <typename T>
typename Tree<T>::iterator Tree<T>::begin() {
  return iterator(this);
}

template <typename T>
typename Tree<T>::iterator Tree<T>::end() {
  return iterator();
}

#endif

User should be able to directly modify val (hence it is public). However, they shouldn't be able to modify any parent/children relationship. Therefore I try to make parent a const pointer, but I cannot make children a list of const pointers because anything inside a std::vector must be assignable. I am considering exposing a GetChildren() method which returns a const std::vector, but that would be inconsistent with how I dealt with parent. Can anyone show a good way to resolve this?

General reviews are welcome. More specifically, I want to know

Is this a good and correct use of pointers?
Is the interface well designed?
Are there any const that I missed?


texts:
I had previously made a script for an Active directory password changer but i wanted to compress the main component into a function by itself to keep it small.

<?php
$_SERVER['rand'] = mt_rand(mt_getrandmax(),mt_getrandmax()); //This variable is just a transaction check for logs and debugging
$psVariables = '-rand "' . $input[0] . '" < NUL -base64_username "' . $input[1] . '" < NUL -base64_password "' . $input[2] . '" < NUL';//all the variables that needed to be submited to Powershell
$psInput = array($_SERVER['rand'],$username,$password);//The Array before a Transport layer takes effect
$psScriptPath = './psTest.ps1';//Path to the Script to execute

function Powershell_Safe($psQuery,$psInput, $psScriptPath){
    //string,array or string,string
    $i = 0;
    if(is_array($input)){foreach $input as $value{$input[$i] = base64_encode(utf8_decode($value)); $i++;}}else{$input = base64_encode($input);}//base64 Transport Layer - Shell_Exec runs the CLI for Windows before passing that to Powershell. Any user input can break the function and code inject at this stage if not encoded!
    $runtime = shell_exec('powershell.exe -ExecutionPolicy ByPass -command "'. $psScriptPath . '" <NUL '. $query);
    while($runtime !== FALSE && FALSE != stristr('Error:', $runtime))//If runtime is not equal to false AND if stristr() is Equal to false
        {print($runtime);}//It's Showtime - variable $runtime is what the powershell script returns to
    unset($psQuery, $psInput, $psScriptPath, $input);
}
?>


texts: Creating a list of list after traversing binary search tree in level order

texts:
Here is my code.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
 public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new LinkedList<List<Integer>>();
        if (root == null) {
            return list;
        } else {
            Queue<TreeNode> q = new LinkedList<>();
            q.add(root);
            while (!q.isEmpty()) {
                int size = q.size();
                LinkedList<Integer> layers = new LinkedList<>();
                while (size != 0) {
                    TreeNode current = q.poll();
                    layers.add(current.val);
                    if (current.left != null) {
                        q.add(current.left);
                    }
                    if (current.right != null) {
                        q.add(current.right);
                    }
                    size--;
                }

                list.add(layers);

            }
        }
        return list;

    }

}

Please let me know if any improvement/correction.


texts:
I'm working on a simple data storing program for my senior year (Secondary School / Grade 12), and there is a user sign-in functionality I've decided to implement. The way I've done this is by storing the usernames and passwords in a text file. They are stored as follows:

userName password
userName password
...

The usernames, I've decided to leave as plain text, as is decided by the user upon registration. The passwords however, I've decided to encrypt by inserting a special character ( '/' , '?' , ':', ...) between each of the characters entered by the user. This is simple to code as I've done:

// password is passed to the function as a string parameter
fstream writer;
writer.open("database.txt", ios::app);

int separators[16];

for (int i = 0; i < 16; i++)
{
    int randomi = rand() % (47 - 33 + 1) + 33;
    separators[i] = randomi;
}

for (int j = 0; j < password.length(); j++)
{
    int randomIndex = rand() % 6;
    writer << (int)password[j] << separators[randomIndex];
}

writer << "\n";

For the time being, I've decided to only use on of the special characters to figure out the decryption mechanism. So, using '/' as the special character, the following is my decryption code:

...
__int64 l=0;
...

for (int i = 0; i < a.length(); i = i + 2) //a is the password read from the file as a string.
{
    if (a[i] - 48 > 4)   //greater than 4 as the ASCII values of alphabets are above 50
    {
        l = l * 10;
        l = l + (a[i] - 48);  //yields the int value from the ASCII number.
        l = l * 10;
        l = l + (a[i + 1] - 48);
    }
}

The above code, takes in the password from the file, and scans for the number 4 (explained in the comment above); if the current number is not 4, it stores its int value in a variable called l. (Pardon the insignificant naming please), and does the same for the next letter, before incrementing i by 2, as the special character's ASCII value is 2 numbers.

There are drawbacks of this, mentioned at the bottom.

The verification mechanism for this system is as:

...
__int64 dy=0;
...
for (int i = 0; i < c.length(); i++) //password passed to decrypt function as string
{
    dy = dy * 100;
    dy = dy + (toupper(c[i])); //toupper so that the alphabet's ASCII value is only 2 digits
}

if (dy == l) // `l` from the decryption mechanism
{
    cout << "VALID";
}
else
{
    cout << "INVALID";
}

This works on the basis that it takes every character's ASCII value and converts it into an int for the entire word.

Example:

User entered password : Mayur
Stored password (in file after encryption) : 77476547894785478247       //while using only the special character `/`
Password converted into `int` format : 7765898582 //each 2 digits corresponds to a character in the user entered password
Decrypted password : 7765898582
Passwords match! Valid!

Major drawbacks:

At the moment, I have difficulties with decrypting for lower case alphabets due to triple digit ASCII values
Password size small due to overflow conditions of the integer format the decryted password is stored to verify.
At the moment, uses same special character to separate alphabets of actual password

I'd like you to pretty much to judge the system, and maybe if someone will post an estimate as to how hard this system would be to crack (given that the special characters will be random), and if there are more efficient ways to go about making this system more secure. (I might decided to encrypt usernames as well).


texts:
I've been learning a lot about functional programming lately and I've recently started learning Haskell to which I'm very new.

I've written a simple number guessing game and I would like to have feedback on what is good or bad about my code and how it could be improved.

#!/usr/bin/env runhaskell

import Text.Printf (printf)
import System.Random (randomRIO)

smallest = 1 :: Integer
biggest = 100 :: Integer

main :: IO ()
main = do
  secret <- randomRIO (smallest, biggest) :: IO Integer
  printf "Find the number between %d and %d.\n" smallest biggest
  loop secret 1 where
    loop :: Integer -> Integer -> IO ()
    loop secret tries = do
      guess <- readLn :: IO Integer
      case compare guess secret of
        LT -> do
          putStrLn "Too small!"
          loop secret $ succ tries
        GT -> do
          putStrLn "Too big!"
          loop secret $ succ tries
        EQ -> do
          printf "You found the number in %d tries!\n" tries


texts:
I have two solutions to the task and they are all passing the visible tests but when it is time to submit, I keep getting my failed to pass all tests. There are still some hidden tests my code isn't passing.

The task reads as follow:

Write a program that checks if a word supplied as the argument is an Isogram. An Isogram is a word in which no letter occurs more than once.

Create a method called is_isogram that takes one argument, a word to test if it's an isogram. This method should return a tuple of the word and a boolean indicating whether it is an isogram.

If the argument supplied is an empty string, return the argument and False: (argument, False). If the argument supplied is not a string, raise a TypeError with the message 'Argument should be a string'.

Example:

is_isogram("abolishment")

Expected result:

("abolishment", True)

The visible tests:

from unittest import TestCase

class IsogramTestCases(TestCase):
  def test_checks_for_isograms(self):
    word = 'abolishment'
    self.assertEqual(
      is_isogram(word),
      (word, True),
      msg="Isogram word, '{}' not detected correctly".format(word)
    )

  def test_returns_false_for_nonisograms(self):
    word = 'alphabet'
    self.assertEqual(
      is_isogram(word),
      (word, False),
      msg="Non isogram word, '{}' falsely detected".format(word)
    )

  def test_it_only_accepts_strings(self):
    with self.assertRaises(TypeError) as context:
      is_isogram(2)
      self.assertEqual(
        'Argument should be a string',
        context.exception.message,
        'String inputs allowed only'
      )

I wrote two different solutions to the task and they both passed the tests without errors but when I try submitting I got
 "Test Spec Failed
Your solution failed to pass all the tests".

Please any elegant way of solving this task?

Solution 1:

def is_isogram(word):
    if type(word) != str:
        raise TypeError('Argument should be a string')

    elif word == "":
      return (word, False)
    else:
        word = word.lower()
        for char in word:
            if word.count(char) > 1:
                return (word, False)
            else:
                return (word, True)

Solution 2:

def is_isogram(string):
    if isinstance(string, str) and len(string) != 0:
        string = string.lower()
        if len(string) == len(set(string)):
            result = True
        else:
            result = False
    elif not string:
      result = False
    else:
        raise TypeError('Argument should be a string')

    return string, result


texts: Clone a linked list with a random pointer

texts:
I'm working on a problem to clone a linked list (each node has a regular next pointer), and each node also has a random pointer which could point to any node in the linked list. Each linked list node has a unique ID and new cloned linked list node should have the same node ID.

One major concern in my current implementation is that I create another randomMap to map from a newly cloned linked list node ID to a newly cloned linked list node. I'm wondering if you have any ideas on saving the mapping (so that the additional \$O(n)\$ space could be saved).

from __future__ import print_function
from collections import defaultdict

class LinkedListNode:
    def __init__(self, nodeID):
        self.nodeID = nodeID
        self.nextNode = None
        self.randomNode = None
    def dump(self):
        node = self
        print (node.nodeID, node.nextNode.nodeID if node.nextNode else -1, node.randomNode.nodeID if node.randomNode else -1)
        node = self.nextNode
        while node:
            print (node.nodeID, node.nextNode.nodeID if node.nextNode else -1, node.randomNode.nodeID if node.randomNode else -1)
            node = node.nextNode
    def cloneList(self):
        node = self
        randomMap = defaultdict(LinkedListNode) # key node ID, value LinkedListNode in new list
        preNode = LinkedListNode(node.nodeID)
        randomMap[node.nodeID] = preNode
        head = preNode
        # setup regular part
        while node.nextNode:
            curNode = LinkedListNode(node.nextNode.nodeID)
            randomMap[node.nextNode.nodeID] = curNode
            preNode.nextNode = curNode
            preNode = curNode
            node = node.nextNode
        # setup up random part
        node = self
        while node:
            randomMap[node.nodeID].randomNode=randomMap[node.randomNode.nodeID]
            node = node.nextNode

        return head

if __name__ == "__main__":
    node1 = LinkedListNode('1')
    node2 = LinkedListNode('2')
    node3 = LinkedListNode('3')
    node4 = LinkedListNode('4')
    node5 = LinkedListNode('5')

    node1.nextNode = node2
    node2.nextNode = node3
    node3.nextNode = node4
    node4.nextNode = node5

    node1.randomNode = node3
    node2.randomNode = node4
    node3.randomNode = node5
    node4.randomNode = node1
    node5.randomNode = node2

    newList = node1.cloneList()
    newList.dump()

Expected output

1 2 3
2 3 4
3 4 5
4 5 1
5 -1 2


texts: Clone a GitLab private repo with Ansible

texts:
I have an ansible playbook that checks out a GitLab private repository. It utilizes the GitLab Users API to generate an SSH key for the target host and adds it to my GitLab user's SSH keys.

This works, but I'm wondering how I can make it better. In particular, each ssh key is titled based on the "{{ ansible_hostname }}_deployer", so each server must have a unique hostname. Is there a better way to name my SSH keys?

Any other suggestions you have are welcome.

Note that the repeated when: not user_ssh_keys.json | selectattr('title', 'equalto', deployer_gitlab_key_title) | list | length > 0 conditions ensure that the tasks that copy the host's SSH public key to GitLab do not run if GitLab already has an SSH key with the same title as what would be uploaded by this host.

group_vars/my_group

# gitlab vars
deployer_user: user
deployer_group: user
deployer_user_ssh_key_file: .ssh/id_rsa
deployer_gitlab_api: https://gitlab.example.com/api/v4

# Generated at
https://gitlab.example.com/profile/personal_access_tokens
deployer_gitlab_token: secret_token_here

deployer_gitlab_key_title: "{{ ansible_hostname }}_deployer"

roles/web/tasks/main.yml

- name: Make sure deployer user has ssh key
  user:
    name: '{{ deployer_user }}'
    generate_ssh_key: yes

- name: "Check if GitLab has this user's SSH key"
  uri:
    url: "{{ deployer_gitlab_api }}/user/keys"
    method: GET
    status_code: [200]
    headers:
      private-token: "{{ deployer_gitlab_token }}"
      Content-Type: "application/json"
  register: user_ssh_keys

- name: Assign ssh key to a variable
  shell:
    cat /home/{{ deployer_user }}/{{ deployer_user_ssh_key_file }}.pub
  register: deployer_user_public_key
  when: not user_ssh_keys.json | selectattr('title', 'equalto', deployer_gitlab_key_title) | list | length > 0

- name: Push the generated ssh key to the GitLab instance
  uri:
      url: "{{ deployer_gitlab_api }}/user/keys"
      method: POST
      status_code: [201, 400]
      headers:
        private-token: "{{ deployer_gitlab_token }}"
        Content-Type: "application/json"
      body: >
        {
          "title": "{{ deployer_gitlab_key_title }}",
          "key": "{{ deployer_user_public_key.stdout_lines.0 }}"
        }
      body_format: json
  when: not user_ssh_keys.json | selectattr('title', 'equalto', deployer_gitlab_key_title) | list | length > 0

- name: Ensure .ssh/config file exists
  file: state=touch path="/home/{{ deployer_user }}/.ssh/config"
  when: not user_ssh_keys.json | selectattr('title', 'equalto', deployer_gitlab_key_title) | list | length > 0

- name: Disable host key checking
  lineinfile: dest=/home/{{ deployer_user }}/.ssh/config line='Host *\n \tStrictHostKeyChecking no\n\tUserKnownHostsFile=/dev/null'
  when: not user_ssh_keys.json | selectattr('title', 'equalto', deployer_gitlab_key_title) | list | length > 0

- name: Add deploy group to sudoers file and validate
  lineinfile: dest=/etc/sudoers state=present regexp='^%{{ deployer_group }}' line='%{{ deployer_group }} ALL=(ALL) NOPASSWD:ALL' validate="visudo -cf %s"

- name: Checkout source code
  git:
    repo: "git@gitlab.example.com:john.doe/my_repo.git"
     dest: /home/{{ deployer_user }}/my_repo
    key_file: /home/{{ deployer_user }}/.ssh/id_rsa
    accept_hostkey: true


texts: Convert FoxPro/dBase DATETIME field to Win32 SYSTEMTIME struct

texts:
I'm trying to write a complete driver for Visual FoxPro's DBF format for Win32.  I found that the way that fields of the DATETIME type are stored in dBase files is a bit strange: it's an 8 byte string where the first four bytes represent the date as the number of days since January 1, 4713 BC, and the last four bytes represent the time as:

(Hours * 3600000) + (Minutes * 60000) + (Seconds * 1000)

The DATE type is much simpler as it represents a YYYYMMDD date as an ASCII string.

Here is my function for converting this date format into a SYSTEMTIME struct:

#include <Windows.h>
#include <sal.h>

_Pre_satisfies_(bFoxProDateTime != NULL && lpSystemTime != NULL && cbFxpTime >= 8)
_Post_satisfies_(lpSystemTime->wYear > 0)
_Success_(return == TRUE)
_Ret_range_(FALSE, TRUE)
_Check_return_
_Must_inspect_result_
BOOL WINAPI FoxProDateTimeToSystemTime(
    _In_reads_(cbFxpTime) BYTE *bFoxProDateTime,
    _In_ SIZE_T cbFxpTime,
    _Out_writes_(1) LPSYSTEMTIME lpSystemTime
)
{
    LONG lDate, lTime;
    CONST DOUBLE dConvert = 2440587.5;
    DOUBLE dTemp;
    LONGLONG uxTime;
    LONGLONG llTime;
    FILETIME ft;

    if (bFoxProDateTime == NULL || lpSystemTime == NULL)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
    ZeroMemory(lpSystemTime, sizeof(SYSTEMTIME));
    if (cbFxpTime < 8)
    {
        SetLastError(ERROR_INSUFFICIENT_BUFFER);
        return FALSE;
    }

    CopyMemory(&lDate, bFoxProDateTime, 4);
    CopyMemory(&lTime, bFoxProDateTime + 4, 4);

    dTemp = (lDate - dConvert) * 86400;
    uxTime = (LONGLONG)dTemp;
    llTime = Int32x32To64(uxTime, 10000000) + 116444736000000000;
    ft.dwLowDateTime = (DWORD)llTime;
    ft.dwHighDateTime = llTime >> 32;
    FileTimeToSystemTime(&ft, lpSystemTime);

    lpSystemTime->wHour = (WORD) (lTime / 3600000);
    lpSystemTime->wMinute = (WORD) ((lTime % 3600000) / 60000);
    lpSystemTime->wSecond = (WORD) (((lTime % 3600000) % 60000) / 1000);

    SetLastError(ERROR_SUCCESS);
    return TRUE;
}

The way the algorithm works right now is a bit clunky since it basically does three conversions in a row to end up with a SYSTEMTIME - first to a UNIX timestamp, then to a FILETIME struct, and finally to a SYSTEMTIME struct. This function works; I've tested it, but I'm wondering if I can get some feedback on how to improve the efficiency of this conversion.


texts:
My path to learning C++ has been a rough one. Currently, I'm writing a project and my knowledge is very outdated. While I can write code that accomplishes the tasks required, I'd like to improve and learn new aspects of the language.

So, I've written a class called Sequencer. It works. It's not great. It's not terrible. But it's based on old code. How would I improve the class with modern code?

#pragma once
#include <regex>
#include <string>
#include <experimental/filesystem>

class Sequencer
{
public:

    //////////////////////
    // CTors / DTor
    Sequencer(std::string const first_frame_in): first_frame_name(first_frame_in)
    {
        bool result = std::regex_search(first_frame_name, first_frame_regex_results, match_pattern);
        prefix = first_frame_regex_results[1];
        std::string frame = first_frame_regex_results[2];
        ext = first_frame_regex_results[3];
        first_frame = std::stoi(frame);
        digit_padding = frame.length();
        current_frame = first_frame;
        out_prefix = "_signature";
        file_delim = ".";

        get_last_frame();
    }

    ~Sequencer() {}

    Sequencer(Sequencer const&) = delete;
    void operator=(Sequencer const&) = delete;

    bool get_next_frame(std::string &next_frame, std::string &name_out)
    {
        if (current_frame <= last_frame)
        {
            tmp_num = add_padding(current_frame);
            next_frame = prefix + file_delim + tmp_num + file_delim + ext;
            name_out = prefix + out_prefix + file_delim + tmp_num + file_delim + "ppm";
            current_frame++;
            return true;
        }
        else
        {
            name_out = "";
            next_frame = "";
            return false;
        }
    }

private:

    void get_last_frame()
    {
        bool test = true;
        std::string tmpname;
        unsigned int i = current_frame + 1;
        do
        {
            tmpname = "C:\\ProgramData\\NVIDIA Corporation\\CUDA Samples\\v9.0\\3_Imaging\\MovieHasher\\data\\" + prefix + file_delim + add_padding(i) + file_delim + ext;
            test = std::experimental::filesystem::exists(tmpname);
            if (test)
                i++;
            else
                i--;
        } while (test);
        last_frame = i;
    }

    std::string add_padding(int frame_num_in)
    {
        std::string outval = std::to_string(frame_num_in);

        int length = outval.length();
        while (length < digit_padding)
        {
            outval = "0" + outval;
            length = outval.length();
        }

        return outval;
    }

    std::string first_frame_name;
    std::regex match_pattern = std::regex("([a-zA-Z]*).([0-9]*).(\\w{3})");
    std::smatch first_frame_regex_results;
    std::string prefix, ext, out_prefix, tmp_num, file_delim;
    int first_frame;
    int last_frame;
    int digit_padding;
    int current_frame;

};

A sample main file to run the Sequencer class

////////////////////////
// INCLUDES

//// System
#include <iostream>
#include <string>

//// User Defined
#include "../../Sequencer.h"

int main(int argc, char **argv)
{
    std::string image_filename = "prefix.00000.ext";
    std::string out_filename = "prefix_signature.00000.ppm";
    Sequencer sequencer(image_filename);

    bool tmp = true;
    do
    {
        tmp = sequencer.get_next_frame(image_filename, out_filename);
        if (tmp)
            std::cout << image_filename << ", " << out_filename << std::endl;
    } while (tmp);

    return 0;
}


texts: Web application for recording blog comments

texts:
I am working on some coursework for a simple Java EE web application that records blog comments. On the add comment page there are two fields: name and comments

I am using a RequestDispatcher to pass control to an acknowledgement.jsp if the fields are not empty, and an error.jsp if one (or both) are empty passing a relevant message to the acknowledgement page.

This is the logic I have:

  RequestDispatcher disp;
  if (!name.isEmpty() && !comment.isEmpty())
  {
      CommentBean commentBean = new CommentBean();
      commentBean.setComment(comment);
      commentBean.setName(name);
      req.setAttribute("comment", commentBean);

      disp = req.getRequestDispatcher("acknowledgement.jsp");
      disp.forward(req, resp);

      return;
  }
  else if (!name.isEmpty() && comment.isEmpty())
  {
      disp = req.getRequestDispatcher("error.jsp");
      statusMessage = "Comment field empty";
      req.setAttribute("status", statusMessage);
      disp.forward(req, resp);
  }
  else if (name.isEmpty() && !comment.isEmpty())
  {
      disp = req.getRequestDispatcher("error.jsp");
      statusMessage = "Name field empty";
      req.setAttribute("status", statusMessage);
      disp.forward(req, resp);
  }
  else
  {
      disp = req.getRequestDispatcher("error.jsp");
      statusMessage = "Name and comment fields empty";
      req.setAttribute("status", statusMessage);
      disp.forward(req, resp);
  }

The code does what I want but I can't help thinking this could be written a lot better although I am not sure how to go about it.


texts: Python implementation of Quicksort using list comprehensions

texts:
I wrote an implementation of quicksort that I think is pythonic. I based it off of this common Haskell implementation:

  quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
    let smallerSorted = quicksort [a | a <- xs, a <= x]
        biggerSorted = quicksort [a | a <- xs, a > x]
    in  smallerSorted ++ [x] ++ biggerSorted

I understand this is not an in-place sort. I also understand that it is optimized for Haskell, which handles recursion very well.

Here's my Python adaptation:

def quicksort(li):
    if li == []:
        return li
    p = li[0]
    lo = [ i for i in li[1:] if i <= p ]
    hi = [ i for i in li[1:] if i > p ]
    return quicksort(lo) + [p] + quicksort(hi)

I think it has the following upsides:

clean looking, pythonic
fast C implementation of linear partitioning

and the following downsides:

does not sort in place
possibly memory inefficient

What are some issues I should be aware of besides the above? Can the algorithm be improved in terms of memory complexity without sacrificing the simplicity and pythonic structure? Should I avoid recursion altogether? Does anyone see bugs or have proposed changes?


texts: Wrapping types with alignment requirements

texts:
Visual Studio 2013 still doesn't support the alignas keyword in C++11. This causes some problems with alignment of types in various situations. Thankfully the compiler will generate an error when it can't guarantee the alignment or at least give a warning.

To solve these errors and warnings I'm implementing a wrapper type that will wrap another type with some alignment restriction regardless of how the wrapper is aligned. Consider two wrapper objects A and B that themselves have arbitrary alignment. Let the wrapped datum be a and b respectively. Then A=B will assign a=b while still keeping a aligned regardless of how B was aligned because b in itself is aligned.

I'm looking for a review on the code on the account of syntax and possible weaknesses in the design and implementation.

template< typename T, std::size_t Align = 16>
class aligned_wrapper{
public:
    typedef T value_type;

    template<typename... Args>
    aligned_wrapper(Args&&... args){
        std::size_t space = sizeof(m_storage);
        auto raw_ptr = reinterpret_cast<void*>(&m_storage);
        auto ptr = std::align(Align, sizeof(T), raw_ptr, space);
        new (ptr)T(std::forward<Args>(args)...);
        m_object = reinterpret_cast<T*>(ptr);
    }

    ~aligned_wrapper(){
        get().~T();
    }

    aligned_wrapper& operator = (const aligned_wrapper& that){
        get() = that.get();
        return *this;
    }

    template<typename U>
    aligned_wrapper(const aligned_wrapper<U>& that)
        : aligned_wrapper(that.get())
    {}

    template<typename U>
    aligned_wrapper(aligned_wrapper<U>&& that)
        : aligned_wrapper(std::move(that.get()))
    {}

    inline T& get(){ return *m_object; }
    inline const T& get() const { return *m_object; }

    void swap(aligned_wrapper& that){
        using std::swap;
        swap(get(), that.get());
    }

    friend void swap(aligned_wrapper& lhs, aligned_wrapper& rhs){
        lhs.swap(rhs);
    }
private:
    std::aligned_storage_t<sizeof(T) + Align - 1, 1> m_storage;
    T* m_object{ nullptr };
};

Although it may look a bit funky, one of the key ideas is that once the aligned_wrapper is constructed, m_object will never change for that instance as the address of this will not change, this guarantees alignment. In other words, not assigning m_object in the assignment operator is intentional.


texts: Setting enum flags by string (in any order)

texts:
I want to set flags which are given in string representation in any order. And it is intimidating, because you have to check like 2^3 possible options in my occassion. I was just wondering is there any better way to do that than just simple brute-force. Any optimization and readability improvment would be great. This is my code:

[Flags]
public enum salaryFeatures
{
Children = 1,
Graduate = 2,
Disability = 4
}

class Program
{

public static void Main()
{
    string Employee = "10023 Mark Male 6.7 70 30 20 Children Graduate";
    salaryFeatures f;
    f = GetFeaturesByString(Employee);
}

public static salaryFeatures GetFeaturesByString(string fields)
{
    bool children = false;
    bool graduate = false;
    bool disability = false;
    salaryFeatures features = new salaryFeatures();

    if (fields.ToLower().Contains("children")) children = true;
    if (fields.ToLower().Contains("graduate")) graduate = true;
    if (fields.ToLower().Contains("disability")) disability = true;

    if (children && graduate && disability)
    {
        return features = salaryFeatures.Children | salaryFeatures.Disability | salaryFeatures.Graduate;
    }
    if (children && graduate)
    {
        return features = salaryFeatures.Children | salaryFeatures.Graduate;
    }
    if (children && disability)
    {
        return features = salaryFeatures.Children | salaryFeatures.Disability;
    }
    if (children)
    {
        return features = salaryFeatures.Children;
    }
    if (graduate && disability)
    {
        return features = salaryFeatures.Graduate | salaryFeatures.Disability;
    }
    if (graduate)
    {
        return features = salaryFeatures.Graduate;
    }
    if (disability)
    {
        return features = salaryFeatures.Disability;
    }
    return features;
}
}


texts:
The code returns a string ready to seed at sites like sudoku-solutions.com.

It works great but as I couldn't find other simple examples for my level I hope for some insights on this and ways to correct what is wrong.

let sudoku = [];

function shuffle(a) {
    for (let i = a.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [a[i], a[j]] = [a[j], a[i]];
    }
    return a;
}

function randomNumber() {
 let num = Math.floor(Math.random() * 9 + 1);
 return num;
}

function randomFiller(a) {
 while (a.length < 9) {
  let num = randomNumber();
  a.push(num);
  if (a.indexOf(num) < a.lastIndexOf(num)) {
   a.pop();
  }
 }
 return a;
}

function populateSudoku() {
 let arr = [];
 while (sudoku.length < 9) {
  arr = [];
  sudoku.push(Array.from(randomFiller(arr)));
 }
 return arr;
}

function arrange3x3() {
 let arr = [];
 let line1 = [];
 let line2 = [];
 let line3 = [];
 for (let i = 0; i < sudoku.length; i++) {
  line1.push(sudoku[i].splice(0, 3));
  line2.push(sudoku[i].splice(0, 3));
  line3.push(sudoku[i].splice(0, 3));
 }
 for (let i = 0; i < sudoku.length; i += 3) {
  sudoku[i].push(line1.splice(0, 3));
 }
 for (let i = 1; i < sudoku.length; i += 3) {
  sudoku[i].push(line2.splice(0, 3));
 }
 for (let i = 2; i < sudoku.length; i += 3) {
  sudoku[i].push(line3.splice(0, 3));
 }
 sudoku = [].concat.apply([], sudoku);
 return sudoku;
}

function shuffleY(lmr) {
 let check = false;
 let x = [];
 let y = [];
 let z = [];
 while (check === false) {
  for (let i = 0; i < sudoku.length; i++) {
   x.push(sudoku[i][lmr][0]);
  }
  for (let i = 0; i < sudoku.length; i++) {
   y.push(sudoku[i][lmr][1]);
  }
  for (let i = 0; i < sudoku.length; i++) {
   z.push(sudoku[i][lmr][2]);
  }
  if (x.every((element, index) => {
   return index === x.lastIndexOf(element);
  }) && y.every((element, index) => {
   return index === y.lastIndexOf(element);
  })) {
   check = true;
  } else {
   x.splice(0);
   y.splice(0);
   z.splice(0);
   for (let i = 0; i < sudoku.length; i++) {
    shuffle(sudoku[i][lmr]);
   }
  }
 }
}

function mirrorSudoku() {
 sudoku.forEach((element, index) => {
  sudoku[index] = [].concat.apply([], element);
 })
 let copy = JSON.parse(JSON.stringify(sudoku));
 for (let i = 0; i < sudoku.length; i++) {
  for (let j = 0; j < sudoku.length; j++) {
   copy[j][i] = sudoku[i][j];
  }
 }
 for (let i = 0; i < copy.length; i++) {
  sudoku[i].splice(0);
  sudoku[i].push(copy[i].splice(0, 3));
  sudoku[i].push(copy[i].splice(0, 3));
  sudoku[i].push(copy[i].splice(0, 3));
 }
}

populateSudoku();
arrange3x3();
shuffleY(0);
shuffleY(1);
shuffleY(2);
mirrorSudoku();
shuffleY(0);
shuffleY(1);
shuffleY(2);

sudoku = [].concat.apply([], sudoku);
sudoku = [].concat.apply([], sudoku);

console.log(sudoku.join(''));


texts:
I want an experienced Haskeller to critique my code and offer changes/suggestions (so I can learn the idioms of the language and culture around Haskell).

I've been using a Tabula Recta for my passwords and used a Python script someone wrote to generate the table and do table traversal.

I've been wanting to learn Haskell and decided to take on building the same program but in Haskell.

I'm new to Haskell but not functional programming (I have Scheme and Erlang under my belt - Erlang I use in production on a daily basis). I feel like I kept compositional style but I doubt I adhered to idiomatic Haskell.

{-# LANGUAGE BangPatterns #-}
{- |
Module      :  tabula.hs
Description :  Generates a tabula recta
Copyright   :  (c) Parnell Springmeyer
License     :  BSD3

Maintainer  :  ixmatus@gmail.com
Stability   :  experimental

Generates and manipulates a tabula recta.
-}

module Main where

import Control.Monad.CryptoRandom
import Crypto.Random

import Data.String.Utils
import Data.List.Split

main :: IO()
main = do
    values <- tabulay ['A'..'Z']
    putStrLn $ "    " ++ join " " (chunksOf 1 ['A'..'Z'])
    putStrLn $ "  + " ++ (take 52 $ cycle "- ")
    putStrLn $ join "\n" (reverse values)

tabulay :: [Char] -> IO [[Char]]
tabulay cmap = tabulay' cmap []
    where tabulay' [] acc    = do return acc
          tabulay' (x:xs) acc = do
            chars <- tabulax 26
            let formatted = [x, '|'] ++ chars
                spaced = join " " (chunksOf 1 formatted)
            tabulay' xs $! (spaced:acc)

tabulax :: Int -> IO [Char]
tabulax cint = tabulax' cint []
    where tabulax' 0 acc    = do return acc
          tabulax' iint acc = do
            val <- randomChoice characterMap
            tabulax' (iint-1) $! (val:acc)

characterMap :: [Char]
characterMap =
    let
        cmap = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9']
        symb = [',', '.', '/', '?', '~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '{', '[', ']', '}', '\\', '|', ':', ';', '"', '\'']
    in cmap ++ symb

randVal :: Int -> IO Int
randVal len = do
    g <- newGenIO :: IO SystemRandom
    let Right (int, _) = crandomR (0, len-1) g :: Either GenError (Int, SystemRandom)

    -- This MUST be strict - otherwise this function will keep too many file handles open
    return $! int

randomChoice :: [Char] -> IO Char
randomChoice ls = do
    randomIndex <- randVal (length ls)
    let val = ls !! randomIndex
    return val


texts:
I'm new to Ruby and as an exercise I implemented different factorial algorithms. Other rules are: raise an ArgumentError exception if n < 0 or if n is not an integer.

I'm interested in whatever feedback you can think of, including Ruby idioms (can something be implemented more idiomatic?). If you see anything that can be improved in any way, let me know.

# While loop
def factorial_w(n)
    validate(n)
    total = 1
    while n > 1
        total *= n
        n -= 1
    end
    total
end

# For loop
def factorial_f(n)
    validate(n)
    total = 1
    for i in (2 .. n)
        total *= i
    end
    total
end

# Recursive
def factorial_r_recursion(n)
    if n < 2
        1
    else
        n * factorial_r(n - 1)
    end
end

def factorial_r(n)
    validate(n)
    factorial_r_recursion(n)
end

# Tail-recursive
def factorial_tr_recursion(n, acc)
    if n < 2
        acc
    else
        factorial_tr(n - 1, n * acc)
    end
end

def factorial_tr(n, acc = 1)
    validate(n)
    factorial_tr_recursion(n, acc)
end

# Iterative with Range.each
def factorial_re(n)
    validate(n)
    if n == 0
        1
    else
        (2 .. n - 1).each {|i| n *= i}
        n
    end
end

# Iterative with Range.inject
def factorial_ri(n)
    validate(n)
    (1 .. n).inject(:*) || 1 # || 1 handles n = 0 so !0 = 1
end

# Iterative with Range.reduce
def factorial_rr(n)
    validate(n)
    (1 .. n).reduce(:*) || 1 # || 1 handles n = 0 so !0 = 1
end

# Stirling's Approximation, will return infinity if n > 170
def factorial_sa(n)
    validate(n)
    Math.sqrt(2 * Math::PI * n) * (n / Math::E) ** n
end

# Helper for argument validation
def validate(n)
    if n < 0 or not n.kind_of? Integer
        raise ArgumentError, "n must be an integer and >= 0"
    end
end


texts: Given a Tic-Tac-Toe gamestate return all wins as text

texts:
In a game of Tic-TacToe given a gamestate:
game_board = [ [1, 0, 1],
               [0, 1, 0],
               [0, 1, 0] ]

I have written the following piece of code to display the output of the gamestate in regards to wins:
game_board = [ [1, 1, 1],
               [0, 1, 0],
               [0, 1, 0] ]

# Horizontals
h = [str(i+1) + ' Row' for i, v in enumerate(game_board) if sum(v) == 3]

# Verticals
v = [str(i+1) + ' Col' for i in range(3) if sum([j[i] for j in game_board]) == 3]

# Diagonals
d = [['Left Diag', '','Right Diag'][i+1] for i in [-1, 1] if sum([game_board[0][1+i], game_board[1][1]], game_board[2][1-i]) == 3]

if any([h,v,d]):
    print('You won on:', h, v, d)
else:
    print('No win yet')

The output of this is:

You won on: ['1 Row'] ['2 Col'] []

I would like to know how my solution could be written in a more Pythonic manner?


texts:
I'm a C# developer looking to learn more about Python and how to think in a more functional programming manner.

I have the following which takes a series of grades and returns the average:

grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]

def grades_sum(scores):
    total = 0
    for score in scores:
        total += score
    return total

def grades_average(grades):
    return grades_sum(grades) / float(len(grades))

print(grades_average(grades))

What are some better functional programming / pythonic ways of approaching this problem?


texts: Can this architecture of base + derived classes be coded more efficient?

texts:
I've got some architecture in my code similar to this. It is about the Construct method in the base class in the example below. This method contains the logic for constructing a building, which is the same in every building. Yet different buildings may want to do things differently, like a different roof. So I've used events to do this. Is this a valid architecture? I know it works, but is there a better way? I want to leave the logic of constructing any building in the base class, and not override it to just build another roof and copying 66% of its code.
Remember this is an example. In the code I had to create, it not uses 3 functions in the Construct base method as the logic flow, but over a dozen.

Base class

public abstract class Building
{
    /// <summary>
    /// use this event in the derived class to lay another foundation.
    /// </summary>
    public event EventHandler OnFoundation;
    /// <summary>
    /// Use this event in the derived class to build different walls.
    /// </summary>
    public event EventHandler OnWalls;
    /// <summary>
    /// Use this event in the derived class to build a different roof.
    /// </summary>
    public event EventHandler OnRoof;

    /// <summary>
    /// The number of floors a building as determines how high it will be.
    /// </summary>
    public readonly int NumberOfFloors;

    /// <summary>
    /// Constructor.
    /// </summary>
    /// <param name="argNumberOfFloors">The number of floors a building as determines how high it will be.</param>
    protected Building(int argNumberOfFloors)
    {
        NumberOfFloors = argNumberOfFloors;
    }

    public void Construct()
    {
        //Lay the foundation.
        if (OnFoundation != null)
        {
            OnFoundation(this, new EventArgs());
        }
        else
        {
            Foundation();
        }
        //Build the walls
        if (OnWalls != null)
        {
            OnWalls(this, new EventArgs());
        }
        else
        {
            Walls();
        }
        //Build the roof
        if (OnRoof != null)
        {
            OnRoof(this, new EventArgs());
        }
        else
        {
            Roof();
        }
    }

    public void Foundation()
    {
        //Lay foundation
    }

    public void Walls()
    {
        for (int i = 0; i < NumberOfFloors; i++)
        {
            //Build walls
        }
    }

    public void Roof()
    {
        //Build roof
    }
}

Implementations

  Villa

public class Villa : Building
{
    public Villa() : base(2)
    {
        base.OnRoof += Villa_OnRoof;
    }

    /// <summary>
    /// A villa gets another roof, the rest stays the same
    /// </summary>
    void Villa_OnRoof(object sender, EventArgs e)
    {
        //Build another roof than the base class would.
    }
}

  SkyScraper

public class SkyScraper : Building
{
    public SkyScraper() : base(60)
    {
        base.OnFoundation += SkyScraper_OnFoundation;
    }

    void SkyScraper_OnFoundation(object sender, EventArgs e)
    {
        //A skycraper needs a better foundation.
    }
}


texts:
Given a list of pairs of integers that represent closed numeric intervals, I need to output a list of intervals where the adjacent intervals are merged together. The code assumes that the intervals do not overlap and that a <= b in all pairs (a, b).

Intervals (a,b) and (c,d) are adjacent if b + 1 == c.

merge []         = []
merge [x]        = [x]
merge ((a, b):(c, d):xs)
    | b + 1 == c = merge ((a, d):xs)
    | otherwise  = (a, b):(merge ((c, d):xs))

Maybe I can simplify this and use fold or something like that? Also, would converting this to a tail recursive version make sense here?


texts:
When hashing a password, I understand it is best not to use functions such as SHA1 or MD5.

This function is working fine and I want to know if it can be improved to increase site security.

class safePassword
{
    public static function makeSafe($password)
    {
        $salt = "mySalt";
        $hash = hash("sha256", $salt.".".$password);
        return $hash;
    }
}


texts: C++ std::vector with always valid iterator/pointer/index/key

texts:
Motivation: Have std::vector<std::unique_ptr<T>> accessibility at std::vector<T> speed.

std::vector have one inconvenience - you can't store pointers nor indexes to elements if the vector grows/alters.

To overcome this problem we usually use vector of pointers / deque (if only grow) / list / etc. Having our elements in heap have significant overhead on creation, traverse, and per element access.

To store "pointer" (or key) to element in vector I have back array of indices.

Condensed version:

struct Key{
   int index;  // index of key_indices
};

struct Element {
    int key_index;   // never changes
    Value value;
};
std::vector<Element> data;       // usual continious vector, no magic here
std::vector<int> key_indices;    // point to data[]. these values changes when erase/insert to data
std::vector<int> free_indices;

void emplace_back(){
   // if have no free_indices
   data.emplace_back();
   key_indices.emplace_back(data.size() - 1);
   data.back().key_index = key_indices.size() - 1;
}

Key get_key(std::vector<Element>::iterator iter){
    return {iter->key_index};
}

Value& operator[](Key key){
   return data[key_indices[key.index]].value;
}

Value& operator[](int index){
   return data[index].value;
}

void erase(std::vector<Element>::iterator iter){
    free_indices.push_back(iter->key_index);
    update_indices(iter + 1, data.end(), -1);
    data.erase(iter);
}
// same with insert, emplace_front, etc.

template<class iter>
void update_indices(iter from, iter to, int shift) {
    for (auto it = from; it != to; ++it)
    {
        key_indices[it->key_index] += shift;
    }
}

And used like:

KeyContainer<Data> list;

list.emplace_back().back().x = 100;
list.emplace_back().back().x = 200;

auto key = list.get_key(list.end()-1);

list.erase(list.begin());               // all indices invalidated
std::cout << list[key].x << std::endl;  // key still valid

In other words Key - is array index that always points to the same element, just like pointer to std::vector<std::unique_ptr<T>> element.

It is approximately 6-10 times faster than std::vector<std::unique_ptr<T>>/list on creation, 3-4 times faster than deque(at least with VS2015/clang). Same speed as vector when traverse/index access. And approx 10% slower with key access. I tried to use pointers instead of indices, but didn't see a difference.

Is there some ready library solution for container like this (vector with indices back-array (or ptr back-array))?

Full code as is (just a concept proof)


texts: Simple function to verify if a number is integer

texts:
Sometimes, there's the need to verify if a given number is an integer or a decimal. Since JavaScript doesn't distinguish between both, I've made an extremelly basic function.

function isInteger(num){
    var numCopy = parseFloat(num);
    return !isNaN(numCopy) && numCopy == numCopy.toFixed();
}

As you can see, it relies on checking if the number without decimals is the same as the parsed value. I'm not so confident about this.

Notice that this may return true for some scientific notation values.

Examples of results:

1.0: true (JavaScript treats <n>.0 as an integer)
1e3: true
1.2345e2: false (equivalent to 123.45)
1.2345e5: true (equivalent to 123450)
1e200: true (equivalent to Infinity)

Is there any more reliable way of checking? The results seem to be consistent with the expected results. Regular expressions are an option but they are clunky.


texts:
This is my solution to find the Number of distinct elements in an array. Is there away fast way to do this? It run-time is O(N).

    public int DistinctNumberOfItems( int[] A ) {

        if (A.length == 0) return 0;
        if(A.length == 1) return 1;

        Set<Integer> set = new TreeSet<Integer>();

        for (int i : A) {

            set.add(i);
    }
        return set.size();
}