texts: Implementation of Private Route with Auth using react-router and Context API

texts:
I'm trying to implement safe routes and checking if the user is authorized using only Context API.

I'm also trying to avoid that the user can see a PrivateRoute, but I'm not sure if I coverred all edge cases.

Also, is there a better way of doing this? Better implemantation or aproach to this?

I just don't want to use Redux or external libraries.

I made a gist but I'm also adding the full code here.

Auth.jsx

import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import { checkIsAuthenticated, authSignUp, authLogin, authLogout } from '../../services/auth'

export const AuthContext = React.createContext({})

export default function Auth({ children }) {

    const [isAuthenticated, setIsAuthenticated] = useState(false)
    const [isLoading, setIsLoading] = useState(true)

    useEffect(() => {
        checkAuth()
    }, [])

    const checkAuth = () => checkIsAuthenticated()
        .then(() => setIsAuthenticated(true))
        .catch(() => setIsAuthenticated(false))
        .then(() => setIsLoading(false))

    const login = credentials => authLogin(credentials)
        .then(setIsAuthenticated(true))
        .catch(error => {
            alert(error)
            setIsAuthenticated(false)
        })

    const logout = () => {
        authLogout()
        setIsAuthenticated(false)
    }

    const signUp = credentials => authSignUp(credentials)
        .then(setIsAuthenticated(true))
        .catch(error => {
            alert(error)
            setIsAuthenticated(false)
        })

    return (
        <AuthContext.Provider value={{ isAuthenticated, isLoading, login, logout, signUp }}>
            {children}
        </AuthContext.Provider>
    )
}

Auth.propTypes = {
    children: PropTypes.oneOfType([
        PropTypes.func,
        PropTypes.array
    ])
}

PrivateRoute.jsx

import React, { useContext } from 'react'
import { Route, Redirect } from 'react-router-dom'
import PropTypes from 'prop-types'
import { AuthContext } from '../Auth/Auth'
import Loading from '../../views/Loading/Loading'

const PrivateRoute = ({ component: Component, ...otherProps }) => {

    const { isAuthenticated, isLoading } = useContext(AuthContext)

    return (
        <Route
            {...otherProps}
            render={props => (
                !isLoading
                    ?
                    (
                        isAuthenticated
                            ?
                            <Component {...props} />
                            :
                            <Redirect to={otherProps.redirectTo ? otherProps.redirectTo : '/signin'} />
                    )
                    :
                    <Loading />
            )}
        />
    )

}

PrivateRoute.propTypes = {
    component: PropTypes.func.isRequired
}

export default PrivateRoute

example.jsx

import React from 'react'
import { Switch, Route } from 'react-router-dom'
import PrivateRoute from './components/PrivateRoute/PrivateRoute'
import Auth from './components/Auth/Auth'

import Header from './components/Header/Header'
import HomePage from './views/HomePage/HomePage'
import SignUp from './views/SignUp/SignUp'
import SignIn from './views/SignIn/SignIn'
import FormList from './views/FormList/FormList'
import PageNotFound from './views/PageNotFound/PageNotFound'

export default function App() {
    return (
        <div>
            <Auth>
                <Header />
                <Switch>
                    <Route exact path="/" component={HomePage} />
                    <Route path="/signup" component={SignUp} />
                    <Route path="/signin" component={SignIn} />
                    <PrivateRoute path="/forms" component={FormList} />
                    <Route component={PageNotFound} />
                </Switch>
            </Auth>
        </div>
    )
}


texts: C# Project Euler #4: Program that finds Largest palindrome product

texts:
So I made a code to improve my programming skills and it works just fine, but it looks chaotic for me. Is there is a better and more efficient way to do it? If you have any ideas/tips I would love to hear them.

using System;

 namespace Palindrome
  {
   internal class Program
   {
    private static int Palindroming(int a)
    {
        var results = 0;

        while (a > 0)
        {
            results = results * 10 + a % 10;
            a /= 10;
        }

        return results;
    }

    private static void Main(string[] args)
    {
        var multiply = 0;
        var largestMultiply = 0;
        var largest = 0;
        for (var i = 100; i <= 999; i++)
        for (var j = 100; j <= 999; j++)
        {
            var temp = multiply;
            multiply = i * j;

            if (multiply == Palindroming(multiply))
                if (temp > largestMultiply)
                {
                    largestMultiply = temp;

                    if (multiply > largestMultiply)
                        largest = multiply;
                }
        }

        Console.WriteLine(largest);
        Console.ReadLine();
    }
  }
}


texts: Generating prime numbers within a range in C++

texts:
I was given a problem to find out all the prime numbers within a range. Just after I wrote the program I found numerous other codes to solve the problem. I am interested to know is my algorithm efficient? Is it like sieve filtration? (before writing this code I had no clear idea on sieve filtration method) or the algorithm I used is bad?

#include<iostream.h>
#include<math.h>

prime_gen

void prime_gen(int a,int b)
{
    int array[4]={2,3,5,7},holder[1000000]={0},count=0,flag=0,length=0,number_count=0;

    for(int i=0;i<b;i++)
    {
        for(int j=0;j<4;j++)
        {
            if(i==array[j])
            {
                break;
            }
            else
            {
                if(i%array[j]==0)
                {
                    count++;
                }
            }
        }
        if(count==0)
        {
            if(i>1)
            {
                holder[length++]=i;
            }
            else
            {
                length=0;
            }
        }
        count=0;
    }

    if(length==0)
    {
        cout<<"No prime numbers exist within the range";
        cout<<"\n";
    }
    else
    {
        cout<<"Prime numbers are:";

        for(int i=0;i<length;i++)
        {
            int t=holder[i];

            for(int check=0;check<sqrt(length);check++)
            {

                if(t!=holder[check])
                {
                    if(t%holder[check]==0)
                    {
                        t=0;
                    }
                }
            }

            if(t!=0&&t>=a)
            {
                number_count++;
                cout<<t<<"\t";
            }
        }

        cout<<"Total count:"<<number_count<<endl;
    }
}

main

int main()
{
    int a,b;

    cout<<"Put the first integer:";
    cin>>a;

    cout<<"Put the second integer:";
    cin>>b;

    prime_gen(a,b);
}


texts:
This is my solution to the Equal Stacks problem on HackerRank. I thinks it's really messy and slow. could you give me some thoughts about how to optimize given code and algorithm(i'm pretty sure problem can be solved way effectively)

import java.io.*;
import java.util.*;
import java.util.stream.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

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

        int n1          = inputStream.nextInt();
        int n2          = inputStream.nextInt();
        int n3          = inputStream.nextInt();

        int n1Height    = 0;
        int n2Height    = 0;
        int n3Height    = 0;

        int h1[]        = new int[n1];
        int h2[]        = new int[n2];
        int h3[]        = new int[n3];

        for(int h1_i=0; h1_i < n1; h1_i++){
            h1[h1_i] = inputStream.nextInt();
            n1Height += h1[h1_i];
        }
        for(int h2_i=0; h2_i < n2; h2_i++){
            h2[h2_i]  = inputStream.nextInt();
            n2Height += h2[h2_i];
        }
        for(int h3_i=0; h3_i < n3; h3_i++){
            h3[h3_i]   = inputStream.nextInt();
            n3Height  += h3[h3_i];
        }
        int highestHeight = 0;
        for(int i=0; i< n3; i++){
            if(heightReachable(n3Height,h2,n2Height) && heightReachable(n3Height, h1, n1Height)){
                highestHeight = n3Height;
                break;
            }
            n3Height -= h3[i];
        }

        System.out.println(highestHeight);

        inputStream.close();
    }
    /**
     * [heightReachable - returns boolean identifying whether or not given      height is reachable by given stack]
     * @param  height      [height which we should check if is reachable or not]
     * @param  stackBlocks [stack blocks array containing height of each block]
     * @param  stackHeight [number of blocks in given stack]
     * @return             [true if height is reachable by removing zero or more elements from the stack and false otherwise]
     */
    private static boolean heightReachable(int height, int[] stackBlocks, int stackHeight){
        for(int i=0; i < stackBlocks.length; i++){
            if(stackHeight == height) return true;
            stackHeight = stackHeight - stackBlocks[i];
        }
        return false;
    }
}


texts: Generating a range of ints as strings in Java 8

texts:
I'll have two integers and will want to generate an array of those two numbers and all the numbers in between as strings (I know the ranges are small).

i.e. given 1004 and 1008. I'd generate "1004", "1005", "1006", "1007", "1008"

I'm familiar with C# and there I'd do something like

var start = 1004;
var end = 1008;
var fullRange = Enumerable.Range(start, end - start + 1)
                          .Select(i => i.ToString())
                          .ToArray();

I need to do this in Java 8 and have come up with

 String[] fullRange = IntStream.range(start, end+1)
                        .mapToObj(String::valueOf)
                        .toArray(String[]::new);

But I'm new to Java and wondered if there's a better / more-readable way to achieve this in Java. Am I just cramming C# into Java?


texts:
I have designed a Backspace button (part of a keyboard which I am designing) in windows forms and it works perfect with no errors (the code works very good). This button deletes what is inside the textbox.

I just want to see other people's views and what they think about my code, so because I am new to c# I think there might be other better ways to design Backspace button. Can you please see if there are any silly unprofessional mistakes in my code?

private void buttonDelete_Click(object sender, EventArgs e)
    {

        textBox1.Focus(); // set the textbox focused.

        if (textBox1.SelectionStart >= 0) //check if there is text to delete

        {
           int TxTindex = textBox1.SelectionStart; // save the index position

            if (textBox1.SelectedText.Length > 0)  //// check if there is selected text
            {

                textBox1.SelectedText = "";

            }

            else
            {

                if (TxTindex >0 && TxTindex == textBox1.Text.Length) // check if there is text in texbox and check if index is at the end of text.

                {

                    textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1, 1);
                    textBox1.SelectionStart = textBox1.Text.Length;

                }

                else // is the index is in between the text?
                {
                    if (TxTindex > 0) // check if there is text in texbox
                    {

                        textBox1.Text = textBox1.Text.Remove(TxTindex - 1, 1);
                        textBox1.SelectionStart = TxTindex - 1; // to set the cursor position after the deleted number between the text.
                    }
                    else
                    {

                        return;
                    }

                }

            }
        }
        else
        {

            return;
        }
    }


texts: Workaround for overloaded constructor in PHP

texts:
I have a class whose purpose is to display a comment.  I'd like to be able to instantiate it by passing a Comment object if I happen to have it available, or just the values if that's what I have available at the time.  Unfortunately PHP doesn't allow overloaded constructors, so here's the workaround I came up with.

class CommentPanel extends Panel {
    //Private Constructor, called only from MakeFrom methods
    private function CommentPanel($text, $userName, $timestamp) {
        parent::Panel(0, $top, System::Auto, System::Auto);

        // Render comment
    }

    public static function MakeFromObject(Comment $comment) {
        return new CommentPanel($comment->text, $comment->User->nickname, $comment->last_updated_ts);
    }

    public static function MakeFromValues($text, $userName, $timestamp) {
        return new CommentPanel($text, $userName, $timestamp);
    }
}

So here's the two methods for instantiating a CommentPanel:

