texts:
I have tried to tackle this question as follows:

The program Calculates the next Working day, taking into account:
   - weekends (Saturdays and Sundays)
   - holidays happening in the middle of the week

param name="OrderDate" the date on which the order is placed
param name="workingDays" the number of workingdays to process the order
returns the date on which the Order is Requested to Ship

    public static DateTime getNextWorkingDay(DateTime OrderDate, int workingDays)
    {
        DateTime Holiday = new DateTime();
        List<DateTime> SelectedHolidays = new List<DateTime>();
        List<HolidayList> HolidayList = new List<HolidayList>();

        int calculatedWorkingDays=0;
        if (workingDays <= 5)
            calculatedWorkingDays = workingDays;
        else if (workingDays % 6 == 0)
        {
            calculatedWorkingDays = workingDays + workingDays / 6 * 2;
        }
        else
        {
            calculatedWorkingDays = workingDays + workingDays / 7 * 2;
        }

        HolidayList =  "Read the list from Json file";

        foreach (var holiday in HolidayList)
        {
            string year = DateTime.Today.Year.ToString();
            Holiday = DateTime.Parse(holiday.MonthAndDayValue + "-" + year);

            if (Holiday.Day == 1 && Holiday.Month == 1)
            {
                year = (DateTime.Today.Year + 1).ToString();
                Holiday = DateTime.Parse(holiday.MonthAndDayValue + "-" + year);
            }

            SelectedHolidays.Add(Holiday.Date);

            if (Holiday.DayOfWeek == DayOfWeek.Sunday || Holiday.DayOfWeek == DayOfWeek.Saturday)
            {
                //do nothing
            }
            else
            {
                if (Holiday.Date == OrderDate.Date)
                    OrderDate.AddDays(1);
                if (Holiday.Date > OrderDate.Date)
                {
                    int K = (int)(Holiday.Date - OrderDate.Date).TotalDays;
                    if (K <= calculatedWorkingDays)
                    {
                        calculatedWorkingDays++;
                    }
                }
            }
        }
        if (OrderDate.DayOfWeek == DayOfWeek.Sunday)
        {
            calculatedWorkingDays++;
        }
        else if (OrderDate.DayOfWeek == DayOfWeek.Saturday || OrderDate.DayOfWeek == DayOfWeek.Friday)
        {
            calculatedWorkingDays += 2;
        }

        // this is required date
        DateTime date_OrderRequestedToShip = OrderDate.AddDays(calculatedWorkingDays);

        //check if the last date fall on a non working day(holiday  or weekend)
        calculatedWorkingDays = 0;
        foreach (DateTime d in SelectedHolidays)
            if (d.Date == date_OrderRequestedToShip.Date)
                calculatedWorkingDays++;
        date_OrderRequestedToShip = date_OrderRequestedToShip.AddDays(calculatedWorkingDays);
        if (date_OrderRequestedToShip.DayOfWeek == DayOfWeek.Sunday)
        {
            calculatedWorkingDays = 1;
        }
        else if (date_OrderRequestedToShip.DayOfWeek == DayOfWeek.Saturday)
        {
            calculatedWorkingDays = 2;
        }

        return date_OrderRequestedToShip.AddDays(calculatedWorkingDays);
    }

The holiday list contains the month and day (MM/dd) part only with out the year part:

{
    "holidayName": "Memorial Day",
    "MonthAndDayValue": "05-30"
}

Can anyone help to tune up or suggest changes to make the code more efficient?


texts: Handling singularities in squircle parametric equations

texts:
In order to plot a squircle using its parametric equations:

The equations can be found in page 9 of this
this article:

Fong, Chamberlain. "Squircular Calculations." arXiv preprint arXiv:1604.02174 (2016).

Unfortunately the following singularities are not handled by those equations:

For t = 0, t = pi/2, t = pi, t = 3pi/2, and t=2*pi

Here is the code to plot these equations in Python
"""Plot squircle shape using its parametric equations"""
import numpy as np
from numpy import pi, sqrt, cos, sin, sign
import matplotlib.pyplot as plt

# FG stands for Fernandez-Guasti who introduced the algebric equations.
def FG_param(r, s, t):
    x = np.ones_like(t)
    y = np.ones_like(t)
    for i, _t in enumerate(t):
        if np.isclose(_t, 0.0):
            x[i] = r
            y[i] = 0.0
        elif np.isclose(_t, pi/2.0):
            x[i] = 0.0
            y[i] = r
        elif np.isclose(_t, pi):
            x[i] = -r
            y[i] = 0.0
        elif np.isclose(_t, 3*pi/2.0):
            x[i] = 0.0
            y[i] = -r
        elif np.isclose(_t, 2*pi):
            x[i] = r
            y[i] = 0.0
        else:
            x[i] = r*sign(cos(t[i]))/(s*sqrt(2)*np.abs(sin(t[i])))*sqrt(1 - sqrt(1-s**2*sin(2*t[i])**2))
            y[i] = r*sign(sin(t[i]))/(s*sqrt(2)*np.abs(cos(t[i])))*sqrt(1 - sqrt(1-s**2*sin(2*t[i])**2))
    return x, y

s = 0.7
r = 1.0
NTHETA = 90
t = np.linspace(0, 2*pi, NTHETA)

x, y = FG_param(r, s, t)

plt.gca().set_aspect('equal')
plt.scatter(x, y, s=5)
plt.show()

The function FG_param looks very clumsy. I appreciate any help to make it more compact and neat.
Thank you


texts:
It has been a while since I've implemented a QuickSort and I wanted to write it down like I remembered.

int MyPartition(List<int> list, int left, int right)
{
    int pivot = list[left];

    while(true)
    {
        while(list[left] < pivot)
            left++;

        while(list[right] > pivot)
            right--;

        if(list[right] == pivot && list[left] == pivot)
            left++;

        if(left < right)
        {
            int temp = list[left];
            list[left] = list[right];
            list[right] = temp;
        }
        else
        {
            return right;
        }
    }
}

void MyQuickSort(List<int> list, int left, int right)
{
    if(list == null || list.Count <= 1)
        return;

    if(left < right)
    {
        int pivotIdx = MyPartition(list, left, right);

        if(pivotIdx > 1)
            MyQuickSort(list, left, pivotIdx - 1);

        if(pivotIdx + 1 < right)
            MyQuickSort(list, pivotIdx + 1, right);
    }
}

Sample usage:

var list = RandomList(1000);
MyQuickSort(list, 0, list.Count - 1);


texts: Applying a dataframe function to a pandas groupby object

texts:
I am trying to apply a function to each group in a pandas dataframe where the function requires access to the entire group (as opposed to just one row). For this I am iterating over each group in the groupby object. Is this the best way to achieve this?

import pandas as pd
df = pd.DataFrame({'id': [1,1,1,1,2,2,2],
                   'value': [70,10,20,100,50,5,33],
                   'other_value': [2.3, 3.3, 7.4, 1.1, 5, 10.3, 12]})
def clean_df(df, v_col, other_col):
    '''This function is just a made up example and might
       get more complex in real life. ;)
    '''
    prev_points = df[v_col].shift(1)
    next_points = df[v_col].shift(-1)
    return df[(prev_points > 50) | (next_points < 20)]
grouped = df.groupby('id')
pd.concat([clean_df(group, 'value', 'other_value') for _, group in grouped])

The original dataframe is

    id  other_value value
0   1   2.3         70
1   1   3.3         10
2   1   7.4         20
3   1   1.1         100
4   2   5.0         50
5   2   10.3        5
6   2   12.0        33

The code will reduce it to

    id  other_value value
0   1   2.3         70
1   1   3.3         10
4   2   5.0         50


texts: Modifying a Word document template with OpenXML

texts:
I have the following program that opens a Word document template using the OpenXML library and replaces a couple of phrases with their counterparts from what will be a database (right now its just dummy data). Something about the if-else struture in the nested  foreach loops bothers me. Is there a better way I can accomplish this task? Would regular expressions be a more viable option?

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;

namespace OpenXmlSearchExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string templatePath = @"C:\users\example\desktop\template.dotx";
            string resultPath = @"C:\users\example\desktop\OpenXmlExample.docx";

            using (WordprocessingDocument document = WordprocessingDocument.CreateFromTemplate(templatePath))
            {
                var body = document.MainDocumentPart.Document.Body;
                var paragraphs = body.Elements<Paragraph>();

                // Iterate through paragraphs, runs, and text, finding the text we want and replacing it
                foreach (Paragraph paragraph in paragraphs)
                {
                    foreach (Run run in paragraph.Elements<Run>())
                    {
                        foreach (Text text in run.Elements<Text>())
                        {
                            if (text.Text == "Plan")
                            {
                                text.Text = string.Format("{0} {1} Plan", DateTime.Now.Year, "Q2");
                            }
                            else if (text.Text == "Project Name")
                            {
                                text.Text = "SUPER SECRET CODE NAME";
                            }
                            else if (text.Text == "WO-nnnn Name")
                            {
                                text.Text = "Maintenance";
                            }
                            else
                            {
                                Console.WriteLine(text.Text);
                                Console.ReadKey();
                            }
                        }
                    }
                }

                // Save result document, not modifying the template
                document.SaveAs(resultPath);
            }
        }
    }
}


texts: How random is this password-generating algorithm?

texts:
This code's sole purpose is to create a very random password, using letters and numbers.

I think that it fulfills its purpose, but I wonder, could it be done better? I'm not talking about efficiency, but security.

In your eyes, how secure is this method for generating passwords, and if it is barely secure at all, what better practices are there for this sort of thing?

import random  as r
import sys
import os
from subprocess import call
alpha_lower = "abcdefghijklmnopqrstuvwxyz"
alpha_upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
call('color a', shell=True)
class MutateSeed(object):
    def __init__(self, seed, alpha_lower, alpha_upper):
        self.seed = seed
        self.mutated_seed = []
        self.alphabet_lower = list(alpha_lower)
        self.alphabet_upper = list(alpha_upper)
    def mutate_seed(self):
        for x in range(self.seed):
            a = r.randint(0, 9)
            b = r.randint(0, 9)
            c = r.randint(0, 9)
            d = r.randint(0, 25)
            e = r.randint(0, 25)
            f = r.randint(0, 25)

            con = r.randint(1, 6)
            if con == 1:
                mut = a
            elif con == 2:
                mut = b
            elif con == 3:
                mut = c
            elif con == 4:
                lower_or_higher = r.randint(0, 1)
                if lower_or_higher == 0:
                    mut = self.alphabet_lower[d]
                elif lower_or_higher == 1:
                    mut = self.alphabet_upper[d]
            elif con == 5:
                lower_or_higher = r.randint(0, 1)
                if lower_or_higher == 0:
                    mut = self.alphabet_lower[e]
                elif lower_or_higher == 1:
                    mut = self.alphabet_upper[e]
            elif con == 6:
                lower_or_higher = r.randint(0, 1)
                if lower_or_higher == 0:
                    mut = self.alphabet_lower[f]
                elif lower_or_higher == 1:
                    mut = self.alphabet_upper[f]

            self.mutated_seed.append(mut)

def Display():
    os.system("cls")
    user_input = int(raw_input("Length of password: "))
    mutate_seed = MutateSeed(user_input, alpha_lower, alpha_upper)
    mutate_seed.mutate_seed()
    display_pass = "".join(str(x) for x in mutate_seed.mutated_seed)
    f = open('PasswordFile.txt', 'a+')
    f.write(display_pass)
    f.write("\n")
    print "\n" "Your Password: "+display_pass+ "\n"
    raw_input("Press Enter to continue: ")
    pass
