texts:
This is a FizzBuzz program, designed to take parameter inputs for start and ending numbers, as well as a "fizz" number and a "buzz" number. The program then outputs the numbers one per line. If the number is divisible by the "fizz" number (normally 3), "fizz" is printed instead, the same with the "buzz" number. If the number is divisible by both, "fizzbuzz" is the output.

I am primarily looking for advice with my choice of logic, syntax, and use of methods with regards to complexity and efficient code. However, all advice is appreciated.

using System;

class FizzBuzzProgram
{
static void Main()
{
    //initialize menu variables
    bool menuvalidinput = false;
    string menuchoice;

    /*get decision if user wants to fizzbuzz, looping
    until a valid input is provided*/
    do {
        Console.WriteLine("Would you like to fizzbuzz? [Y]/[N]");
        menuchoice = Console.ReadLine();
        menuchoice = menuchoice.ToLower();  //convert to lowercase
        if (menuchoice == "y" | menuchoice == "n"){
            menuvalidinput = true;          //accept input
        } else {
            Console.WriteLine("Sorry, input was not valid.");
        }
    } while (menuvalidinput == false);
    //end of input loop

    //interpret the result of either "y" or "n"
    if (menuchoice == "y"){
        FizzBuzzWithInput();
    } else {
        Console.WriteLine("That's ok, have a nice day!");
    }
}

static void FizzBuzzWithInput()
{
    //initialize fizzbuzz input (FBinput*) variables
    int FBinputS, FBinputE, FBinputF, FBinputB;
    bool FBvalidinput = false;

    /*take input for start and end values,
    if start is larger than end ask again*/
    do {
        Console.WriteLine("What number would you like to start from?");
        FBinputS = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("What number would you like to end at?");
        FBinputE = Convert.ToInt32(Console.ReadLine());

        if (FBinputS > FBinputE){   //check of start and end values
            Console.WriteLine("You chose a starting number larger than your ending number;");
            Console.WriteLine("please input new values.");
        } else {
            FBvalidinput = true;    //accept input
        }
    } while (FBvalidinput == false);
    //end validation loop

    //take fizz and buzz inputs, classically 3 and 5 respectively
    Console.WriteLine("What number would you like to fizz?");
    FBinputF = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("What number would you like to buzz?");
    FBinputB = Convert.ToInt32(Console.ReadLine());

    //call the actual FizzBuzz method
    RunFizzBuzz(FBinputS, FBinputE, FBinputF, FBinputB);
}

static void RunFizzBuzz(int FBstart, int FBend, int FBfizz, int FBbuzz)
{
    //initialize the display string
    string c;

    Console.WriteLine("\nFizzbuzz time!\n");

    //fizzbuzz loop
    for (int i = FBstart; i <= FBend; i++){
        //set c to blank string
        c = "";

        if(i%FBfizz == 0){
            c = c + "fizz";
        }
        if(i%FBbuzz == 0){
            c = c + "buzz";
        }
        if(c.Length == 0){  /*"if the number is not fizz or buzz"
                            aka: if(i%FBfizz!=0 & i%FBbuzz!=0)*/
            c = Convert.ToString(i);
        }
        //print display string of number i
        Console.WriteLine(c);
    }
    //end fizzbuzz loop

    Console.WriteLine("\nFizzbuzz complete!");
    Console.ReadLine();
}
}


texts:
I would like to know how to make my code better. I'm still a newbie in Android, so any tips are appreciated.

The code is an AsyncTask class extender that formats data into a nice looking Spannable String. It works, but it's quite slow, even if ran on a background thread.

//SlideContentType is an enumerable with 4 options: Movie, Action, Game, Music
//SlideContent is a class that stores info about a specific movie/song/game etc...
public class PickCardAsyncTask extends AsyncTask<Pair<SlideContent.SlideContentType, List<SlideContent>>, Integer, Pair<SpannableStringBuilder, String>> {