$cp = CommentPanel::MakeFromObject($comment);
// or...
$cp = CommentPanel::MakeFromValues($text, $user, $last_updated_ts);
// but not
$cp = new CommentPanel(); //Runtime error

I'm moderately satisfied, although it's not near as intuitive as an overloaded constructor.  Any thoughts on improving this?


texts:
I'm using simple script to handle tab menu like this:

HTML:

Info

Orders

Models

Balance

and CoffeeScript:

jQuery ($) ->
 class Nav
  constructor: (@elements) ->
    self = @
    wHash = document.location.hash.replace("#", "") or "info"

    # activate element by location hash
    @.activate document.getElementById "personal-#{wHash}"

    # bind element activation on click
    elements.click ->
      self.activate @

  activate: (elem) ->
    @elements.removeClass "active"
    $(elem).addClass "active"

    # set a proper hash
    wHash = elem.id.split("-")[1]
    document.location.hash = "##{wHash}"

    # load proper content into an inner section
    # it works very fast and is the reason i use this type of navigation in the first place

    $("#personal-content").load "/user/#{wHash}"

 new Nav $("#personal").find("li")

This code works, but i'm pretty sure that it's very far away from best practices, and can be greatly improved, as these are my first tries in CoffeeScript. So the question is, can this code be beautified in some way?


texts:
Below is a class,Countdown, that takes seconds as input from an entry, and starts counting down when the "Start" button is pressed, while displaying the time left on a label:

import tkinter as tk
import datetime

class Countdown(tk.Frame):
    '''A Frame with label to show the time left, an entry to input the seconds to count
    down from, and a start button to start counting down.'''
    def __init__(self, master):
        super().__init__(master)
        self.create_widgets()
        self.show_widgets()
        self.seconds_left = 0
        self._timer_on = False

    def show_widgets(self):

        self.label.pack()
        self.entry.pack()
        self.start.pack()

    def create_widgets(self):

        self.label = tk.Label(self, text="00:00:00")
        self.entry = tk.Entry(self, justify='center')
        self.entry.focus_set()
        self.start = tk.Button(self, text="Start", command=self.start_button)

    def countdown(self):
        '''Update label based on the time left.'''
        self.label['text'] = self.convert_seconds_left_to_time()

        if self.seconds_left:
            self.seconds_left -= 1
            self._timer_on = self.after(1000, self.countdown)
        else:
            self._timer_on = False

    def start_button(self):
        '''Start counting down.'''
        self.seconds_left = int(self.entry.get())   # 1. to fetch the seconds
        self.stop_timer()                           # 2. to prevent having multiple
        self.countdown()                            #    timers at once

    def stop_timer(self):
        '''Stops after schedule from executing.'''
        if self._timer_on:
            self.after_cancel(self._timer_on)
            self._timer_on = False

    def convert_seconds_left_to_time(self):

        return datetime.timedelta(seconds=self.seconds_left)

if __name__ == '__main__':
    root = tk.Tk()
    root.resizable(False, False)

    countdown = Countdown(root)
    countdown.pack()

    root.mainloop()

Review Concern(s):

My main concern is to code in an easy to read, efficient, and well-structured manner while still learning the language and concepts such as OOP. Feel free to mention the tiniest issue or improvement that comes to your mind, as I am a beginner and I probably need it.

Note: This was an answer in SO.


texts: Natural sorting/comparing algorithm in TypeScript

texts:
This code sorts string that may contain numbers in natural order, that's it, "item 2" comes before than "item 10". It currently ignores case. I plan to implement options to handle case sensitivity and descending order.

For me it's fast enough, faster than other implementations I've seen using regexes. Apart from the first lines, it's JavaScript.

I made it returning the actual sorting function so we can cache its config object.

I'd like to know if it have any issues regarding Unicode, code style, etc. I plan to handle descending order like this, codified into a helper function.

return 0 - result;

For case sensitivity, I'd strip toUpperCase().

"use strict";

interface NaturalKeyFunc {
    (obj: any): any;
}

interface NaturalSortConfig {
    keyFunc?: NaturalKeyFunc;
    //desc?: boolean;
    //caseInsensitive?: boolean;
}

function naturalSort(config?: NaturalSortConfig) {

    return function(a, b) {

        if (typeof a === "number" && typeof b === "number")
            return a - b;

        if (a === null || b === null)
            return NaN;
        if (a === undefined || b === undefined)
            return NaN;
        if (Array.isArray(a) || Array.isArray(b))
            return NaN;

        if (Object.prototype.toString.call(a) === "[object Object]" || typeof Object.prototype.toString.call(b) === "[object Object]") {
            if (!config && !config.keyFunc)
                return NaN;
            if (typeof a === "object")
                a = config.keyFunc(a);
            if (typeof b === "object")
                b = config.keyFunc(b);
        }

        if (typeof a !== "string" || typeof b !== "string")
            return a - b;

        if (a.length === 0 || b.length === 0)
            return a.length - b.length;

        var s1: string = a,
            s2: string = b,
            indexA = 0, indexB = 0,
            numberA, numberB,
            charA, charB,
            difference;

        do {
            numberA = 0;
            while (indexA < s1.length) {
                charA = s1[indexA];
                indexA++;
                if (!(charA >= "0" && charA <= "9")) break;

                numberA = numberA * 10 + parseInt(charA);
            }

            numberB = 0;
            while (indexB < s2.length) {
                charB = s2[indexB];
                indexB++;
                if (!(charB >= "0" && charB <= "9")) break;

                numberB = numberB * 10 + parseInt(charB);
            }

            if (charA === " " && charB === " ") {
                while (indexA < s1.length && s1[indexA] === " ") {
                    indexA++;
                }
                while (indexB < s2.length && s2[indexB] === " ") {
                    indexB++;
                }
            }

            difference = numberA - numberB;
            if (difference !== 0) return difference;
            if (charA !== charB) {
                if (charA === ".") return -1;
                if (charB === ".") return 1;
                return charA.toUpperCase().charCodeAt(0) - charB.toUpperCase().charCodeAt(0);
            }
        } while (indexA < s1.length && indexB < s2.length);

        return (indexB - s2.length) - (indexA - s1.length);
    }
}

Some tests:

let natu = naturalSort();

it("can sort numbers inside strings", function () {
    expect(natu("a1", "a2")).toBeLessThan(0);
    expect(natu("1 item", "1 item")).toEqual(0);
    expect(natu("item 1", "item 1")).toEqual(0);
    expect(natu("item 1", "item 2")).toBeLessThan(0);
    expect(natu("item 1", "item 10")).toBeLessThan(0);
    expect(natu("item 2", "item 10")).toBeLessThan(0);
    expect(natu("item 1 item a", "item 1 item a")).toEqual(0);
    expect(natu("item 1 item 1", "item 1 item 10")).toBeLessThan(0);
    expect(natu("item 01", "item 1")).toEqual(0);
});


texts: Converting an integer to a hexadecimal string representation in Java

texts:
I have rolled my own Java method for converting ints to the hexadecimal Strings:
import java.util.Arrays;
import java.util.Random;

public class Main {

    /**
     * Converts the input integer into its textual hexadecimal representation.
     *
     * @param a the integer to convert.
     * @return the string representing {@code a} in hexadecimal notation.
     */
    public static String intToHexString(int a) {
        StringBuilder stringBuilder = new StringBuilder(Integer.BYTES * 2);
        boolean inLeadingZeros = true;

        while (a != 0) {
            char digit = toHexChar(a & 0xf);
            a >>>= 4;

            if (inLeadingZeros) {
                if (digit != 0) {
                    inLeadingZeros = false;
                    stringBuilder.append(digit);
                }
            } else {
                stringBuilder.append(digit);
            }
        }

        if (inLeadingZeros) {
            return "0";
        }

        return stringBuilder.reverse().toString();
    }

    // Converts the integer digit to its textual hexadecimal representation:
    private static char toHexChar(int digit) {
        return digit >= 0 && digit < 10 ?
                (char)(digit + '0') :
                (char)(digit - 10 + 'a');
    }

    private static final int ITERATIONS = 10_000_000;
    private static final int WARMUP_ITERATIONS = 10_000_000;

    private static void warmup() {
        System.out.println("Warming up...");
        Random random = new Random();

        for (int i = 0; i < WARMUP_ITERATIONS; i++) {
            int a = random.nextInt();
            intToHexString(a);
            Integer.toHexString(a);
        }

        System.out.println("Warming up done.");
    }

    private static void benchmark() {
        long seed = System.nanoTime();
        Random random = new Random(seed);
        System.out.println("Seed = " + seed);

        int[] inputArray = new int[ITERATIONS];
        String[] outputArray1 = new String[inputArray.length];
        String[] outputArray2 = new String[inputArray.length];

        for (int i = 0; i < inputArray.length; i++) {
            inputArray[i] = random.nextInt();
        }

        // Benchmarking intToHexString:
        long startTime = System.nanoTime();

        for (int i = 0; i < ITERATIONS; i++) {
            outputArray1[i] = intToHexString(inputArray[i]);
        }

        long endTime = System.nanoTime();

        System.out.println(
                "intToHexString in " +
                        ((endTime - startTime) / 1000_000) +
                        " milliseconds.");

        // Benchmarking Integer.toHexString:
        startTime = System.nanoTime();

        for (int i = 0; i < ITERATIONS; i++) {
            outputArray2[i] = Integer.toHexString(inputArray[i]);
        }

        endTime = System.nanoTime();

        System.out.println(
                "Integer.toHexString in " +
                        ((endTime - startTime) / 1000_000) +
                        " milliseconds.");

        System.out.println("Methods agree: " + Arrays.equals(outputArray1,
                                                             outputArray2));
    }

    public static void main(String[] args) {
        warmup();
        benchmark();
    }
}

Sample output

Warming up...
Warming up done.
Seed = 1290249323142300
intToHexString in 1041 milliseconds.
Integer.toHexString in 562 milliseconds.
Methods agree: true

Critique request
Please tell me anything that comes to mind.


texts:
https://arxiv.org/pdf/2009.07047v1.pdf
I don't have a lot of experience in building a network model. I would like to build the Encoder and Generator network model from the above article.
Here is my attempt :
import torch.nn as nn

class ResnetBlock(nn.Module):
    def __init__(self, dim, norm_layer, activation=nn.ReLU(False), kernel_size=3):
        super().__init__()

        pw = (kernel_size - 1) // 2
        self.conv_block = nn.Sequential(
            nn.ReflectionPad2d(pw),
            norm_layer(nn.Conv2d(dim, dim, kernel_size=kernel_size)),
            activation,
            nn.ReflectionPad2d(pw),
            norm_layer(nn.Conv2d(dim, dim, kernel_size=kernel_size)),
        )

    def forward(self, x):
        y = self.conv_block(x)
        out = x + y
        return out

class Encoder(nn.Module):
    """
    Network used for the VAE (Encoder) as well as in the GAN (i.e. Discriminator).
    In other words, it is the same architecture as the image discriminator.

    Attributes:
        num_features (int) :
    """

    def __init__(self, num_features):
        super().__init__()

        self.encoder = nn.Sequential(
            nn.Conv2d(num_features, 256, knernel_size=7, stride=1)
            nn.Conv2d(256, 128, knernel_size=4, stride=2)
            nn.Conv2d(128, 64, knernel_size=4, stride=2)
        )

        self.resnet_block = ResnetBlock(64, kernel_size=3)

    def forward(self, x):

        out = self.encoder(x)
        out = self.resnet_block(out)

        return out