while True:
    Display()


texts:
I've got a project I've been working on that connect to a file server and writes some data to a text file. In order to do this I added a textbox for the user to type their username and a passwordbox well for the password. In my models I have an interface called IPassword that looks like the following:

public interface IPassword
{
    SecureString Password { get; }
}

Using MVVM Light I created a RelayCommand and tied it to a button. When the button is clicked it calls the function ExportList (I've removed any code relating to my file server location):

    public void ExportList(object parameter)
    {
        var passwordContainer = parameter as IPassword;
        NetworkCredential credentials;
        string folder = String.Empty;

        if (passwordContainer != null && IsEnabled == true)
        {
            var securePassword = passwordContainer.Password;
            var password = ConvertToUnsecureString(securePassword);

            credentials = new NetworkCredential();
            credentials.UserName = Username;
            credentials.Password = password;
            credentials.Domain = "domain name";

            folder = "folder location";
            WriteToNetworkFolder(folder, credentials);
        }

        else
        {
            folder = "local folder location";
            WriteToLocalFolder(folder);
        }
    }

    private string ConvertToUnsecureString(SecureString password)
    {
        if (password == null)
        {
            return String.Empty;
        }

        IntPtr unmanagedString = IntPtr.Zero;
        try
        {
            unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(password);
            return Marshal.PtrToStringUni(unmanagedString);
        }

        finally
        {
            Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString);
        }
    }

    private void WriteToNetworkFolder(string folder, NetworkCredential credentials)
    {
        // Open the connection to the server
        using (new NetworkConnection(folder, credentials))
        {
            foreach (string location in LocationsPicked)
            {
                string fileName = folder + "\\" + location + ".txt";

                // Write out the lines to each text file
                try
                {
                    using (StreamWriter writer = new StreamWriter(fileName, true))
                    {
                        for (int i = 0; i < address.PhysicalAddresses.Count; i++)
                        {
                            writer.WriteLine(address.PhysicalAddresses[i]);
                        }
                    }
                }

                catch (IOException ioe)
                {
                    Console.WriteLine("The file was not written.");
                    Console.WriteLine(ioe.Message);
                    Console.WriteLine(ioe.StackTrace);
                }
            }

            UpdateStatusBar("Success! Your MAC address(es) were successfully exported!");
        }
    }

The main reason I did it this way was because you cannot use databinding to get the password from a passwordbox due to security reasons. Is this the best way to handle this situation? If not, then how would you recommend getting the password?


texts:
I am learning typescript with React and come up with this small program that each button count how many time by clicking and record which button got click. Please help me to take a look if all the code are the best practice.
import * as React from "react";
import "./styles.css";

interface ButtonContainerProps {
  options: string[];
}
interface ButtonProps {
  value: string;
  setSelectedOption(value: string): any;
}

const Button: React.FunctionComponent<ButtonProps> = (props): JSX.Element => {
  const { value, setSelectedOption } = props;
  const [count, setCount] = React.useState(0);
  const clickHandler = React.useCallback(() => {
    setCount(count + 1);
    setSelectedOption(value);
  }, [count, value, setSelectedOption]);
  return <button onClick={clickHandler}>{`${value}: ${count}`}</button>;
};

const Scoreboard: React.FunctionComponent<{
  selectedOption: null | string;
}> = ({ selectedOption }): JSX.Element => {
  return (

      {selectedOption
        ? `The selected option is ${selectedOption}`
        : `Please click following button to make an option`}

  );
};

const ButtonContainer: React.FunctionComponent<ButtonContainerProps> = ({
  options
}): JSX.Element => {
  const [selectedOption, setSelectedOption] = React.useState<string | null>(
    null
  );
  return (

      <Scoreboard selectedOption={selectedOption} />
      {options.map((option) => (
        <Button
          key={option}
          value={option}
          setSelectedOption={setSelectedOption}
        />
      ))}

  );
};
export default function App() {
  return (

Button Container

      <ButtonContainer options={["apple", "orange", "pear"]} />

  );
}


texts: More semantic way of achieving a hover tooltip effect

texts:
I have tried 2 approaches to creating a hover tooltip effect: one is rather simple and the other just a tinge complex. My questions is about semantics but also about which method is better even later on for code dubbing.

Simple CSS-3 tooltip:

*{
    box-sizing:border-box;
}

.block{
    position: relative;
    padding:15px 25px;
    border-radius: 50px;
    background: #444;
    color: #fff;
    position: relative;
    top: 150px;
    left: 50%;
    cursor: pointer;
}

.tooltip{
    position: absolute;
    bottom: 100%;
    z-index: 9999;
    color: #fff;
    background: red;
    padding:15px 5px;
    border-radius: 15px;
    width: 80px;
    margin-bottom: 20px;
    right: 50%;
    margin-right: -40px;
    font-weight: bold;
    text-transform: uppercase;

}

.tooltip:after{
    position: absolute;
    content: '';
    width: 0;
    height: 0;
    border: 8px solid transparent;
    border-top-color:orange;
    left: 50%;
    margin-left: -8px;
    top: 100%;
}

.tooltip{
    opacity: 0;
    transform:rotateZ(45deg);
    transform-origin:50% calc(100% + 6em);
    transition:transform .5s, opacity .2s;
    transition-timing-function: ease, cubic-bezier(.17,.67,.4,1.39);
}

.block:hover .tooltip{
    transform:rotateZ(0deg);
    transform-origin:50% calc(100% + 6em);
    opacity: 1;
}

Here's an external link.

The rather more complex CSS-3 hover tooltip:

   .tooltip {
  display: inline;
  position: relative;
  top: 150px;
  left: 150px;
  z-index: 999;
}

/* Trigger text */

.tooltip-item {
  background: rgba(0,0,0,0.3);
  cursor: pointer;
  display: inline-block;
  font-weight: 700;
  padding: 0 10px;
}

/* Gap filler */

.tooltip-item::after {
  content: '';
  position: absolute;
  width: 360px;
  height: 20px;
  bottom: 100%;
  left: 50%;
  pointer-events: none;
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
}

.tooltip:hover .tooltip-item::after {
  pointer-events: auto;
}

/* Tooltip */

.tooltip-content {
  position: absolute;
  z-index: 9999;
  width: 360px;
  left: 50%;
  margin: 0 0 20px -180px;
  bottom: 100%;
  text-align: left;
  font-size: 0.765em;
  line-height: 1.4;
  box-shadow: -5px -5px 15px rgba(48,54,61,0.2);
  background: #2a3035;
  opacity: 0;
  cursor: default;
  pointer-events: none;
}

.tooltip-effect-5 .tooltip-content {
  width: 180px;
  margin-left: -90px;
  transform-origin: 50% calc(100% + 6em);
  transform: rotateZ(45deg);
  transition: opacity .5s, transform .5s;
  transition-timing-function: ease, cubic-bezier(.17,.67,.4,1.39);
}

.tooltip:hover .tooltip-content {
  opacity: 1;
  transform: translate3d(0,0,0) rotate3d(0,0,0,0);
}

/* Arrow */

.tooltip-content::after {
  content: '';
  top: 100%;
  left: 50%;
  border: solid transparent;
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  border-color: transparent;
  border-top-color: #444;
  border-width: 10px;
  margin-left: -10px;
}

/* Tooltip content*/

.tooltip-text {
  font-size: 0.9em;
  line-height: 1.35;
  display: block;
  padding: 1.31em 1.21em 1.21em 0;
  color: #fff;
}

Here is an external link.

I just want to know which would actually be a better method overall.


texts: Finding Pythagorean Triple that sums to 1000

texts:
I am doing this Project Euler Question #9:

  A Pythagorean triplet is a set of three natural numbers, \$a < b < c\$, for which,

  $$a^2 + b^2 = c^2$$

  For example, \$3^2 + 4^2 = 9 + 16 = 25 = 5^2\$.

  There exists exactly one Pythagorean triplet for which \$a + b + c =
> 1000\$.
  Find the product \$abc\$.

I have implemented the code but I feel like it runs slow and doesn't perform well enough:

def check_pathagorean(a, b, c):
    return (a**2) + (b**2) == (c**2)

SUM = 1000

for i in range(1, SUM):
    for j in range(i+1, SUM):
        c = SUM - (i + j)
        if(check_pathagorean(i, j, c)):
            if i + j + c == SUM:
                print i * j * c
                break

What could I do to make this run faster and better?


texts:
Codacy is telling me this method has a complexity of 13. I need some tips on how to reduce it, more specifically inside the forEach loop.

I've already changed it from an if/else` if hell, but it seems it wasn't enough.

function addGenresAndThemesFromWork(work){
    let workDetails = {workId: work.$.id, genres: [], themes: []};
    let workInfo = work.info;

    if (typeof workInfo === 'object') {
        Object.keys(workInfo).forEach(function (key) {
            let workfInfoType = workInfo[key].$.type;
            let workInfoValue = workInfo[key]._;

            switch (workfInfoType.toLowerCase()) {
                case 'genres':
                    workDetails.genres.push(workInfoValue);
                    if (Genres.findOne({name: workInfoValue}) === undefined) {
                        Genres.insert({
                            name: workInfoValue
                        });
                    }
                    break;
                case 'themes':
                    workDetails.themes.push(workInfoValue);
                    if (Themes.findOne({name: workInfoValue.toLowerCase()}) === undefined) {
                        Themes.insert({
                            name: workInfoValue.toLowerCase()
                        });
                    }
                    break;
                case 'main title':
                    workDetails.name = workInfoValue;
                    break;
                case 'plot summary':
                    workDetails.plot = workInfoValue;
                    break;
                case 'objectionable content':
                    if (workInfoValue.toLowerCase() === 'ma') {
                        workDetails.mature = true;
                    }
                    break;
                case 'picture':
                    let workImg = workInfo[key].img[1];
                    if (workImg !== undefined) {
                        workDetails.picture = workImg.$;
                    } else {
                        if (workInfo[key].img[0] !== undefined) {
                            workDetails.picture = workInfo[key].img[0].$;
                        }
                    }
                    break;
                case 'alternative title':
                    if (workInfo[key].$.lang.toLowerCase() === 'ja') {
                        workDetails.alternativeTitle = workInfoValue;
                    }
                    break;
            }
        });
    }

    if (!_.has(workDetails, 'picture')) {
        workDetails.picture = {src: '/default.jpg', temporary: true};
    }

    persistWorkDetails(workDetails);
    }


texts: C# Multiple ASYNC requests single response (Promise like)

texts:
I'm no too good with async processes in C#. I need to implement method, that can be called multiple times by async requests, but request data and serve response once. I've created this method, inspired by common JS promise pattern:

private Task<bool> DoSomething(string key)
{
    // generating unique key
    string cacheKey = "do-comething-" + key;
    // searching cache for a Task in progress
    var cachedRequest = MemoryCache.Default.Get(cacheKey, null) as Task<bool>;

    // if found - return old Task
    if (cachedRequest != null)
    {
        return cachedRequest;
    }

    TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();

    CacheItemPolicy cip = new CacheItemPolicy()
    {
        AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(60))
    };

    // storing Task object in cache
    MemoryCache.Default.Set(cacheKey, tcs.Task, cip);

    try
    {
        // do something long here
        tcs.TrySetResult(true);
    }
    catch(Exception ex)
    {
        tcs.TrySetResult(false);
    }
    finally
    {
        MemoryCache.Default.Remove(cacheKey);
    }
    return tcs.Task;
}