    @Override
    protected Pair<SpannableStringBuilder, String> doInBackground(Pair<SlideContent.SlideContentType, List<SlideContent>>... pairs){

        //Get a reference to the list of all Slide Contents containing movies/games/etc.
        List<SlideContent> list = (List<SlideContent>) pairs[0].second;

        //Select a random item in the list
        Random random = new Random();
        random.setSeed(System.nanoTime());
        int randomNr = random.nextInt(list.size());
        SlideContent currentContent = list.get(randomNr);

        //The link and the content are released as a pair
        String websiteLink = currentContent.movieWebsite;

        //End result variable
        SpannableStringBuilder coloredString = new SpannableStringBuilder();

        //Do the appropriate actions
        if(pairs[0].first == SlideContent.SlideContentType.Movie){

            //Format the information from the Slide Content into a nice looking Spannable String
            SpannableString text = new SpannableString(currentContent.movieTitle);
            text.setSpan(new StyleSpan(Typeface.BOLD), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            coloredString.append(text);

            coloredString.append(" (" + currentContent.movieYear + ")\n");

            text = new SpannableString(currentContent.movieGenres);
            text.setSpan(new RelativeSizeSpan(0.7f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            text.setSpan(new ForegroundColorSpan(Color.GRAY), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            coloredString.append(text);
            coloredString.append("\n");

            text = new SpannableString(currentContent.movieDescription);
            text.setSpan(new RelativeSizeSpan(0.8f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            coloredString.append(text);
            coloredString.append("\n");

            text = new SpannableString("Movie rated " + currentContent.movieRating + " out of 10.");
            text.setSpan(new RelativeSizeSpan(0.7f), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            text.setSpan(new ForegroundColorSpan(Color.GRAY), 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            coloredString.append(text);

        }
        //Return a pair of the Spannable String Builder and the link to the related website
        return new Pair<>(coloredString, websiteLink);
    }
}


texts: Fetching user information along with user posts in Angular

texts:
Here is my code with 2 services, one is messageService which is used to get user messages:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import 'rxjs/add/operator/retry';
import 'rxjs/add/operator/catch';
import { handleError } from '../common/error-handler';

@Injectable({
  providedIn: 'root'
})
export class MessagesService {
  private _config = environment;

  constructor(private http: HttpClient) { }

  getMessages() {
    return this.http.get(`${this._config.apiUrl}/messages`)
      .retry(3)
      .map(data => (data && data['messages']) || [])
      .catch(handleError);
  }

}

And the other is usersService which is used to get user information based on user_id:

import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
import { Injectable } from '@angular/core';
import { handleError } from '../common/error-handler';

@Injectable({
  providedIn: 'root'
})
export class UsersService {
  private _config = environment;

  constructor(private http: HttpClient) { }

  getUser(user_id) {
    return this.http.get(`${this._config.apiUrl}/users/${user_id}/public_profile`)
      .retry(3)
      .map(data => data || {})
      .catch(handleError);
  }
}

And in the constructor of my component:

    @Component({
      selector: 'wall',
      templateUrl: './wall.component.html',
      styleUrls: ['./wall.component.css']
    })
    export class WallComponent {

      constructor(private messageService: MessagesService,
                  private usersService: UsersService) {

        this.messageService.getMessages()
              .switchMap(response => {
                let resArray: any[] = response.map(
                  post => {
                    return Observable.zip(
                      this.usersService.getUser(post.user_id),
                      Observable.of(post)
                    );
                  });
                  return Observable.merge(...resArray)
              }).switchMap(res => {
                res[1]['user'] = res[0];
                this.messages.push(res[1]);
                return Observable.of(res[1]);
              })
              .subscribe(final_post => {
                console.log('final post:', final_post)
              })
        }
    }

The question is how should I get user messages using Observable and then getting users information for each message (each message may have different user information), then merging them into one object which finally  will be used in the desired component with fewer Observable pipelines? I suppose using merge and then again switchMap to merge these data is not optimal and best practice.


texts:
Here is my method:

public JsonResult ValidateAll(string toys)
{
    Dictionary<string, object> res = new Dictionary<string, object>();
    List<string> result_check = new List<string>();

    string[] lines = toys.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);

    foreach (string line in lines)
    {
         string toyName = line;

         string toy_tmp = toyName.Trim();
         string toy_tmp2 = HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(toyName)).Replace("&#228;", "&auml;").Trim();
         string toy_tmp3 = toyName.Replace("\u00a0", " ").Trim();
         string toy_tmp4 = HttpUtility.HtmlDecode(toyName.Trim());
         string toy_tmp5 = HttpUtility.HtmlDecode(toyName.Replace("\u00a0", " ").Replace(" ", " ").Trim());

         string tableInDatabase = "";

         //Check if the toy is a doll
         tblDoll doll = (from x in db.tblDoll
                                  where (x.doll_name == toy_tmp || x.doll_name == toy_tmp2 || x.doll_name == toy_tmp3 || x.doll_name == toy_tmp4 || x.doll_name == itoy_tmp5)// || x.doll_name == toy_tmp6)
                            select x)
                            .FirstOrDefault();

         if (doll != null)
         {
             table = "doll";
             result_check.Add("1");
             continue;
         }

         if (table == "")
         {
             var car = (from x in db.tblCar
                       where (x.car_name == toy_tmp || x.car_name == toy_tmp2 || x.car_name == toy_tmp3 || x.car_name == toy_tmp4)
                       select y).FirstOrDefault();
             if (car != null)
             {
                 table = "car";
                 result_check.Add("1");
                 continue;
              }

          }

         //Do the same as for Car and Doll, do it for Plane and Boat too
    }
    res.Add("ok", result_check);
    return Json(res, JsonRequestBehavior.AllowGet);

}

What I'm trying to do is this: the input string is a name of a toy. I have four tables for toys in my db: Car, Doll, Plane, Boat. I need to find in which table is the toy (the input string).


texts: Robustness of this first difference function

texts:
Here is a first difference function I threw together for a quick check in another program:

use std::ops::Sub;

fn first_difference<T>(input: &Vec<T>) -> Vec<T::Output>
    where T: Sub<Output = T> + Clone {

    let vec_len = input.len();

    input.iter().take(vec_len-1).enumerate().map(|(ind, val)| {
            val.clone() - input[ind+1].clone()
    }).collect()
}

Some things that I'm not happy with are:

Indexing the input while iterating over itself (I could use .chunks(2) but I need to visit each non-first non-last item twice)
Cloning each value inside the map (I couldn't make the trait annotation work for &T)

I also don't know if the function needs more machinery to protect against unexpected inputs (I'm not very experienced with strongly typed languages).

What can or should be done with this function?


texts: Efficiency of binary search and improvements

texts:
Below you can see my binary search method, and as a relatively new programmer I am looking for any suggestions on how it could be improved.

bool found = false;
int min = 0;
int max = 9;
int avg;
int anArray[] = {1,2,3,4,5,6,7,8,9,10};

int userNumber;

printf("Enter a number between 1 and 10:\n");
scanf("%d", &userNumber);

while(!found){
    avg = (min+max)/2;
    if(anArray[avg]==userNumber){
        found = true;
        break;
    }
    if(anArray[avg]<userNumber)
        min = avg+1;
    else if(anArray[avg]>userNumber)
        max = avg-1;
    if( (min==max) && (anArray[max]!=userNumber) )
        break;
}
if(found)
    printf("The number is in index [%d]\n", avg);
else
    printf("Number not found\n");


texts: Building Data abstraction for line segments using "objects"

texts:
I follow this definition of "object":An object is a value exporting a procedural interface to data or behavior. Objects use procedural abstraction for information hiding, not type abstraction. Object and and their types are often recursive. Objects provide a simple and powerful form of data abstraction. They can be understood as closures, first-class modules, records of functions, or processes. Objects can also be used for procedural abstraction. from this paper
Below is the given exercise:

Exercise 5: Segments
Consider the problem of representing line segments in a plane. Each segment is represented as a pair of points: a starting point and an ending point. Define a constructor make-segment and selectors start-segment and end-segment that define the representation of segments in terms of points. Furthermore, a point can be represented as a pair of numbers: the x coordinate and the y coordinate. Accordingly, specify a constructor make-point and selectors x-point and y-point that define this representation. Finally, using your selectors and constructors, define a procedure midpoint-segment that takes a line segment as argument and returns its midpoint (the point whose coordinates are the average of the coordinates of the endpoints)

It is taught in class that data abstraction is the methodology to create barrier between "how data values are used" and "how data values are represented". Also, an abstract data type is some collection of selectors and constructors, together with some behaviour conditions (invariants).
It is compound data that needs data processing which actually enables to think about data abstraction because the user would like to use this compound data as single unit.
Below code is building "data abstraction" and "ADT" for "line segments" using python objects
# Representation - start
#Constructor
def make_point(x, y):
    return (x, y)

#Selector
def x_coordinate(point):
    return point[0]

#Selector
def y_coordinate(point):
    return point[1]

#Constructor
def make_segment(point1, point2):
    return (point1, point2)

#Selector
def start_segment(lineSegment):
    return lineSegment[0]

#Selector
def end_segment(lineSegment):
    return lineSegment[1]

#Representation - end

#Use -start
def midpoint_segment(lineSegment):
    return make_point((x_coordinate(start_segment(lineSegment)) + x_coordinate(end_segment(lineSegment)))/2, (y_coordinate(start_segment(lineSegment)) + y_coordinate(end_segment(lineSegment)))/2)

#Use - end

#Driver code from user
p1 = make_point(1,2)
p2 = make_point(3, 4)
line = make_segment(p1, p2)
midpoint = midpoint_segment(line)
print(midpoint)

In the above code, constructor and selectors constitute ADT.
In the above two implementations:

There is an abstract data type that supports an invariant1:
If we construct point p from x-coordinate a and y-coordinate b, then x_coordinate(p), y_coordinate(p)  must equal a, b

There is an abstract data type that supports an invariant2:
If we construct a line segment l from point p1 and point p2, then start_segment(l)______end_segment(l) must equal p1______p2

In the above implementation:

Parts of the program that use line segments to perform computation use midpoint_segment.

Parts of the program that implement midpoint_segment use constructor and selectors only

Parts of the program that create line segments use constructor make_segment

Parts of the program that implement constructor for line segment use tuple

Parts of the program that implement selectors for line segments use [] for indexing tuples.

So, above implementation has set of "objects" that build "Data abstraction"
Is my understanding correct on designing data abstraction and ADT for line segments?


texts: Reimplementation of a Hashtable and hash function

texts:
package com.raja.util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class Hashtable {
    private Object[] slots;
    private int capacity;

    Hashtable(int size) {
        capacity = size;
        slots = new String[size];
        Arrays.fill(slots, "-1");
    }

    // Simple hash function that puts values in the randomly generated index that generated within the limits of the given Hashtable size
    public void myHashFunction(Object[] elements, Object[] slots) {
        Random random = new Random();
        for (int n = 0; n < elements.length; n++) {
            int randomIndex = randomIndex(0, capacity, random);
            if(randomIndex < capacity){
                while((String)slots[randomIndex] != "-1" && randomIndex != capacity){
                    randomIndex = randomIndex(0, capacity, random);
                }
                slots[randomIndex] = elements[n];
            }
        }
    }

    //Generates a random number in the limits of begin and end
    private static int randomIndex(int begin, int end, Random aRandom){
        if (begin > end) {
          throw new IllegalArgumentException("Start cannot exceed End.");
        }
        long range = (long)end - (long)begin + 1;
        long fraction = (long)(range * aRandom.nextDouble());
        int randomNumber =  (int)(fraction + begin);
        if(randomNumber == end)
            randomNumber--;
        return randomNumber;
      }

    // Returns the value stored in the Hash slots
    public Object getValue(int key) {
        if(getKeys().contains(key)){
            return slots[key];
        } else return null;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{ ");
        for(int i = 0; i < slots.length; i++){
            if(slots[i] != "-1")
                sb.append(i+"->" + slots[i] + ", ");
        }
        sb.append("}");
        int lastIndex = sb.lastIndexOf(",");
        sb.replace(lastIndex, lastIndex + 1, "");
        return sb.toString();
    }

    // Returns the key indexes where the elements got stored.
    public Set<Integer> getKeys(){
        Set<Integer> keys = new HashSet<Integer>();
        if(slots != null){
            for(int index = 0; index < slots.length; index++){
                if(slots[index] != "-1"){
                    keys.add(index);
                }
            }
        }
        return keys;
    }

    //Testing : Storing A-Z alphabets in Hashtable
    public static void main(String[] args) {
        Object[] elements = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
        Hashtable myHashtable = new Hashtable(1000);  //Big size (i.e. 1000) is used to illustrate the random hash keys
        myHashtable.myHashFunction(elements, myHashtable.slots);
        System.out.println("Keys = "+ myHashtable.getKeys());
        if(myHashtable.getKeys().size() != elements.length) {
            System.out.println("Oops!, some element(s) were not stored in your hashtable");
        }
        System.out.println("Your Hashtable = " + myHashtable);
    }
}

The output of this program would be something like:

Keys = [611, 954, 199, 406, 892, 25, 214, 633, 265, 391, 759, 102, 307, 236, 990, 36, 432, 918, 433, 40, 435, 522, 591, 775, 250, 726]
Your Hashtable = { 25->O, 36->S, 40->I, 102->H, 199->D, 214->N, 236->X, 250->Y, 265->K, 307->B, 391->F, 406->A, 432->M, 433->Q, 435->C, 522->V, 591->U, 611->G, 633->P, 726->J, 759->W, 775->R, 892->Z, 918->E, 954->T, 990->L }


texts:
I'm implementing HTTP traffic monitor (proxy) for my project right now. It's performance is satisfactory. I've updated regex settings and improved performance but I think there are also ways to make it better.

//mipt
public class TrafficMonitor
{
    private int _port;
    private bool _isWorking;
    private TcpListener _listener;
    private static readonly Regex myReg = new Regex(@"Host: (((?<hostName>.+?):(?<port>\d+?))|(?<hostName>.+?))\s+",
                RegexOptions.Compiled);
    public TrafficMonitor(int port)
    {
        _port = port;
        _listener = new TcpListener(IPAddress.Parse("127.0.0.1"), _port);
    }

    public void Start()
    {
        _listener.Start();
        _isWorking = true;

        while (_isWorking)
        {
            TcpClient client = _listener.AcceptTcpClient();
            Task.Factory.StartNew(() => Worker(client.Client));
        }
    }

    public void Stop()
    {
        _isWorking = false;
        _listener.Stop();
    }

    private void Worker(Socket clientSocket)
    {
        if (clientSocket.Connected)
        {
            byte[] httpRequest = ReadToEnd(clientSocket);

            Match m = myReg.Match(Encoding.ASCII.GetString(httpRequest));
            string hostName = m.Groups["hostName"].Value;
            int port = 0;

            if (!int.TryParse(m.Groups["port"].Value, out port))
            {
                port = 80;
            }
            IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
            IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], port);

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(endPoint);
            if (socket.Send(httpRequest, httpRequest.Length, SocketFlags.None) == httpRequest.Length)
            {
                byte[] httpResponse = ReadToEnd(socket);
                if (httpResponse != null && httpResponse.Length > 0 )
                    clientSocket.Send(httpResponse, httpResponse.Length, SocketFlags.None);
            }
            socket.Close();
            clientSocket.Close();
        }
    }

    private byte[] ReadToEnd(Socket socket)
    {
        byte[] recievedData = new byte[socket.ReceiveBufferSize];
        int len = 0;

        using (MemoryStream m = new MemoryStream())
        {
            while (socket.Poll(1000000, SelectMode.SelectRead) && (len = socket.Receive(recievedData, socket.ReceiveBufferSize, SocketFlags.None)) > 0)
            {
                m.Write(recievedData, 0, len);
            }

            return m.ToArray();
        }
    }
}


texts: Group chars in an array if they have the same start and end elements

texts:
I am trying to work through this challenge, I have come up with a solution but however I look at the problem statement and the examples provided I cant help but come to the conclusion that the "example 3" and "test case 2" as explained in the problem statement are wrong.

I would appreciate it if someone could review my solution and the problem statement and provide any feedback.

  problem statement:

  You are working on developing a movie with Amazon Video that consists
  of a series of shots: short pieces of video from a particular camera
  angle. You want to devise an application to easily group identical
  shots in a video into scenes (a sequence of shots). Shots are
  identical when they are labeled with the same letter, and everything
  in between identical shots is considered part of same scene. There is
  already an algorithm that breaks the video up into shots and labels
  them.

  Write a function which will partition a sequence of shot labels into
  minimal subsequences so that a shot label only appears in a single
  subsequence. The output should be the length of each subsequence.

  Input The input to the function/method consists of an argument -
  inputList, a list of characters representing the sequence of shots.

  Output Return a list of integers representing the length of each
  scene, in the order in which it appears in the given sequence of
  shots.

  Examples Example 1: Input inputList = [a, b, c]

  Output [1, 1, 1]

  Explanation: Because there are no recurring shots, all shots can be in
  the minimal length 1 subsequence.

  Example 2: Input inputList = [a, b, c, a]

  Output [4]

  Explanation: Because ‘a’ appears more than once, everything between
  the first and last appearance of ‘a’ must be in the same list.

  Example 3: Input: inputList = [a, b, a, b, c, b, a, c, a, d, e, f, e,
  g, d, e, h, i, j, h, k, l, i, j]

  Output: [9, 7, 8]

  Testcase 1: Input: [a, b, c, d, a, e, f, g, h, i, j, e]

  Expected Return Value: 5 7

  Testcase 2: Input: [z, z, c, b, z, c, h, f, i, h, i]

  Expected Return Value: 6 5

my solution and test cases:

using System.Collections.Generic;
using Xunit;

namespace LengthEachSceneChallenge
{
  public class Task
  {
    public List<int> lengthEachScene(List<char> inputList)
    {
        var counts = new List<int>();
        for (int i = 0; i < inputList.Count; i++)
        {
            var item = inputList[i];
            var lastIndex = inputList.LastIndexOf(item);

            if (i == lastIndex)
            {
                counts.Add(1);
            }
            else
            {
                counts.Add(i == 0 ? lastIndex + 1 : lastIndex - i + 1);
                i = lastIndex;
            }
        }
        return counts;
    }

    [Fact]
    public void Example1()
    {
        var data = new List<char>() { 'a', 'b', 'c' };

        Assert.Equal(new List<int>() { 1, 1, 1 }, lengthEachScene(data));
    }

    [Fact]
    public void Example2()
    {
        var data = new List<char>() { 'a', 'b', 'c', 'a' };

        Assert.Equal(new List<int>() { 4 }, lengthEachScene(data));
    }

    [Fact]
    public void Example3()
    {
        var data = new List<char>() { 'a', 'b', 'a', 'b', 'c', 'b', 'a', 'c', 'a', 'd', 'e', 'f', 'e', 'g', 'd', 'e', 'h', 'i', 'j', 'h', 'k', 'l', 'i', 'j' };

        Assert.Equal(new List<int>() { 9, 7, 8 }, lengthEachScene(data));
    }

    [Fact]
    public void TestCase1()
    {
        var data = new List<char>() { 'a', 'b', 'c', 'd', 'a', 'e', 'f', 'g', 'h', 'i', 'j', 'e' };

        Assert.Equal(new List<int>() { 5, 7 }, lengthEachScene(data));
    }

    [Fact]
    public void TestCase2()
    {
        var data = new List<char>() { 'z', 'z', 'c', 'b', 'z', 'c', 'h', 'f', 'i', 'h', 'i' };

        Assert.Equal(new List<int>() { 6, 5 }, lengthEachScene(data));
    }
}

}

count Length of each sequence of chars according to start and end characters


texts: Decimal to binary and binary to decimal convertor

texts:
Please review this code. How can I optimise this code?

#include <iostream>
#include <vector>
#include <algorithm> // std::reverse
#include <cmath> // pow()

typedef unsigned long long int ulli;

bool is_binary(ulli num)
{
    bool status = true;
    while (true)
    {
        if (num == 0)
        {
            break;
        }
        else
        {
            int temp = num % 10;
            if (temp > 1)
            {
                status = false;
                break;
            }
            num = num / 10;
        }
    }
    return status;
}

std::vector<ulli> decimal_to_binary(int val)
{
    std::vector<ulli> result;
    int rem;
    if (val == 0)
    {
        result.push_back(0);
        return result;
    }
    while (val != 0)
    {
        rem = val % 2;
        result.push_back(rem);
        val = val / 2;
    }
    std::reverse(result.begin(), result.end());
    return result;
}

int binary_to_decimal(ulli val)
{
    int sum = 0;
    int rem, i = 0;
    while (val > 0)
    {
        rem = val % 10;
        sum += pow(2, i) * rem;
        val = val / 10;
        i++;
    }
    return sum;
}

void display(std::vector<ulli>& vec)
{
    for (int i = 0; i < vec.size(); i++)
    {
        std::cout << vec[i];
    }
    std::cout << '\n';
}

int main()
{
    int option;
    std::cout << "1. Decimal to Binary \n2. Binary to Decimal \n";
    std::cout << "Enter your option\n";
    std::cin >> option;

    switch(option)
    {
        case 1:
          {
             int num;
             std::cout <<"\nEnter Decimal number\n";
             std::cin >> num;
             std::vector<ulli> binary = decimal_to_binary(num);
             std::cout << "The binary equivalent of " << num <<" is :\n";
             display(binary);
             break;
          }
        case 2:
          {
             ulli binary_num;
             x:
             std::cout << "\nEnter Binary number\n";
             std::cin >> binary_num;
             bool flag = is_binary(binary_num);
             if (!flag)
             {
                std::cout << "The number is not binary\n";
                goto x;
             }
             int decimal = binary_to_decimal(binary_num);
             std::cout << "The decimal equivalent of " << binary_num << " is :\n";
             std::cout << decimal << '\n';
             break;
          }
        default: std::cout << "Enter option 1 or 2\n";
    }
}


texts:
I looked for a way to order one interface by key in Golang and print the concatenated values.
Because I couldn't find any solution I will share mine.
Please feel free to share a better solution.

Imagine that we have a struct and we want to print the values ordered by key.

type Point struct {
    X string
    Y string
    A string
    C string
}

var result interface{} = Point{"1", "2", "4", "5"}

The expected result should be 4512

My solution is:

func sortStructures(structure interface{}) string {
    var result string
    v := reflect.ValueOf(structure)

    //Add all the key of a struct to a array
    values := make([]string, v.NumField())
    for i := 0; i < v.NumField(); i++ {
        values[i] = v.Type().Field(i).Name
    }

    //Sort the keys of the structure
    sort.Strings(values)

    //Concat the values of the ordered keys
    for j := 0; j < len(values); j++ {
        result += v.FieldByName(values[j]).String()
    }

    return result
}

Please note the in my case I needed to get the concatenated string of the values, but I think that with this example you can modify and use for other outputs.

I would like to ask if there is a more efficient way to do it?

Example: Go Play


texts:
The task was to check for pairs of anagrams in a string list.

I first sorted all the words. and looped over the letters.
The interview continues with a follow-up, to do the same with limited memory.
I tried to implement a Hash function.

The dictionary return value is only for my convince in order to see all the pairs. I could just print it into the console instead.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;
    using System.Threading.Tasks;

    namespace ConsoleApplication2
    {
    public class ReverseString
    {
        public ReverseString()
        {
            List<string> anagarms = new List<string>();
            anagarms.Add("Gilad");
            anagarms.Add("dilaG");
            anagarms.Add("bat");
            anagarms.Add("but");
            anagarms.Add("utb");
            pairs = PairAnagrams(anagarms);
            pairs = PairAnagramsHash(anagarms);
        }

        Dictionary<string, string> PairAnagrams(List<string> wordsList)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            foreach(var item in wordsList)
            {
                if (dictionary.ContainsValue(item))
                {
                    continue;
                }
                foreach(var item2 in wordsList)
                {
                    if(item.Length != item2.Length || item.Equals(item2))
                    {
                        continue;
                    }

                    var sortedWord1 = item.ToArray();
                    Array.Sort(sortedWord1);
                    var sortedWord2 = item2.ToArray();
                    Array.Sort<char>(sortedWord2);
                    int i;
                    for (i = 0; i < sortedWord2.Length; i++)
                    {
                        if (sortedWord2[i] != sortedWord1[i])
                        {
                            break;
                        }
                    }
                    if(i == sortedWord1.Length)
                    {
                        dictionary.Add(item, item2);
                    }
                }
            }
            return dictionary;
        }

        Dictionary<string, string> PairAnagramsHash(List<string> wordList)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();

            foreach (var item in wordList)
            {
                foreach (var item2 in wordList)
                {
                    if (item.Equals(item2) || dictionary.ContainsKey(item2))
                    {
                        continue;
                    }
                    if (HashFunction(item) == HashFunction(item2))
                    {
                        dictionary.Add(item, item2);
                    }
                }
            }
            return dictionary;
        }

        public int HashFunction(string word)
        {
              int result = 0;
              var charArray = word.ToArray();
              for (int i = 0; i < word.Length; i++)
              {
                  result += charArray[i] * 37;
              }
              return result;
        }
    }
}


texts:
I have a library that defines a bunch of ISprite interfaces, like IPieceSprite and ITileSprite. Then, it defines a global ISpriteFactory that should be supplied to the library upon initialization. ISpriteFactory should create concrete objects based on the interfaces mentioned.

I made this rough implementation, but it makes my skin crawl. What would be a better approach to this problem?

public class SpriteFactoryMock: ISpriteFactory {

    public SpriteType Create<SpriteType>() where SpriteType: ISprite {

        var type = typeof(SpriteType);
        if (type == typeof(ITileSprite))    return (SpriteType)(Object)(new TileSprite());
        if (type == typeof(IPieceSprite))   return (SpriteType)(Object)(new PieceSprite());

        return default(SpriteType);
    }
}

Considering other alternatives, I guess I could create a method for every ISprite interface, and that would work a bit better. I might do that if all hope for the previous approach is lost.


texts:
I have a large matrix samples, I want to make another matrix sampleProb which is the same size, but modified as below:

%samples is a 1000*1000 matrix, M = 1000
sampleProb = zeros(1000);
for i = 1:size(samples, 2)
  for j = 1:M
    for k = 1:M
      if (k ~= j)
        sampleProb(j, i) = sampleProb(j, i) + normcdf(samples(j, i) - samples(k, i));
      end
    end
  end
end
sampleProb = sampleProb./M;

I know it's best to avoid for loops when possible in Matlab and operations should be vectorised, but I can't figure out what to do. How can I optimise this for performance?


texts:
I wrote this Python script to rename specified files to "titlecase", for example:

hello.txt to Hello.txt
hello there.txt to Hello There.txt
path/to/file.txt to path/to/File.txt

The main script:

#!/usr/bin/env python

import os
import re
import argparse

re_junk = re.compile(r'[._-]')
re_spaces = re.compile(r'\s\s+')

def print_rename(old_filename, new_filename):
    print('{} -> {}'.format(old_filename, new_filename))

def do_rename(old_path, new_path):
    print_rename(old_path, new_path)
    os.rename(old_path, new_path)

def get_new_path(old_path):
    """ Get the new path, titlecased and (a little bit) sanitized.
    - Only operate on the basename:
        + don't touch parent directories
        + don't touch the extension
    - Sanitize:
        + replace junk characters with space
        + replace multiple spaces with single space
        + trim extra spaces at start and end

    :param old_path: the path to rename
    :return: titlecased and a little bit sanitized new path
    """
    dirpart, filepart = os.path.split(old_path)
    if filepart.startswith('.'):
        return old_path

    base, ext = os.path.splitext(filepart)
    base = re_junk.sub(' ', base)
    base = re_spaces.sub(' ', base).strip()
    if not base:
        return old_path

    return os.path.join(dirpart, base.title() + ext)

def titlecase(old_path, fun):
    if not os.path.exists(old_path):
        return

    new_path = get_new_path(old_path)
    if old_path == new_path:
        return

    fun(old_path, new_path)

def main():
    parser = argparse.ArgumentParser(description='Rename files to "titlecased" and "sanitized".')
    parser.add_argument('-n', '--dry-run', action='store_true', help='Print what would happen, don\'t rename')
    parser.add_argument('paths', nargs='+')

    args = parser.parse_args()
    fun = print_rename if args.dry_run else do_rename

    for path in args.paths:
        titlecase(path, fun)

if __name__ == '__main__':
    main()

Unit tests:

#!/usr/bin/env python

import unittest

from titlecase import get_new_path

class TestTitleCase(unittest.TestCase):
    def test_hello(self):
        self.assertEqual('Hello', get_new_path('hello'))

    def test_hello_txt(self):
        self.assertEqual('Hello.txt', get_new_path('hello.txt'))

    def test_hello_there_txt_dotted(self):
        self.assertEqual('Hello There.txt', get_new_path('hello.there.txt'))

    def test_hello_there(self):
        self.assertEqual('Hello There', get_new_path('hello there'))

    def test_hello__there(self):
        self.assertEqual('Hello There', get_new_path('hello  there'))

    def test_dot(self):
        self.assertEqual('.', get_new_path('.'))

    def test_dotdot(self):
        self.assertEqual('..', get_new_path('..'))

    def test_subdir(self):
        self.assertEqual('some/path/File.txt', get_new_path('some/path/file.txt'))

    def test_subdir_nobasename(self):
        self.assertEqual('some/path/.txt', get_new_path('some/path/.txt'))

    def test_subdir_dotdot(self):
        self.assertEqual('../path/File.txt', get_new_path('../path/file.txt'))

    def test_subdir_dotdot_in_middle(self):
        self.assertEqual('some/../path/File.txt', get_new_path('some/../path/file.txt'))

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

Is there a better way I missed? Anything to improve?
Better names maybe? Interesting unit test cases I missed?

(This script (along with some other utility scripts) is on GitHub.)


texts: ffmpeg batch script for video resizing - improved

texts:
I posted a question here ffmpeg batch script for video resizing but I forgot the issue of the rotation and the video files were scaled with wrong dimensions.

Below is the improved version of the script

#!/bin/bash

set -eu

status=true
fail() {
    echo "$@" >&2
    status=false
}

# Resize a single file
resize() {
    exiftool -p 'Filename:$filename Megapixel:$megapixels Dimension:$imagesize Rotation:$rotation' $1
    if exiftool -if '$imageheight == 1920 && $imageheight == 1080' $1 >     /dev/null
    then
        fail "-> No need to convert"
        return
    fi

    filename="$(date +%s)".mp4
    rotation=$(exiftool -p '$rotation' $1)

    if [ "${rotation}" -eq 0 ] || [ "${rotation}" -eq 180 ]
    then
        scaling="-1:720"
    elif [ "${rotation}" -eq 90 ] || [ "${rotation}" -eq 270 ]
    then
        scaling="720:-1"
    else
        fail "-> Unhandled rotation"
        return
    fi

    if
        ffmpeg -v error -stats -i "$1" -map_metadata 0 \
               -vf scale="$scaling" -c:v libx264 -crf 23 \
               -c:a copy "$filename" < /dev/null &&
            exiftool -TagsFromFile "$1" '-all:all>all:all' \
                     -overwrite_original "$filename"
    then
        # success
        rename 's/.mp4/.success.mp4/' $1
        mv "$filename" $1
        true
    else
        rename 's/.mp4/.error.mp4/' $1
        # failed; destroy the evidence
        rm -f "$filename" 2>/dev/null
        fail "-> Failed to convert"
    fi
}

[ $# -gt 0 ] || fail "Usage: $0 FILE FILE..."

for arg
do
    if [ -f "$arg" ]
    then
        resize "$arg"
        echo
    elif [ -e "$arg" ]
    then
        fail "$arg: not a plain file or directory"
    else
        fail "$arg: file not found"
    fi
done

exec $status # true or false


texts:
I'm completely new at programming and have started to study computer science this fall. Our first lab is going to require us to make a very simple web page like the picture LAB attached. I was wondering if I could get some good critique on my HTML code and learn some best practices while I'm at it.

<!DOCTYPE html>

<title> EECS1012 – Lab 1 </title>

 About Alen Harriet

 Passionate self-learner. Taking a CS Degree to learn more formal materials like Operating Systems and Computer Architecture, and to have strong fundamentals. My dream is to hopefully work for Google someday.

 My IP address: 192.XXX.XX.XX

 Courses I'm taking this semester.

 EECS 1012

 EECS 1001

 FA VISA 2065

 AP GEOG 2060

 My weekly timetable

     Time
     Monday
     Tuesday
     Wednesday
     Thursday
     Friday

     9am

     10am

     11am

     noon

     1:30pm
        LE EECS 1012

     FA VISA 2065

     2:30pm
      LE EECS 1012

     FA VISA 2065

     3:30pm
      LE EECS 1012

     FA VISA 2065

     4:30pm
      LE EECS 1012  LE EECS 1001

     FA VISA 2065

     5:30pm
      LE EECS 1001  LE EECS 1012

     AP GEOG 2060

     6:30pm
      LE EECS 1012

     AP GEOG 2060

     7:30pm
      LE EECS 1012

     AP GEOG 2060

 My Two Favourite Foods - With Links


texts:
I'm posting my C++ code for LeetCode's LRU Cache. If you have time and would like to review, please do so. Thank you!
Problem

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the
least recently used item before inserting a new item.

The cache is initialized with a positive capacity.

Follow up:

Could you do both operations in O(1) time complexity?

Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4

Accepted C++
#include <list>
#include <unordered_map>

class LRUCache {
public:
    const int size;
    std::list<size_t> lru;
    std::unordered_map<int, std::list<size_t>::iterator> cache;
    std::unordered_map<int, int> key_val_map;

    LRUCache(const int capacity) : size(capacity) {}

    // Getter constant memory
    int get(int key) {
        if (key_val_map.count(key) == 0) {
            return -1;
        }

        update(key);
        return key_val_map[key];
    }

    // Setter constant memory
    const void put(int key, int value) {
        if (key_val_map.size() == size && key_val_map.count(key) == 0) {
            clear();
        }

        update(key);

        key_val_map[key] = value;
    }

    // Add a new key
    const void update(int key) {
        if (key_val_map.count(key)) {
            lru.erase(cache[key]);
        }

        lru.push_front(key);
        cache[key] = lru.begin();
    }

    // Erase cache
    const void clear() {
        key_val_map.erase(lru.back());
        cache.erase(lru.back());
        lru.pop_back();
    }
};

Reference
On LeetCode, there is a class usually named Solution with one or more public functions which we are not allowed to rename.

146. LRU Cache - Problem

146. LRU Cache - Discuss


texts:
We have a rule that all of our validation messages must be in a summary, and thus the default "this field is required" doesn't cut it because the messages lose their context in a summary and therefore need specific field indicators.

I have a solution that I like rather well, but it soon became clear that there was a need for messages outside of just the required field (email, URL, custom methods like phoneUS, etc), so I made some additions to my function.

I've been using jQuery for a while, but I'm not an expert in the optimization area, so I wanted to get some expert help on whether the function below could be optimized...my question is, "is there actually a better way to handle custom error messages in a summary?"

$('.required, .email').each(function(index) {
  var $this = $(this);

  var label = (
    $this.is(':radio')
    ? $("label[data-name='"+$this.attr('name')+"']")
    : label = $("label[for='"+$this.attr('id')+"']")
  );

  var customMessages = [{}];

  if($this.hasClass('required')){
    customMessages.required = "'" + label.text() + "' is required.";
  }

  if($this.hasClass('email')){
    customMessages.email = "'" + label.text() + "' has an invalid email address.";
  }

  $this.rules("add", {
    messages: customMessages
  });
});

Here is the jsFiddle:
http://jsfiddle.net/GD5nw/1/


texts: Sieve of Eratosthenes for prime generation

texts:
I was originally going to write this intro as just being the bare-bones "here's my problem, here are some ideas, what do you recommend" format (which I am still going to follow, mind you), but I've decided to also add some backstory to it.

In high school I would write inefficient programs that generated mathematically significant results, at least to me, and then have hours of fun optimizing and revising the code until it was as clean and fast as I could make it. While I was writing this sieve, I was exploring the generation of primes.

Currently, the code will generate a range of natural numbers from \$1\$ to \$N\$ and store it in a list. Then the program will iterate through that list, marking each multiple of a prime as \$0\$ and storing each prime in a secondary list.

While this solution works just fine, one of the optimizations that I could never wrap my head around writing the code for was removing the multiples of primes instead of simply marking them as \$0\$.

The benefits of doing this are as follows:

Faster execution
Less memory usage
No need for cleanup
No if statements required

The problem is that I'm having a hard time wrapping my head around how I could perform this optimization and still remove multiples of each prime efficiently. If anyone has any ideas on how to do this in TI-Basic, please mention it.

What other optimizations could I make to the code as it is now?

Note: I do use an indentation system here because I loved the readability that indentation provides to languages like Python. Could this have any noticeable impact on the performance of the program?

:ClrList L2
:Input "END: ",E
:E->dim(L1:Fill(1,L1:cumSum(L1->L1
:For(A,2,E)
::If L1(A:Then
:::L1(A->L2(dim(L2)+1
:::For(B,2A,E,A
::::0->L1(B
:::End
::End
:End
:L2

Clarification:

E->dim(L1:Fill(1,L1:cumSum(L1->L1 generates the range from \$1\$ to \$N\$.


texts:
Looking for a cleaner (possibly one liner) way to write the following

my $spec_2d = ( );
foreach ( @spec ) {
  $spec_2d[$_][0] = $spec[$_];
}
@spec = @spec_2d;

Basically I'm making an array an array of arrays


texts:
I have looked at some previous posts and changed my code accordingly.  Do you have some suggestions about my current code?

Here are my specific questions:

What should top() return if the stack is empty?
Why it’s better to use size_t for count?
I didn’t use new to create the stack in main().  Do I need to call the destructor? If no, why? If yes, how should I do it?
According to the rule of three, how will I define the assignment operator for stack? Can you give one example?
I feel I have some misunderstanding about private.  I put top_node in the private section, but why I am able to access top_node in the copy constructor?

The following code compiles and runs.

#include<iostream>
using namespace std;

template<class T>
class MyStack{
public:
    MyStack(): top_node(nullptr), count(0){};

    MyStack(MyStack& st){
        top_node = new Node(st.top());
        Node* temp = st.top_node->next;
        Node* pre = top_node;
        while(temp){
            Node* cur = new Node(temp->val);
            pre->next = cur;
            temp = temp->next;
        }
        count = st.size();
    }

    void push(T item){
        Node* temp = new Node(item);
        if(empty()){
            top_node = temp;
        }else{
            temp->next = top_node;
            top_node = temp;
        }
        count++;
    }

    void pop(){
        if(empty()){
            cout<<"Nothing to pop!"<<endl;
            return;
        }
        Node* temp = top_node;
        top_node = temp->next;
        delete temp;
    }

    int top() const{
        if(empty()){
            cout<<"Nothing to top!"<<endl;
            return -1;
        }
        return top_node->val;
    }

    size_t size() const{
        return count;
    }

    void print() const{
        Node* temp = top_node;
        while(temp){
            cout<<temp->val<<" ";
            temp = temp->next;
        }
        cout<<endl;
    }

    bool empty() const{
        return count==0;
    }

    ~MyStack(){
        Node* temp = top_node;
        while(temp){
            Node* t = temp;
            temp = temp->next;
            delete t;
        }
        top_node = nullptr;
    }

private:
    struct Node{
        T val;
        Node* next;
        Node(T x): val(x), next(nullptr){};
    };
    Node* top_node;
    size_t count;

};

int main(){

    MyStack<char> sasa;
    cout<<"default top: "<<sasa.top()<<endl;
    cout<<"default count: "<<sasa.size()<<endl;

    sasa.pop();
    sasa.push('a');
    sasa.push('p');
    sasa.push('p');
    sasa.print();
    sasa.top();
    cout<<"The current size is "<<sasa.size()<<endl;
    sasa.pop();
    sasa.print();
    cout<<"if empty: "<<sasa.empty()<<endl;

    MyStack<char> sec(sasa);
    sec.print();

    return 0;
}


texts:
I am solving some problems from CodeChef but I am stuck on the Matches problem:

  Ari and Rich are playing a pretty confusing game. Here are the rules
  of the game:

  The game is played with two piles of matches. Initially, the first pile contains N matches and the second one contains M matches.
  The players alternate turns; Ari plays first.
  On each turn, the current player must choose one pile and remove a positive number of matches (not exceeding the current number of
  matches on that pile) from it.
  It is only allowed to remove X matches from a pile if the number of matches in the other pile divides X.
  The player that takes the last match from any pile wins.

  Solve(N,M)

  If its Ari's turn and N%M==0 then Ari wins else Rich wins.
  If N%M!=0 then player try every possible moves and check if he wins any one of them in end.

My solution uses Dynamic Programmming, so I have used functools.lru_cache to save function results. But I am getting TLE error in some test cases.How can I further optimize the code?

from functools import lru_cache

@lru_cache(maxsize=None)
def Solve(X,Y,Player=True):
    if X%Y==0:
        return Player
    else:
        temp=X
        X=X%Y
        if Player==Solve(max(X,Y),min(X,Y),not Player):
            return Player
        while temp!=X+Y:
            X=X+Y
            if Player==Solve(max(X,Y),min(X,Y),not Player):
                return Player
        return not Player


texts:
So this is (I think) a premiere for python. A function that translates brainfuck code to python code. It does a few optimizations (It chains +,-,>,< together to one operation). I don't think you can do more optimizations, but I am open for ideas. At the beginning of the created source code there will be a few imports (defaultdict and getch) and a few function definitions (add, sub, putch) and obviously the data structures data and index. Is there anything I could improve? Anything else I could optimize away?

def translate(sourcecode):
    out = [
        (0, "from collections import defaultdict"),
        (0, "from msvcrt import getch"),
        (0, "putch = lambda x: print(chr(x), end='')"),
        (0, "data = defaultdict(int)"),
        (0, "index = 0"),
        (0, "def add(x):data[index] = (data[index] + x) % 256"),
        (0, "def sub(x):data[index] = (data[index] - x) % 256"),
    ]
    level = 0
    count = 0
    operation = None
    for c in sourcecode:
        if c == operation:
            count += 1
        else:
            if operation == "+":
                out.append((level, f"add({count!r})"))
            elif operation == "-":
                out.append((level, f"sub({count!r})"))
            elif operation == ">":
                out.append((level, f"index += {count!r}"))
            elif operation == "<":
                out.append((level, f"index -= {count!r}"))
            operation = None

            if c in "+-><":
                operation = c
                count = 1
            elif c == ".":
                out.append((level, "putch(data[index])"))
            elif c == ",":
                out.append((level, "data[index] = getch()[0]"))
            elif c == "[":
                out.append((level, "while data[index]:"))
                level += 1
            elif c == "]":
                assert level
                level -= 1
    return "\n".join("    " * indent + line for indent, line in out)

print(translate("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."))

(if you are not on windows, you need an alternative to the getch function)


texts: Using two handlers for a GraphQL project; handle query with the second one if the first one is not capable of

texts:
I'm trying to use both SuperGraph as-a-library and GqlGen.
So I have two handlers:

the first one is SuperGraph; this checks that it can carry out the operation

the second one is GqlGen; this checks that it can carry out the operation if the first one can't

The code I'm using is this:
type reqBody struct {
    Query string `json:"query"`
}

func Handler(sg *core.SuperGraph, next http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        bodyBytes, _ := ioutil.ReadAll(r.Body)
        r.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))

        var rBody reqBody
        err = json.NewDecoder(bytes.NewBuffer(bodyBytes)).Decode(&rBody)

        ctx := context.WithValue(r.Context(), core.UserIDKey, "user_id")
        res, err := sg.GraphQL(ctx, rBody.Query, nil)
        if err == nil {
            render.JSON(w, r, res) // go-chi "render" pkg
        } else {
            next.ServeHTTP(w, r)
        }
    }
}

func main() {
    r := chi.NewRouter()

    r.Group(func(r chi.Router) {
        r.Post("/graphql", Handler(supergraph, gqlgen))
    })
}

QUESTIONS

Can I avoid these lines at all?
  bodyBytes, _ := ioutil.ReadAll(r.Body)
  r.Body = ioutil.NopCloser(bytes.NewReader(bodyBytes))

Is there a better way to handle all this?

I know I can use a GraphQL gateway to join multiple schemas under the same endpoint, but is it really worth it? Is my idea/code really bad?


texts:
The code beyond approximates the error-function erf(x) with following formular \$erf(x)=1-(a_1t+a_2t^2+a_3t^3)e^{-x^2})\$ for \$x\geq0\$ inclusive the identity \$erf(-x)=-erf(x)\$.

Is it okay to end the program in the middle of a code with exit(EXIT_FAILURE)? I just tried to avoid it and came to following solution, where the program always ends with return 0 at the end of the main-programm:
https://codepaste.net/ek8ed5 So the question is whats's the more correct way?

(I hope a moderator can paste this code section in here please, because somehow I didn't make it work to show it as nicely formatted code, sorry!)

What else can I improve?

.

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

#define p 0.47047
#define a_1 0.3480242
#define a_2 -0.0958798
#define a_3 0.7478556

double ErrorFunction(double x);

int main(void)
{
  double x = 0;

  do
  {
    printf("Enter any value x to show erf(x): ");

    if (scanf_s("%lf", &x) != 1)
    {
      printf("error: invalid input\n");
      exit(EXIT_FAILURE);
    }
    else
    {
      printf("\n erf(x)=%f\n\n", ErrorFunction(x));
    }

  } while (x != 0);

  return 0;
}

double ErrorFunction(double x)
{
  double t = 0;

  if (x < 0)
  {
    x = -x;
    t = 1 / (1 + p*x);
    return -(1 - (a_1*t + a_2*t*t + a_3*t*t*t)*exp(-(x*x)));
  }
  else
  {
    t = 1 / (1 + p*x);
    return 1 - (a_1*t + a_2*t*t + a_3*t*t*t)*exp(-(x*x));
  }
}


texts: More idiomatic way to handle simple file writing in C#?

texts:
Is there anything you would change about the following function? I welcome any feedback on style, correctness, etc. Thank you for reading.

Some of my questions are:

Obviously, I catch the exception and convert it to a return value because I don't want to take down the application in case of an error. Would it be better to allow the exception to propagate up and handle it there (in the function that is coordinating the creation of the set of import files)?
Is there another, "better-in-general" way of writing to files?

private static bool CreateImportFile(string path, string content)
{
    try
    {
        using (var fileStreamWriter = File.CreateText(path))
        {
            fileStreamWriter.Write(content);
            fileStreamWriter.Close();
        }
    }
    catch (IOException e)
    {
        Console.WriteLine("Failed to write import file due to IOException. " + e.Message);
        return false;
    }

    return true;
}


texts:
Like anything that shouldn't be done, I decided to see if it is possible to match <script> tags robustly using regexes in PHP. Since there is no arbitrary nesting, I figured it should at least be possible.

This is what I came up with. It is designed to handle every edge case I could think of, including:

arbitrary attributes in the opening script tag
single and multiline comments and single and double-quoted strings (which might include arbitrary escape sequences) in the javascript which may contain the characters </script>
Captures the smallest script tag it finds.

Did I miss anything? Ideally, I want it to match exclusively anything a browser would consider a script element (might not be possible), but at the very least, I would like it to match only well-formed script tags with well-formed javascript.

Here is the string for the regex that I am passing to preg_match:

'#<script(?:[^>"]*(?:"[^"]*")?)*>((?:"(?:[^\\\\\\n"]*(?:\\\\.)*)*"|\'(?:[^\\\\\\n\']*(?:\\\\.)*)*\'|<[^/]?|/\\*(?:[^*]|\\*[^/]?)*\\*/|//.*|/[^/*]|[^\'"</])*)</script>#';

Note: I am not using this in production.


texts:
I am in the midst of writing a simple job board and I have the URL's filtering and working how I want, everything works - I just want to know if I can improve it, if there are any security concerns, and if it is horribly inefficient.

Take the following URL section - foo.com/in/london/at/google/do/design

I assign each section a variable and work out the location, company, and category.

Other use cases that work:

Switching the order - foo.com/at/google/in/london/do/design
Having less parameters - foo.com/in/london/at/google

My code to figure out all these variables is:

$regex = "[^a-zA-Z0-9,-]";
$a = isset($_GET["a"]) ? preg_replace("/".$regex."/", "", $_GET["a"]) : "";
$aa = isset($_GET["aa"]) ? preg_replace("/".$regex."/", "", $_GET["aa"]) : "";
$b = isset($_GET["b"]) ? preg_replace("/".$regex."/", "", $_GET["b"]) : "";
$bb = isset($_GET["bb"]) ? preg_replace("/".$regex."/", "", $_GET["bb"]) : "";
$c = isset($_GET["c"]) ? preg_replace("/".$regex."/", "", $_GET["c"]) : "";
$cc = isset($_GET["cc"]) ? preg_replace("/".$regex."/", "", $_GET["cc"]) : "";

if ($a == "in" && $aa != null) { $searchLocation = $aa; }
if ($b == "in" && $bb != null) { $searchLocation = $bb; }
if ($c == "in" && $cc != null) { $searchLocation = $cc; }

if ($a == "at" && $aa != null) { $searchCompany = $aa; }
if ($b == "at" && $bb != null) { $searchCompany = $bb; }
if ($c == "at" && $cc != null) { $searchCompany = $cc; }

if ($a == "do" && $aa != null) { $searchCategory = $aa; }
if ($b == "do" && $bb != null) { $searchCategory = $bb; }
if ($c == "do" && $cc != null) { $searchCategory = $cc; }

if ($a == "missinghtml") { $errorUrl = true; }

I'm looking at this thinking there must be a better to do this. Is this section secure? Any thoughts on this are much appreciated. Like I say it works, but can it be better?


texts:
I have a single page application where the resources sit on the classpath. Any request for a resource that doesn't exist should redirect to the index.html page. Resources should be mapped to memory on first request and then all subsequent requests should load from memory.

Have I made any mistakes with how I should be using direct ByteBuffers, it feels overly laborious, but that could just be the API?

class MemoryMappedClasspathHttpServlet extends HttpServlet {

    private final ConcurrentMap<String, ByteBuffer> mappedResources = new ConcurrentHashMap<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestPath = req.getPathInfo();

        if (requestPath.equals("/")) {
            requestPath = "/web/index.html";
        } else {
            requestPath = "/web" + requestPath;

            if (MemoryMappedClasspathHttpServlet.class.getResource(requestPath) == null) {
                requestPath = "/web/index.html";
            }
        }

        ByteBuffer buffer = mappedResources.computeIfAbsent(requestPath, MemoryMappedClasspathHttpServlet::loadResourceFromClasspath);

        Channels.newChannel(resp.getOutputStream())
            .write(buffer.duplicate());
    }

    private static ByteBuffer loadResourceFromClasspath(String classpathItem) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream();
             InputStream is = MemoryMappedClasspathHttpServlet.class.getResourceAsStream(classpathItem)) {

            byte[] buffer = new byte[8092];

            for (int len; (len = is.read(buffer)) != -1; ) {
                os.write(buffer, 0, len);
            }

            os.flush();

            byte[] bytes = os.toByteArray();

            ByteBuffer directBuffer = ByteBuffer.allocateDirect(bytes.length);
            directBuffer.put(bytes);
            directBuffer.flip();

            return directBuffer;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}


texts: Extracting values from dictionaries where the keys match

texts:
I have two Dictionaries with around 65,000 KeyValuePairs each. I used foreach and if-else statements to compare them and get values, but it goes very slow. How could I optimize my code and gain more speed?

private void bgwCompare_DoWork(object sender, DoWorkEventArgs e)
{
    var i = 0;

    foreach (KeyValuePair<string, string> line1 in FirstDictionary)
    {
        foreach (KeyValuePair<string, string> line2 in SecondDictionary)
        {
            if (line1.Key == line2.Key)
            {
                ResultDictionary.TryAdd(line1.Value, line2.Value);

                ListViewItem item = new ListViewItem(line1.Value);
                item.SubItems.Add(line2.Value);

                ResultList.Items.Add(item);
            }

            i++;
            bgwCompare.ReportProgress(i * 100 / (FirstDictionary.Count() * SecondDictionary.Count()));
        }
    }
}


texts: Copy a FileInputStream to a file, either as text or as a string of bytes

texts:
I have written a small program that reads input from a text file and then writes this output to a text file. The method contains a switch which decides whether to output to the file as text or as a literal string of the bytes. How could I refactor this code to only include a single if statement block instead of two to switch between these two modes? I am also interested if there is a more optimal way of writing this code overall.

I have tried to create just one switch at the beginning of the code which would change the output files from output-text-txt to output-bytes.txt (which are located in the resources folder) as well as changing the writing method (whether it writes the integer or string literals). I encounter difficulty when I need to write the bytes because the method asks for either an integer or a string and I am not sure how I would change these writing methods with just one if statement at the beginning of the code (due to it asking for int c as a parameter)

public class ByteStreamTest {

    private static File input;
    private static File output;

    public static void main(String args[]) throws Exception {
        new ByteStreamTest().write(true);
        new ByteStreamTest().write(false);
    }

    public ByteStreamTest() {}

    public void write(boolean asText) {

        input = new File(getClass().getClassLoader().getResource("input.txt").getPath());

        if (asText) {
            output = new File(getClass().getClassLoader().getResource("output-text.txt").getPath());
        } else {
            output = new File(getClass().getClassLoader().getResource("output-bytes.txt").getPath());
        }

        FileInputStream in = null;
        FileWriter fw = null;

        try {

            in = new FileInputStream(input);
            fw = new FileWriter(output);

            int c;

            while ((c = in.read()) != -1) {
                if (asText) {
                    fw.write(c);
                } else {
                     fw.write(String.valueOf(c) + System.getProperty("line.separator"));
                }
            }

            in.close();
            fw.close();

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

This isn't really a question that has to do with the functionality of the code, I am simply interested in refactoring the code to include as little if statements as possibly optimizing it further.


texts: Get rows from a table and add rows to google charts

texts:
The Code

PHP:

<?php
session_start();

if ($_SESSION['Username'] == "")
{
    header('Location: Login.php');
}
?>

Java Script:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    //Google Stuff
    google.charts.load('current', {packages: ['corechart']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
        // Define the chart to be drawn.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Element');
        data.addColumn('number', 'Percentage');
        data.addRows([
            <?php

            include 'php/dbh.php';

            $Rows = array();

            $sql = "SELECT * FROM Sales";

            $Result = mysqli_query($conn, $sql);

            if ($Result)
            {
                while ($row = mysqli_fetch_assoc($Result)) {
                    $Rows[] = $row;
                }
            }
                $ListArray = array();
                foreach ($Rows as $row)
                {
                    asort($row);
                    $row = explode(",", $row['Products']);
                    $ListArray = $row;

                }

                $numItems = count($ListArray);
                $i = 0;
                foreach ($ListArray as $item)
                {
                    $i2 = 0;
                    $Newitem = ltrim($item);
                    $sql2 = "SELECT * FROM submenus WHERE Name='".$Newitem."'";
                    $Result = mysqli_query($conn, $sql2);
                    if (!$Result)
                    {
                        print_r(mysqli_error($conn));
                    }
                    if ($Result)
                    {
                        while ($row = mysqli_fetch_assoc($Result))
                        {
                            $i2 = $row['Sales'];

                        }
                    }

                    if(++$i === $numItems)
                    {
                        echo "['".$item."',".$i2."]";
                    }
                    else
                    {
                        echo "['".$item."',".$i2."],";
                    }
                }

                ?>
            ]);

        // Set chart options
    var options = {
    title:'Sales',
    titleTextStyle: {color: 'white', bold: true},
    height:300,
    backgroundColor: '#3a3939',
    color: '#fff',
    legend: {textStyle: {color: 'white'}},
    hAxis: {gridlines: {color: 'black'}}};

  // Instantiate and draw the chart.
  var chart = new google.visualization.PieChart(document.getElementById('SalesChar'));
  chart.draw(data, options );
    }

   </script>

HTML:

    <fieldset class="Sales">
        <legend style="color: white;">Sales</legend>
        <div id="SalesChar"/>
    </fieldset>

How it works

The PHP Code just start a session and if the Username is == "" it will redirect to the login page.

The Java Script is Located in the header of a webpage and it simply load and draw rows, inside the data.addRows([]); There is a PHP code that first gets a table called Sales, then for each row it will explode the column called products so it gets  multiple string and then add it to a array then for each string it will get from another table called submenus then if everything goes right it will echo something like this ['Test', 2]

The Html is located in the body and it is only there because it is indicating where the chart should be drawn

What i want to know

i want to know if there is any way possible to make the PHP that is located inside the javascript more compact and more readable (i mean easier to understand) and take a less space.

I am open to any other suggestion


texts: AABB Intersections with Space Partitions, A Sample Code Performance and Reliability

texts:
I have originally written the following Matlab code to find intersection between a set of Axes Aligned Bounding Boxes (AABB) and space partitions (here 8 partitions). I believe it is readable by itself, moreover, I have added some comments for even more clarity.

function [A,B] = AABBPart(bbx,it)                                     % bbx: aabb, it: iteration
global F
IT = it+1;
n = size(bbx,1);
F = cell(n,it);
A = Part([min(bbx(:,1:3)),max(bbx(:,4:6))],it,0);                     % recursive partitioning
B = F;                                                                % matlab does not allow
    function s = Part(bx,it,J)                                        %   output to be global
        s = {};
        if it < 1; return; end
        s = cell(8,1);
        p = bx(1:3);
        q = bx(4:6);
        h = 0.5*(p+q);
        prt = [p,h;...                                                % 8 sub-parts (octa)
            h(1),p(2:3),q(1),h(2:3);...
            p(1),h(2),p(3),h(1),q(2),h(3);...
            h(1:2),p(3),q(1:2),h(3);...
            p(1:2),h(1),h(1:2),q(3);...
            h(1),p(2),h(3),q(1),h(2),q(3);...
            p(1),h(2:3),h(1),q(2:3);...
            h,q];
        for j=1:8                                                     % check for each sub-part
            k = 0;
            t = zeros(0,1);
            for i=1:n
                if all(bbx(i,1:3) <= prt(j,4:6)) && ...               % interscetion test for
                        all(prt(j,1:3) <= bbx(i,4:6))                 %   every aabb and sub-parts
                    k = k+1;
                    t(k) = i;
                end
            end
            if ~isempty(t)
                s{j,1} = [t; Part(prt(j,:),it-1,j)];                  % recursive call
                for i=1:numel(t)                                      % collecting the results
                    if isempty(F{t(i),IT-it})
                        F{t(i),IT-it} = [-J,j];
                    else
                        F{t(i),IT-it} = [F{t(i),IT-it}; [-J,j]];
                    end
                end
            end
        end
    end
end

Concerns:

In my tests, it seems that probably few intersections are missing, say, 10 or so for 1000 or more setup. So I would be glad if you could help to find out any problematic parts in the code.
I am also concerned about using global F. I prefer to get rid of it.
Any other better solution in terms of speed, will be loved.

Note that the code is complete. And you can easily try it by some following setup.

n = 10000;                        % in the original application, n would be millions
bbx = rand(n,6);
it = 3;
[A,B] = AABBPart(bbx,it);


texts: Record parsing to Scala object with some unknown fields

texts:
I am getting some customer data but don't know the complete schema beforehand. I want to parse this data and create a Scala object from it. But due to unknown fields in the record, I fill only the important fields and remaining record data is dumped in a remData placeholder field. This remData is used so that we can still see the customer data in output and can add more fields in future.

The customer provides 3-4 types of such feeds with each feed having 15-20 fields. I want to generate a generic framework for such parsing. I tried this code and it works but I wonder if there are any common patterns for such type of parsing or a cleaner approach.

class Record{
    var imptField1 =""
    var imptField2 =""
    var remData =""
    def this(data:String){
      this()
      val fieldKeyValues = data.split(",")
      for( fieldKeyValue <- fieldKeyValues){
        val tokens = fieldKeyValue.split("=")
        val key = tokens(0)
        key match{
          case "imptField1"=> this.imptField1 = tokens(1)
          case "imptField2"=> this.imptField2 = tokens(1)
          case _ => this.remData +=fieldKeyValue+","
        }
      }
   }
 }

I also tried using Jackson objectMapper for that but it doesn't provide the functionality of dumping unknown fields in a placeholder. Please suggest a more efficient/cleaner way of doing this.


texts:
Haven't any experience writing recursive functions.(Generally tend to avoid them - not sure if that's a negative). What do you think about the following?
This is also my first time using JUnit, I'd appreciate input if I'm doing something wrong there.

Challenge: Create a digital Root Function.
Specifications:
A digital root is the recursive sum of all the digits in a number.
Given n, take the sum of the digits of n.
If the resulting value has two digits, continue reducing until a single-digit number is produced.
This is only applicable to the natural numbers.

Solution:
public static int getDigitalRoot(int num) {
        if (Integer.toString(num).length() == 1) { return num; }
        int result = 0;

        for (char c : Integer.toString(num).toCharArray()) {
            result += Character.getNumericValue(c);
        }

        return getDigitalRoot(result);
    }

Tests:
@Test
    public void Tests() {
      assertEquals(6 , Utilities.getDigitalRoot(942));
      assertEquals(7, Utilities.getDigitalRoot(16));
    }


texts:
I'm mostly looking to get feedback on how well I've implemented the C++ language. But I would also like feedback on my algorithm. Did I make it more complex than it needs to be? Is there anything I could have done better?

Things my algorithm prevents:

IIII <- "too many multiples," better represented as IV
IIIV <- "cannot add the same digit to a subtraction," better represented as VI
IVI <- "addition cannot follow subtraction," better represented as V
IXX <- "cannot subtract from a multiple," better represented as XIX

Things it does not prevent (that I'm aware of):

XICV <- "bad format," better represented as CXIV
IXIX <- "repeated subtraction," better represented as XVIII
VV <- "multiple is value of existing digit," better represented as X

Note: This uses the rules of roman numerals I was taught, and I realize that there isn't really a an accepted standard of rules for representing numbers using roman numerals.

#include <string>
#include <stack>
#include <iostream>
#include <ctype.h> // required for tolower()

using namespace std;

int get_roman_value( char );
int roman_to_decimal( string& );

int main( int argc, char* argv[] )
{

    if( argc > 1 )
    {
        string roman(argv[1]);
        try {
            cout << roman_to_decimal(roman) << endl;
        } catch( const char* e ) {
            cerr << e << endl;
        }

    }

    return 0;
}

int get_roman_value( char digit )
{
    switch( tolower(digit) )
    {
        case 'i': return    1; break;
        case 'v': return    5; break;
        case 'x': return   10; break;
        case 'l': return   50; break;
        case 'c': return  100; break;
        case 'd': return  500; break;
        case 'm': return 1000; break;
        default: throw "bad digit";
    }
    return 0;
}

int roman_to_decimal( string& roman )
{

    int decimal = 0;    // the final result
    int multiple = 0;   // keeps track of multiples, eg. In XXV, X would be a multiple
    int current = 0;    // the digit currently being processed
    int last_add = 0;   // the last digit that wasn't a multiple, or subtraction operation
    int last_sub = 0;
    stack<int> digits;  // queue of the digits
    string::iterator i; // iterator to loop through the roman string

    for( i = roman.begin(); i < roman.end(); i++ )
        digits.push( get_roman_value(*i) );

    do
    {

        // get the current digit
        current=digits.top(), digits.pop();

        // if there are too many multiples, then throw up
        if( multiple > 2 )
            throw "too many multiples";

        // check for a substraction operation
        if( !digits.empty() && current > digits.top() )
        {
            if( multiple > 0 )
                throw "cannot subtract from a multiple";
            if( last_add == digits.top() )
                throw "addition cannot follow subtraction";
            decimal+=(current-digits.top()), last_sub=digits.top(), digits.pop();
        }
        // check for multiples
        else if( !digits.empty() && current == digits.top() )
            decimal += current, multiple++;
        // regular addition operation
        else
            if( last_sub == current )
                throw "cannot add the same digit to a subtraction";
            else
                decimal+=current, multiple=0, last_add=current;

    } while( !digits.empty() );

    return decimal;

}


texts: Best practice to load settings to the web application

texts:
I have to load settings to an app when it's opened (It's an Electron application and I'm loading settings from the local json file)

I'm loading settings right after the page is loaded:

document.onreadystatechange = function(){
    if (document.readyState === 'complete'){
        loadSettings();
    }
}

but I think this is not the right way to do it because at first, the page sets inputs, like checkboxes, as they are in HTML file and only after that, changes their values again according to settings.
I want to know what is the best practice to load the settings to a web app.


texts: Creating indexes from a theoretical decimal/int, splitting into before and after arrays

texts:
I'm currently populating before and after arrays with indexes, based on a number provided. If the input going in is an int, there will be three indexes (left, middle and right). If it is a decimal, there will just be two (left, right). There will me a maximum of three indexes to sort into a maximum of two arrays (before and after). To understand, here is some expected input/output:

input: 1
output: before [] after [0, 1, 2]

input: 1.5
output: before [] after [1, 2]

input: -3.4
output: before [3, 4] after []

input: 0
output: before [1] after [0, 1]

Essentially, the input index gets floored and ceiling'd (or, in the case of a whole number, their next/previous integers are used along with the original input). If any of the resulting integers are below 0, they get put in the before array, but their index is made absolute, otherwise they go into the after array. If they do get put into the before array, then they are put in to reverse order, such that they remain sorted in numerical order.

I have the below working code. But I feel like I could do much better. How would the community go about optimising this?

var input = document.getElementById('input');
var button = document.getElementById('button');
var ouput = document.getElementById('output');

function getOutput(input) {

  var left = Math.floor(input);
  var right = Math.ceil(input);
  var middle;

  var before = [];
  var after = [];

  if (right == left)
    left--,
    middle = left + 1,
    right = left + 2;

  if (left < 0)
    before.unshift(Math.abs(left));
  else
    after.push(left);

  if (middle < 0)
    before.unshift(Math.abs(middle));
  else if (typeof middle == 'number')
    after.push(middle);

  if (right < 0)
    before.unshift(Math.abs(right));
  else
    after.push(right);

  return {before: before, after: after};

}

function buttonPressed () {

  var i = parseFloat(input.value);
  var msg = 'not a number';

  if (!isNaN(i)) {

    var o = getOutput(i);

    msg = 'before [' + o.before.toString() + '] ahead [' + o.after.toString() + ']';

  }

  ouput.innerHTML = msg;

}
<input id="input" type="text">
<input id="button" type="button" value="get" onclick="javascript:buttonPressed();">

My interest is in the getOutput method. The other stuff is for demonstration purposes.

Update

I have adjusted the expected output and the code from the original question, after being prompted to rethink from the comments.


texts: Elixir SQL Query Returning Structs or Counts

texts:
I have a few raw queries which are similar to each other in that it is mostly duplicate code with the difference being that one returns structs and the other returns counts of how many there are.

How would it be best to reduce this into possibly one function? I was thinking that maybe a opts \\ :return_struct would  work for checking to see if a count was requested or the objects themselves.

  @doc """
  Returns the lazy for a time period of days. Lazy customers
  are the ones that have not had a transaction in a period of time
  """
  def lazy_customers(merchant_id, date) do
    sql = """
      WITH lazy_transactions AS (
        WITH new_transactions AS (
             select * from transactions
             where merchant_id = $1 and inserted_at > $2::date
           ), older_transactions AS (
                select * from transactions
                where merchant_id = $1 and inserted_at < $2::date
             )
        SELECT * from older_transactions
        WHERE user_id NOT IN (select user_id from new_transactions)
      )
      SELECT * from users where id IN (select user_id from lazy_transactions)
    """

    result = Ecto.Adapters.SQL.query!(MyApp.Repo, sql, [merchant_id, string_to_date(Date.to_string(date))])
    Enum.map(result.rows, &MyApp.Repo.load(User, {result.columns, &1}))
  end

  @doc """
  Returns the lazy for a time period of days. Lazy customers
  are the ones that have not had a transaction in a period of time
  """
  def lazy_customers_count(merchant_id, date) do
    sql = """
      WITH lazy_transactions AS (
        WITH new_transactions AS (
             select * from transactions
             where merchant_id = $1 and inserted_at > $2::date
           ), older_transactions AS (
                select * from transactions
                where merchant_id = $1 and inserted_at < $2::date
             )
        SELECT * from older_transactions
        WHERE user_id NOT IN (select user_id from new_transactions)
      )
      SELECT COUNT(id) FROM users WHERE id IN (SELECT user_id FROM lazy_transactions)
    """

    result = Ecto.Adapters.SQL.query!(MyApp.Repo, sql, [merchant_id, string_to_date(Date.to_string(date))])
    result.rows
      |> List.flatten
      |> List.first
  end

The real differences is on the bottom line of the raw SQL where either SELECT * FROM ... or  SELECT COUNT(id) FROM ... is changed. The next change is how result is handling in terms of returning a count or an array of %Transaction{} structs.

How can I DRY this up a little?


texts: Is there a better way of implementing this control structure?

texts:
I have the following control structure that I would like to improve:

if(number >= 100)    then doSetInc(id, 8, 20)
elseif(number >= 91) then doSetInc(id, 8, 30)
elseif(number >= 81) then doSetInc(id, 8, 50)
elseif(number >= 7)  then doSetInc(id, 8, 70)
elseif(number >= 1)  then doSetInc(id, 8, 100)
end


texts: Function to check whether entire list is prime numbers

texts:
I have a prime function which accepts a list of numbers and checks if all of the numbers in the list are prime.

Here is my code:

from math import sqrt
def primes(lista):
    return all(True if n == 2 else bool(all(n % x for x in list(range(3, int(sqrt(n)+1), 2))+ [2])) for n in lista)

Can I make this code more readable without making the actual function slower?


texts: Enable or disable sections of a model according to user input

texts:
I am using sed command to comment in or out sections in my model according to user input (commenting is done by prefixing the line with !).  Once this is done, I rebuild my model to get a new executable. An example of a model file (named as scm_code_ex.txt in the script) is:

code
code
code-auto
code-auto
code-auto
code
code
code
code
code-agg
code-agg
code-agg
code
code
code
code
code
code
code
code

My script asks the user which sections of the code to comment out (off means comment out):

#!/bin/bash
# This script will comment in or out sections in the code text file
echo "- Aggregation (on) or (off) (type in ans)?"
read agg

echo "- Autoconversion (on) or (off) (type in ans)?"
read auto

#Revert to original with everything ON.

#On autoconversion
    sed -e'3s/\!//' scm_code_ex.txt >scm_code_ex.tmp
    sed -e'4s/\!//' scm_code_ex.tmp >scm_code_ex.tmp2
    sed -e'5s/\!//' scm_code_ex.tmp2 >scm_code_ex.tmp3

#On aggreagation
    sed -e '10s/\!//' scm_code_ex.tmp3 > scm_code_ex.tmp4
    sed -e '11s/\!//' scm_code_ex.tmp4 > scm_code_ex.tmp5
    sed -e '12s/\!//' scm_code_ex.tmp5 > scm_code_ex.txt

#Remove unwanted files
rm *.tmp*

#Modifications according to conditions

if [ "$agg" == 'on' ] && [ "$auto" == 'on' ]; then
#the conditional statemet above needs spacing in
#all the right steps otherwise it will not work

echo ""
echo "agg on ... auto on "
echo "Rebuild model now"
echo ""

elif [ "$agg" == 'off' ] && [ "$auto" == 'off' ]; then

#commenting out autoconversion section lines 3-5
    sed -e "3s/^/!/g" scm_code_ex.txt > scm_code_ex.tmp
    sed -e "4s/^/!/" scm_code_ex.tmp > scm_code_ex.tmp2
    sed -e "5s/^/!/" scm_code_ex.tmp2 > scm_code_ex.tmp3

    #the ^ means go to the beginning of the line and add the character !

#commenting out aggregation section lines 10-12
    sed -e "10s/^/!/" scm_code_ex.tmp3 > scm_code_ex.tmp4
    sed -e "11s/^/!/" scm_code_ex.tmp4 > scm_code_ex.tmp5
    sed -e "12s/^/!/" scm_code_ex.tmp5 > scm_code_ex.txt

#Remove unwanted files
rm *.tmp*

echo ""
echo "agg off ... auto off "
echo "Rebuild model now"
echo ""

elif [ "$agg" == 'on' ] && [ "$auto" == 'off' ]; then

#commenting out autoconversion section lines 2-5
    sed -e "3s/^/!/g" scm_code_ex.txt > scm_code_ex.tmp
    sed -e "4s/^/!/" scm_code_ex.tmp > scm_code_ex.tmp2
    sed -e "5s/^/!/" scm_code_ex.tmp2 > scm_code_ex.txt

#Remove unwanted files
rm *.tmp*

echo ""
echo "agg on ... auto off "
echo "Rebuild model now"
echo ""

elif [ "$agg" == 'off' ] && [ "$auto" == 'on' ]; then

#commenting out aggregation section lines 10-12

    sed -e "10s/^/!/" scm_code_ex.txt > scm_code_ex.tmp4
    sed -e "11s/^/!/" scm_code_ex.tmp4 > scm_code_ex.tmp5
    sed -e "12s/^/!/" scm_code_ex.tmp5 > scm_code_ex.txt

#Remove unwanted files
rm *.tmp*

echo ""
echo "agg off ... auto on"
echo "Rebuild model now"
echo ""
fi

I'm very new to programming so I'm wondering how to make this better. For example, can sed be applied to a range of lines in one command? (I could not find something similar). To comment out lines 3-5, I tried sed "3,5{s/^/!/}" scm_code_ex.txt but that didn't work.


texts: Kattis "Chasing Subs" custom decryption challenge

texts:
I wrote a function to solve a problem in Java, but it's still too brute force, and I'd like to optimize in terms of runtime.

Link to the description of the problem. The input consists of two lines: a fragment of plaintext, preceded by the message that is encrypted using some unknown character-to-character mapping. The challenge is to find out where the plaintext fragment could have come from.

What I have tried in the code below is to go over the encrypted string char by char (for the length of my key every time), and try to make a dictionary. If I could successfully assign every character from the key to a character from the encrypted text in a deterministic manner, then I note it down in a counter, and start over from the next character in the encrypted text.

So far this solution works on every test, until it reaches huge test case where my "brute force" solution is exceeding the time limit.

Any ideas on how could I improve performance or try a different approach?

package chasingsubs;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;

public class ChasingSubs {

    private void decrypt(String line, String key) {
        int counter = 0;
        int startIndex = 0;
        for (int i = 0; i < line.length() - key.length() + 1; i++) {
            HashMap<Character, Character> dictionary = new HashMap<>();
            HashSet<Character> used = new HashSet<>();

            for (int j = 0; j < key.length(); j++) {
                Character keyChar = key.charAt(j);
                Character sourceChar = line.charAt(i+j);

                if (dictionary.get(keyChar) == null) {
                    if (!used.contains(sourceChar)) {
                        dictionary.put(keyChar, sourceChar);
                        used.add(sourceChar);
                    }else{
                        break;
                    }
                } else if (!dictionary.get(keyChar).equals(sourceChar)) {
                    break;
                }

                if (j == key.length() - 1) {
                    counter++;
                    if (counter == 1) {
                        startIndex = i;
                    }
                }
            }
        }
        if (counter == 0) {
            System.out.println("0");
            return;
        }
        if (counter == 1) {
            System.out.println(line.substring(startIndex, startIndex + key.length()));
            return;
        }
        System.out.println(counter);
    }

    public static void main(String[] args) {
        ChasingSubs base = new ChasingSubs();
        Scanner scanner = new Scanner(System.in);
        base.decrypt(scanner.nextLine(), scanner.nextLine());
    }

}


texts: PHP function (in WordPress) echoing HTML

texts:
I'm really new to PHP, and a little less so in WordPress. I've created a working function that spits out some static HTML into a page template in WordPress. I'd like to know if there is a best practice for this, perhaps someone can help.

function my_html_function() {
    echo '
Title

A list item

A list item

A list item

A list item

';
    }

And within my WP page template I use:

<?php echo my_html_function(); ?>

This HTML is static and won't be changed.


texts: Cleaning and simplifying function that returns a number based on certain values


texts:
Original question: Basic Config Class

One problem I know about is Initialize() not being threadsafe, which I am sorting as we speak, so please disregard that.

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

namespace Apple.Application.Base.Config
{
    internal class AppleConfig
    {
        /// <summary>
        /// List of configuration items
        /// </summary>
        private Dictionary<string, string> _configItems;

        /// <summary>
        /// Config file info
        /// </summary>
        private readonly FileInfo _configFile;

        /// <summary>
        /// Log4net logger.
        /// </summary>
        private readonly ILog _log;

        /// <summary>
        /// Checks if class has been initialized.
        /// </summary>
        private readonly bool _initialized;

        /// <summary>
        /// AppleConfig constructor.
        /// </summary>
        /// <param name="fileP=path"></param>
        public AppleConfig(string filepath)
        {
            if (_initialized)
                return;

            _configItems = new Dictionary<string, string>();
            _configFile = new FileInfo(filepath);
            _log = LogManager.GetLogger(typeof(AppleConfig));
            _initialized = Initialize();
        }

        /// <summary>
        /// Initializes AppleConfig
        /// </summary>
        private bool Initialize()
        {
            try
            {
                foreach (string line in File.ReadLines(_configFile.FullName).Where(IsConfigurationLine))
                {
                    var splittedLine = line.Split('=');

                    String key = splittedLine[0];
                    String value = splittedLine[1];

                    _configItems[key] = value;
                }

                return true;
            }
            catch (Exception exception)
            {
                _log.Error(exception); // assuming overload that takes an exception.
                return false;
            }
        }

        /// <summary>
        /// Checks for valid config line
        /// </summary>
        /// <param name="Line">String to check</param>
        /// <returns></returns>
        private bool IsConfigurationLine(string line)
        {
            return !line.StartsWith("#") && line.Contains("=");
        }

        /// <summary>
        /// Returns a config items value by its key.
        /// </summary>
        /// <param name="Key">Config Key</param>
        /// <returns>Config Value</returns>
        public string GetConfigElement(string key)
        {
            if (!IsInitialized)
                return null;

            return _configItems[key];
        }

        /// <summary>
        /// Checks if class has been initialized.
        /// </summary>
        public bool IsInitialized
        {
            get { return _initialized; }
        }

        /// <summary>
        /// Refreshes config
        /// </summary>
        public void RefreshConfig()
        {
            if (!_initialized)
                return;

            Initialize();
        }
    }
}


texts: Extracting spreadsheet cells using Apache POI

texts:
I'm working with Apache POI framework.

This code go through sheets, row and get value of cells. I will try to get value from directly indicated column. I need this because I want convert only some information from xls to csv.

FileOutputStream fos = new FileOutputStream(outputFile);

Workbook workbook = null;
for (File input : inputFile) {
  String ext = FilenameUtils.getExtension(input.toString());

  if (ext.equalsIgnoreCase("xlsx")) {
    workbook = new XSSFWorkbook(new FileInputStream(input));
  } else if (ext.equalsIgnoreCase("xls")) {
    workbook = new HSSFWorkbook(new FileInputStream(input));
  }

  int numberOfSheets = workbook.getNumberOfSheets();
  Row row;
  Cell cell;
  Sheet sheet = null;
  int[] kolumny = {1, 2, 3, 4, 5, 6, 7, 50, 51, 52, 53, 54, 55};

  for (int i = 1; i < numberOfSheets; i++) {
    sheet = workbook.getSheetAt(i);
    if (sheet.getLastRowNum() > 24) {
      Iterator<Row> rowIterator = sheet.iterator();
      while (rowIterator.hasNext()) {
        row = rowIterator.next();
        for (int j = 23; j < sheet.getLastRowNum(); j++) {
          if (row.getRowNum() == j) {
            if (row.getCell(1) == null || row.getCell(1).getCellType() == Cell.CELL_TYPE_BLANK) {
              break;
            }
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
              cell = cellIterator.next();
              for (int kolumna : kolumny) {
                if (cell.getColumnIndex() == kolumna) {
                  if (cell != null) {
                    switch (cell.getCellType()) {
                      case Cell.CELL_TYPE_BOOLEAN:
                        data.append(cell.getBooleanCellValue() + ",");
                        break;
                      case Cell.CELL_TYPE_NUMERIC:
                        data.append(cell.getNumericCellValue() + ",");
                        break;
                      case Cell.CELL_TYPE_STRING:
                        data.append(cell.getStringCellValue() + ",");
                        break;
                      case Cell.CELL_TYPE_BLANK:
                        data.append("" + ",");
                        break;
                      default:
                        data.append(cell + ",");
                    }
                  }
                }
              }
            }
            data.append('\n');
          }
        }
      }
    }
  }
}


texts:
I am trying to overwrite an object in an array if the title property exists, otherwise just push it to the array. I found two approaches and I wonder which one is the preferred one.
Performance is not really and issue but I wonder whether mutability could be, or just there is a better way to do this altogether.
On this snippet I am using a for loop to edit the original array:

const data = [
  {
    title: 'AAA',
    people: [ 'John', 'Megan',]
  },{
    title: 'BBB',
    people: [ 'Emily', 'Tom']
  }
]

// If inputTitle is not on any of data's title it will append not overwritte
const inputTitle = 'AAA'
const inputPeople = ['Peter', 'Jane']

for (const obj of data) {
  if (obj.title === inputTitle) {
    obj.people = inputPeople
    break
  } else {
    data.push({
      title: inputTitle,
      people: inputPeople
    })
    break
  }
}

console.log(data)

Here I am using high order functions and spread to do the same:

const data = [
  {
    title: 'AAA',
    people: [ 'John', 'Megan',]
  },{
    title: 'BBB',
    people: [ 'Emily', 'Tom']
  }
]

// If inputTitle is not on any of data's title it will append not overwritte
const inputTitle = 'AAA'
const inputPeople = ['Peter', 'Jane']

let res = []

if (data.some(({ title }) => title === inputTitle)) {
  res = data.map(obj => {
    if (obj.title === inputTitle)
      obj.people = inputPeople
    return obj
  })
} else {
  res = [...data, { title: inputTitle, people: inputPeople}]
}

console.log(res)

In the real task I am reading the data array from a json file with node and writing the changes back to it.