class Generator(nn.Module):
    def __init__(self, num_features):
        super().__init__()

        self.resnet_block = ResnetBlock(64, kernel_size=3)

        self.generator = nn.Sequential(
            nn.Conv2d(64, 128, knernel_size=4, stride=2)
            nn.Conv2d(128, 256, knernel_size=4, stride=2)
            nn.Conv2d(256, num_features, knernel_size=7, stride=1)
        )

    def forward(self, x):
        out = self.resnet_block(x)
        out = self.generator(x)
        return out

I am not sure the model Encoder and Generator are properly well coded according to


texts:
Is there any way to improve or optimize the speed of this? I can't think of any ways to do it in one pass.

static byte[] ConcatenateBuffers(params byte[][] list)
{
    int totalLen = 0;
    for (int i = 0; i < list.Length; ++i)
        totalLen += list[i].Length;
    byte[] ret = new byte[totalLen];
    int offset = 0;
    for (int i = 0; i < list.Length; ++i)
    {
        Array.ConstrainedCopy(list[i], 0, ret, offset, list[i].Length);
        offset += list[i].Length;
    }
    return ret;
}


texts:
I've written this Java code to implement merge sort:

import java.util.*;

public class MergeSort {

    int[] a;

    MergeSort() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the number of items: ");
        a = new int[scan.nextInt()];

        for (int i = 0; i < a.length; ++i) {
            a[i] = scan.nextInt();
        }

    }

    int[] mergeSort2(int beg, int end) {
        if (beg == end) {
            int []result = new int[]{a[beg]};         /****new array allocation****/
            return result;
        }

        int[] left = mergeSort2(beg, (beg + end) / 2);
        int[] right = mergeSort2((beg + end) / 2 + 1, end);
        int[] result = new int[end - beg + 1];        /****new array allocation****/
        System.out.println("left.length = "+left.length+", right.length = "+right.length+", result.length = "+result.length);

        int i, l, r;
        for (i = 0, l = 0, r = 0; l < left.length && r < right.length; ++i) {
            if (left[l] >= right[r]) {
                result[i] = right[r];
                r++;
            } else if (left[l] < right[r]) {
                result[i] = left[l];
                l++;
            }
        }

        if (l == left.length) {
            for (; r < right.length; ++r, ++i) {
                result[i] = right[r];
            }
        } else if (r == right.length) {
            for (; l < left.length; ++l, ++i) {
                result[i] = left[l];
            }
        }
        return result;
    }

    public static void main(String[] args) {
        MergeSort ms = new MergeSort();
        int[] result = ms.mergeSort2(0, ms.a.length - 1);
        System.out.println();
        for (int i = 0; i < result.length; ++i) {
            System.out.print(result[i] + " ");
        }
    }
}

Every time I want to return left and right to merge into result, I've to allocate result again (same for cases where length == 1). How can I avoid this allocation during recursion?


texts: Solving 15-puzzle algorithm using IDA* or A*

texts:
I am currently using the BestFirst algorithm to solve the puzzle 15. It works well when I have a simple inputs and takes about 1-20 seconds to solve the puzzle. But when it comes to complicated inputs, it might takes forever to run. I'm just wondering if there is any way to improve my algorithm's performance.

Main.java

final int _ = 0;
State initialState = new State(
_,  1, 4,  2,
9,  5, 3,  12,
8,  6, 7, 11,
14, 10, 13, 15);

cList open = new cList();
cList closed = new cList();
open.InsertFront(initialState);

while(!open.isEmpty()){
   State st = open.RemoveFront();
   closed.InsertBack(st);
   if(st.isGoal()) {showPath(st); break;}
   State[] ss = st.NextStates();
   for(State s:ss){
      if(!closed.isExist(s))
         if(!open.ExistOrSubstitue(s))
            open.InsertSorted(s);
    }
 }

cList

private ArrayList<State> list = new ArrayList<State>(1000);
public void InsertFront(State s){ list.add(0,s); }
public void InsertBack(State s){ list.add(s);}
public State RemoveFront(){ return list.remove(0); }
public boolean isEmpty(){ return list.isEmpty(); }
public void InsertSorted(State s){
  int i=0;
  while(i<list.size()){
    if(list.get(i).compareTo(s)>0) break;
    i++;
  }
  list.add(i,s);
}

public boolean isExist(State s){
  for(Object state:list) if (state.equals(s)) return true;
  return false;
}

public boolean ExistOrSubsitute(State s){
  for(int i=0;i<list.size();i++){
    State state =list.get(i);
    if(state.equals(s)) {
        if(s.getEV()<state.getEV()){
          list.remove(i);
          InsertSorted(s);
        }
        return true;
    }
  }
  return false;
}


texts: Is there a more readable way to write this add to a list only if the element not exists? (perfectionistic)

texts:
Take a timer in your hands, then have a look to the following code. What is it doing?
I took 52 seconds to realize more or less what it does..
It compares a list called categories with an actual element. If it already exist in the list it takes it and stores to the category variable. Otherwise it creates this new element, stores it into the category variable and also add it to the list.

Mmm... very not clear to me. I strongly prefer the second piece of code.
What do you think? How would you rewrite the code to make it more readable?
Do you find an utility in generalizing patterns like this one and creating classes and framework for handling this behaviors in a standardized way?