Is it ok, or I'm totally out of it? Any advice will be highly appreciated. Thanks.


texts:
I've started a course about the MVC pattern applied to the web. I want to improve my PHP programming skills so I've decided to write a simple boilerplate for my webapps that use the front controller pattern. The code is working fine, but I think maybe it can be improved. Any suggestion about will be appreciated.

Front controller routing class

<?php

class Router{

  private $controller;
  private $model;
  private $path;

  public function __construct(Model $model, $tpl, Controller $controller){
    $this->model = $model;
    $this->tpl = $tpl;
    $this->controller = $controller;
  }

  public function route(){
      if(isset($_SERVER['PATH_INFO'])){
          $this->path = $_SERVER['PATH_INFO'];
          $this->pathSplit = explode('/', ltrim($this->path));
      }else{
          $this->pathSplit = '/';
      }
      if($this->pathSplit == '/'){
          echo $this->controller->index();
      }
      else{
          $req_ctr = ucfirst($this->pathSplit[1]).'Controller';
          $req_action = $this->pathSplit[2];
            if(file_exists($req_ctr.'.php')){
              $controller = new $req_ctr($this->model, $this->tpl);
              if(method_exists($controller ,$req_action)){
                echo $controller->$req_action();
              }
              #else{}
            }
            #else{}
        }
  }

}

?>

.htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php/$1 [L]


texts: Finding maximum Collatz sequence between 1-1000000

texts:
I'm trying to find maximum the Collatz sequence between 1 and 1000000. I wrote the following code below. I guess it is correct but it is extremely slow. Can you give me a few hints to make it faster?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool myfn(int i, int j) { return i<j; }

int collatz(int x);

int main()
{
    vector <int> myvector;
    for(int i = 1; i < 1000000; i++)
    {
        myvector.push_back(collatz(i));
    }

    cout<<*max_element(myvector.begin(),myvector.end(),myfn);

    return 0;

}

int collatz(int x)
{
    int counter = 1;

    while(1)
    {
        if(x == 1)
            break;

        if(x % 2 == 0)
        {
            x = x / 2;
            counter++;
        }
        else
        {
            x = 3 * x + 1;
            counter++;
        }
    }

    return counter;
}


texts: Count and group rows for six months prior

texts:
I've written the following query for SQL server:

SELECT YEAR(Meeting_Date) year, MONTH(Meeting_Date) month, COUNT(project) meetings
FROM
meetings
WHERE Meeting_Date BETWEEN
CAST(DATEPART(year,DATEADD(m,-6,GETDATE())) as varchar(4)) + '-' + CAST(DATEPART(month,DATEADD(m,-6,GETDATE())) as varchar(2)) + '-01'
AND
DATEADD(d,-1,CAST(DATEPART(year,GETDATE()) as varchar(4)) + '-' + CAST(DATEPART(month, GETDATE()) as varchar(2)) + '-01')
GROUP BY YEAR(Meeting_Date), MONTH(Meeting_Date)
ORDER BY YEAR(Meeting_Date), MONTH(Meeting_Date)

This code counts up how many meetings there were for the six months prior to this one.  It works perfectly, but I'm sure there's a better way of figuring the months than I have.


texts: React Component Reuse with 2 similar components

texts:
I have 2 variations of components that I wanted to create in React. They both use Radio buttons with the only difference is one adds an image to one side of it.

The first method will use just one component but use conditional logic to display the appropriate HTML:

    getImgDiv(iconFile) {
        return (

);
    }
    render() {
        var radioId = this.props.radioGroup + this.props.value.replace(" ", "");
        var iconFile = this.props.iconFile;
        var innerLabel = "label-inner no-img";
        var imgDiv = "";
        if (iconFile !== undefined && iconFile !== null && iconFile !== "") {
            iconFile = "/img/" + iconFile;
            innerLabel = "label-inner"; // add appropriate class when there is an image
            imgDiv = this.getImgDiv(iconFile);
        }

        return (

                <Field
                    name={this.props.radioGroup}
                    component="input"
                    type="radio"
                    value={this.props.value}
                    id={radioId}
                />

                        {imgDiv}

{this.props.text}

        );
    }

The second method, I was thinking of just creating 2 slightly different React classes to handle each case... 1 called RadioBtn the other RadioBtnIcon with the img section added:

function RadioBtn({ radioGroup, value, text }) {
    var radioId = radioGroup + value.replace(" ", "");
    return (

            <Field
                name={radioGroup}
                component="input"
                type="radio"
                value={value}
                id={radioId}
            />

{text}

    );
}

However, its bugging me that neither of these approaches seems particularly elegant...

Any suggestions guys?

Many Thanks,

Phil.


texts:
The searching algorithm that I created is dependent upon the sorting algorithm (which many of you have seen in my previous question). I believe that the sorting algorithm can't be better (for beginner-level programmers like me) but I would like to know what you think about my descriptions for the searching algorithm.
I would appreciate your insight on the commented sections of my code (again, for the searching algorithm).
And if there are any other changes I can make, please don't hesitate to let me know.
def sorting_algorithm(list):
    for index in range(1, len(list)):
        current = list[index]
        while index > 0 and list[index - 1] > current:
            list[index] = list[index - 1]
            index = index - 1
            list[index] = current
    return list

print("the sorted list is", (sorting_algorithm([45, 14, 1, 7, 98, 23, 102, 57])))

#SEARCHING ALGORITHM CODE:

def searching_algorithm(list, num):
    fir = 0                                        #the first number of the list.
    las = len(list)-1                              #the last number of the list.
    i = -1                                         #the index is at the last number of the list.
    while (fir <= las) and (i == -1):              #the first number is less than or equals to the last number and the
                                                   #index is at -1 (so the last number).
        mid = (fir + las) // 2                     #the middle number is equal to the first num divided by the last number
                                                   #but without the remainder part.
        if list[mid] == num:                       #if the middle number of the list equals the number
            i = mid                                #then the index is moved to the middle number of the list.
        else:                                      #if that isn't true then we move on to the following condition.
            if num<list[mid]:                      #if the number is less than the middle number of the list
                las = mid -1                       #then the index moves one to the right.
            else:                                  #if that isn't true either, then move on to the following condition.
                fir = mid +1                       #then the program will conclude that the number is the greater than
                                                   #the middle number.
    return i

print("your number is at index",searching_algorithm([1, 7, 14, 23, 45, 57, 98, 102], 23))


texts: CSS list-style with Font-Awesome toolkit

texts:
I will design a list with a Font-Awesome design arrows.
My code already works fine, but I will improve it.

ul.long_arrow_right_red,ul.long_arrow_right_gold     {list-style: none;}
ul.long_arrow_right_gold li:before {content:"\f178"; font-family: FontAwesome;display: block;float: left;width: 1.5em;color:gold;}
ul.long_arrow_right_red  li:before {content:"\f178"; font-family: FontAwesome;display: block;float: left;width: 1.5em;color:red;}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" />

Title

Lorem

Epsum

Title

Questions:

How to use an extra class which define only the color for the li icon? The text inside shouldn't change the color.

Existing other css code, which I use for text coloring:

.red{color:red;}
.gold{color:gold;}

I think it would be better not do have duplicate following statements:

font-family: FontAwesome;display: block;float: left;width: 1.5em;

How to combine them with a different content: definition?
If you have other improvement ideas, please tell me them.


texts:
To get my feet wet with shell scripting I wrote this "minimal command line
password manager" (aka pwm) taking inspiration from the well known pass.

It uses gpg and creates a keypair on the first start. It can perform four simple actions: list all entries stored, add, show the content of or remove an entry.

I'd like to get some feedback. I "spotted" two main issues and I also have two questions.

Issues:

read command will trim starting and trailing spaces;
[ -d $KEY_STORE_DIR ] as check to decide if keys should be generated may be a bit "weak" if for example the previous generation failed: it will return "true" (since $KEY_STORE_DIR will exists) and key generation command will never be called again causing troubles;

Questions:

Am I "abusing" gpg? I mean, am I doing something "stupid" with it? I don't use it a lot, I'm not an "expert", what I need is just a way to encrypt and decrypt files using the same passphrase (secret key passphrase here), I hope I'm using it in a "legit and safe" way.
I "wrapped" gpg commands inside strings and then called them simply writing $VAR_NAME. Is this somehow "bad practice" in shell scripting?

pwm

#!/bin/sh

# pwm: command line password manager.
# Encrypts passwords using gpg key created at the first start of the program.
# The private key passphrase acts as "master password" to show stored passwords,
# so choose it carefully.
# Passwords are stored inside $PWM_STORE_DIR while gpg home directory is
# $KEY_STORE_DIR.
#
# Usage:
#   pwm             # list all entries stored
#   pwm entry       # show content of entry
#   pwm -a entry    # add entry
#   pwm -r entry    # remove entry

PWM_STORE_DIR="$HOME/.pwm"
KEY_STORE_DIR="$PWM_STORE_DIR/.key"

GPG_BASE="gpg --quiet --homedir $KEY_STORE_DIR"
GPG_GEN_KEY="$GPG_BASE --full-generate-key"
GPG_ENCRYPT="$GPG_BASE --default-recipient-self --encrypt --output"
GPG_DECRYPT="$GPG_BASE --decrypt"

exit_with_error()
{
        printf "Error: %s\n" "$1" >&2
        exit 1
}

pwm_init()
{
        type gpg > /dev/null 2>&1 || exit_with_error "gpg is required"

        [ -d "$KEY_STORE_DIR" ] && return

        mkdir -p "$KEY_STORE_DIR"
        chmod -R 700 "$PWM_STORE_DIR"
        $GPG_GEN_KEY
}

add_entry()
{
        local entry="$1"

        [ -f $entry ] && exit_with_error "$entry already exists"

        if [ -t 0 ]; then
                printf "%s" "Enter password to be stored: "
                stty -echo
        fi

        read -r password

        if [ -t 0 ]; then
                stty echo
                printf "%b" "\n"
        fi

        printf "%s" "$password" | $GPG_ENCRYPT "$entry"
        chmod 600 "$entry"
}

show_entry()
{
        local entry="$1"

        [ -f $entry ] || exit_with_error "$entry doesn't exist"
        $GPG_DECRYPT "$entry" && printf "%b" "\n"
}

remove_entry()
{
        local entry="$1"

        [ -f $entry ] || exit_with_error "$entry doesn't exist"
        rm -i "$entry"
}

main()
{
        pwm_init

        case $# in
        0)
                ls -1 "$PWM_STORE_DIR"
                ;;
        1)
                show_entry "$PWM_STORE_DIR/$1"
                ;;
        2)
                case "$1" in
                "-a")
                        add_entry "$PWM_STORE_DIR/$2"
                        ;;
                "-r")
                        remove_entry "$PWM_STORE_DIR/$2"
                        ;;
                *)
                        exit_with_error "unknown option $1"
                        ;;
                esac
                ;;
        *)
                exit_with_error "wrong number of arguments"
                ;;
        esac
}

main "$@"


texts: JavaScript date format string to php date format string convert

texts:
Please find the following scenario, I've dynamic JS date format string from API but I am looking for the best way to convert the format that accepts in PHP date format. For now, I wrote it my own way but I doubt there should be a standard solution.
JS time format: YYYY-MM-DD / YYYY/MM/DD
Need PHP format: Y-m-d / Y/m/d
I've written the solution this way, please let me know if you find something else in a better way than this.
function dateFormatStringConvert(string $format) : string
{
    foreach (['-', '/'] as $operator) {
        if (strpos($format, $operator) !== false) {
            return implode($operator, array_map(function ($piece){
                return $piece[0]=='M' || $piece[0]=='D' ? strtolower($piece[0]) : $piece[0];
            }, explode($operator, $format)));
        }
    }
    return 'm-d-Y';
}


texts: Producing variants of a password based on command-line flags

texts:
I created a python script that attempts to find weak passwords based on a keyword.  I really enjoy programming with Python but I don't have a ton of experience so I'm hoping to get feedback on whether I should change how I have implemented anything below so that I am in line with best practices.

The code below is basically just processing all of the arguments and making calls to specific functions based on what flags/arguments are passed in.

Are there any obvious changes that I should make to the code below?  Is this the correct way to handle arguments of this nature?

#get the password and options from the command line
opts, args = getopt.getopt(sys.argv[1:], ':o:t:d:g:necf')
# print opts
# print args
password = args[0].lower()

outputFile = ''
target = ''
data = ''
text = ''
numbersFlag = False
copyFlag = False
fullFlag = False
requestFlag = False

for opt, arg in opts:
    if opt == "-o": #output file
        outputFile = arg
    if opt == "-f": #generate full password list
        fullFlag = True
    elif opt == "-t": #target of the POST request
        requestFlag = True
        target = arg
    elif opt == "-d": #data for the POST requet
        requestFlag = True
        data = arg
    elif opt == "-c": #copy output to the clipboard
        copyFlag = True
    elif opt == "-g": #text to be searched for in POST response
        requestFlag = True
        text = arg
    # elif opt == "-e": #append extra character
    #   letters.append(dummyCharacters)
    elif opt == "-n": #append numbers to end
        numbersFlag = True

#load full or basic password list based on arguments passed in
passwords = fullSub(password) if fullFlag else basicSub(password)
if fullFlag:
    passwords = fullSub(password)
elif numbersFlag:
    passwords = appendNumbers(password)
else:
    passwords = basicSub(password)

#save passwords to file
if outputFile != '':
    f = open(outputFile, 'w')
    for password in passwords:
        f.write("".join(password) + '\n')
    f.close()
#copy passwords to clipboard
elif copyFlag:
    pwList = ''
    i=0
    for password in passwords:
        i+=1
        pwList += "".join(password) + '\n'
    print `i` + " passwords copied to the clipboard."
    pyperclip.copy(pwList)
#make request using passwords
elif requestFlag:
    #make sure all required values were passed in
    if data == '':
        print "You must provide data in order to make a HTTP request.  Example: -d email=test@test.com&password={0}"
        sys.exit()
    elif text == '':
        print "You must specify what text to search for in the response in order to make a HTTP request. Example: -g success:true"
        sys.exit()
    elif target == "":
        print "You must specify a target URL in order to make a HTTP request"
        sys.exit()
    makeRequests(target, data, passwords,text)
else:
    i = 0
    for password in passwords:
        i+=1
        print "".join(password)
    print `i` + " passwords generated."


texts:
How good is this algorithm? Personally I think it's over-complicated and needs some improvement. Should I be using iterators here (I think it's "harder" this way) or indexing? Should I stick with a vector or try other containers? Is a vector (array) of pointers generally better than one of objects?

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
struct StringOccurrence //stores word and number of occurrences
{
    std::string m_str;
    unsigned int m_count;
    StringOccurrence(const char* str, unsigned int count) : m_str(str), m_count(count) {};
};

int main()
{
    std::string path;
    std::cout << "enter file name: " << std::endl;
    std::cin >> path;
    std::ifstream in(path);
    if (!in) //check if file path is valid
    {
        std::cerr << "failed to load file!" << std::endl;
        return -1;
    }

    std::vector<std::string>vec;
    std::string lineBuff;
    while (std::getline(in, lineBuff)) // write multiline text to vector of strings
    {
        vec.push_back(lineBuff);
    }

    std::vector<StringOccurrence*> strOc;
    std::string stringBuff;

    for (auto it = vec.begin(); it < vec.end(); it++) //itterate through each line
    {
        for (auto it2 = it->begin(); it2 < it->end();it2++) //itterate through each letter
        {
            if (*it2 != ' ') //keep adding letters to buffer until space (word)
            {
                stringBuff += *it2;
            }
            if (*it2 == ' ' || it2 + 1 == it->end()) //(need fix?)
            {
                if (*(it2 - 1) == ' ') //check for reccurring spaces so they are not counted as words
                {
                    continue;
                }
                for (auto it3 = strOc.begin(); it3 < strOc.end(); it3++)
                {
                    if (stringBuff == (*it3)->m_str) //if word was found increase count
                    {
                        (*it3)->m_count++;
                        goto end; //skip next step (need fix?)
                    }
                }
                strOc.push_back(new StringOccurrence(stringBuff.c_str(), 1)); //if word was not found add it
            end:
                stringBuff.clear(); //empty buffer for next word
            }
        }
    }

    std::ofstream out("test2.out"); //write to file
    for (auto it = strOc.begin();it < strOc.end();it++)
    {
        out << (*it)->m_str << ' ' << (*it)->m_count << std::endl;
    }

    return 0;
}


texts:
I'm creating an unordered list element in Backbone via Underscore templating:

Hello World

I'm wondering two things:

Is setting style still considered bad practice when creating elements through templating?
Should I be setting the style using jQuery after I generate the HTML from the template? This would be done inside of Backbone's render instead of inside of the template.

Something like:

render: function () {

    this.$el.html(this.template(this.model.toJSON()));
    this.$el('#FrontRack').css({ backgroundImage: ... }); // Example

    return this;
}


texts:
I'm developing a simple application that crawls web pages to obtain some information. For this I used and tested some libraries, like crawler4j, jsoup, jaunt and htmlunit. I change the crawler APIs several times because sometimes perceived that one served me better in a certain feature than the one I was using. I may have to do it again, and every time I do so I have to go around the code making various refactorings.

So I decide to separate the calls for these APIs in a kind of encapsulated class that holds all the operations I have to do with these API. So if I decide to change the crawler API I just point to another implementation of
CrawlerApiHandler.

I have troubles to identify one design pattern to mitigate this problem.

Below the 2 classes and the interface I created so far:

I named with suffix handler, but I don't know if it is it's appropriate.

/**
 * Created by alexandre on 29/01/2016.
 */
public interface CrawlerApiHandler {
    String visit (String url);
}

public class JauntApiHandlerImpl implements CrawlerApiHandler {
    UserAgent userAgent;

    public JauntApiHandlerImpl(UserAgent userAgent) {
        this.userAgent = userAgent;
    }

    @Override
    public String visit(String url) {
        try {
            return userAgent.visit(url).toString();
        } catch (ResponseException e) {
            return "";
        }
    }
}

public class JsoupCrawlerApiHandler implements CrawlerApiHandler {
    public static final String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36";

    @Override
    public String visit(String url) {
        try {
            return Jsoup.connect(url).timeout(20000)
                    .userAgent(USER_AGENT).get().toString();
        } catch (IOException e) {
            //LOG
            return "";
        }
    }
}


texts:
Challenge:

  Given two strings, A and B. Find if there is a substring that appears
  in both A and B.

Specifications:

  Several test cases will be given to you in a single file. The first
  line of the input will contain a single integer T, the number of test
  cases.

  Then there will be T descriptions of the test cases. Each description
  contains two lines. The first line contains the string A and the
  second line contains the string B.

  For each test case, display YES (in a newline), if there is a common substring.
  Otherwise, display NO.

Implementation:

import java.util.Scanner;
import java.util.Set;
import java.util.HashSet;

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

        for (int i = Integer.parseInt(input.nextLine()); i> 0; i--) {
            String sub1 = toDiscreteString(input.nextLine());
            String sub2 = toDiscreteString(input.nextLine());
            boolean success;
            if (sub1.length() < sub2.length()) {
                success = hasCommonSubString(sub1, sub2);
            } else {
                success = hasCommonSubString(sub2, sub1);
            }
            System.out.println(success ? "YES" : "NO");
        }
    }

    private static boolean hasCommonSubString(String shorter, String longer) {
        for (int i = 0; i < shorter.length(); i++) {
            if (longer.indexOf(shorter.charAt(i)) > -1) {
                return true;
            }
        }
        return false;
    }

    private static String toDiscreteString(String input) {
        Set<Character> set = new HashSet<>();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            if (set.add(input.charAt(i))) {
                result.append(input.charAt(i));
            }
        }
        return result.toString();
    }
}

This is a challenge found on HackerRank and passes all test cases. Is there a more efficient method? Is this overly-convoluted? Java 8 is available.


texts:
I implemented a Sudoku validation program.
Can this be optimized even further in terms of performance?

public class ValidSudoku {
    public boolean verifySudoku(int arr[][], int num, int i, int j, int row, int col) {
        return (verifyRow(arr, num, i, j, col)
               && verifyCol(arr, num, i, j, row)
               && verifyGrid(arr, num, i, j));

    }

    public boolean verifyRow(int arr[][], int num, int i, int j, int col) {
        int k;
        for (k = 0; k < col; k++) {
           if ((arr[i][k] == num) && (j != k)) {
                return false;
            }
        }
        return true;
    }

    public boolean verifyCol(int arr[][], int num, int i, int j, int row){
        int k;
        for (k = 0; k < row; k++) {
            if ((arr[k][j] == num) && (i != k)) {
                return false;
            }
        }
        return true;
    }

    public boolean verifyGrid(int arr[][], int num, int i, int j) {
        int k, l;
        int start_row = i - (i % 3);
        int start_col = j - (j % 3);
        for (k = 0; k < 3; k++) {
            for (l = 0; l < 3; l++) {
                if ((arr[k + start_row][l + start_col] == num) && (i != k + start_row) && (j != l + start_col)) {
                    return false;
                }
            }
        }
        return true;
    }

    public static void main(String args[]) {
        ValidSudoku v = new ValidSudoku();
        int i, j;
        int arr[][] = {{3, 1, 6, 5, 7, 8, 4, 9, 2},
                       {5, 2, 9, 1, 3, 4, 7, 6, 8},
                       {4, 8, 7, 6, 2, 9, 5, 3, 1},
                       {2, 6, 3, 4, 1, 5, 9, 8, 7},
                       {9, 7, 4, 8, 6, 3, 1, 2, 5},
                       {8, 5, 1, 7, 9, 2, 6, 4, 3},
                       {1, 3, 8, 9, 4, 7, 2, 5, 6},
                       {6, 9, 2, 3, 5, 1, 8, 7, 4},
                       {7, 4, 5, 2, 8, 6, 3, 1, 9}};
        for (i = 0; i < 9; i++) {
            for (j = 0; j < 9; j++) {
                if (!v.verifySudoku(arr, arr[i][j], i, j, 9, 9)) {
                    System.out.print(arr[i][j] + "nay");
                }
            }
        }
    }
}


texts: Method that filters a list parameters based on different fields

texts:
I have this code which is a callback for Filter in WPF ICollectionView. When I run code analysis, the cyclometic complexity is reported to be 11. I consider this line by line comparison gives a better readability. How can I improve the cyclomatic complexity or improve this code in general?

 private bool FilterLicenseList(object item)
 {
     var license = item as LicenseEntry;
     if (!string.IsNullOrEmpty(Filter.Firm) && !license.Firm.Contains(Filter.Firm)) return false;
     if (!string.IsNullOrEmpty(Filter.RegistrationCode) && !license.RegistrationCode.Contains(Filter.RegistrationCode)) return false;
     if (!string.IsNullOrEmpty(Filter.LicenseCode) && !license.LicenseCode.Contains(Filter.LicenseCode)) return false;
     if (!string.IsNullOrEmpty(Filter.Branch) && !license.Branch.Contains(Filter.Branch)) return false;
     if (Filter.Active != null && license.Active != Filter.Active) return false;
     return true;
  }