foreach (var summaryOdd in odds)
{
    var category = new PlacedCategory();
    var eventId = summaryOdd.Championship;

    if (categories.Any(cat => cat.Name == eventId))
    {
        category = categories.First(cat => cat.Name == eventId);
    }
    else
    {
        category.Name = eventId;
        categories.Add(category);
    }

foreach (var summaryOdd in odds)
{
    var category = new PlacedCategory();
    var eventId = summaryOdd.Championship;

    category = FindOrCreateCategoryByEventId(categories, eventId);


texts:
I am building a web server from scratch and trying to make certain tasks faster by embedding C code into the mix for performance. Specifically I'm worried about how the std::string class with the .find() and other functions compare to straight pointer arithmetic.

#include <iostream>
#include <map>
#include <string>

std::map<std::string, std::string> http_request;

void parse_header( void * );

int main()
{

    char * msg= "GET / HTTP/1.1\r\n"
                "Host: 192.241.213.46:6880\r\n"
                "Upgrade-Insecure-Requests: 1\r\n"
                "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
                "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/602.4.8 (KHTML, like Gecko) Version/10.0.3 Safari/602.4.8\r\n"
                "Accept-Language: en-us\r\n"
                "Accept-Encoding: gzip, deflate\r\n"
                "Connection: keep-alive\r\n\r\n";

    parse_header( msg );

}

void parse_header( void *msg )
{
    char *head = (char *) msg;
    char *mid;
    char *tail = head;

    if( sizeof( msg ) == 0 )
    {
        return;
    }

    // Find request type
    while( *head++ != ' ');
    http_request[ "Type" ] = std::string( ( char * ) msg ).substr( 0 , ( head - 1) - tail );

    // Find path
    tail = head;
    while( *head++ != ' ');
    http_request[ "Path" ] = std::string( ( char * ) msg ).substr( tail - ( char *)msg , ( head - 1) - tail );

    // Find HTTP version
    tail = head;
    while( *head++ != '\r');
    http_request[ "Version" ] = std::string( ( char * ) msg ).substr( tail - ( char *)msg , ( head - 1) - tail );

    // Map all headers from a key to a value
    while( true )
    {
        tail = head + 1;
        while( *head++ != '\r' );
        mid = strstr( tail, ":" );

        // Look for the failed strstr
        if( tail > mid )
            break;

        http_request[ std::string( ( char * ) msg ).substr( tail - ( char *)msg , ( mid ) - tail  ) ] = std::string( ( char * ) msg ).substr( mid + 2 - ( char *) msg , ( head - 3 ) - mid );
    }

    // Determine if successful
    std::cout << http_request[ "Host" ] << std::endl;
    std::cout << http_request[ "Upgrade-Insecure-Requests" ] << std::endl;
    std::cout << http_request[ "Accept" ] << std::endl;
    std::cout << http_request[ "User-Agent" ] << std::endl;
    std::cout << http_request[ "Accept-Language" ] << std::endl;
    std::cout << http_request[ "Accept-Encoding" ] << std::endl;
    std::cout << http_request[ "Connection" ] << std::endl;
}

Data comes in via the linux socket.send() function, so it is a void * type. I directly send that data to a parse_header function to create a std::map for easy access. Is it necessary to be this low-level, or can this speed be obtained by the STL?

Note: I killed OO design for a minimal example. The end-goal has an HTTP class.

Note++: I'd prefer to have this code review pertain to performance rather than c++ semantics, I'd like it to be as conforming as possible while also being fast and lightweight. This seems to be the purest form of the cluge of C/C++.


texts:
I consume an API which gives me this type of JSON:

{
  "data": {
    "name": "Start",
    "pid": "1",
    "position": {
      "data": {
        "x": "31",
        "y": "330"
      },
      "metadata": "empty"
    }
  },
  "metadata": "empty"
}

I have created the classes with objects with the same structure as the above JSON. I use the retrofit lib in Android which inside uses GSON for parsing the JSON.

My model classes would be like this:

MResponse.class

public class MResponse {

    @SerializedName("data")
    public User user;

    String metadata;
}

User.class

public class User {

    public String name;

    public String pid;

    @SerializedName("position")
    public PositionData positionData;
}

PositionData.class

public class PositionData {

    @SerializedName("data")
    public Position position;

    public String metadata;
}

Position.class

public class Position {

    public String x;

    public String y;
}

Now this works fine for me. But as you can see for every model I have to create a parent which will have the same structure just changes the child. This fact doubles the classes that I use for my models. I would like to ask if there is a better way to avoid all these classes.

I don't want to use inner classes. I was thinking that the guys that have done the JSON like this must have had a reason why they did it like this and also a way to make the parsing more easier.

Usually I was used to parse this kind of JSON structure:

{
  "data": {
    "name": "Start",
    "pid": "1",
    "position": {
      "x": "31",
      "y": "330"
    }
  }
}

And here it's easier if I would follow the solution above.

EDIT

Also any solution in Kotlin is welcomed


texts:
My aim was to build a small, simple program that would show me my school timetable for the present day as well as the following day. I am new to PyQt(5) and programming in general. I started programming about 5 months ago on and off just as a fun side hobby. I started with basic text-based programs which gradually got more complex and this is my first (useful) GUI program. Any thoughts/suggestions?

import datetime
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QHBoxLayout, QApplication, QWidget, QLabel)
from PyQt5.QtGui import (QIcon, QPixmap)

#My weekly school timetable
Mon = '\n1       Spanish\n2       Spanish\n3       Music\n4       Music\n5       English Literature\n6       English Literature\n7       History\n8       History'
Tue = '\n1       Social Studies\n2       Social Studies\n3       Spanish\n4       Spanish\n5       Information Technology\n6       Information Technology\n7       English Literature\n8       English Language'
Wed = '\n1       English Literature\n2       English Literature\n3       Information Technology\n4       Information Technology\n5       HSB\n6       HSB\n7       Mathematics\n8       Mathematics'
Thu = '\n1       History\n2       History\n3       English Language\n4       English Language\n5       HSB\n6       HSB\n7       Mathematics\n8       Mathematics'
Fri = '\n1       Music\n2       Music\n3       English Language\n4       English Language\n5       Mathematics\n6       Mathematics\n7       Social Studies\n8       Social Studies'

#Returns day in terms of Monday = 0, Tuesday = 1...
day = datetime.datetime.today().weekday()

if day==0:
    the_day = Mon
    tomorrow = Tue
if day==1:
    the_day = Tue
    tomorrow = Wed
if day==2:
    the_day = Wed
    tomorrow = Thu
if day==3:
    the_day = Thu
    tomorrow = Fri
if day==4:
    the_day = Fri
    tomorrow = ''
elif day==5 or day==6:
    the_day = ''
    tomorrow = Mon

if day in range(5):
    today = '<b>Today\'s Timetable:<\b>'
    next_day = '<b>Tomorrow\'s Timetable:<\b>'
else:
    today = ''
    next_day = '<b>Monday\'s Timetable:<\b>'

class timetable(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        if day==4:
            lbl = QLabel(self)
            pixmap = QPixmap('weekend.jpg')
            smaller_pixmap = pixmap.scaled(160, 300, Qt.KeepAspectRatio, Qt.FastTransformation)
            lbl.setPixmap(smaller_pixmap)
            lbl.move(-3, 162)
            lbl.show()

        elif day==5 or day==6:
            lbl = QLabel(self)
            pixmap = QPixmap('weekend.jpg')
            smaller_pixmap = pixmap.scaled(160, 300, Qt.KeepAspectRatio, Qt.FastTransformation)
            lbl.setPixmap(smaller_pixmap)
            lbl.move(-3, 0)
            lbl.show()

        title0 = QLabel(today, self)
        title0.move(5,5)

        schedule0 = QLabel(the_day, self)
        schedule0.move(5, 16)

        title1 = QLabel(next_day, self)
        title1.move(5,150)

        schedule1 = QLabel(tomorrow, self)
        schedule1.move(5, 160)

        self.setGeometry(7, 30, 150, 287)
        self.setFixedSize(self.size())
        self.setWindowTitle('Timetable')
        self.setWindowIcon(QIcon('icon.png'))
        self.show()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = timetable()
    ex.show()
    sys.exit(app.exec_())
    #created with PyQt5 using Python 3.5


texts:
My code style is capped 128 characters, not 80 characters. This abstract base class constructor initializes some resources which are injected in the implementations. However, I cannot assume that will be always the case, so I used some try catching to and Apache Commons Lang3 Validate to validate my inputs and throw applicable errors. The base class is normally implemented as a stateless ejb, because of the database rollback features. The BusinessConfigurationException extends Exception and is annotated with @ApplicationException(rollback = true), so that these checked exceptions will be thrown without being wrapped in an EJBException and will do a rollback of all database actions correctly.

/**
 * BaseController constructor with injectable parameters.
 *
 * @param configBundle Configuration parameters for the application.
 * @param errorsBundle Error messages thrown by the application.
 * @param em Needs to be injected from implementation.
 * @param clazz The class that implements the BaseEntity.
 * @throws BusinessConfigurationException When the property value returns an error somehow.
 */
public BaseController(final ResourceBundle configBundle, final ResourceBundle errorsBundle, final EntityManager em,
        final Class<T> clazz) throws BusinessConfigurationException {
    try {
        Validate.notNull(configBundle);
        this.baseURI = configBundle.getString("HOST_NAME") + configBundle.getString("APPLICATION_NAME")
                + configBundle.getString("BASE_PATH");
    } catch (NullPointerException | MissingResourceException | ClassCastException ex) {
        log.error("Cannot initialize baseURI in BaseController constructor.", ex);
        throw new BusinessConfigurationException(ex.getMessage());
    }
    try {
        Validate.notNull(errorsBundle);
        this.errorsBundle = errorsBundle;
    } catch (NullPointerException ex) {
        log.error("Cannot initialize errorsBundle in BaseController constructor.", ex);
        throw new BusinessConfigurationException(ex.getMessage());
    }
    try {
        Validate.notNull(em);
        this.em = em;
    } catch (NullPointerException ex) {
        log.error("Cannot initialize em in BaseController constructor.", ex);
        throw new BusinessConfigurationException(findErrMsg("EM_NOT_AVAILABLE"));
    }
    // No business exceptions thrown for valdidations below. This is a programmer fault.
    Validate.notNull(clazz);
    Validate.isAssignableFrom(clazz, BaseEntity.class);
    this.clazz = clazz;
    this.resourceName = clazz.getSimpleName().toLowerCase();
}


texts: Connection request to LinkedIn profiles on search page

texts:
I implemented a script for a LinkedIn user to connect with all profiles on a LinkedIn search page and move to the next one automatically.

As I am a new javaScript programmer, could someone look at my code and tell me how to write better code?

// Every 1 second, click all the connect buttons on the result page
window.setInterval(function () {
    $("a:contains('Connect')").each(function (index, a) {
        $(this).trigger('click');
    });

    //Scroll down to the button of the page
    window.scrollTo(0, document.body.scrollHeight);
}, 1000);

//Click Next after every 5 seconds
window.setInterval(function () {
    $("a:contains('Next >')")[0].click();
}, 5000);

Steps to run and test are all given here.


texts: Encapsulation of client side logic in web page

texts:
Is this the best way of doing this.
The sample code is a simple lookup of postnr (read zipcode).
I'm trying to encapsulate all the client side logic inside one "class".

Is this the way of doing callbacks? The this/that stuff sort of creeps me out a little
Should the constructor just be a place where you declare variables? I have a init function call here that sets things up. But it is public and I wonder if there is some best practice around this?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Untitled Page</title>

  Postnr <input type="text" id="postnr" />
  Poststed <input type="text" id="poststed" />


texts:
Please review for readability.

/*
Takes a screenshot of the current tab, then scales it to width and height.
Returns null if the tab is smaller than width and height.
Crops the screenshot to maintain aspect ratio.
Also crops the screenshot to avoid scaling down by more maximumScaleFactor.
*/
var GetCurrentScreenshot = function (width, height, maximumScaleFactor) {
    return new RSVP.Promise(function (resolve) {
        chrome.tabs.captureVisibleTab(null, { format: 'png' }, function (dataURL) {
            var sourceImage = new Image();
            sourceImage.onload = function () {
                var canvas = document.createElement("canvas");
                var cropWidth = sourceImage.width;
                var cropHeight = sourceImage.height;
                if (cropWidth < width || cropHeight < height) {
                    resolve(null);
                    return;
                }
                var outputRatio = width / height;
                var inputRatio = cropWidth / cropHeight;
                if (outputRatio > inputRatio) {
                    cropHeight = cropWidth / outputRatio;
                } else {
                    cropWidth = cropHeight * outputRatio;
                }

                //This should be impossible
                if (cropWidth > sourceImage.width) cropWidth = sourceImage.width;
                if (cropHeight > sourceImage.height) cropHeight = sourceImage.height;

                if (cropWidth > width * maximumScaleFactor) {
                    cropHeight = cropHeight / (cropWidth / (width * maximumScaleFactor));
                    cropWidth = width * maximumScaleFactor;
                }

                canvas.width = width;
                canvas.height = height;
                canvas.getContext("2d").drawImage(sourceImage, 0, 0, cropWidth,
                    cropHeight, 0, 0, width, height);
                resolve(canvas.toDataURL());
            };
            sourceImage.src = dataURL;
        });
    });
};


texts:
The code consists of 4 functions that result in a figure with 3 subplots:

a sine wave
a cosine wave
and the superposition of both (a bichromatic wave).

I have shown in 4 ways, the first two are basically plot the same way, but the generation of the waves are different.  I also show different methods, by adding subplots directly using plt.subplots(3, 1), also by adding one at a time using plt.subplot(3,1,i), and the last function uses the sine and cosine plot data to create the bichromatic wave.

I would like to know what to improve for the code, and also what to improve for the methods in using matplotlib ..?

import matplotlib.pyplot as plt
import math
pi = math.pi

ex_1 = "1. Using lists (comprehension) to contain A*sin(a*x), B*cos(b*x), and the superposition. \
Using plt.subplots to created the plots."

def trig_subplots_1(x=[], amplitude=(1, 1), frequency=(1, 1)):

    sine = [amplitude[0]*math.sin(frequency[0]*i) for i in x]
    cosine = [amplitude[1]*math.cos(frequency[1]*i) for i in x]
    superposition = [s+c for s,c in zip(sine, cosine)]

    fig, ax = plt.subplots(3,1)

    ax[0].plot(x, sine)
    ax[0].set_title('Sine wave')

    ax[1].plot(x, cosine)
    ax[1].set_title('Cosine wave')

    ax[2].plot(x, superposition)
    ax[2].set_title('Bichromatic wave')

    plt.tight_layout()
    plt.show()

ex_2 = "2. Generate A*sin(a*x), B*cos(b*x), and the superposition by list.append in a for-loop. \
Using plt.subplots to created the plots."

def trig_subplots_2(x=[], amplitude=(1, 1), frequency=(1, 1)):

    sine, cosine, superposition = [], [], []
    for i in x:
        sine.append( amplitude[0]*math.sin(frequency[0]*i) )
        cosine.append( amplitude[1]*math.cos(frequency[1]*i) )
        superposition.append( sine[-1] + cosine[-1] )

    fig, ax = plt.subplots(3,1)

    ax[0].plot(x, sine)
    ax[0].set_title('Sine wave')

    ax[1].plot(x, cosine)
    ax[1].set_title('Cosine wave')

    ax[2].plot(x, superposition)
    ax[2].set_title('Bichromatic wave')

    plt.tight_layout()
    plt.show()

ex_3 = "3. Similar as no.1, but creating each subplot axes by using plt.subplot(nrows, ncols, index)."

def trig_subplots_3(x=[], amplitude=(1, 1), frequency=(1, 1)):

    sine = [amplitude[0]*math.sin(frequency[0]*i) for i in x]
    cosine = [amplitude[1]*math.cos(frequency[1]*i) for i in x]
    superposition = [s+c for s,c in zip(sine, cosine)]

    plt.subplot(3,1,1)
    plt.title('Sine wave')
    plt.plot(x, sine)

    plt.subplot(3,1,2)
    plt.title('Cosine wave')
    plt.plot(x, cosine)

    plt.subplot(3,1,3)
    plt.title('Bichromatic wave')
    plt.plot(x, superposition)

    plt.tight_layout()
    plt.show()

ex_4 = "4. Similar as no.1, but the superposition wave is generated after plotting the sine and cosine then and \
get the y values from each plot using .get_ydata()."

def trig_subplots_4(x=[], amplitude=(1, 1), frequency=(1, 1)):

    sine = [amplitude[0]*math.sin(frequency[0]*i) for i in x]
    cosine = [amplitude[1]*math.cos(frequency[1]*i) for i in x]

    fig, ax = plt.subplots(3,1)

    sine_plot = ax[0].plot(x, sine)
    ax[0].set_title('Sine wave')

    cosine_plot = ax[1].plot(x, cosine)
    ax[1].set_title('Cosine wave')

    superposition = sine_plot[0].get_ydata() + cosine_plot[0].get_ydata()
    ax[2].plot(x, superposition)
    ax[2].set_title('Bichromatic wave')

    plt.tight_layout()
    plt.show()

x = [i*0.01*pi for i in range(1000)]
amplitude = (1, 1)
frequency = (1, 0.75)

print(ex_1)
trig_subplots_1(x, amplitude, frequency)
print(ex_2)
trig_subplots_2(x, amplitude, frequency)
print(ex_3)
trig_subplots_3(x, amplitude, frequency)
print(ex_4)
trig_subplots_4(x, amplitude, frequency)


texts:
I took a challenge on CodeEval. Although the code seems to work for the examples taken from the site, I feel it is not really pretty and must be more complicated than it should be.

  Description:

  The sentence 'A quick brown fox jumps over the lazy dog' contains
  every single letter in the alphabet. Such sentences are called
  pangrams. You are to write a program, which takes a sentence, and
  returns all the letters it is missing (which prevent it from being a
  pangram). You should ignore the case of the letters in sentence, and
  your return should be all lower case letters, in alphabetical order.
  You should also ignore all non US-ASCII characters.In case the input
  sentence is already a pangram, print out the string NULL.

import sys
filepath = sys.argv[1]
f = open(filepath)
wholealphabet = ('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')
for line in f:
    sortedletters = list(set(line.lower()))
    i = 0
    while i != len(sortedletters):
        if wholealphabet.count(sortedletters[i]) != 0:
            i = i + 1
        else:
            sortedletters.pop(i)
    missingletters = ""
    for letter in wholealphabet:
        if sortedletters.count(letter) == 0:
            missingletters +=letter
    if len(missingletters) == 0:
        print("NULL")
    else:
        print(missingletters)


texts: Reporting new USB storage devices on Linux and macOS with Python

texts:
Synopsis:
I wanted something for macOS (and Linux;  maybe eventually Windows) that would simply wait for the user to connect a storage device and automatically select, or otherwise output the information to be used, read, manipulated, etc.
In its current form, it just prints to the shell, but you could assign the output to a list or variable for read/write operations and so on. It will respond to any new entries in the /dev system directory, including most USB devices, SD Cards, Webcams, and so on. You can test it by running the script in one window, and running something like sudo touch /dev/{x,y,z} in another.
I plan to use it to help people (those of us who are less technically inclined) migrate to Linux by automating the creation of bootable flash drives, but you can do what you like with it.
Open-ended feedback and suggestions are welcome. Please try to post example code pertaining to your suggestions, and don't be afraid to say something positive.
Usage:
user@macOS:~$ ./devlisten.py
/dev/disk2
/dev/rdisk2
/dev/disk2s1
/dev/rdisk2s1

Code:
#!/usr/bin/env python3

import os
import re
import time
import difflib

try:
    os.mkdir('/tmp/dev')
except FileExistsError:
    pass
except FileNotFoundError:
    print('No /tmp directory found.')
    exit()
except OSError:
    print('Read-only file system.')
    exit()

file1 = open('/tmp/dev/1', 'w')
for x in os.listdir('/dev'):
    file1.write(x + '\n')
file1.close()

try:

    diff = False
    while diff == False:
        time.sleep(0.25)

        file2 = open('/tmp/dev/2', 'w')
        for x in os.listdir('/dev'):
            file2.write(x + '\n')
        file2.close()

        text1 = open('/tmp/dev/1').readlines()
        text2 = open('/tmp/dev/2').readlines()

        for line in difflib.unified_diff(text1, text2):
            for line in re.finditer(r'(?<=^\+)\w.*$', line, re.MULTILINE):
                print('/dev/' + line.group(0))
                diff = True

except KeyboardInterrupt:

    print()
    exit()


texts:
I have a performance issue causing test->code->test cycle to be really slow. The slowness is hard to avoid, since I am doing some heavy image processing, and I am trying to accelerate things a bit by not running functions when it is not needed. For ex: compute some numbers from big images -> serialize results in text files -> resume computations from text files.

Currently, I commit the text files containing the results to share them with the team, and let other people run the tests quickly. But I have to make sure that whenever one dependency is updated (src images, preprocessing functions, etc), those value are recomputed. I looked for a tool which would allow me to describe dependencies and production rules to automate the process and avoid committing data in the codebase. I thought about makefile, but I read a lot of negative advice against it. I found stuff like Scons and other build automation tools, but those are for building software, and they do not seem adapted for my task.

I decided to write a small lib to tackle this issue (my environment is mainly Python and some C). The goal was to have objects knowing the production rule for their own output, and aware of the other objects they depend upon. An object knows if its output is up-to-date by comparing the current MD5 checksum of the file against the last one (stored somewhere in a small temp file).

Am I reinventing a wheel here? Is there a tool out there I should use instead of a custom lib? If not, is this a good pattern for taking care of this problem?

import os
import path
from md5 import md5 as stdMd5

# path.root is the root of our repo
hashDir = os.path.join(path.root, '_hashes')

def md5(toHash):
    return stdMd5(toHash).hexdigest()

class BaseRule(object):
    '''base object, managing work like checking if results are up to date, and
    calling production rules if they are not'''

    outPath = None

    def __init__(self, func):
        self.func = func

    @property
    def hashPath(self):
        return os.path.join(hashDir, md5(self.outPath))

    def getOutHash(self):
        with open(self.outPath) as f:
            fileHash = md5(f.read())
        return fileHash

    def isUpToDate(self):
        if not os.path.exists(self.outPath):
            return False
        if not os.path.exists(self.hashPath):
            return False
        with open(self.outPath) as f:
            fileHash = self.getOutHash()
        with open(self.hashPath) as f:
            storedHash = f.read().strip()
        return storedHash == fileHash

    def storeHash(self):
        if not os.path.exists(hashDir):
            os.makedirs(hashDir)
        with open(self.hashPath, 'w') as f:
            f.write(self.getOutHash())

    def get(self):
        inputPathes = dict([(key, inp.get()) for key, inp in self.inputs.items()])
        if not self.isUpToDate():
            self.func(outPath=self.outPath, **inputPathes)
            self.storeHash()
        return self.outPath

class StableSrc(BaseRule):
    'source file that never change'

    inputs = {}

    def __init__(self, path):
        self.outPath = path

    def isUpToDate(self):
        return True

def rule(_inputs, _outPath):
    'decorator used to declare dependencies'

    class Rule(BaseRule):
        inputs = _inputs
        outPath = _outPath

    return Rule

def copyTest():
    'test function'

    import shutil

    @rule({'inp' : StableSrc('test.txt')}, 'test2.txt')
    def newTest(inp, outPath):
        print 'copy'
        shutil.copy(inp, outPath)

    @rule({'inp' : newTest}, 'test3.txt')
    def newNewTest(inp, outPath):
        print 'copy2'
        shutil.copy(inp, outPath)

    return newNewTest.get()

if __name__ == '__main__':
    copyTest() # will copy test.txt to test2.txt and test3.txt. If ran a second time, won't copy anything


texts:
Note: I do know that Python libraries provide a Linked list and Stack. This implementation has been done to practice Python and some of the data structures and algorithms.

I have implemented Queue as a Single linked list. Feel free to make suggestions. Note: The code works.

Targeted Big O:

Search: O(n), EnQueue and DeQueue: O(1)

Methods:

en_queue(value): insert values
de_queue(): remove values
is_empty(): check to see if Queue is empty
peek_front(): look at what head points to without removing
peek_back(): look at what tail points to without removing
search(value): check to see if a value is in the Queue
length(): return size

Classes:

class Node:
    def __init__(self, value):
        self.data = value
        self.front = None

class Queue:
    def __init__(self):
        self.head = None
        self.tail = None
        self.count = 0

    def en_queue(self, value):
        new_node = Node(value)

        if self.tail is not None:
            # make the front attribute of old node point to new node
            self.tail.front = new_node

        else:
            # if first ever node in Queue both front and tail will point to it
            self.head = new_node

        self.tail = new_node
        self.count += 1

    def de_queue(self):
        if not self.is_empty():
            # point head to next node
            self.head = self.head.front
            print("sucess")
            self.count -= 1
        else:
            print("Empty QUEUE")

    def __iter__(self):
        node = self.head
        while node:
            yield node
            node = node.front

    def is_empty(self):
        if self.head is None and self.tail is None:
            return True
        else:
            return False

    def peek_front(self):
        return self.head.data

    def peek_back(self):
        return self.tail.data

    def queue_search(self, value):
        # start from the head
        p = self.head
        while p is not None:
            # make p reference to next node
            if p.front is not None:
                if p.data == value:
                    print("Found value")
                    return p.data
                p = p.front
            else:
                print("fail")
                return 0

    def length(self):
        return self.count

Test:

from stack_Queue import Queue

def main():

    print("-------Test Queue---------")
    print("-------Test En Queue------")
    my_queue = Queue()
    test_list = [1, 2, 3, 4, -2000000, 'a', 500000, 50]

    for i in test_list:
        my_queue.en_queue(i)
    print("-------En Queue Done-------")
    for i in my_queue:
        print(i.data)
    print("------Queue Print Done-----")
    print("------Queue Print Done-----")
    print(my_queue.peek_back())
    print(my_queue.peek_front())
    print("----------De Queue---------")
    my_queue.de_queue()
    print("--------De Queue Done------")
    for i in my_queue:
        print(i.data)
    print("-----Queue Print Done------")
    print("-----Test search-------")
    x = my_queue.queue_search('a')
    print(x)
    print("-------Full De Queue-------")
    while my_queue.length() != 0:
        my_queue.de_queue()
    print("--------De Queue Done------")
    for i in my_queue:
        print(i.data)
    print("-----Queue Print Done------")

if __name__ == "__main__":
    main()

Result:

-------Test Queue---------
-------Test En Queue------
-------En Queue Done-------
1
2
3
4
-2000000
a
500000
50
------Queue Print Done-----
------Queue Print Done-----
50
1
----------De Queue---------
sucess
--------De Queue Done------
2
3
4
-2000000
a
500000
50
-----Queue Print Done------
-----Test search-------
Found value
a
-------Full De Queue-------
sucess
sucess
sucess
sucess
sucess
sucess
sucess
--------De Queue Done------
-----Queue Print Done------

Process finished with exit code 0


texts:
I cannot edit the QueryPermissions class because it is an external .dll that was given to me to use. Yes, I realize it's a bad practice to use an out variables, but I am pushing for a rewrite of that service.

As you can see below the two methods do the almost the EXACT same thing only one uses a groupkey and the other uses a userkey and then calls the appropriate method. For whatever reason I am drawing a blank on refactoring these methods.

public IEnumerable<Node> GetNodesForUser(int userKey, IEnumerable<OnlineReport> onlineReports)
{
    var nodes = new List<Node>();
    foreach (var onlineReport in onlineReports)
    {
        var parentNode = new Node {Text = onlineReport.Key, Value = onlineReport.Value};
        var webQueries = new List<WebQuery>();
        //Line that is different
        _QueryPermissions.GetQueriesForTaskAndUser(Int32.Parse(onlineReport.Value), userKey, ref webQueries, true);
        foreach (var childNode in webQueries.Select(webQuery => new Node(parentNode){Text = webQuery.QueryTitle, Value = webQuery.QueryKey.ToString()}))
        {
            parentNode.Children.Add(childNode);
        }
        nodes.Add(parentNode);
    }
    return nodes;
}

public IEnumerable<Node> GetNodesForGroup(int groupKey, IEnumerable<OnlineReport> onlineReports)
{
    var nodes = new List<Node>();
    foreach (var onlineReport in onlineReports)
    {
        var parentNode = new Node { Text = onlineReport.Key, Value = onlineReport.Value };
        var webQueries = new List<WebQuery>();
        //Line that is different
         _QueryPermissions.GetQueriesForTaskAndUserGroup(Int32.Parse(onlineReport.Value), groupKey, ref webQueries, true);
        foreach (var childNode in webQueries.Select(webQuery => new Node(parentNode) { Text = webQuery.QueryTitle, Value = webQuery.QueryKey.ToString() }))
        {
            parentNode.Children.Add(childNode);
        }
        nodes.Add(parentNode);
    }
    return nodes;
}


texts: Assigning atomic number based on atomic symbol

texts:
I currently have the following code:

unsigned int symToZ(const std::string & sym){
    unsigned int atomicNum;
    if(sym == "H"){atomicNum = 1;}
    else if(sym == "He"){atomicNum = 2;}
    else if(sym == "Li"){atomicNum = 3;}
    else if(sym == "Be"){atomicNum = 4;}
    else if(sym == "B"){atomicNum = 5;}
    else if(sym == "C"){atomicNum = 6;}
    else if(sym == "N"){atomicNum = 7;}
    else if(sym == "O"){atomicNum = 8;}
    else if(sym == "F"){atomicNum = 9;}
    ...

    return atomicNum;
}

The code simply takes in a string sym (which is the atomic symbol, such as He, F, Au, and so on), and converts it to the respective atomic number. As you can see, it involves a lot of repeated code. For such simple code, I feel it is needlessly complex.

How can this be done more effectively?


texts: Logic in a card matching game controller

texts:
I have a card matching game with a model of:

Card
Deck
PlayingCard
PlayingCardDeck

And another model called CardMatchingGame.

Now, I had a task to add a button to the view for new game, which deals the cards again and setting the labels to 0 (#flips and score).

I added this method:

- (IBAction)newGame:(UIButton *)sender {

    self.flipsCount = 0;
    self.game = nil;
    for (UIButton *button in self.cardButtons) {
        Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:button]];
        card.unplayble = NO;
        card.faceUp = NO;
        button.alpha = 1;
    }

    self.notificationLabel.text = nil;
    [self updateUI];
}

And this is the whole viewcontroller:

#import "CardGameViewController.h"
#import "PlayingCardsDeck.h"
#import "CardMatchingGame.h"

@interface CardGameViewController ()

@property (weak, nonatomic) IBOutlet UILabel *flipsLabel;
@property (weak, nonatomic) IBOutlet UILabel *notificationLabel;
@property (weak, nonatomic) IBOutlet UILabel *scoreCounter;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *cardButtons;

@property (strong, nonatomic) CardMatchingGame *game;
@property (nonatomic) int flipsCount;

@end

@implementation CardGameViewController

//creating the getter method that creates a new card game.
-(CardMatchingGame *) game {

    if (!_game) _game = [[CardMatchingGame alloc] initWithCardCount:self.cardButtons.count usingDeck:[[PlayingCardsDeck alloc] init]];
    return _game;
}

//creating a setter for the IBOutletCollection cardButtons
-(void) setCardButtons:(NSArray *)cardButtons {

    _cardButtons = cardButtons;
   [self updateUI];
}

//creating the setter for the flipCount property. Whick is setting the flipsLabel to the right text and adding the number of counts.
-(void) setFlipsCount:(int)flipsCount {

    _flipsCount = flipsCount;
    self.flipsLabel.text = [NSString stringWithFormat:@"Flips: %d", self.flipsCount];

}

-(void) updateUI {

    for (UIButton *cardButton in self.cardButtons) {
        Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:cardButton]];
        [cardButton setTitle:card.contents forState:UIControlStateSelected];
        [cardButton setTitle:card.contents forState:UIControlStateSelected|UIControlStateDisabled];
        cardButton.selected = card.isFaceUp;
        cardButton.enabled = !card.unplayble;
        if (card.unplayble) {
            cardButton.alpha = 0.1;
        }

        //updating the score
        self.scoreCounter.text = [NSString stringWithFormat:@"Score: %d", self.game.score];

        //if notification in CardMatchingGame.m is no nil, it will be presented
        if (self.game.notification) {

        self.notificationLabel.text = self.game.notification;

        }
    }
}