texts: Extracting pattern and simplifying testing

texts:
I observe the same pattern in a number of my classes but can't extract/abstract it due the tight coupling inside each particular implementation.

Having the class accepting an optional number of dependencies onto its constructor:

public Repository(IBuilder, IFormatter, ILoader, ISelector)

With the single method passing its arguments to the first dependency. Passing result to the second. And so on. Returning result of the last dependency:

public XElement Do(int i)
{
    string q = _builder.Build(i);
    string f = _formatter.Format(q);
    XDocument d = _loader.Load(f);
    XElement r = _selector.Select(d);
    return r;
}

(names of the classes, methods and variables are random, just to illustrate the pattern)

Can it be refactored to decouple the flow from the types of dependencies, arguments and return values?

It also will simplify the (unit) testing because currently I make sure that a dependency N passes its result to a dependency N+1:

[TestMethod]
public void Do_Should_Pass_Result_Of_Build_To_Format()


texts: Python merge sort for a list containing distinct values

texts:
This code below is what I think should be the implementation of merge sort in Python and it works as expected. It sorts the given list, where we can safely assume that all values are distinct. But after considering some online implementations I am doubtful about mine. So the base question is "Is this even Merge sort?".

def merge(arr):
    # base case
    length = len(arr)
    half = length//2
    if length == 1 or length == 0:
        return arr
    # recursive case
    firstHalf = merge(arr[:half])  # sort first half
    secondHalf = merge(arr[half:])  # sort second half
    length_firstHalf = len(firstHalf)
    length_secondHalf = len(secondHalf)
    sortedList = []

    i, j = 0, 0  # variables for iteration
    while i != length_firstHalf and j != length_secondHalf:  # add elements into the new array until either of then two sub arrays is completely traversed
        if firstHalf[i] > secondHalf[j]:
            sortedList.append(secondHalf[j])
            j += 1
            continue
        if firstHalf[i] < secondHalf[j]:
            sortedList.append(firstHalf[i])
            i += 1
    return(sortedList + firstHalf[i:] + secondHalf[j:])  # return the array after adding whats left of sub array which wasnt completely traversed


texts:
I'm looking for some assistance with a PHP script I'm writing. It creates a table that is then exported to an Excel file for download.

The issues as I see them are as follows:

$students contains 559 items and the $classes has 22 items and $attributes has 6 items:

    <?php foreach($students as $student){
    $pupil = Students::retrieveByPK($student['adno']); ?>

    <?php echo strtoupper($pupil->surname); ?>
    <?php echo $pupil->first_name; ?>
    <?php echo $pupil->year_group; ?>
    <?php foreach($classes as $class){
        $shortYear = str_replace('Year ', '',$pupil->year_group);
        $slashPos = strpos($class['class_name'],'/');
        $className = $shortYear.substr($class['class_name'],1);
        $classId = Classes::idFromClassName($className);
        foreach($attributes as $attribute){
           $attr = AttributeResults::getExportAttribute($pupil->adno, $classId, $attribute['attribute_id']); ?>
        <?php echo $attr[0]['attribute_value']; ?>
        <?php } ?>
     <?php } ?>

    <?php } ?>

I'm essentially running the AttributeResults::getExportAttribute method in the region of 74000 times. Is there a better way of bringing this data back?


texts: Encryption via multiplication of hex-converted, multiplied ASCII values

texts:
The idea behind the encryption is that it stores the key within the final encrypted password. When the user inputs a password for the first time, they also have to pick an element from a list of elements, and that determines where in the final, encrypted password the key is stored.

This is crucial for decryption.

The algorithm proceeds as follows:

User inputs a password.

The password is split into the individual characters, then stored in a list.

User inputs a key. (The key corresponds to an element in a list in the program, either 1, 2 or 3)
Each character in the list is translated into its ASCII number, and the original list is overwritten.
Each ASCII number is then multiplied by a random number.

The random number is stored as the variable x.

Each multiplied number is then converted into hex.
Random hex values are added to either side of the already encrypted password.
The element of the list that corresponds to the key (random_key) is replaced by the hex value of x.
The final encrypted password is stored in a file.

Note: Decryption is possible, but, I'm still working on it.

import random
import getpass

def joinit(iterable, delimiter):
    it = iter(iterable)
    yield next(it)
    for x in it:
        yield delimiter
        yield x

password = getpass.getpass('Please input a password.\n')
lst = []
key = input('Please pick a list number. Write it down!!')
random_key = [1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4]
for i in range(0, len(password)-1):
    lst.append(ord(password[i]))
print lst
x = random.randint(1,1000)
for i in range(0, len(password)-1):
    lst[i] *= x
for i,z in enumerate(lst):
        lst[i] = hex(z)
print lst
i = 2
lst2 = []

for i in range(0,4):
    hexhex = random.randint(1000,2000)
    hex(hexhex)
    lst.insert(0,hex(hexhex))
    print hexhex
for i in range(0,4):
    hexhex = random.randint(1000,2000)
    hex(hexhex)
    lst.append(hex(hexhex))
    print hexhex
lst[key] = hex(x)
result = []
for e in lst:
    result.append(e)
    result.append('|')
result.pop()

penultimate = ''.join(str(v) for v in result)
print result
print '\n'*3
print penultimate
file = '/home/vhx/Documents/code/tkinter/encryption/password.txt'
target = open(file, 'w')
target.truncate()
target.write(penultimate)

I designed this encryption method for a login system that encrypts the inputted password before comparing it to the one stored in the file. This way the password is never decrypted, and thus cannot (hopefully) be stolen.

I have a few questions:

Can the code be made any more efficient? Is there anything in there that can be simplified or removed altogether?
Is the idea itself sound (security wise)?
Has something like this been tried before?


texts:
I'm currently playing with D3.js.

While doing so I use this JSON-file as a data source: http://codepen.io/chriscoyier/pen/taqCe

Example of the structure:

{
  "fathers" : [
    {
      "id" : 0,
      "married" : false,
      "name" : "Robert Wilson",
      "sons" : null,
      "daughters" : [
        {
          "age" : 21,
          "name" : "Nancy"
          },
        {
          "age" : 30,
          "name" : "Amy"
          }
        ]
      },
    {
      "id" : 1,
      "married" : true,
      "name" : "Robert Thomas",
      "sons" : null,
      "daughters" : [
        {
          "age" : 22,
          "name" : "Melissa"
          },
        {
          "age" : 6,
          "name" : "Susan"
          }
        ]
      },
      ...
    ]
  }

I'm only interested in "daughters".
I have mapped the objects into a flat array structure.
The code I used:

var fathers = data.fathers,
      separator = '-------------------',
      persons = []; // collector array

   // Filling the collector array with the
   //   desired data.
   fathers.forEach(function(value) {

     value['daughters'].forEach(function(value) {
       persons.push(value);
     });

   });

It works fine. My complete code here: http://codepen.io/mizech/pen/WrNzJe

But I wonder:
Aren't there better ways (in native JavaScript, no frameworks) then iterating?

Would be pleased if anyone has an idea and would share it.


texts: Make a method that uses Expression> for filtering and sorting more flexible

texts:
I have a method in a service that performs a Linq-to-SQL query:
public async Task<IEnumerable<Incident>> GetIncidentsAsync<TOrderBy>(
    Expression<Func<Incident, bool>> whereExpression,
    Expression<Func<Incident, TOrderBy>> orderByExpression
)
{
    return await (
        from i in _context.Incidents
        // inner join
        .Include(i => i.IncidentType)
        .Where(whereExpression)
        .OrderBy(orderByExpression)
        // left-outer join
        join ft in _context.Driver on i.FaultTypeId equals ft.Id into ift
        from faultTypes in ift.DefaultIfEmpty()
        // left-outer join
        join v in _context.Vehicles on i.VehicleSerialNo equals v.VehicleSerialNo into iv
        from vehicles in iv.DefaultIfEmpty()
        select new Incident
        {
            Id = i.Id,
            IncidentTypeId = i.IncidentTypeId,
            IncidentType = i.IncidentType,
            // datetimes
            Occurred = i.Occurred,
            Reported = i.Reported,
            Resolved = i.Resolved,
            //
            VehicleSerialNo = i.VehicleSerialNo,
            Vehicle = vehicles,
            //
            DriverSerialNo = i.DriverSerialNo,
            Driver = drivers
        }
   ).ToListAsync();
}

Improvements:

having to manually compose the Incident to be returned feels like an anti-pattern
handle situations where the whereExpression is null; this will try an exception now
handle situations where the orderByExpression is null; this will try an exception now
change the sorting direction from ascending to descending by changing the orderByExpression (if this is possible)
is there value to marking the method as <TOrderBy>?


texts:
Is there a better (functional or more idiomatic) way to get the first positive number that is not included in a set?

val set = Set(4, 1, 2, 0, 5)
var x = 0
while(set(x)) x += 1
println(x) // Should print 3


texts:
Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters.

For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb".

I found few solutions online like. I felt they were bit too complex. I have tried to simply the solution. But it still lacks readability. How can i further improve?

public class DailyCodingProblem13 {
    public static void main(String args[]) {
        String s = "abcba";
        int k = 2;
        int result = solution(s, k);
        System.out.println(result);

        s = "aabacbebebe";
        k = 2;
        result = solution(s, k);
        System.out.println(result);

        s = "aabbcc";
        k = 3;
        result = solution(s, k);
        System.out.println(result);
    }

    static int solution(String s, int k) {
        int n = s.length();
        int max = 0;
        String maxLengthString = null;
        if (n == 0 || k == 0) {
            return max;
        } else {
            StringBuilder window = new StringBuilder();
            Set<Character> set = new HashSet<>();
            for (int i = 0; i < n; i++) {
                Character ch = s.charAt(i);
                // If
                if (set.size() == k && !set.contains(ch)) {
                    // Fetch the last index of the first character at window. Discard the string
                    // before the last index.
                    window = new StringBuilder(
                            window.substring(window.lastIndexOf(Character.toString(window.charAt(0))) + 1));
                    set.clear();
                    for (int j = 0; j < window.length(); j++) {
                        set.add(window.charAt(j));
                    }
                }
                set.add(ch);
                window.append(ch);
                if (window.length() > max) {
                    max = window.length();
                    maxLengthString = window.toString();
                }
            }
        }
        System.out.println("String with max length is " + maxLengthString.toString());
        return max;
    }

}

Note: This is my huumble effort to create a opensource project with best solutions for leetcode problems. This is not for increasing my score in any coding challenges.

Link to my project.


texts:
I have inherited the Java function below, and it works the way it should, but you have to look at it for a minute to figure out exactly what is going on. Is there a more succinct or elegant way to encode this logic?

private Float applyFactors(Float originalValue, Float localFactor, Float globalFactor){
    if (globalFactor == null || globalFactor == 0){
        if (localFactor == null || localFactor == 0){
            return null;
        } else {
            return localFactor * originalValue;
        }
    } else {
        if (localFactor == null || localFactor == 0){
            return globalFactor * originalValue;
        } else {
            return localFactor * originalValue * globalFactor;
        }
    }
}