//Here I created a method to flipCards when the card is selected, and give the user a random card from the deck each time he flips the card. After each flip i'm incrementing the flipCount setter by one.
- (IBAction)flipCard:(UIButton *)sender {

    [self.game flipCardAtIndex:[self.cardButtons indexOfObject:sender]];
    self.flipsCount++;
    [self updateUI];
}

//cleaning the history using the cleanHistory method in CardMatchingGame.m and creating a new game by setting geme to nil
- (IBAction)newGame:(UIButton *)sender {

    self.flipsCount = 0;
    self.game = nil;
    for (UIButton *button in self.cardButtons) {
        Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:button]];
        card.unplayble = NO;
        card.faceUp = NO;
        button.alpha = 1;
    }

    self.notificationLabel.text = nil;
    [self updateUI];
}

@end

Could you please tell me if this is a logical solution? I'm a very new programmer and critiques are important to me.


texts: Transforming XML with null checks vs variables

texts:
I'm working on an Spring Integration application that transforms a XML (converted by Jaxb) into a custom Object by checking various information given in the XML.

The problem is that I can't trust the data that has been sent to me and I have to do null checks everywhere. Can't decide if storing the result of a null check is better or is there another solution?

Solution 1: Do the null checks everywhere, and when we call another method, do the same null checks when needed. Which I dislike very much.

public void mapSpecificField(XmlObject xmlObject) {

    if (xmlObject != null) {
        if (xmlObject.getName() != null) {
            if (xmlObject.getName().equals("TYPE_A")) {
                if (xmlObject.getIdentifiers() != null
                        && !xmlObject.getIdentifiers().isEmpty()
                        && xmlObject.getIdentifiers().get(0) != null) {
                    String mainId = xmlObject.getIdentifiers().get(0).toLowerCase();

                    if (xmlObject.getXmlSubObjects() != null) {
                        for (XmlSubObject subObject : xmlObject.getXmlSubObjects()) {
                            if (subObject != null && subObject.getLocation() != null) {
                                mapOtherStuff(subObject);
                            }
                        }
                    }
                }
            } else {
                if (xmlObject.getIdentifiers() != null
                        && !xmlObject.getIdentifiers().isEmpty()
                        && xmlObject.getIdentifiers().get(0) != null) {
                    String mainId = xmlObject.getIdentifiers().get(0).toUpperCase();
                }
            }
        }
    }
}

Solution 2: Do the null checks in an inner class and store the result in those variables. Which I like but not sure if memory wise it's a smart thing to do...

The inner helper class:

static class Helper {
    String type = null;
    String mainId = null;

    public Helper(XmlObject xmlObject) {
        if (xmlObject != null) {
            // Common
            if (xmlObject.getName() != null) {
                type = xmlObject.getName();
                // Specific mapping
                if (xmlObject.getIdentifiers() != null && !xmlObject.getIdentifiers().isEmpty() && xmlObject.getIdentifiers().get(0) != null) {
                    if (type.equals("TYPE_A")) {
                        mainId = xmlObject.getIdentifiers().get(0).toLowerCase();
                    } else {
                        mainId = xmlObject.getIdentifiers().get(0).toUpperCase();
                    }
                }
            }
        }
    }

And the previous class using the helper:

public void mapSpecificField(XmlObject xmlObject) {
    Helper helper = new Helper(xmlObject);

    String mainId = helper.mainId;

    if ("TYPE_A".equals(helper.type)) {
        if (xmlObject.getXmlSubObjects() != null) {
            for (XmlSubObject subObject : xmlObject.getXmlSubObjects()) {
                if (subObject != null && subObject.getLocation() != null) {
                    mapOtherStuff(subObject);
                }
            }
        }
    }
}

Or if anyone has a Solution 3, I'd be up for it as I really need some opinions...

Please do note that my original class has about 8 different types & lots of fields to map and I'm splitting the mapping into few methods that sometimes need the same variables. I can't share it here as it's pretty long but the classes above show exactly what it looks like.


texts:
I am developing a high-performance(real-time) system, it requires message passing between its component. speed and accuracy is at most priority. I have explored a few options. ConcurrentQueue<T> is super fast BlockingCollection<T> provides a better API. also BlockingCollection<T> waits for the producer to produce the message. the problem is BlockingCollection<T> is not fast enough for the job. also, it uses locks internally which may lead to locking contention. so I tried to develop a queue that provides blocking behavior(waits for the producer to produce message) and does not use lock internally. here what I have come up with

    public class BlockingConcurrentQueue<T> : IDisposable
    {
        private readonly ConcurrentQueue<T> _internalQueue;
        private AutoResetEvent _autoResetEvent;
        private long _consumed;
        private long _isAddingCompleted = 0;
        private long _produced;
        private long _sleeping;

        public BlockingConcurrentQueue()
        {
            _internalQueue = new ConcurrentQueue<T>();
            _produced = 0;
            _consumed = 0;
            _sleeping = 0;
            _autoResetEvent = new AutoResetEvent(false);
        }

        public bool IsAddingCompleted
        {
            get
            {
                return Interlocked.Read(ref _isAddingCompleted) == 1;
            }
        }

        public bool IsCompleted
        {
            get
            {
                if (Interlocked.Read(ref _isAddingCompleted) == 1 && _internalQueue.IsEmpty)
                    return true;
                else
                    return false;
            }
        }

        public void CompleteAdding()
        {
            Interlocked.Exchange(ref _isAddingCompleted, 1);
        }

        public void Dispose()
        {
            _autoResetEvent.Dispose();
        }

        public void Enqueue(T item)
        {
            _internalQueue.Enqueue(item);

            if (Interlocked.Read(ref _isAddingCompleted) == 1)
                throw new InvalidOperationException("Adding Completed.");

            Interlocked.Increment(ref _produced);
            if (Interlocked.Read(ref _sleeping) == 1)
            {
                Interlocked.Exchange(ref _sleeping, 0);
                _autoResetEvent.Set();
            }
        }

        public bool TryDequeue(out T result)
        {
            if (Interlocked.Read(ref _consumed) == Interlocked.Read(ref _produced))
            {
                Interlocked.Exchange(ref _sleeping, 1);
                _autoResetEvent.WaitOne();
            }

            if (_internalQueue.TryDequeue(out result))
            {
                Interlocked.Increment(ref _consumed);
                return true;
            }
            return false;
        }
    }

I seek your expertise to review

Sequence Guarantee
Any Performance improvement
Am I doing anything wrong which may break in race condition


texts: Making backtracking Sudoku solver more functional

texts:
I'm implementing the backtracking solving algorithm for a Sudoku in F#.  I'm wondering if I could make my code better respect the functional programming paradigm or even just making it simpler/better.

let solve originalSudoku =
    let sudoku = Array2D.copy originalSudoku