texts:
I wrote my own implementation of the linux cat command in C for my computer laboratory class. We were asked to replicate its functionality with no options passed as arguments or with just the -b, -n and -s options.

I'm posting the code here because, although it works fine, i feel a little bit insecure about. Firstly because i think i "over-coded" it a bit, specially on the option handling part, and also, because i'm still not very confortable working with pointers and so i am not very sure if my approach does not generate memory leaks or malfunctions.

Here it is:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#define BUF_SIZE 1024

int readStdin(int index, int bflag, int nflag){
  char buffer[BUF_SIZE];
  while(fgets(buffer, BUF_SIZE, stdin)){ //reads from the standard input and prints the input
    if (nflag){
      printf("     %d  %s", index, buffer);
      index++;
    }
    if (bflag){
      if (*buffer == '\n'){
        printf ("%s", buffer);
      }
      else{
        printf ("     %d  %s", index, buffer);
        index++;
      }
    }
    else {
      printf("%s", buffer);
    }
  }
  return index; //returns the incremented index to perpetuate its use
}

int readFile(char* filename, FILE* fp, int index, int bflag, int nflag){
  char ch;
  char s[BUF_SIZE];
  if (fp==NULL){ //in case the file doesn't exist
    printf("%s: No such file or directory\n", filename);
    exit(1);
  }

  if (bflag){
    while ((fgets(s,BUF_SIZE,fp))){
      if (strcmp(s,"\n") == 0){
        printf (" %s", s);
      }
      else {
        printf ("     %d  %s", index, s);
        index++;
      }
    }
    fclose(fp);
  }
  if (nflag){
    while ((fgets(s,BUF_SIZE,fp))){
      printf ("     %d  %s", index, s);
      index++;
    }
    fclose(fp);
  }
  else{
    while ((ch=fgetc(fp)) != EOF){ //printing loop
      putchar(ch);
    }
    fclose(fp);
  }
  return index;
}

void readArgs(int argc, char* argv[]){
  FILE* fp;
  int index = 1; //line index. to be used in case -b or -n is passed as an argument
  int option; //option passed as argument
  int bflag = 0; //-b option deactivated by default
  int nflag = 0; //-n option deactivated by default
  opterr = 0; //deactivates getopt's default error messages

  //checks if there are options passed as argument and updates their flags
  while ((option = getopt(argc, argv, "bn")) != -1){
    switch (option){
      case 'b':
              bflag = 1;
              break;
      case 'n':
              nflag = 1;
              break;
      case '?': //in case there was some problem
              exit(1);
    }
  }

  if (bflag == 1 && nflag == 1){ //if -b and -n are passed as argument, b overrides n
    nflag = 0;
  }

  for (int i=optind; i<argc; i++){
    if (*argv[i] == '-'){ //in case of '-' in argv[i], reads from stdin and prints
      index = readStdin(index, bflag, nflag);
      clearerr(stdin);
    }
    else { //prints the contents of the file in *argv[i]
      fp = fopen(argv[i], "r");
      index = readFile(argv[i], fp, index, bflag, nflag);
    }
  }
}

int main(int argc, char* argv[]){
  if (argc<2){ //if there are no arguments
    readStdin(1,0,0);
    return 0;
  }
  readArgs(argc, argv); //otherwise
  return 0;
}

I didn't implement the -s option because i cant think of a way to handle it at the same time as the other options. That's why i think that the way i am handling the options part is a bit inefficient.

Any suggestions?


texts:
I wrote a simple client for handlersocket server, but I'm not a professional Java programmer and would like to know the opinion of Java developers on my code.

Well I have not yet decided how to implement a class HSResult.

My project is here

HSResult store initial query and answer as List of ChannelBuffers, where each ChannelBuffer it chunk of response according to the protocol.

package kom.handlersocket.result;

import org.jboss.netty.buffer.ChannelBuffer;
import kom.handlersocket.query.HSQuery;
import kom.handlersocket.core.SafeByteStream;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class HSResult {
    private final HashMap<HSQuery, List<ChannelBuffer>> resultSet =
        new LinkedHashMap<HSQuery, List<ChannelBuffer>>();
    private final Charset charset;

    public HSResult(Charset charset) {
        this.charset = charset;
    }

    public void add(HSQuery query, List<ChannelBuffer> result) {
        resultSet.put(query, result);
    }

    public void debug() {
        SafeByteStream output = new SafeByteStream(1024, 65536, charset);

        for (Map.Entry<HSQuery, List<ChannelBuffer>> entry: resultSet.entrySet()) {
            entry.getKey().encode(output);
            System.out.print(new String(output.toByteArray(), charset));
            output.reset();

            for (ChannelBuffer buffer : entry.getValue()) {
                System.out.print(buffer.toString(charset));
                System.out.print("-");
            }

            System.out.println();
        }
    }
}


texts: Project Euler #82 - path sum: three ways

texts:
Project Euler problem 82 asks:

Here's my solution:

def main():
    matrix = [
        [131, 673, 234, 103,  18],
        [201,  96, 342, 965, 150],
        [630, 803, 746, 422, 111],
        [537, 699, 497, 121, 956],
        [805, 732, 524,  37, 331]
    ]

    size = len(matrix)
    best = [matrix[row][0] for row in range(size)]

    for col in range(1, size):
        column = [matrix[row][col] for row in range(size)]
        tmp = column[:]

        for i in range(size):
            column[i] += best[i] # right

            for j in range(0, i): # up
                if sum([best[j]]+tmp[j:i+1]) < column[i]:
                    column[i] = sum([best[j]]+tmp[j:i+1])

            for k in range(i, size): # bottom
                if sum([best[k]] +tmp[i:k+1]) < column[i]:
                    column[i] = sum([best[k]] +tmp[i:k+1])

        best = column
        #print(best)

    return min(best)

if __name__ == "__main__":
    print(main())

Please advise how it can be improved.


texts:
Code: I have a list of ~15,000 Euclidean points which represent a connected graph. I'm trying to solve/approximate the traveling salesman problem with this graph.

Problem: Finding neighbors, i.e. calculating the distance between each point, is very slow.

The points are stored in a vector as City objects:

class City {
public:
    City(int id, int xCoord, int yCoord);

    int getCityID() const;
    int getXCoord() const;
    int getYCoord() const;

    void addNeighbor(const City &city);
    void removeNeighbor(int cityID);
    unsigned long getNeighborCount();
    Neighbor nearestNeighbor();
private:
    int id;
    int xCoord;
    int yCoord;
    std::vector<Neighbor> neighbors;
};

And neighbors are added like so:

void City::addNeighbor(const City &city) {
    int distance = Utilities::distanceSquared(*this, city);

    // Prevent cities listing themselves as neighbors
    if (distance > 0) {
        Neighbor neighbor(city.getCityID(), distance);
        neighbors.push_back(neighbor);
    }
}

And the distance is calculated by this function:

unsigned int Utilities::distanceSquared(City a, City b) {
    return static_cast<unsigned int>(
        pow(b.getXCoord() - a.getXCoord(), 2) +
        pow(b.getYCoord() - a.getYCoord(), 2)
    );
}

Finally, I test the speed of this operation like so:

// Get input
std::string filename = "tsp_example_3.txt";
std::vector<City> input = Utilities::readFile(filename);

for (int c1 = 0; c1 < input.size(); c1++) {
    for (int c2 = 0; c2 < input.size(); c2++) {
        input[c1].addNeighbor(input[c2]);
        // Utilities::distanceSquared(input[c1], input[c2]); // ~30 seconds
    }
}

When I simply calculate the distance between points (Utilities::distanceSquared()), it takes about 30 seconds (I'm not sure if this is good or bad for doing simple math on ~225,000,000 integers). When I try to use my addNeighbor() function, the program runs for at least ten minutes without completing.

Any ideas on how I might speed up this operation?


texts: Using encryption/hashing to create a secure login

texts:
I am creating a login for an encrypted chat application which retrieves login information from a MySQL database. I have got to the point where I feel pretty confident that (to the best of my knowledge) it is relatively secure. I am trying to learn so feel free to criticize!

import hashlib
import mysql.connector
from tkinter import *
from tkinter import messagebox
from cryptography.fernet import Fernet

chat = Tk() #Api I am using to create the GUI for the application

#Connect to MySQL database
try:
    loginFRetrieve = open("LK.bin", "rb") #Retrieving Encryption key from file
    retrivedKey =  loginFRetrieve.read()
    loginFRetrieve.close()

    loginFRetrieve = open("LC.bin", "rb") #Retrieving MySQL server login credentials
    retrivedLC = loginFRetrieve.read()
    loginFRetrieve.close()

    cipher = Fernet(retrivedKey)
    retrivedLC = cipher.decrypt(retrivedLC) #Decrypting server login data from file
    retrivedLC = retrivedLC.decode('utf-8')
    lC = retrivedLC.split()

    mydb = mysql.connector.connect(host=lC[0],user=lC[1],passwd=lC[2],database=lC[3])
    del(lC)
except mysql.connector.Error as err:
    chat.withdraw()
    messagebox.showerror("Database Error", "Failed to connect to database")
    exit()

mycursor = mydb.cursor()

#hashPass hashes and returns a string of characters using SHA-256 algorithm
def hashPass(hP):
    shaSignature = \
        hashlib.sha256(hP.encode()).hexdigest()
    return shaSignature

#userExists checks a database too see if username exists in the database
def userExists(userName):
    mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % userName)
    userResult = mycursor.fetchall()
    if userResult:
        return True
    return False

#Creates a new user in the connected SQL database.
def newUser(nU, nP):
    if userExists(nU) == False:
        mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % nU)
        mycursor.fetchall()
        r = hashPass(nP)
        sql = "INSERT INTO logins(username, passwordhash) VALUES(%s,%s)"
        val = (nU, r)
        mycursor.execute(sql, val)
        mydb.commit()
        chat.title(string="User created")
    else:
        messagebox.showwarning("User Creation Error", "User already exists")

#Checks the connected SQL database for an existing user.
def existingUser(uN, pW):
    if userN.get() != "":
        if userExists(uN) == True:
            encryptedPass = hashPass(pW)
            mycursor.execute("SELECT * FROM logins")
            passResult = mycursor.fetchall()
            for row in passResult:
                if row[1] == uN and row[2] == encryptedPass:
                    chat.title(string="Login Successful!")
                elif row[1] == uN and row[2] != encryptedPass:
                    messagebox.showerror("Login Error", "Password does not match our records")
        else:
            messagebox.showerror("Login Error", "User does not exist")
    else:
        messagebox.showwarning("Login Error", "Please enter a username")


texts:
This is a relatively simple implementation of the Sieve of Eratosthenes in Rust. The main objective is to find the \$n\$th prime quickly when \$n\$ might grow to huge numbers.

pub fn nth(n: u32) -> u32 {
    // A convenient variable that will help in simplifying a complicated expression
    let x = if n <= 10 { 10.0 } else { n as f64 };

    // The prime counting function is pi(x) which is approximately x/ln(x)
    // We need the inverse of that. A good estimate is ceil(x * ln(x * ln(x)))
    let limit: usize = (x * (x * (x).ln()).ln()).ceil() as usize;
    let mut sieve = vec![true; limit];
    let mut count = 0;

    // Exceptional case for 0 and 1
    sieve[0] = false;
    sieve[1] = false;

    for prime in 2..limit {
        if !sieve[prime] {
            continue;
        }
        if count == n {
            return prime as u32;
        }
        count += 1;

        for multiple in ((2 * prime)..limit).step_by(prime) {
            sieve[multiple] = false;
        }
    }
    return <u32>::max_value();
}

This entire function would be present in main.rs or lib.rs, as necessary.

Please feel free to nitpick on any aspect of the code. Suggestions to make the code cleaner or more efficient are welcome.


texts: Find the longest line in 2D (MxM) array (vertical, horizontal, or diagonal)

texts:
Find the length of the longest line with given square (MxM) matrix. (vertical, horizontal, or diagonal allowed) (Length of the longest line = number of consecutive 1's)

i.e.)
input:

{
{0,0,0,0,0,0,0,0},
{0,0,1,0,1,0,0,0},
{0,1,0,1,0,0,0,0},
{1,1,1,1,1,1,1,0},
{0,1,0,0,0,1,0,0},
{1,1,0,0,0,0,1,0},
{0,1,0,0,0,0,0,1},
{0,0,0,0,0,0,0,0}
}

output: 7 (The 4th horizontal row is the longest line in this case.)

My java code:

public class LongestLine {
    private int hmax = 0;
    private int vmax = 0;
    private int rdmax = 0; // right down direction
    private int ldmax = 0; // left down direction

    public int longestLine(int[][] grid) {

        for(int i = 0; i < grid.length; i++) {
            for(int j = 0; j < grid[i].length; j++) {
                if(grid[i][j] == 1) update(grid, i, j);
            }
        }

        return Math.max(Math.max(hmax, vmax), Math.max(rdmax, ldmax));
    }

    private void update(int[][] grid, int i, int j) {
        int h = 1, v = 1, rd = 1, ld = 1;

        if(j < grid[i].length - 1 && grid[i][j+1] == 1) {
            if(j == 0 || grid[i][j-1] != 1) h = updateH(grid, i, j+1, h);
        }
        if(i < grid.length - 1 && grid[i+1][j] == 1) {
            if(i == 0 || grid[i-1][j] != 1) v = updateV(grid, i+1, j, v);
        }
        if(j < grid[i].length - 1 && i < grid.length - 1 && grid[i+1][j+1] == 1) {
            if(j == 0 || i == 0 || grid[i-1][j-1] != 1) rd = updateRD(grid, i+1, j+1, rd);
        }
        if(j > 0 && i < grid.length - 1 && grid[i+1][j-1] == 1) {
            if(j == grid[i].length - 1 || i == 0 || grid[i-1][j+1] != 1) ld = updateLD(grid, i+1, j-1, ld);
        }

        hmax = Math.max(h, hmax);
        vmax = Math.max(v, vmax);
        rdmax = Math.max(rd, rdmax);
        ldmax = Math.max(ld, ldmax);
    }

    private int updateH(int[][] grid, int i, int j, int h) {
        h++;
        if(j < grid[i].length - 1 && grid[i][j+1] == 1) h = updateH(grid, i, j+1, h);
        return h;
    }

    private int updateV(int[][] grid, int i, int j, int v) {
        v++;
        if(i < grid.length - 1 && grid[i+1][j] == 1) v = updateV(grid, i+1, j, v);
        return v;
    }

    private int updateRD(int[][] grid, int i, int j, int rd) {
        rd++;
        if(j < grid[i].length - 1 && i < grid.length - 1 && grid[i+1][j+1] == 1)
            rd = updateRD(grid, i+1, j+1, rd);
        return rd;
    }

    private int updateLD(int[][] grid, int i, int j, int ld) {
        ld++;
        if(j > 0 && i < grid.length - 1 && grid[i+1][j-1] == 1)
            ld = updateLD(grid, i+1, j-1, ld);
        return ld;
    }
}

My code seems to work, but I'm not sure if this is the most efficient code. Do you think this is OK? Or are there any faster/simpler implementation? (Answer in Java format preferred.)


texts: Dictionary of key signatures for various major and minor scales

texts:
I've been working on a simple program that matches a scale with its key signature. It's fairly simple, but I feel there is redundancy in the dict I created since I don't know how I could assign two keys for a value. Furthermore, I tried setting the dict in classes, but I didn't know how to format it correctly.

The strings are written in Spanish since this was a program requested by my friend.

major_and_sharp_notes = {
    'do mayor':'ninguna',
    'sol mayor':'fa#',
    're mayor':'fa#, do#',
    'la mayor':'fa#, do#, sol#',
    'mi mayor':'fa♯, do♯, sol♯, re♯',
    'si mayor':'fa♯, do♯, sol♯, re♯, la♯',
    'fa sostenido mayor':'fa♯, do♯, sol♯, re♯, la♯, mi♯',
    'do sostenido mayor':'fa♯, do♯, sol♯, re♯, la♯, mi♯, si♯',
}

minor_and_sharp_notes = {
    'la menor':'ninguna',
    'mi menor':'fa♯',
    'si menor':'fa♯, do♯',
    'fa sostenido menor':'fa♯, do♯, sol♯',
    'do sostenido menor':'fa♯, do♯, sol♯, re♯',
    'sol sostenido menor':'fa♯, do♯, sol♯, re♯, la♯',
    're sostenido menor':'fa♯, do♯, sol♯, re♯, la♯, mi♯',
    'la sostenido menor':'fa♯, do♯, sol♯, re♯, la♯, mi♯, si♯',
}

major_and_flat_notes = {
    'fa mayor':'si♭',
    'si bemol mayor':'si♭, mi♭',
    'mi bemol mayor':'si♭, mi♭, la♭',
    'la bemol mayor':'si♭, mi♭, la♭, re♭',
    're bemol mayor':'si♭, mi♭, la♭, re♭, sol♭',
    'sol bemol mayor':'si♭, mi♭, la♭, re♭, sol♭, do♭',
    'do bemol mayor':'si♭, mi♭, la♭, re♭, sol♭, do♭, fa♭',
}

minor_and_flat_notes = {
    're menor':'si♭',
    'sol menor':'si♭, mi♭',
    'do menor':'si♭, mi♭, la♭',
    'fa menor':'si♭, mi♭, la♭, re♭',
    'si bemol menor':'si♭, mi♭, la♭, re♭, sol♭',
    'mi bemol menor':'si♭, mi♭, la♭, re♭, sol♭, do♭',
    'la bemol menor':'si♭, mi♭, la♭, re♭, sol♭, do♭, fa♭',
}

def search():
    while True:
        user_search = input('Escriba la tonalidad para encontrar su armadura:').lower()
        response = "La armadura de %s es: " % user_search

        if user_search in major_and_sharp_notes:
            print(response + major_and_sharp_notes[user_search])

        elif user_search in minor_and_sharp_notes:
            print(response + minor_and_sharp_notes[user_search])

        elif user_search in major_and_flat_notes:
            print(response + major_and_flat_notes[user_search])

        elif user_search in minor_and_flat_notes:
            print(response + minor_and_flat_notes[user_search])

        elif user_search == 'quit':
            return False

        else:
            print("Estas seguro que esa es una tonalidad?")

def main():
    print ('Bienvenido al buscador de armaduras por Jfelix\n'
           'Escriba \'quit\' cuando termine de buscar.\n'
        )
    search()

if __name__ == '__main__':
    main()


texts:
RoundRobin is an implementation of the Round-robin style tournament:

public class RoundRobin implements Tournament {
    private final Game game;
    private final List<Player> allPlayers;
    private final List<Player> remainingPlayers;

    public RoundRobin(Game game){
        this.game = game;
        this.allPlayers = new ArrayList<>();
        this.remainingPlayers = new ArrayList<>();
    }

    /**
     * Starts a round of a game, selecting players in a round-robin fashion
     */
    @Override
    public Round nextRound() {
        int playersRemaining = getPlayerCount();
        List<Player> nextPlayers = new ArrayList<>();
        while (playersRemaining > 0) {
            playersRemaining = addPlayers(nextPlayers, playersRemaining);
            if (remainingPlayers.isEmpty()) {
                populateRemainingPlayers(nextPlayers);
            }
        }

        return new Round(game, nextPlayers);
    }

    /**
     * Repopulates the remaining player list, avoiding players that have already been used if the game disallows it
     */
    private void populateRemainingPlayers(List<Player> usedPlayers){
        if (game.allowDuplicatePlayers()) {
            remainingPlayers.addAll(allPlayers);
        } else {
            Set<Player> addedPlayers = new HashSet<>(usedPlayers);
            remainingPlayers.addAll(allPlayers.stream()
                    .filter(addedPlayers::contains).collect(Collectors.toList()));
        }
        Collections.shuffle(remainingPlayers, Controller.random);
    }

    /**
     * Adds players to the upcoming game
     */
    private int addPlayers(List<Player> nextPlayers, int playersRemaining) {
        if (remainingPlayers.size() < playersRemaining) {
            nextPlayers.addAll(remainingPlayers);
            playersRemaining-=remainingPlayers.size();
            remainingPlayers.clear();
            return playersRemaining;
        }
        Set<Player> chosenPlayers = new HashSet<>(remainingPlayers.subList(0, playersRemaining));
        nextPlayers.addAll(chosenPlayers);
        remainingPlayers.removeAll(chosenPlayers);
        return 0;
    }

    /**
     * Checks to make sure there are enough players to play, and returns the number of players we are going to play with
     */
    private int getPlayerCount(){
        if (allPlayers.size() < Math.max(game.minPlayers(), 1) && !game.allowDuplicatePlayers()){
            throw new NotEnoughPlayersException();
        }
        int playerCount = Math.min(allPlayers.size(), game.maxPlayers());
        if (playerCount == -1){
            return allPlayers.size();
        }
        return playerCount;
    }

    /**
     * Adds players to the pool
     */
    @Override
    public void addPlayers(List<Player> players) {
        this.allPlayers.addAll(players);
        this.remainingPlayers.addAll(players);
        Collections.shuffle(this.remainingPlayers, Controller.random);
    }
}

Some notes:

This is for a personal project, so feel free to overhaul the entire thing if you'd like
Game stores data/logic of the actual game, while a Round is an instance of a game.
Games can define a minimum/maximum number of players.  If the maximum is -1, then it allows for infinite amount of players.
A round should have as many players as possible.
Oftentimes games don't care if there are multiple instances of the same player in a game.


texts:
Looking for feedback especially regarding design/structure/naming but also anything else that can be improved upon.

Task: Given a (hardcoded) matrix, find out if a given string can be found without visiting a cell twice.
Movement is restricted to horizontal/vertical and only adjacent cells can be visited.
Print "True" if the input string can be found "False" otherwise.

Matrix:

ABCE
SFCS
ADEE

Example:

Input: CSE

Result: True. (Start from the C in the 2nd row, go right, go up)

Source code:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <tuple>
#include <set>

using std::get;
using std::make_tuple;

const std::vector<std::vector<char>> matrix =
{
    {'A', 'B', 'C', 'E'},
    {'S', 'F', 'C', 'S'},
    {'A', 'D', 'E', 'E'},
};

const std::vector<std::tuple<int, int>> directions =
{
    make_tuple(-1, 0),
    make_tuple(0, 1),
    make_tuple(1, 0),
    make_tuple(0, -1),
};

std::set<std::tuple<int, int>> used;
std::string chars;

bool find_next_match(size_t index, std::tuple<int, int> cur_pos)
{
    if (index == chars.size() - 1) return true;

    ++index;

    used.insert(cur_pos);

    for (const auto &dir : directions)
    {
        auto new_pos = make_tuple(get<0>(cur_pos) + get<0>(dir), get<1>(cur_pos) + get<1>(dir));

        if (get<0>(new_pos) < 0 || get<0>(new_pos) > 2) continue;
        if (get<1>(new_pos) < 0 || get<1>(new_pos) > 3) continue;

        if (used.count(new_pos)) continue;

        if (matrix[get<0>(new_pos)][get<1>(new_pos)] != chars[index]) continue;

        if (find_next_match(index, new_pos)) return true;
    }

    used.erase(cur_pos);

    return false;
}