    let isValidNumber (x,y) n =
        let square =
            let (x1,y1) = (x/3)*3,(y/3)*3
            [| for i in x1..(x1+2) do for j in y1..(y1+2)->(i,j) |]
            |> Array.forall(fun (i,j)->sudoku.[i,j]<>n)
        let line =
            [|0..8|] |> Array.forall(fun i->x=i || sudoku.[i,y]<>n)

        let column =
            [|0..8|] |> Array.forall(fun i->y=i || sudoku.[x,i]<>n)

        line && column && square

    let rec isGridValid position=
        let x,y = position/9, position%9
        if position = 9*9 then
            true
        else if originalSudoku.[x,y] <> 0 then
            isGridValid(position+1)
        else
            let isValid = isValidNumber (x,y)
            let testCurrentCase n =
                if isValid n then
                    sudoku.[x,y] <- n
                    isGridValid(position+1)
                else
                    false
            if ( not([|0..9|] |> Array.exists(testCurrentCase))) then
                sudoku.[x,y] <- 0
                false
            else true

    isGridValid 0 |> ignore

    sudoku


texts: Deleting duplicate elements from a single-linked list in C++11

texts:
The code below is a simple coding exercise I got from a book that asks to remove the duplicates from a single-linked list (using a simple struct; this is part 2, see part 1 here).

Question 1: Is there a better way to delete a Node than by creating a temporary variable temp and deleting that. I actually tried deleting p directly and it worked. I find this surprising because after I delete p I would expect p->next to be a segmentation fault. Is this a compiler-specific trickery or is it a safe practice?

Question 2: I'm a little confused about passing pointers by reference. If I don't pass head by reference in insert, it doesn't work; but passing them by copy to remove_duplicates works (that is, the second call to print_node doesn't print the original list). Why?

#include <iostream>
#include <unordered_map>

struct Node {
  int data;
  Node* next;
};

void insert(Node*& head, const int data) {
  head = new Node {data, head};
}

void print_node(Node* head) {
  if (!head) return;

  std::cout << head->data;
  for(auto p = head->next; p; p = p->next) {
    std::cout << "->" << p->data;
  }
  std::cout << std::endl;
}

void remove_duplicates(Node * head) {
  if (!head || !head->next) return;

  std::unordered_map<int, bool> map {{head->data, true}};
  for (auto p = head->next, prev = head; p; p = p->next) {
    if (map[p->data]) {
      prev->next = p->next;
      Node* temp {p};
      delete temp;
    } else {
      map[p->data] = true;
      prev = p;
    }
  }
}

int main(int argc, char* argv[]) {
  Node* my_list {};
  insert(my_list, 2);
  insert(my_list, 1);
  insert(my_list, 3);
  insert(my_list, 2);
  insert(my_list, 2);
  insert(my_list, 1);
  insert(my_list, 4);
  print_node(my_list);
  // 4->1->2->2->3->1->2
  remove_duplicates(my_list);
  print_node(my_list);
  // 4->1->2->3
}


texts: Get 5 to 10 characters and flip their case

texts:
This small programme is an exercise that my teacher gave us.
n is an alphabetic input that its length must be between 5 and 10. You have to insert the characters of the input one by one to a list called T. Then, add the reverse case of letters to another list called V. So if there is a capital letter in T it would be lower in list V and you have to only print V at the end.
This is my code, is there any better solution or cleaner one perhaps?
T = []
V = []
n = input("Enter a character")
while len(n) not in range(5, 11) or n.isalpha() == False:
    n = input("Enter a characters between 5 and 11, and only characters ")

print(n)
for i in range(len(n)):
    T.append(n[i])

for i in range(len(T)):
    if T[i].isupper():
        V.append(T[i].lower())
    else:
        V.append(T[i].upper())

print(V)


texts:
Each data structure has its own time complexities.  The biggest one that jumps out at you is the hash table.  The average times for Insertion, Deletion and Searching are all O(1).  But it's really just constant time, since there can be multiple reps through each of these to find the right spot.  The real question is, can we do each of those operations in exactly one operation, if space wasn't an issue?

Recently I was working on the radix sort, and figuring out how to speed it up as much as possible.  The one thing I settled on was doing a 2-byte counting sort, thus you would only have to loop once through.  Then I got to thinking about the trie I used before, with integers where I traversed through by modding the number by 10 each time through.

This seemed to be faster than any other data structure that I've tried, but wanted to make it faster.  What I tried today was treating the trie as a guaranteed 2-level tree: each node with \$2^{16}\$ (65536) children.  That way I can reference each number like this: root->link[twoByte1]->link[twoByte2].  Where twoByte1 is the first 16 bits, and twoByte2 is the second 16-bit chunk.  Problem is, this is a lot of memory.  Instead, I decided to make an array of structures, with \$2^{16}\$ bool (uint8_t) values instead, and ran across the same issue.  To fix this, I made the following structure.

struct trie {
    unsigned int link[2048];
};