int main (int argc, char **argv)
{
    std::ifstream infile(argv[1], std::ios::in | std::ifstream::binary);

    std::string line;
    while (getline(infile, line))
    {
        chars.clear();
        chars = line;

        bool found = false;
        for (int m = 0; m < 3; ++m)
        {
            for (int n = 0; n < 4; ++n)
            {
                if (matrix[m][n] == chars[0])
                {
                    used.clear();
                    if (find_next_match(0, make_tuple(m, n)))
                    {
                        found = true;
                        break;
                    }
                }
                if (found) break;
            }
        }

        if (found) std::cout << "True\n";
        else std::cout << "False\n";
    }
}

Edit 1:

I changed the find_next_match function to operate on the string directly instead of passing an addiontal argument to keep the amount of arguments under 3 (as per recommendation in Robert C. Martins Clean Code)

Revision 2 based on advice by @vnp

Edit 2:

Revision 3 based on advice by @miscco


texts:
I am writing my own wrapper for PostgreSQL (but it can be used for other engines too).

I am using this desgin:

PSQLPreparedStatement st("SELECT ? FROM ? WHERE name = '? xx' AND surname = 'xx ? xx';");
st.SetValue(0, "*");
st.SetValue(1, "test_table");
st.Prepare();

st.SetValue(0, "name");
st.Prepare();

PostgreSQLWrapper psql;
psql.Connect();

PSQLInsert insert{ "name", "surname" };
insert.SetTable("test_table");
insert.AddRow({ { "name", "xx" }, { "surname", "x" } });
insert.AddRow({ { "name", "xyyyx" }});

std::unordered_map<MyStringAnsi, MyStringAnsi> data;
psql.RunQuery("UPDATE test_table SET name='John'");

//============
// Example 1
PSQLSelect select;
select.SetBaseTable("test_table");
select.AddColumn("name");
select.AddColumn("surname");
select.AddColumn("id");

auto lambda = [&](std::unordered_map<COL_NAME, char *> & data, int row, int totalRows) -> void
{
    printf("%s %s %s\n", data["name"], data["surname"], data["id"]);
};

psql.Select(select, lambda);

//===============
// Example 2
psql.Select("SELECT name, surname, id FROM test_table", [&](std::unordered_map<COL_NAME, char *> & data, int row, int totalRows) -> void
    {
        printf("%s %s %s\n", data["name"], data["surname"], data["id"]);
    }
);

In the background, the classes create SQL queries through string processing. I cache almost everyhing to speed things up. I am also using my string class with some search/replace substring modifications (like the KMP algorithm).

It is written to be readable code with easy to add new functionality and easy to read source code.

Is this an OK solution? Is it worthwile to add some more functions and made this an open library project?


texts: concise way to build an object from an array of objects

texts:
The following code is working as expected but I'm wondering if there's a way to use Object.assign, or some other approach, to build the derivedData object so that it doesn't need to be initialized as an empty object and then populated in a subsequent step.
const data = [
  {"period": "2021-05-01", "quantity": "28"},
  {"period": "2021-06-01", "quantity": "42"},
  {"period": "2021-07-01", "quantity": "66"}
];

const derivedData = {};
data.forEach(o => {
  derivedData[o.period] = o.quantity
});

console.log(data);
console.log(derivedData);

Expected output of derivedData:
{
  "2021-05-01": "28",
  "2021-06-01": "42",
  "2021-07-01": "66"
}


texts:
How may I optimize the following function to write a xls file from a list of dictionaries using the openpyxl library in Python?

The current logic behind feels very very wrong

The dict list:

things = [
    {
        "Fruit": "Orange",
        "Flavour": "Good",
        "Expiration": "21May20"
    },
    {
        "Fruit": "Apple",
        "Flavour": "Good",
        "Expiration": "19May20"
    },
    {
        "Fruit": "Banana",
        "Flavour": "Regular",
        "Expiration": "16May20"
    }
]

The functions that I have:

from openpyxl import Workbook, load_workbook

def create_xls(filepath):
    wb = Workbook()
    wb.save(filepath)

def write_xls(filepath, dictionary):
    wb = load_workbook(filepath)
    sheet = wb.active

    headers = [x for x in dictionary[0]]

    for index, value in enumerate(headers):
        sheet.cell(row=1, column=index+1).value = value

    for i, x in enumerate(dictionary):
        for idx,value in enumerate(x.values()):
            sheet.cell(row=i+2, column=idx+1).value = value

    wb.save(filepath)

Thank you!


texts:
I made this code to compute definite integrals in Processing. It works by getting the rectangle between the maximum value between the previous function value and the current function value, and then I calculate the area by multiplying the maximum value described before and the step. And finally, the integral is just summing all the areas.

I will do a version based on trapezoids, but that could get really slow because I would need to use the square root function witch is computationally intensive to compute.

Any suggestions are welcome.

float step = 0.0001;
int iterations = 0;

// y = x
float f1(float x) {
  return 2 * x;
}

float integral(int a, int b) {
  float sum = 0.0;
  float prevI = a;

  for (float i = a; i < b; i += step) {
    float h = max(f1(prevI), f1(i));
    sum += step * h;

    prevI = i;
    iterations++;
  }
  return sum;
}

void setup() {
  println(integral(0, 1));
  println(iterations);
}


texts:
I've made a simple drawer using CSS3 and jQuery that works with hover and click. It seems to be working fine but surely there's a simpler way of writing the code.

Fiddle: http://jsfiddle.net/73MpU/

$("#bottom-page").click(function () {
    $("#top-page").addClass("push");
});

$("#bottom-page").mouseover(function () {
    $("#top-page").addClass("nudge-right");
});

$("#bottom-page").mouseleave(function () {
    $("#top-page").removeClass("nudge-right");
});

$("#top-page").click(function () {
    $(this).removeClass("push");
    $(this).removeClass("nudge-left");
});

$("#top-page").mouseover(function () {
    if ($(this).hasClass("push")) {
        $(this).addClass("nudge-left");
    }
});

$("#top-page").mouseleave(function () {
    if ($(this).hasClass("push")) {
        $(this).removeClass("nudge-left");
    }
});

So, I simplified my code a bit. Is this valid?

Edit:

$("#bottom-page").hover(function () {
    $("#top-page:not(.push)").toggleClass("nudge-right");
});

$("#bottom-page").click(function () {
    $("#top-page:not(.push)").removeClass("nudge-right");
    $("#top-page:not(.push)").addClass("push");
});

$("#top-page").hover(function () {
    if ($(this).hasClass("push")) {
        $(this).toggleClass("nudge-left");
    }
});

$("#top-page").click(function () {
    if ($(this).hasClass("push")) {
        $(this).removeClass("push nudge-left");
    }
});


texts:
This system has to manage students, teachers, staff and grading. This is for production and is not a school assignment. As such, please let me know if I can improve on any aspect. :)

My main concern is automation. I'd like my software to be able to run regardless if I still exist.

I'm using SQLite as the database:

create table User
(
ID integer primary key autoincrement,
Username string,
Password string
);

create table Area
(
ID integer primary key autoincrement,
Name string
);

create table Subject
(
ID integer primary key autoincrement,
Name string,
Abbreviation string,
IDArea integer references Area(ID)
);

create table Level
(
ID integer primary key autoincrement,
Name string,
Principle string
);

create table Grade
(
ID integer primary key autoincrement,
Name string,
IDLevel integer references Level(ID),
Observation string
);

create table StaffType
(
ID integer primary key autoincrement,
Name string
);

create table Staff
(
ID integer primary key autoincrement,
IDStaffType integer references StaffType(ID),
Name string,
LastNameFather string,
LastNameMother string,
DateOfBirth string,
PlaceOfBirth string,
Sex string,
Carnet string,
Telephone string,
MobilePhone string,
Address string,
FatherName string,
MotherName string,
FatherContact string,
MotherContact string,
FatherPlaceOfWork string,
MotherPlaceOfWork string,
DateOfHiring string,
YearsOfService string,
Formation string,
Specialty string,
Category string,
Salary string
);

create table GradeParalelo
(
ID integer primary key autoincrement,
IDGrade integer references Grade(ID),
IDStaff integer references Staff(ID),
Name string
);

create table Student
(
ID integer primary key autoincrement,
IDGradeParalelo integer references GradeParalelo(ID),
Rude string,
Name string,
LastNameFather string,
LastNameMother string,
DateOfBirth string,
PlaceOfBirth string,
Sex string,
Carnet string,
Telephone string,
MobilePhone string,
Address string,
FatherName string,
MotherName string,
FatherMobilePhone string,
MotherMobilePhone string,
FatherProfession string,
MotherProfession string,
FatherPlaceOfWork string,
MotherPlaceOfWork string,
Observations string
);

create table Attendance
(
ID integer primary key autoincrement,
IDStudent integer references Student(ID),
Attended string,
Date string
);

create table SubjectGrade
(
ID integer primary key autoincrement,
IDGrade integer references Grade(ID),
IDSubject integer references Subject(ID)
);

create table ScoreRecord
(
ID integer primary key autoincrement,
IDSubject integer references Subject(ID),
IDStudent integer references Student(ID),
FirstTrimester integer,
SecondTrimester integer,
ThirdTrimester integer,
FinalGrade integer,
Year string
);

Any glaring room for improvement?


texts:
I'm working on a project the scenario: teacher model then is the teacher has not a profile the institute which working at will upload the courses does this is written the way I have tried in the course model?

class Course(models.Model):
   course_name = models.CharField(max_length=20)
   student = models.ManyToMany(Student)
   institute_name = models.ForeignKey(Institute,on_delete=models.CASCADE , null=True,blank=True)
   teacher_name = models.ForeignKey(Teacher ,on_delete=models.CASCADE,blank=True,null=True)
   tags = models.ManyToManyField(Category,on_delete=models.CASCADE)
   time = models.DateTimeField(auto_now_add=True)
   update = models.DateTimeField(auto_now=True)

Then define:

if user loggedin in  user.is_institute

So querying in an institute like this:

if loggedin in user.is_teacher

And then will work on the teacher model. Does this structure fine?

I've heard generic foreign keys but I'm not sure if it working with API!?

from django.contrib.contenttypes.models import ContentType

Teacher, Institute have different fields name

Thanks


texts:
How can I refactor my code to remove the label and the need for it? I am aware that a loop with label is "forbidden". But I can not find a way to rewrite this without the label.

private List<myList> sortLinks(SegmentType s, Set<myList> LinkSet) {
        List<myList> LinkList = new LinkedList<myList>();

        String dep = s.getDep().toString();
        mainLoop: for (int index = 0; !LinkSet.isEmpty(); index++) {

            for (Iterator<myList> iterator = LinkSet.iterator(); iterator.hasNext(); ) {
                myList link = iterator.next();
                if (link.getLegDep().toString().equals(dep)) {
                    iterator.remove();
                    link.setLine(s.getLineCode());
                    link.setNb(s.getNb());
                    link.setSuff(s.getSuff());
                    link.setIndex(index);
                    linkList.add(link);

                    dep = link.getDest().toString();
                    continue mainLoop;
                }
            }

            return Collections.emptyList();
        }
        return linkList;
    }