I decided to use 2048 unsigned integers (or signed, wasn't sure if there would be a difference) instead.  That way I can treat each bit as the true/false value during look up.  In order to reference each position, I would take the first 16 bytes, and reference the element he same way as before, but the 2nd I would divide by 32 to find out which element of the integer array to use, and mod the number again by 32 to find out which bit to look at.  The following is the code I used to reference it:

uint8_t getData (int data, uint16_t& dir, uint16_t& pos, uint8_t& x) {
    dir = (data >> 0)  & 0xffff;
    pos = (data >> 16) & 0xffff;
    x   =  pos / 32;
    return pos % 32;
}

The insert function was simply finding the spot and turning the bit on.  To do this, I would get the data from the function above, then OR the specific bit with 1.  Similarly with deletion, only I would invert the bit string, then AND it, to turn it off.  Then to search for that element, I would just return the specific bit.  Help with how to clear the bit was found in How do you set, clear, and toggle a single bit? on SO.

Here is the code for those three functions:

void insert(trie *root, int data) {
    uint16_t dir, pos;
    uint8_t x, y = getData(data, dir, pos, x);
    root[dir].link[x] |= 1 << y;
}
bool find(trie *root, int data) {
    uint16_t dir, pos;
    uint8_t x, y = getData(data, dir, pos, x);
    return root[dir].link[x] & (1 << y);
}
void remove(trie *root, int data) {
    uint16_t dir, pos;
    uint8_t x, y = getData(data, dir, pos, x);
    root[dir].link[x] &= ~(1 << y);
}

From here it was as simple as initializing the array of structs.  The great thing is that with the number of elements coming in, the data structure will never grow any farther out.  Also, in the case of threading, since I'm only turning the bits on during insertion, I don't think I would need to synchronize any of the threads.  Therefore it could be speed up with threading.  What are your thoughts on this? I made a test case on Ideone.  I ran a test on a Linux machine running on an i7, and was able to process 250 million integers every 2.5 seconds.


texts: Minimum Number of swaps required to group all ones together in array of 0s and 1s

texts:
Problem Statement:

Given a binary array data, return the minimum number of swaps required to group all 1’s present in the array together in any place in the array.

Example 1:

Input: [1,0,1,0,1]

Output: 1

Explanation:

There are 3 ways to group all 1's together:

[1,1,1,0,0] using 1 swap.

[0,1,1,1,0] using 2 swaps.

[0,0,1,1,1] using 1 swap.

The minimum is 1.

Example 2:

Input: [0,0,0,1,0]

Output: 0

Explanation:

Since there is only one 1 in the array, no swaps needed.

Example 3:

Input: [1,0,1,0,1,0,0,1,1,0,1]

Output: 3

Explanation:

One possible solution that uses 3 swaps is [0,0,0,0,0,1,1,1,1,1,1].

This is my solution. I used sliding window.

First I counted total number of ones in the given array.

To group the 1s in minimum number of swaps we have to group them up in a cluster where their density is already more.

So I made an array which keeps a count of 1s encountered till that element

Then I created a window of the size of total 1s in that array and moved that window till the end to find which sub array had maximum number of 1s, because this is the area where we will insert other 1s

The code is as follows

int minSwaps(vector<int>& data) {
        // Size of given array
        int size = data.size();

        // Total ones in given array
        int totalOnes = 0;

        // Counting total ones in array
        for(int i = 0 ; i < size;++i){
            if(data[i]==1) totalOnes++;
        }

        if(totalOnes==size) return 0;
        if(totalOnes==0) return 0;

        // Using a winow of the size of total ones
        int window = totalOnes;

        // maxOnes will store the value of maximum ones in any sliding window of size 'window'
        int maxOnes = INT_MIN;

        // This array will store total number of ones till index i
        vector<int> onesTillNow(size,0);

        if(data[0]==1)
            onesTillNow[0]=1;
        else
            onesTillNow[0]=0;

        for(int i = 1; i < size;++i){
            if(data[i]==1)
                onesTillNow[i] = onesTillNow[i-1] + 1;
            else
                onesTillNow[i] = onesTillNow[i-1];
        }

        for(int i = window - 1; i < size ; ++i){
            if(i == window - 1 )
                totalOnes = onesTillNow[i];
            else
                totalOnes = onesTillNow[i] - onesTillNow[i-window];

            if(totalOnes > maxOnes) maxOnes = totalOnes;
        }
        return window - maxOnes;
    }

Can you suggest any improvements to this or a better way to do it?


texts:
I just wrote the following javascript (jQeury loaded):

var valid, ui;

try {
    $.each(this._cache, function() {
        $.each(this, function() {
            $.each(this, function() {
                if (this.label.toLowerCase() === valueLowerCase) {
                    valid = true;
                    ui = {item: $.extend({}, this) };
                    throw 'Control flow throw, please rethrow if accidently caught';
                }
            });
        });
    });
} catch(e) {}

My coworker suggested I rewrite this as follows:

var valid, ui;

$.each(this._cache, function() {
    $.each(this, function() {
        $.each(this, function() {
            if (this.label.toLowerCase() === valueLowerCase) {
                valid = true;
                ui = {item: $.extend({}, this) };
            }
            return !valid;
        });
        return !valid;
    });
    return !valid;
});

I think this is a valid case of using exceptions as control flow. Which way is the correct way to do this?


texts:
I did the Divisible Sum Pairs problem on HackerRank

  input: n is length of array ar, k is an integer value.
  a pair is define only if ar[i]+ar[j] is dividable by k where i < j.
  Problem: find and return pairs in array.

def divisibleSumPairs(n, k, ar):
    i=0       #pointer 1
    j=1       #pointer 2 is faster than p1
    count =0  #pointer 3 will only increment 1 once j = n-1 (second last element)
    pairs=0
    while count < n-1:
        if (ar[i]+ar[j])%k==0:
            pairs+=1
        j+=1
        count+=1
        if count==n-1:
            i+=1
            j=i+1
            count =i
    print(pairs)

Code visualized

step 1:
 i  j
[a][b][c][e][f]
compare (i,j)
 i     j
[a][b][c][e][f]
compare (i,j)
 i        j
[a][b][c][e][f]
compare (i,j)
 i           j
[a][b][c][e][f]
compare (i,j)
i+=1
j=i+1

step2
    i  j
[a][b][c][e][f]
compare (i,j)
        .
        .
        .
        .
step n
          i  j
[a][b][c][e][f]
compare (i,j)
finish

I have a couple of questions:

Does this algorithm have a name?
Is there other way (maybe better, faster)?
Is there some code I could have done better/ differently?

#some test  data n=6 , k=3 ar =[1, 3, 2, 6, 1, 2]


texts: Determine serializer on per-action basis for DjangoRestFramework ModelViewSet

texts:
I have a Profile object with two fields. One is safe for the public to see, while the other contains private data.

class Profile(models.Model):
    owner = models.OneToOneField(User) #django.contrib.auth.models
    public_field = models.TextArea()
    private_field = models.TextArea()

I have two DjangoRestFramework serializers for this model:

class BasicProfileSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Profile
        fields = ('url', 'owner', 'public_field')

class FullProfileSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Profile
        fields = ('url', 'owner', 'public_field', 'private_field')
        read_only_fields = ('owner',)

Lastly, I have a ModelViewSet for this object. Here, I would like to always use the BasicProfileSerializer for list and create actions. For all other actions, I would like to use the FullProfileSerializer only if the user making the request is_staff or is the owner of the Profile object.

class ProfileViewSet(viewsets.ModelViewSet):
    queryset = Profile.objects.all()
    permission_classes = (IsOwnerOrStaffOrReadOnly,)

    def get_serializer_class(self):
        if self.action in ['list', 'create']:
            return BasicProfileSerializer
        elif get_object_or_404(self.queryset, pk = self.kwargs['pk']).owner == self.request.user or self.request.user.is_staff:
            return FullProfileSerializer

Is there a better / more correct way to do the lookup in the elif block?


texts:
The following code works, but the filter operation is bottlenecking my analysis. Do you have an idea how I can make the filter operation faster?
Do you have other comments about the codestyle?

import sys
import pandas as pd
import numpy as np
from numpy.random import randint, rand, choice, permutation

ID = [value for sublist in
      ((value for _ in range(length))
          for value, length in enumerate(randint(1, 10, 70000)))
      for value in sublist]

data = pd.DataFrame(rand(len(ID), 3), columns=['A', 'B', 'C'])

data['ID'] = ID

data['dt'] = randint(0, sys.maxsize, len(data)).astype('M8[ns]')
data.loc[choice([True, False], len(data), [0.05, 0.95]), 'dt'] = None

data = data.apply(permutation)

# Until here the data was only prepared to be similar to my actual data.
# The following command should be optimized.
data.groupby('ID').filter(lambda x: not x['dt'].isnull().any())


texts: Longest substring with unique characters

texts:
Find the length of the longest substring without repeating characters

Any comments on my code?

public class LongestSubstring {
    /**
     * First version. O(n^2) runtime
     * For each character, find the longest substring starting
     * with this character and update max
     * @param s
     * @return
     */
    public int lengthOfLongestSubstringV1(String s) {
        char[] c = s.toCharArray();
        int n = c.length;
        int max = 0;

        for (int i = 0; i < n; i++){
            // localMax is the size of the longest substring starting with character i
            // and that has no repeated character
            int localMax = findLocalMax(c,i);
            // update max if localMax > max
            max = (max > localMax) ? max : localMax;
        }
        return max;
    }

    /**
     * find the largest substring that has no repeated character
     * starting at character i in array c
     * @param c
     * @param i
     * @return
     */
    public int findLocalMax(char[] c, int i){
        int n = c.length;
        // seen: characters already seen
        HashSet<Character> seen = new HashSet<Character>();
        int localMax = 0;

        for (int j = i; j < n; j++){
            // c[j] was seen already
            if (seen.contains(c[j])){
                return localMax;
            }
            else{
                seen.add(c[j]);
                localMax++;
            }
        }
        return localMax;
    }

    /**
     * Second version. O(n^2) runtime
     * if a character is seen again,
     * @param s
     * @return
     */
    public int lengthOfLongestSubstringV2(String s) {
        char[] c = s.toCharArray();
        int n = c.length;
        // currentLetters: HashSet of the letters contained in the current substring
        HashSet<Character> currentLetters = new HashSet<Character>();
        // pointer1 points to the beginning of the substring
        int pointer1 = 0;
        int max = 0;
        int currentCount = 0;

        // pointer2 points to the end of the substring
        for (int pointer2 = 0; pointer2 < n; pointer2++){
            if (currentLetters.contains(c[pointer2])){
                // if the letter c[pointer2] has already been seen
                // remove all the letters before the first occurrence
                // of this letter to consider the substring beginning after
                // this first occurrence
                while (c[pointer1] != c[pointer2]){
                    currentCount--;
                    currentLetters.remove(c[pointer1]);
                    pointer1++;
                }
            }
            else{
                // otherwise, add the letter to the substring
                currentCount++;
                currentLetters.add(c[pointer2]);
            }
            max = (max > currentCount) ? max : currentCount;
        }

        return max;
    }
}

public class TestLongestSubstring {
    LongestSubstring lgs = new LongestSubstring();
    @Test
    public void testEmptyString(){
        String s = "";
        assertEquals(0,lgs.lengthOfLongestSubstringV1(s));
        assertEquals(0,lgs.lengthOfLongestSubstringV2(s));
    }

    @Test
    public void testSameCharacterExpects1(){
        String s = "bbbb";
        assertEquals(1,lgs.lengthOfLongestSubstringV1(s));
        assertEquals(1,lgs.lengthOfLongestSubstringV2(s));
    }

    @Test
    public void testabcabcbbExpects3(){
        String s = "abcabcbb";
        assertEquals(3,lgs.lengthOfLongestSubstringV1(s));
        assertEquals(3,lgs.lengthOfLongestSubstringV2(s));
    }
}

public class TestLongestSubstringRunner {
    public static void main(String args[]){
        Result result = JUnitCore.runClasses(TestLongestSubstring.class);
        for (Failure failure : result.getFailures()){
            System.out.println(failure.toString());
        }
        System.out.println(result.wasSuccessful());
    }
}


texts:
I've been practicing my algorithms using The Algorithm Design Manual. I've decided to implement the depth first search section (5.8) using javascript. Note you can execute the code here if you don't have node.js.

var doDFS = function(graph, source, directed, processVertexEarly, processVertexLate, processEdge, logOff) {
    var finished = false;
    var time = 0;
    var discovered = [];
    var processed = [];
    var entry_time = [];
    var exit_time = [];
    var parent = [];

    if (!logOff) console.log();
    if (!logOff) console.log('*****************************');
    if (!logOff) console.log('DFS starting at', source, 'for adjacency list:');
    if (!logOff) console.log(graph);

    (function recDoDFS(u) {
        if (finished) return;
        discovered[u] = true;
        if (!logOff) console.log('DISCOVERED', u);
        time = ++time;
        entry_time[u] = time;

        processVertexEarly(u);

        var adjList = graph[u];
        for (var i = 0; i < adjList.length; i++) {
            v = adjList[i];
            if (!discovered[v]) {
                parent[v] = u;
                recDoDFS(v);
            } else if (!processed[v] || directed) {
                processEdge(u, v);

                if (finished) return;
            }
        }
        processVertexLate(u);

        time = ++time;
        exit_time[u] = time;

        processed[u] = true;
    })(source);

    if (!logOff) console.log();
    if (!logOff) console.log('%%%%%%%%%%%%%%% DFS Info %%%%%%%%%%%%%%%');
    for (var i = 0; i < graph.length; i++) {
        if (!logOff) console.log();
        if (!logOff) console.log('NODE', i);
        if (!logOff) console.log('discovered:', discovered[i]);
        if (!logOff) console.log('processed:', processed[i]);
        if (!logOff) console.log('parent:', parent[i]);
        if (!logOff) console.log('entry time:', entry_time[i]);
        if (!logOff) console.log('exit time:', exit_time[i]);
        if (!logOff) console.log();
    }
    if (!logOff) console.log('############ DFS OVER ############');
    if (!logOff) console.log();
};

var PVE = function(v, logOff) {
    if (!logOff) console.log('Early processed vertex:', v);
};

var PVL = function(v, logOff) {
    if (!logOff) console.log('Late processed vertex:', v);
};

var PE = function(u, v, logOff) {
    if (!logOff) console.log('Processed edge:', '(' + u + ', ' + v + ')');
};

var adjList = [
    [1],
    [0, 4, 5],
    [3, 4, 5],
    [2, 6],
    [1, 2],
    [1, 2, 6],
    [3, 5],
    [8],
    [],
    []
];

doDFS(adjList, 0, false, PVE, PVL, PE);


texts: Accessing a REST WebService and updating local HTML objects with Modular JS

texts:
I have this code I am doing to make my code modular js:

$(function(){
    var url, settings ={};
    var language = mainSettings.getLanguage(); /* there is an object in the page called mainSettings with current language */
    function applyLanguageSettings() {
        if (language == "en") {
         settings.web = "en";

        }
        else {
         settings.web = "es";
        }
    }

    applyLanguageSettings();
    //Get element
    var pageName= location.pathname.split("/").pop();
    pageName = pageName.substring(0, pageName.indexOf('.aspx'));
    baseUrl = mainSettings.getUrl() + settings.web + "/db/items?$filter=PageName eq '"+ pageName + "'";
    var dfd = $.ajax({
    url: baseUrl,
    method: "GET",
    headers : {
        "accept": "application/json;odata=verbose"
    }
})

dfd.done(function(data, status, jqXHR){
        if(data.d && data.d.results && data.d.results.length >0){
            var results = data.d.results;
            var card = data.d.results[0];
            var obj = {};
            obj.Title = value.Title;
            obj.ImageSource = value.Img;
    $("#Img").attr("src",obj.ImageSource);
    $("#Title").text(obj.Title);

          }
    });
})

I'm trying to access a REST-based Web-Service using JavaScript, then update a couple local HTML elements with the result of the download.

I have a couple questions:

Do I have to define a namespace and put my code inside to make it modular? Do I have to make my code modular in the first place? I don't see how I can turn this straightforward code into modular code.
For the apply language settings, I am not sure if am doing the right thing by defining a function then calling the function below it. Do I need to use IIFE?
Calling the $("#Title"), do I need to get the container in HTML once, and use .find()? What's the benefit of using .find() over what I am doing here?
Is my if condition to check for the data done in the right way?


texts:
Given two strings, find the common characters.

Is there better implementation for this problem?

#include<iostream>
#include<string>
#include<algorithm>

std::string   find_intersection(std::string & first, std::string & second)
{
   std::sort(std::begin(first),std::end(first));
   std::sort(std::begin(second), std::end(second));
   int length = std::min(first.length(), second.length());
   std::string result(length,' ');
   std::set_intersection(std::begin(first),std::end(first),std::begin(second),std::end(second),std::begin(result));

   result.shrink_to_fit();
   return result;
}

int main()
{
   std::string first="GermanTown";
   std::string second="Georgia";
    std::cout<<find_intersection(first,second)<<"\n";
   return 0;
}


texts:
now = datetime.datetime.utcnow()
now.strftime('%d %b %Y %I:%M:%S.%f')[:-3] + now.strftime(' %p')

Is there a cleaner solution for this? I don't want the extra 000 to appear everytime in %f.

EDIT: Got some more possible combinations:

now.strftime('%d %b %Y %I:%M:%S.%f')[:-3] + (' PM' if now.hour > 11 else ' AM')
now.strftime('%d %b %Y %I:%M:%S.X %p').replace('X', str(now.microsecond / 1000))