texts: Array indexing with copy constructor, assignment operator and index operator overload

texts:
The code below is a custom array class that handles indexing, copying, printing, etc. explicitly.
Is there a better approach for specification (declaration and definition) of the assignment operator (with swap function) and the index [] operator?
Furthermore, are there any improvements that can be made to the other methods to improve functionality?

// Overloading operators for Array class
#include<iostream>
#include<cstdlib>

using namespace std;

// A class to represent an integer array
class Array{
private:
    int *ptr;
    int size;
public:
    Array(int *p = NULL, int s = 0);
    Array(const Array&);
    ~Array();
    Array& operator= (Array);

    // Overloading [] operator to access elements in array style
    int &operator[] (int);

    // Utility function to print contents
    void print() const;

    friend void swap(Array& first, Array& second);};

// Implementation of [] operator.  This function must return a
// reference as array element can be put on left side
int &Array::operator[](int index){
    if (index >= size || index < 0){
       throw out_of_range("Index out of Range error");
    }
    return ptr[index];
}

// constructor for array class
Array::Array(int *p, int s){
    size = s;
    ptr = NULL;
    if (s != 0){
        ptr = new int[s];
        for (int i = 0; i < s; i++)
            ptr[i] = p[i];}
}

// destructor for array class
Array::~Array(){
    delete[] ptr;
    ptr = NULL;}

// copy constructor for array class
Array::Array(const Array& A) {
    size = A.size;
    ptr  = new int[size];
    for (int i = 0; i < size; i++)
        ptr[i] = A.ptr[i];}

//swap friend function of assignment operator
void swap(Array& first, Array& second){
    using std::swap;
    swap(first.size, second.size);
    swap(first.ptr, second.ptr);}

//Assignment operator for array class
Array& Array::operator=(Array other){
    swap(*this, other);
    return *this;}

//print function for array elements
void Array::print() const{
    cout << "{";
    for(int i = 0; i < size; i++)
        cout<<ptr[i]<<" ";
    cout<<"}"<<endl;}

// Driver program to test above methods
int main()
{
    int a[] = {1, 2, 3, 4, 5, 6};
    Array arr1(a, 6);
    arr1[0] = 7;
    arr1.print();
    Array arr2 = arr1;
    arr2.print();
    arr1[-1] = 4;
    return 0;
}


texts:
I have folder1 that contains other folders (which may contain other folders etc). This process stops at some point where a folder contains only files, and some of them end with the string "img".

I would like to write to a file for each line:

the complete path of the file (if ends with, say "img")
the immediate folder that contains it

something like

/path/start/folder1/folder2/.../folderN/file123-img folderN

My Python 3 code is

import os
file_list = []
with open("fileList.txt", "w") as fp:
    for root, folders, files in os.walk('path/start/'):
        if folders == []:
            for fil in files:
                if fil.endswith('img'):
                    final = (root.split("/"))[-1]
                    fp.write(root + "/"+fil + " " + final +"\n")

I wonder if i could use more pythonic tool (like comprehensions) instead for - if - for - if


texts:
On click on a div, a form replace this div. When the user clicks outside the form, the form is hidden and the div is re-show. For this, I implemented this process and I want your feedback, please.

function showForm(){
   hide the div
   show the form, and set value of a form textarea
    textarea.focus();
}

function hideForm(id_form) {
    hide the form
    show the div
}

$(document).ready(function() {
    $("form[name=theform] :submit").mousedown(function() {
         myprocess with ajax (not important)
    });
});

$(document).ready(function() {
    $("form[name=theform] textarea").focusout(function(e){
        When a form textarea loses the focus, the form is hide with this function :
        hideForm($(this).closest("form").attr('id'));
    });
});

// The process beginning
$(document).ready(function(){
    $('div[name=thediv]').click(showForm);
});

I have used the function blur() at the beginning, but it was difficult with the submit button, so I chose this process containing mousedown and focusout.

Can these 2 functions (mousedown and focusout) provoke problems? What do you think about this process?


texts: Imperative Sieve of Eratosthenes using destructive updates in Haskell

texts:
I've implemented the prime sieve of Eratosthenes in Haskell using a mutable array of unboxed Bools instead of the usual pure and immutable datastructures.

My main concern with this code is speed. For large upper bounds, it runs approximately 70% slower than C code implementing the same algorithm.
Memory is already optimal (1 bit per number plus some small overhead).

I would also like to know if the code is reasonably idiomatic, considering the fact that is impure, and basically non-functional (meaning imperative).
Any nitpicks are appreciated.

import Prelude
import System.Environment (getArgs)
import Data.Array.Unboxed (UArray, (!))
import Data.Array.Storable (newArray, readArray, writeArray, getBounds)
import Data.Array.ST (STUArray, runSTUArray)
import Control.Monad (when)
import Control.Monad.ST (ST)

markMultiplesAsNotPrime :: STUArray s Int Bool -> Int -> ST s ()
markMultiplesAsNotPrime isPrime k = do
  (_, n) <- getBounds isPrime
  kIsPrime <- readArray isPrime k
  when kIsPrime $ do
    let multiples = takeWhile (<=n) $ iterate (+k) (k+k)
    mapM_ (\i -> writeArray isPrime i False) multiples

sieve :: Int -> UArray Int Bool
sieve n | n < 0 = undefined
sieve n = runSTUArray $ do
  isPrime <- newArray (2, n) True :: ST s (STUArray s Int Bool)
  let kMax = isqrt' n
  let ks = takeWhile (<=kMax) . iterate (+1) $ 2
  mapM_ (markMultiplesAsNotPrime isPrime) ks
  return isPrime

isqrt' :: Int -> Int
isqrt' = ceiling . (sqrt :: Double -> Double) . fromIntegral

primesSmallerThanOrEqualTo :: Int -> [Int]
primesSmallerThanOrEqualTo n | n < 2 = []
primesSmallerThanOrEqualTo n = let
    isPrime = sieve n
  in
    [i | i <- [2 .. n], isPrime ! i]

main :: IO ()
main = do
  args <- getArgs
  mapM_ (print . last . primesSmallerThanOrEqualTo . read) args

In case it is relevant:
I compiled and executed the code on an amd64 CPU using "The Glorious Glasgow Haskell Compilation System, version 7.10.3" with the optimization switch "-O2".

Some timings (as measured with the runtime system switch "-s", best of five runs): $$ \begin{array}{4c} n & π(n) & t [s] & \log\left(\frac{t_2}{t_1}\right) \bigg/ \log\left(\frac{π(n_2)}{π(n_1)}\right) \\ 10^4 & 1.23 \cdot 10^3 & 2 \cdot 10^{-3} & - \\ 10^5 & 9.59 \cdot 10^3 & 4 \cdot 10^{-3} & 0.3 \\ 10^6 & 7.85 \cdot 10^4 & 1.0 \cdot 10^{-2} & 0.4 \\ 10^7 & 6.65 \cdot 10^5 & 9.3 \cdot 10^{-2} & 1.04 \\ 10^8 & 5.76 \cdot 10^6 & 1.25 \cdot 10^0 & 1.20 \\ 10^9 & 5.08 \cdot 10^7 & 1.43 \cdot 10^1 & 1.12 \\ 10^{10} & 4.55 \cdot 10^8 & 1.61 \cdot 10^2 & 1.10 \\ 10^{11} & 4.12 \cdot 10^9 & 1.88 \cdot 10^3 & 1.12 \end{array} $$


texts: RungeKutta method in C, pointers and arrays

texts:
Now the program works, but is it correct? Sometimes it works in C anyway. Could I improve it somehow (not numerically, just C-wise)? I need to allocate the array as I do right? Since I am returning it and not just using it inside the function.

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

/* Approximates a solution to a differential equation on the form:
   y'(t) + ay(t) = x(t)
   y(0) = b
*/
double* runge_kutta_2nd_order(double stepSize, double a, double b, double (*x) (double), double upto)
{
    int resultSize = ((int) (upto / stepSize)) + 2;
    double yt = b;
    double time;
    double k1,k2,ystar1,ystar2;
    int index = 1;

    //double *results = (double*) malloc(resultSize * (sizeof(double)));
    double *results = malloc(resultSize * sizeof(*results));
    if(results == NULL)
    {
        printf("\nCould not allocate memory. Exiting program.");
        exit(0);
    }

    results[0] = b;

    for(time = 0; time < upto; time += stepSize) //<=
    {
        k1 = x(time) - a * yt;
        ystar1 = yt + stepSize * k1;
        k2 = x(time + stepSize) - a * ystar1;
        ystar2 = yt + (k1 + k2) / 2 * stepSize;
        yt = ystar2;
        results[index] = ystar2;
        index++;
    }
    return results;
}

void free_results(double **r)
{
    free(*r);
    *r = NULL;
}

double insignal(double t)
{
    return exp(t/2)*(sin(5*t) - 10*cos(5*t));
}

int main(void)
{
    int i;
    double *res = runge_kutta_2nd_order(0.01,-1,0,&insignal,10);

    printf("\nRunge Kutta 2nd order approximation of the differential equation:");
    printf("\ny'(t) - y(t) = e^(t/2) * (sin(5t) - 10cos(5t))");
    printf("\ny(0) = 0");
    printf("\n0 <= t <= 10");

    for(i=0; i<1001; i+=100){
        printf("\ni = %lf => y = ", 0.01*i);
        printf("%lf", res[i]);
    }
    printf("\n");

    free_results(&res);

    return 0;
}


texts: Putting 3 different on click functions into one reusable function

texts:
I have image slider with thumbnails, simple one where I account for left and right arrow clicks that show respective images and thumbnail clicks that load related image. Functions have a lot in common and I'm trying to figure out how to put them into one and use it for all 3 different events, but am having trouble as thumbnail one is slightly different.

//Handle next-image click on product single page
    $('.images').on('click', '#next-image', function(e) {
        e.preventDefault();
        var current = $('.thumbnail-link.first');

        //Check if thumbnail is last, if it is make first thumbnail next
        if(current.next().hasClass('thumbnail-link')) {
            next = current.next('.thumbnail-link');
        } else {
            next = $('.thumbnail-link').first();
        }

        //Grab image src from data-image attribute
        var image = next.data('image');

        $('.woocommerce-main-image')
        .find('img')
        .animate({
            opacity: 0
        }, 300, function() {
            $(this).attr('src', image);
            $(this).animate({opacity: 1}, 300);

        })
        current.removeClass('first');
        next.addClass('first');
    });

    //Handle prev-image click on product single page
    $('.images').on('click', '#prev-image', function(e) {
        e.preventDefault();
        var current = $('.thumbnails .first');

        //Check if thumbnail is last, if it is make first thumbnail next
        if(current.prev().hasClass('thumbnail-link')) {
            prev = current.prev('.thumbnail-link');
        } else {
            prev = $('.thumbnail-link').last();
        }

        //Grab image src from data-image attribute
        var image = prev.data('image');

        $('.woocommerce-main-image')
        .find('img')
        .animate({
            opacity: 0
        }, 300, function() {
            $(this).attr('src', image);
            $(this).animate({opacity: 1}, 300);
        })
        current.removeClass('first');
        prev.addClass('first');
    });

    //Handle click on thumbnail
    $('.thumbnails').on('click', '.thumbnail-link', function(e) {
        e.preventDefault();
        var current = $('.thumbnail-link.first'),
            image = $(this).data('image');

        $('.woocommerce-main-image')
        .find('img')
        .animate({
            opacity: 0
        }, 300, function() {
            $(this).attr('src', image);
            $(this).animate({opacity: 1}, 300);
        })

        current.removeClass('first');
        $(this).addClass('first');
    });


texts:
I've written a small routing system in PHP but I'm not sure if it's done the right way and what changes can they be done to the code and improvements.

<?php
namespace Twelve\Router;

    use Twelve\Utils\Utils;
    class Router
    {
        public
            $routeMaps = [],
            $controller;
        private $_route = [];

        public function add($name, $pattern, $controller, array $params = [])
        {
            if(!isset($this->routeMaps[$name]))
                $this->routeMaps[$name] =
            [
                'pattern' => $pattern,
                'controller' => $controller,
                'params' => $params,
            ];
        }
        public function findMatch($url)
        {
            foreach($this->routeMaps as $routeMap)
            {
                $this->regex = $this->buildRegex($routeMap['pattern'], $routeMap['params']);
                // Let's test the route.
                if(preg_match($this->regex, $url))
                {
                    return (array) $routeMap['controller'];
                }
            }
        }
        public function buildRegex($uri, array $params)
        {
            // FInd {params} in URI
            if(preg_match_all('/\{(?:[^\}]+)\}/', $uri, $this->matches, PREG_SET_ORDER))
            {
                foreach($this->matches as $isMatch)
                {
                    // Swap {param} with a placeholder
                    $this->uri = str_replace($isMatch, "%s", $uri);
                }
                // Build final Regex
                $this->finalRegex = '/^' . preg_quote($this->uri, '/') . '$/';
                $this->finalRegex = vsprintf($this->finalRegex, $params);

                return $this->finalRegex;
            }
        }
        public function dispatch(array $route = [], $url)
        {
            $this->setController($route['0']);
            $this->setAction($this->getController());
            $this->setParams(explode('/', $url));
            $this->controller = $this->getController();
            array_pop($this->controller);
            $this->controller = implode('\\', $this->controller);
            call_user_func_array([new $this->controller, $this->action], $this->params);
        }

        public function setController($controller)
        {
            $this->controller = explode(':', $controller);
        }

        public function getController()
        {
            return $this->controller;
        }
        public function setAction($action)
        {
            $this->action = end($action);
        }
        public function getAction()
        {
            return $this->action;
        }

        public function setParams($params)
        {
            $this->params = array_slice($params, 4);
        }

        public function getParams()
        {
            return $this->params;
        }
        public function run($uri, array $route = null)
        {
            $route = $this->findMatch($uri);
            Utils::var_dump($route);
            $this->dispatch($route, $uri);
        }
    }


texts: Reducing memory footprint in anagram-finding program for text

texts:
public static bool IsAnagramOf(this string word1, string word2)
{
    return word1.OrderBy(x => x).SequenceEqual(word2.OrderBy(x => x));
}

public static void Main()
  {
    Console.SetIn(new StreamReader(Console.OpenStandardInput(8192)));
    string test = Console.ReadLine();
    string[] split = test.Split(new Char[] { ',', '.', ' ' },
                         StringSplitOptions.RemoveEmptyEntries);
    for (int i = 0; i < split.Length; i++)
    {
        foreach (string s in split)
        {
            if (split[i] != s)
                if (split[i].IsAnagramOf(s))
                {
                    Console.WriteLine(s);

                }
        }

    }
    Console.ReadLine();
}


texts:
I wrote the following function for the purpose of reusability:

template<typename T>
bool contains(vector<T> v, T x)
{
      if (v.empty())
           return false;
      if (find(v.begin(), v.end(), x) != v.end())
           return true;
      else
           return false;
}

Is this the correct way to do, oor is there any better (or more efficient) way?


texts: Oracle PL/SQL decryption function breaking index?

texts:
I have a package called pkg_crypto.

My select looks like this:

SELECT "SEQ", pkg_crypto.decrypt("NAME", 'secret') name, pkg_crypto.decrypt("TEL", 'secret') tel
FROM MYTABLE
ORDER BY "SEQ" DESC

This takes about 3 seconds for a few thousand records. (Average of 10 runs is 3.032s.)

Now, if I change it to either of the following, the query completes in about 0.2 seconds (average of 10 runs is 0.203s):

SELECT "SEQ", "NAME", "TEL"
FROM MYTABLE
ORDER BY "SEQ" DESC

SELECT "SEQ", pkg_crypto.decrypt("NAME", 'secret') name, pkg_crypto.decrypt("TEL", 'secret') tel
FROM MYTABLE

What seems to be happening is that if I use the decrypt and order by on the same command, it will re-sort the records and ignore the index that exists on "SEQ".

I suspect this may be a problem with the implementation of the pkg_crypto package that I am using.  Its code is as follows:

CREATE OR REPLACE PACKAGE PKG_CRYPTO AS

    FUNCTION encrypt (
        input_string        IN  VARCHAR2 ,
        key_data IN VARCHAR2 := 'DEFDB'
    ) RETURN RAW;

    FUNCTION decrypt (
        input_string        IN  VARCHAR2 ,
        key_data IN VARCHAR2 := 'DEFDB'
    ) RETURN VARCHAR2;

END PKG_CRYPTO;PACKAGE BODY pkg_crypto
IS
-- .. .... error code . message . .. .. .. ...
    SQLERRMSG   VARCHAR2(255);
    SQLERRCDE   NUMBER;

-- ... .. .. key_data . .... .. .. default . 12345678 . ....
    FUNCTION encrypt (input_string IN VARCHAR2 , key_data IN VARCHAR2 := 'DEFDB')
     RETURN RAW
    IS

        key_data_raw        RAW(2000);
        converted_raw       RAW(2000);
        encrypted_raw       RAW(2000);

    BEGIN

-- ... data . .... .. RAW . .....
        converted_raw := UTL_I18N.STRING_TO_RAW(input_string, 'AL32UTF8');
        key_data_raw     := UTL_I18N.STRING_TO_RAW(key_data, 'AL32UTF8');

-- DBMS_CRYPTO.ENCRYPT . ... .. encrypted_raw . ...
        encrypted_raw :=
             DBMS_CRYPTO.ENCRYPT(
                 src => converted_raw ,
-- typ ... .... ... ..... ... . ...
--., key value bype . . ... .... ...
                 typ => DBMS_CRYPTO.DES_CBC_PKCS5 ,
                 key => key_data_raw ,
                 iv =>  NULL);

        RETURN encrypted_raw;
    END encrypt;

    FUNCTION decrypt (input_string IN VARCHAR2 , key_data IN VARCHAR2 := 'DEFDB')
     RETURN VARCHAR2
    IS
        converted_string    VARCHAR2(2000);
        key_data_raw        RAW(2000);
        decrypted_raw    VARCHAR2(2000);

    BEGIN

        key_data_raw     := UTL_I18N.STRING_TO_RAW(key_data, 'AL32UTF8');

        decrypted_raw :=
            DBMS_CRYPTO.DECRYPT(
                 src => input_string ,
                 typ => DBMS_CRYPTO.DES_CBC_PKCS5 ,
                 key => key_data_raw ,
                 iv =>  NULL);

-- DBMS_CRYPTO.DECRYPT .. .. .. .... raw data . varchar2 . .... .!
        converted_string := UTL_I18N.RAW_TO_CHAR(decrypted_raw, 'AL32UTF8');

        RETURN converted_string;
    END decrypt ;
END pkg_crypto;

I've also attempted changing the query around a bit, but it hasn't been fruitful: the following take the same 3 seconds:

SELECT "SEQ", pkg_crypto.decrypt("NAME", 'secret') name, pkg_crypto.decrypt("TEL", 'secret') tel
FROM
(
    SELECT "SEQ", "NAME", "TEL" FROM MYTABLE ORDER BY "SEQ" DESC
)

and

SELECT "SEQ", pkg_crypto.decrypt("NAME", 'secret') name, pkg_crypto.decrypt("TEL", 'secret') tel
FROM
(
    SELECT "SEQ", "NAME", "TEL" FROM MYTABLE
)
ORDER BY "SEQ" DESC


texts: Project Euler #12: Highly divisible triangular number

texts:
I want to receive advice on my code. It is too slow... The problem I am trying to solve is:

  What is the value of the first triangle number to have over five hundred divisors?

import math
import numpy as np
import copy
from operator import add
memoi_table = {}

#check whether the x is prime or not
#to do a prime factorization
def prime_finder(x):
    cnt = 0
    a = math.sqrt(x)
    sqrt_number = int(math.floor(a))
    for i in range(2,sqrt_number+1):
        if x % i == 0:
            cnt = cnt +1
            break
    if cnt == 0:
        return True
    else:
        return False

#Do a prime_factorization
#Do a dynamic programing with memoization table
#Do a recursive method to cover the triangular number
#ex)Triangular number = 1,3,6,10,15,21,28
#When we treat 10, we couldn't utilize dynamic programming => Recursive method
def prime_factorization(x):
    global memoi_table
    memoi_table[x] = {}

    if prime_finder(x) == True:
        memoi_table[x][x] = 1

    for i in range(2,math.floor(math.sqrt(x)+1)):
        if (prime_finder(i) == True) and (x % i == 0):
            new_x = x / i
            if not new_x in memoi_table.keys():
                prime_factorization(new_x)
                #Recursive way

            if new_x in memoi_table.keys():
                memoi_table[x] = memoi_table[new_x].copy()
                #to shallow copy
            if i in memoi_table[x].keys():
                memoi_table[x][i] = memoi_table[x][i] + 1
            else:
                memoi_table[x][i] = 1
    return (x,memoi_table[x])
#ex) 20 => return (20,(2:2,5:1))

# To calculate the number of divisor based on prime factorization
def find_number_of_divisor(x):
    global memoi_table
    number_of_divisor = 1
    for key in memoi_table[x].keys():
        number_of_divisor = number_of_divisor * (memoi_table[x][key]+1)
    return number_of_divisor

#Let's do it
def main():
    global memoi_table
    n = 0
    while True:
        n = n + 1
        Triangular_number = n * (n + 1) / 2
        prime_factorization(Triangular_number)
        num_divisor = find_number_of_divisor(Triangular_number)

        if num_divisor > 500:
            return (Triangular_number,num_divisor)
            break

print(main())


texts: Complexity in multiple if-else algorithms

texts:
I am learning Algorithms, Part I on coursera.org. I just watched the first lecture then tried to write some code in C#. The class basically stores list of connected numbers. You can add numbers that connected together by calling Union and check if they are connected by calling AreConnected. Code is as follows:

public class UnionFind
{
    private readonly List<HashSet<int>> source;

    public static UnionFind Create()
    {
        return new UnionFind();
    }

    private UnionFind()
    {
        this.source = new List<HashSet<int>>();
    }

    public void Union(int left, int right)
    {
        var isLeftExist = this.source.FirstOrDefault(o => o.Contains(left));
        var isRightExist = this.source.FirstOrDefault(o => o.Contains(right));

        if (isLeftExist == null &&
            isRightExist == null)
        {
            var hash = new HashSet<int>();
            hash.Add(left);
            hash.Add(right);

            this.source.Add(hash);
        }
        else if (isLeftExist != null &&
            isRightExist == null)
        {
            isLeftExist.Add(right);
        }
        else if (isRightExist != null &&
            isLeftExist == null)
        {
            isRightExist.Add(left);
        }
        else
        {
            // found left and right
            this.source.Remove(isRightExist);

            foreach (var item in isRightExist)
            {
                isLeftExist.Add(item);
            }
        }
    }

    public bool AreConnected(int left, int right)
    {
        return this.source
            .Any(o =>
                o.Contains(left) &&
                o.Contains(right));
    }

To make it easier to understand, this is unit test class.

[TestClass]
public class UnionFindTests
{
    [TestMethod]
    public void SimpleUnionTest()
    {
        int left = 10;
        int right = 20;

        var uf = UnionFind.Create();

        uf.Union(left, right);
        Assert.IsTrue(uf.AreConnected(left, right));
    }

    [TestMethod]
    public void DuplicateUnionTest()
    {
        int left = 10;
        int right = 10;

        var uf = UnionFind.Create();

        uf.Union(left, right);
        Assert.IsTrue(uf.AreConnected(left, right));
    }

    [TestMethod]
    public void MultipleLinksUnionTest()
    {
        int left1 = 10;
        int left2 = 20;
        int left3 = 30;

        int right1 = 15;
        int right2 = 25;
        int right3 = 35;

        var uf = UnionFind.Create();
        uf.Union(left1, right1);
        uf.Union(left2, right2);
        uf.Union(left3, right3);

        uf.Union(left1, right2);
        Assert.IsTrue(uf.AreConnected(left2, right1));
    }
}

UnionFind works find and pass all tests in unit test. The problem is I found method Union has many if-else and I want to get rid of it. Is there a simpler way of implementing Union method?


texts:
I have the following C# method to split a path string.  The only thing I know is a fixed string in the path and I have to split the full path into two parts, first part should be one level below the fixed string and the rest should be the second part.

For example, if I have the following path:

 string mainText = @"C:\Abc\Fixed\MyTemp\Japan\Tokyo";

then my firstPart would be "C:\Abc\Fixed\MyTemp" and second part "Japan\Tokyo"

I want to improve this method in terms of memory and speed.

private static void SplitPath(string mainText, out string firstPart, out string secondPart)
        {
            firstPart = string.Empty;
            secondPart = string.Empty;
            if (!string.IsNullOrEmpty(mainText))
            {
                string strConstatnt = "Fixed";
                List<string> splitted = mainText.Split(new char[] { '\\' }).ToList();
                int indexToFixed = splitted.IndexOf(strConstatnt);
                StringBuilder sbFirst = new StringBuilder();
                StringBuilder sbSecond = new StringBuilder();
                if (indexToFixed >= 0)
                {
                    for (int i = 0; i < splitted.Count; i++)
                    {
                        if (i < (indexToFixed + 2))
                        {
                            sbFirst.Append(splitted[i] + "\\");
                        }
                        else
                        {
                            break;
                        }
                    }

                    for (int i = (indexToFixed + 2); i < splitted.Count; i++)
                    {
                        sbSecond.Append(splitted[i] + "\\");
                    }
                }
                if (sbFirst.Length > 0)
                {
                    firstPart = sbFirst.Remove(sbFirst.Length - 1, 1).ToString();
                }
                if (sbSecond.Length > 0)
                {
                    secondPart = sbSecond.Remove(sbSecond.Length - 1, 1).ToString();
                }
            }
        }


texts:
This is a short piece of code but I feel like it could be done more elegantly. What am I missing?

The goal: if there are any items in a list, and none of them have a given property, set one of them to have that property.

static void GuaranteeAtLeastOne<T>(IEnumerable<T> list, Func<T,bool> getter, Action<T> setter)
{
    if (list.Any() && !list.Any(getter))
    {
        setter(list.First());
    }
}


texts: Checking if entity exist in Google App Engine Datastore using JPA 1

texts:
Below is my method in checking if entity already exist.

public boolean isExist(String genreName) throws PersistenceException{
    EntityManager em = EMF.get().createEntityManager();
    boolean flag = false;

    try{
        Genre genre = em.find(Genre.class, genreName);
        if (genre != null)
            flag = true;

    }finally{
        em.close();
    }

    return flag;
}

Is the code above ok? Please suggest.


texts:
I have a C# function like below, and in the else block, the function must return something. I don't know whether returning null is a good practice or not.

public Nullable<Point> GetSprite(int x, int y)
{
    if (x <= xCount && y <= yCount)
    {
        return new Point(x * spriteHeight, y * spriteWidth);
    }
    else
    {
        return null;
    }
}


texts:
I'm trying to implement a regularization term for the loss function of a neural network.

from torch import nn
import torch
import numpy as np

reg_sig = torch.randn([32, 9, 5])
reg_adj = torch.randn([32, 9, 9, 4])

Maug = reg_adj.shape[0]

n_node = 9
n_bond_features = 4
n_atom_features = 5

SM_f = nn.Softmax(dim=2)
SM_W = nn.Softmax(dim=3)

p_f = SM_f(reg_sig)
p_W = SM_W(reg_adj)

Sig = nn.Sigmoid()

q = 1 - p_f[:, :, 4]
A = 1 - p_W[:, :, :, 0]

A_0 = torch.eye(n_node)
A_0 = A_0.reshape((1, n_node, n_node))
A_i = A

B = A_0.repeat(reg_sig.size(0), 1, 1)

for i in range(1, n_node):
    A_i = Sig(100 * (torch.bmm(A_i, A) - 0.5))

    B += A_i

C = Sig(100 * (B - 0.5))

reg_g_ij = torch.randn([reg_sig.size(0), n_node, n_node])

for i in range(n_node):
    for j in range(n_node):
        reg_g_ij[:, i, j] = q[:, i] * q[:, j] * (1 - C[:, i, j]) + (1 - q[:, i] * q[:, j]) * C[:, i, j]

I believe that my implementation is computationally not efficient and would like to have some suggestions on which parts I can change. Specifically, I would like to get rid of the loops and do them using matrix operations if possible. Any suggestions or working examples or links to useful torch functions would be appreciated


texts:
I have written a code for a tic-tac-toe game and it works well. But, I don't know whether it is an efficient one. Any help on how to optimize it?

def restart():

    num=[0 for i in range(9)]
    board=[" " for i in range(9)]
    a=2
    start(board,a,num)

def wincheck(t):

    for i in range(8):
        if t[win[i][0]]==t[win[i][1]] and t[win[i][0]]==t[win[i][2]] and
                            t[win[i][1]]==t[win[i][2]] and t[win[i][0]]!=" ":
            if t[win[i][0]]=="X":
                print("Player 1 wins")
            else:
                print("Player 2 wins")
            playa = input("Do you want to play again? Y/N")
            if playa.lower() == "y":
                restart()
            else:
                exit(0)
def display_board(t,a,num):

    print( " "*3+'|'+" "*3+'|'+" "*3)
    print("{0:^3}|{1:^3}|{2:^3}".format(t[6],t[7],t[8]))
    print( " "*3+'|'+" "*3+'|'+" "*3)
    print("-"*11)
    print( " "*3+'|'+" "*3+'|'+" "*3)
    print("{0:^3}|{1:^3}|{2:^3}".format(t[3],t[4],t[5]))
    print( " "*3+'|'+" "*3+'|'+" "*3)
    print("-"*11)
    print( " "*3+'|'+" "*3+'|'+" "*3)
    print("{0:^3}|{1:^3}|{2:^3}".format(t[0],t[1],t[2]))
    print( " "*3+'|'+" "*3+'|'+" "*3)
    wincheck(t)
    if 0 not in num:
        print("Draw")
        restart()
    start(t,a,num)

def start(board,a,num):

    if a%2==0:
       p1n=int(input("Player 1, Enter a number from 1 to 9"))
       if p1n not in num:
           num[p1n-1]=p1n
           print(num)
       else:
           print("Please enter in a free space")
           start(board,a,num)
       board[p1n-1]="X"
       a=a+1
       display_board(board,a,num)
    else:
       p2n=int(input("Player 2, Enter a number from 1 to 9"))
       if p2n not in num:
           num[p2n-1]=p2n
           print(num)
       else:
           print("Please enter in a free space")
           start(board,a,num)
       board[p2n-1]="O"
       a=a+1
       display_board(board,a,num)

a=2

board=[" " for i in range(9)]

num=[0 for i in range(9)]

win = [[0,1,2],[3,4,5],[6,7,8],[0,4,8],[6,4,2],[6,3,0],[7,4,1],[8,5,2]]

start(board,a,num)


texts: Function to get type of the value entered in a textbox

texts:
Just for fun, I tried creating a function that takes the value entered in a textbox, and determines the type of it. Below is the full code.

 public string GetType(string inputValue)
    {
        //Variables for the parse result
        //Can be discarded. Used because parse function mandates output variable
        int intParseResult;
        decimal decimalParseResult;
        bool boolParseResult;

        //Parse for different datatypes and check the output
        if (int.TryParse(inputValue, out intParseResult))
        {
            return typeof(int).Name;
        }
        if (decimal.TryParse(inputValue, out decimalParseResult))
        {
            return typeof(decimal).Name;
        }
        if (bool.TryParse(inputValue, out boolParseResult))
        {
            return typeof(bool).Name;
        }
        //If all parse fails, return string type.
        return typeof(string).Name;
    }

Since the text property is a string, I am trying to parse the input into different types, and returning the type name based on it.

As of now, I see two quick issues. One is that it will need one if condition for each data type. Second is that function is creating variables and discarding them unnecessarily.

I am looking for suggestions on how to improve this code. Again, this code is created just for fun, so no urgency. I will just like to see different possible ways to improve the code.


texts: Transform a Binary Search Tree into a Greater Sum Tree

texts:
Given a Binary Search Tree (where all nodes on the left child branch are less than the node), and all nodes to the right are greater/equal to the node), transform it into a Greater Sum Tree where each node contains sum of it together with all nodes greater than that node. Example diagram is here:

Looking for code review, optimizations and best practices.

public class GreaterSumTree implements Iterable {

    private TreeNode root;

    public GreaterSumTree(List<Integer> list) {
        create(list);
    }

    private void create (List<Integer> items) {
        root = new TreeNode(items.get(0));

        final Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        final int half = items.size() / 2;

        for (int i = 0; i < half; i++) {
            if (items.get(i) != null) {
                final TreeNode current = queue.poll();
                final int left = 2 * i + 1;
                final int right = 2 * i + 2;

                if (items.get(left) != null) {
                    current.left = new TreeNode(items.get(left));
                    queue.add(current.left);
                }
                if (right < items.size() && items.get(right) != null) {
                    current.right = new TreeNode(items.get(right));
                    queue.add(current.right);
                }
            }
        }
    }

    public static class TreeNode {
        private TreeNode left;
        private int item;
        private TreeNode right;

        TreeNode(int item) {
            this.item = item;
        }
    }

    public static class IntObject {
        private int sum;
    }

    /**
     * Computes the greater sum, provided the tree is BST.
     * If tree is not BST, then results are unpredictable.
     */
    public void greaterSumTree() {
        if (root == null) {
            throw new IllegalArgumentException("root is null");
        }
        computeSum (root, new IntObject());
    }

    private void computeSum(TreeNode node, IntObject intObj) {
        if (node != null) {
            computeSum(node.right, intObj);
            int temp = node.item;
            node.item = intObj.sum;
            intObj.sum = intObj.sum + temp;
            computeSum(node.left, intObj);
        }
    }

    /**
     * Returns the preorder representation for the given tree.
     *
     * @return  the iterator for preorder traversal
     */
    @Override
    public Iterator iterator () {
        return new PreOrderItr();
    }

    private class PreOrderItr implements Iterator {
        private final Stack<TreeNode> stack;

        public PreOrderItr() {
            stack = new Stack<TreeNode>();
            stack.add(root);
        }

        @Override
        public boolean hasNext() {
            return !stack.isEmpty();
        }

        @Override
        public Integer next() {
            if (!hasNext()) throw new NoSuchElementException("No more nodes remain to iterate");

            final TreeNode node = stack.pop();

            if (node.right != null) stack.push(node.right);
            if (node.left != null) stack.push(node.left);

            return node.item;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("Invalid operation for pre-order iterator.");
        }
    }
}

Here is a test case:

public class GreaterSumTreeTest {

    @Test
    public void test() {
        Integer[] a = {1, 2, 7, 11, 15, 29, 35};
        GreaterSumTree greaterSumTree = new GreaterSumTree(Arrays.asList(a));
        greaterSumTree.greaterSumTree();

        int[] expected = {71, 87, 89, 72, 35, 42, 0};
        int[] actual = new int[a.length];
        int counter = 0;
        Iterator itr = greaterSumTree.iterator();
        while (itr.hasNext()) {
           actual[counter++] = (Integer) itr.next();
        }
        assertTrue(Arrays.equals(expected, actual));
    }

}


texts:
This code returns true if the sentence is a palindrome, and false otherwise. Is there a better way of doing this?

def palindrome?(sentence)

  array_stripped_sentence = sentence.reverse.downcase.delete('').split('')
  array_stripped_sentence == sentence.downcase.delete(' ').split('')

end

puts palindrome?("Never odd or even")


texts: Store first value of http request with rxjs but keep doing httprequest

texts:
With RXJS library :
I need to store values from the FIRST http request, but keep doing other http request on demand.

I have done this code so far, and that is working. But I think there is a more elegant way.

const Rx = require("rxjs");
let numHttp = 0;
const httpRequest = () => {
    let a = [];
    numHttp = numHttp + 1;
    for (let i = 0; i < 10; ++i) {
        a.push({ num: i, http: numHttp });
    };
    return new Rx.BehaviorSubject(a)
        .do(a => {
            console.log("antoher http request");
            if (getC.getValue() === undefined) {
                getC.next(a)
            }
        })
        // .do(n => { if (getB.) getB.next(n) })
}
const getB = () => {
    const a = new Rx.BehaviorSubject();
    return a
};
getC = getB();
httpRequest().subscribe(d => d);
httpRequest().subscribe(d => d);
getC.subscribe(data => console.log('cache', data))
httpRequest().subscribe(d => d);
httpRequest().subscribe(d => d);


texts: Append multiple children to a node at once

texts:
This my attempt at an answer for a question over on SO: Append multiple items in JavaScript

I'd like to know if I've made any mistakes as far as writing idiomatic ES6 JavaScript (mainly regarding convention and performance).

While satisfying, I'm pretty sure adding this behavior directly to Node.prototype is probably the wrong approach. I'm also concerned that maybe it should handle other inputs (like a NodeList?) and not just arrays as a single argument.

Node.prototype.appendChildren = function() {
  let children = [...arguments];

  if (
    children.length == 1 &&
    Object.prototype.toString.call(children[0]) === "[object Array]"
  ) {
    children = children[0];
  }

  const documentFragment = document.createDocumentFragment();
  children.forEach(c => documentFragment.appendChild(c));
  this.appendChild(documentFragment);
};

foo.appendChildren(bar1, bar2, bar3);
foo.appendChildren([bar1, bar2, bar3]);


texts: 2-factor authentication code generator in Python 3

texts:
Google has an Authenticator app that, given a secret and the time, shows a 6-digit code. The code cycles every 30 seconds. I wrote an implementation in Python 3 (can be run in Python 2 with some changes) that optionally generates a qrcode for a new user and/or just shows the current code displayed in the Authenticator app.

import hmac, base64, struct, hashlib, time, pyqrcode, random, sys, os

def get_hotp_token(secret, intervals_no):
    key = base64.b32decode(secret)
    msg = struct.pack(">Q", intervals_no)
    h = hmac.new(key, msg, hashlib.sha1).digest()
    o = h[19] & 15
    h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
    return h

def get_totp_token(secret):
    return get_hotp_token(secret, intervals_no=int(time.time())//30)

# This works whenever I run it, but I'm not 100% sure it conforms to RFC standards
# Also, I'm not sure if the secret is every allowed to not be 16 bytes
def generate_secret(length=16):
    random_secret = ""
    characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
    for _ in range(length):
        random_secret += random.choice(characters)
    return random_secret

# Pads secret with zeroes and separates with a space
def format_secret(secret, to_length=6):
    padded = '0'*(6-len(str(secret)))+str(secret)
    return padded[:3] + ' ' + padded[3:]

# Sets up a user given a label, username, and generates/takes a secret
# Is there a better way to do the "y/n: " stuff?
def setup_user():
    label = input("Label: ").replace(' ', '%20')
    user = input("User: ").replace(' ', '%20')
    secret = input("Auto-generate secret? y/n: ")

    if secret.lower() == "y":
        secret = generate_secret()
    else:
        secret = input("Secret: ")

    return label, user, secret

secret = "DID NOT SET SECRET"

# Again, is there a better way to do the "y/n: "?
if input("Setup user? y/n: ").lower() == "y":
    label, user, secret = setup_user()

    if input("Show qr-code? y/n: ").lower().strip() == "y":
        # I'm unsure if this URL breaks when certain characters are in the label or username
        qr_url = "otpauth://totp/%s:%s?secret=%s&issuer=%s" % (label, user, secret, label)
        url = pyqrcode.create(qr_url)
        os.system('cls' if os.name == 'nt' else 'clear')
        # Is it possible to make the qrcode smaller when printed in Terminal/Console?
        print(url.terminal(quiet_zone=1))
else:
    secret = input("Secret: ")
    os.system('cls' if os.name == 'nt' else 'clear')

print("User secret: ", secret)

sys.stdout.write("\r%s" % format_secret(get_totp_token(secret)))
sys.stdout.flush()
# This next line is my code to time-sync the timer. I'm not sure if it actually works though.
# I think it might have to do with using modular arithmetic on a float
time.sleep(1 - time.time() % 1)

while True:
    # These next couple of lines format a progress bar for how many seconds are left until a new code.
    seconds = int(30 - time.time() % 30)
    lines = "-" * int(seconds)# / 3)
    blocks = "█" * (30 - len(lines))
    progress = "|" + blocks + lines + "|"

    sys.stdout.write("\r%s" % format_secret(get_totp_token(secret)) + "\t" + progress)
    sys.stdout.flush()

    time.sleep(1)

This uses the pyqrcode library, which does not ship standard with Python.

I noticed that sometimes, the code does not change exactly when it does in the Authenticator app. This may be a problem with my time-syncing code.

What are your thoughts on quality of code, usability, pythonic-ness, and correctness?


texts: Observing PEP maximum line size, particularly when formatting localized timestamps

texts:
I have this function that I use to publish a message but I need to do this long conversion for time and date. Maybe there's a better way to convert it to make smaller. Otherwise I'm stuck with this long line. I guess I could use slashes, is guidelines on readability for using slashing or is arbitrary.

  SMS.publish('/jobs',{
                           'batchdate': job.get('batchdate'),
                           'job': job.get('name'),
                            'Script execution date (EST)':pytz.utc.localize(datetime.datetime.utcfromtimestamp(time.time())).astimezone(pytz.timezone('US/Eastern')).strftime('%Y-%m-%d %H:%M:%S'),
                             'Start time(EST)':pytz.utc.localize(datetime.datetime.utcfromtimestamp(float(job.get('starttime')))).astimezone(pytz.timezone('US/Eastern')).strftime('%Y-%m-%d %H:%M:%S'),
                            'Current runtime': change_format_num( cur_runtime),
                            'Average runtime': change_format_num(avg_time)
                                     })


texts:
I have an unordered_map<int, std::shared_ptr<foo>> into which I want to lazily create the instances of foo based on callbacks. These callbacks would come from potentially a pool of threads, so to handle this, at the start I create the map and insert empty shared_ptr<>s into the map for all possible indexes. Now I have the code below which is designed to create the foo instance based on demand.

Is my implementation of double checked locking with shared_ptr<> correct?

void Publish(const bar& data)  {
    auto id = data.get_id();
    auto it = foos_.find(id);
    if (it == foos_.end()) {
      // throw
    }
    // Check if this is present
    auto sp = std::atomic_load_explicit(&(it->second), std::memory_order_relaxed);
    std::atomic_thread_fence(std::memory_order_acquire);
    if (!sp) {
      // Create the instance of the foo for this id
      std::lock_guard<std::mutex> lock(mutex_);
      (void) lock;
      // Check again
      sp = std::atomic_load_explicit(&(it->second), std::memory_order_relaxed);
      if (!sp) {
        // Create new foo
        sp = std::make_shared<foo>(...);
        std::atomic_thread_fence(std::memory_order_release);
        std::atomic_store_explicit(&(it->second), sp, std::memory_order_relaxed);
      } // Someone else created it...
    }

    // Push the data in
    sp->Publish(data);
  }


texts:
I have this constructor (from a Service) where I'm setting a few variables, but two of them include HTML. Is there a best way to set those values, maybe by creating a method in the class to set them?

public function __construct($builder, $id, $nickname, $title, $options)
{
        $this->builder     = $builder;
        $this->id          = $id;
        $this->icon        = ''; // This one
        $this->title       = ''.$title.''; // This one as well
        $this->nickname    = camel_case(Str::ascii($nickname));
        $this->attributes  = $this->builder->extractAttributes($options);
}


texts:
I made this program to rename variables in json files, part of the functions rely on recursivity which i'm not confortable with so I would like some feedback on readability and performance.

import configparser

def seek_in_array(json_array, conversions):
    """seeks all data in a json array"""
    converted = []
    for it_list in range(len(json_array)):
        if isinstance(json_array[it_list], dict):
            converted.append(seek_and_convert(json_array[it_list], conversions))
        elif isinstance(json_array[it_list], list):
            converted.append(seek_in_array(json_array[it_list], conversions))
        else:
            converted.append(json_array[it_list])
    return(converted)

def seek_and_convert(json_file, conversions):
    """seeks all data in a json file an converts it"""
    converted = {}
    for key in json_file.keys():
        if conversions.has_option('CONVERSIONS', key):
            option = conversions.get('CONVERSIONS', key)
        else:
            option = key
        if isinstance(json_file[key], dict):
            converted[option] = seek_and_convert(json_file[key], conversions)
        elif isinstance(json_file[key], list):
            converted[option] = seek_in_array(json_file[key], conversions)
        else:
            converted[option] = json_file[key]
    return(converted)

def load_conversion_table():
    """loads the configfile containing the conversions to be made"""
    conversions = configparser.ConfigParser()
    conversions.read('conversion_table.ini')
    return conversions

def main():
    conversions = load_conversion_table()
    file = {
              '_id': '006480206',

              'change1': 'HEY'
              'A_THING': 'HEY'
              'an_array': [
                {
                  'A_THING_in_the_array': '00648020600017',
                  'oh_no_,_change_that':'O',
                  'plz_dont_change_me': '12',
                  'listenning_to_disco_music': True,
                  'le_list': {
                    'le_variable': 'baguette !',
                    'le_change': 42,
                  },
                  "that's a trap": {},
                  "change_it_anyway": {},
                  'another_array': [
                    {
                      'change1': 'HANS !',
                      'change2': 'JA !?'
                    },
                    {
                      'nei': 'yas'
                      'change1': 'the very test',
                    },
                    {
                      'change1': 'ran out of idea',
                      'yas_yas': 'nomnomnom'
                    },
                    {
                      'OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOH': 'such long name'
                    }
                  ]
                }
              ]
            }
    print(seek_and_convert(file, conversions))

if __name__ == "__main__":
    main()

Here is the config file you'll need to run the program, put both file in the same folder.
conversion_table.ini:

[CONVERSIONS]
change1 = success1
oh_no_,_change_that = oh_no_,_success_that
plz_dont_change_me = plz_dont_success_me
le_change = le_success
change_it_anyway = success_it_anyway
change2 = success2


texts: Displaying a leader board from a text file and calculating points

texts:
The text file is laid out like this: first name, last name, wins, losses

dex,kop,5,6

desder,jok,0,11

aslan,vert,11,0

jax,sas,2,9

buy,guy,1,10

Code:

def points():

    template = "|{0:<30}|{1:<30}|{2:<30}|{3:<30}|{4:<30}"
    lol = template.format("1st name: ","2nd Name: ", "won: ", "lost: ","points: ")

    print(lol)

    with open(r'prac2.txt', 'r') as file:

        for line in file:

            data = line.strip().split(',')

            if int(data[2]) >= 1:

                poin = int(data[2]) * 3

                data.append(poin)

                print(template.format(data[0], data[1], data[2], data[3], data[4]),'\n')

        file.close()

points()

The program should only display players that have won at least 1 game and calculate their points, a win is equal to 3 points.

Any suggestions as to how to improve the code any would be great.


texts:
A picture says more than a thousand words, so here's a mock-up. The actual choices are different, this is just a sample.

A user first has to choose between Red, Blue and Green. Upon selecting an option, additional form elements are displayed, depending on the choice. For Blue, a Date  and Font are required.

Currently, there's no need for a third level, but who knows what the future brings. In order to represent this data, I've come up with the following model (after many attempts).

public class SampleWizard
{
    public enum ColourChoice
    {
        Red,
        Blue,
        Green
    }

    public class RedModel
    {
        public IEnumerable<SelectListItem> AvailableShapes { get; set; }

        public int Shape { get; set; }

        public DateTime Date { get; set; }
    }

    public class BlueModel
    {
        public enum FontChoice
        {
            Arial,
            Helvetica,
            Other,
        }

        public DateTime Date { get; set; }

        public FontChoice Font { get; set; }

        public IEnumerable<SelectListItem> AvailableOtherFonts { get; set; }

        public int OtherFont { get; set; }
    }

    public ColourChoice Colour { get; set; }

    public RedModel Red { get; set; }

    public BlueModel Blue { get; set; }
}

I'm using Enums for hard-coded choices, so I can make decisions based on the value. ints come from the database and do not matter in the programmed decision flows.

This works, but I can't help but feel like this is an ugly solution and I'm worried about future modifications. I've never had to make something like this before so I can't make decisions based on past experiences.

The UI design is more or less set in stone, unless strong arguments can be made against it. (I'd need to bring them up to the designer and project manager.)


texts: Integer seconds to formated string mm:ss

texts:
I have a String like "Time left (XX)" or "You need stay here for (XX)" and int as second. I use those two variables to format label like "string (mm:ss)" example "Time left (59:23)".

private String timeDescription(String pDescription,int pTime) {

    final String preformatedTime = secondsToString(pTime);
    final String timeForReturn = putTimeInXX(pDescription,preformatedTime);
    return timeForReturn;
}

private String secondsToString(int pTime) {
    final int min = pTime/60;
    final int sec = pTime-(min*60);

    final String strMin = placeZeroIfNeede(min);
    final String strSec = placeZeroIfNeede(sec);
    return String.format("%s:%s",strMin,strSec);
}

private String placeZeroIfNeede(int number) {
    return (number >=10)? Integer.toString(number):String.format("0%s",Integer.toString(number));
}

private String putTimeInXX(String pDescription,String pTime) {
    String[] apartDescription = pDescription.split("XX");

    StringBuilder descriptionForReturn = new StringBuilder();
    for (int i = 0; i < apartDescription.length; i++) {
        descriptionForReturn.append(apartDescription[i]);
        if (i == 0) {
            descriptionForReturn.append(pTime);
        }
    }
    return descriptionForReturn.toString();
}


texts:
I implemented as an exercise a function which maps over object values in Typescript, and I am truly horrified by my type annotations.
The function:
type map = <F, T>(f:callback<F, T>) => mapping<F, T>;
type callback<F, T> = (value:F, index:number, entries:Entry<F>[]) => T;
type Entry<T=any> = [key:String, value:T];
type mapping<F, T> = <I extends Dic<F>>(obj:I) => Protect<I, Record<keyof I, T>>;
type Dic<T> = Record<string, T>;
type Protect<A, B> = A extends B ? A : B;

const map:map = f => obj =>
    Object.fromEntries(
        Object.entries(obj)
            .map(([key, value], i, arr):Entry =>
                [key, f(value, i, arr)]));

Example of usage:
const double = map((x:number) => x * 2);
const shout = map((x:any) => String(x) + '!');

type Abc = {
    a: number,
    b: number,
    c: number,
};

const foo:Abc = {a: 1, b: 2, c: 3}; // Abc
const bar = double(foo); // Abc {a: 2, b: 4, c: 6}
const foobar = shout(foo); // Record<keyof Abc, string> {a: '1!', b: '2!', c: '3!'}

I wanted to preserve as much type information as possible:

bar is still of type Abc
foobar is holding on to Abc's keys.

I also get type checking when writing the callback.
// @ts-expect-error
const typeError = map((x:number) => x)({a: 1, b: "2"})

I don't know if I over-engineered it but I can't stand to look at this code and this often happens to me in Typescript. I end up extracting as many things as possible in type aliases and I'm not sure it's such a good idea. it clutters the namespace, I have to find good names, type aliases don't expand in VSCode tooltips which is sometimes annoying and I still find the result difficult to look at.

Could this be simplified?
Just how do you manage long or complex type definitions so that your code looks good?

Thank you!


texts: Two-dimensional array, modified one field at a time

texts:
Title says it all. I'm basically initializing a two-dimensional array and changing the fields one at a time.

It might be a good idea to do this OO.
A Grid class seems right, perhaps as a subclass of Array. So far I haven't been able to successfully port it. Pointers would probably be a good idea as well.

Note this is kind of a sandbox project at the moment. I'm a novice in JS and trying to wrap my head around how I can handle data efficiently (particularly memory efficient, CPU is not as relevant).

Partial reviews are also welcome.

Array.initialize = function(iRows, iColumns, cInit) {
    var array = [];
    for (var i = 0; i < iRows; ++i) {
        var columns = [];
        for (var j = 0; j < iColumns; ++j) {
            columns[j] = initial;
        }
       array[i] = columns;
    }
  return array;
}

Array.shoot = function(row, column, array) {
  array[row][column] = "H";
  return array;
}

var myGrid = Array.initialize(12, 12, "U");
myGrid = Array.shoot(5, 5, myGrid);
myGrid = Array.shoot(0, 4, myGrid);

console.log(myGrid);


texts:
At work, we have a "pair programming ladder" where you can keep track of who is pairing with whom (based on check-ins).  The idea is to promote "promiscuous pairing" where each developer eventually pairs with every other developer.

In our team, this was being updated manually, so I thought of writing a script that will parse the logs and generate a table.

Given these are the names of the developers:

  "Adam", "Bill", "Carl", "David", "Eddie", "Frank", "George"

The output would look like so:

       |Adam
Bill   |0      |Bill
Carl   |0      |2      |Carl
David  |1      |0      |0      |David
Earl   |0      |0      |3      |0      |Earl
Frank  |0      |0      |0      |2      |1      |Frank
George |0      |0      |0      |0      |2      |0      |George
Solo   |1      |0      |0      |0      |0      |1      |0      |Solo
Other  |1      |0      |0      |0      |0      |2      |1      |0      |Other

This is my script:

from git import *
import re
from collections import Counter

list = ["Adam", "Bill", "Carl", "David", "Eddie", "Frank", "George"]

def build():
    repo = Repo("/home/developer/work/commerce-git/commerce-project")
    master = repo.heads.master
    pairsDict = {}
    for commit in repo.iter_commits(master, since='2013-02-06+14:00', reverse=True):
        for person in list:
            if person not in pairsDict:
                pairsDict[person] = Counter()
            if person in commit.message:
                pairedWith = ""

                m = re.search('(\w+)/(\w+)\s', commit.message)
                if not m:
                    pairedWith = "Solo"
                else:
                    if m.group(1) == person:
                        pairedWith = m.group(2) #pair is right of slash
                    else:
                        pairedWith = m.group(1) #pair is left of slash
                    if pairedWith not in list:
                        pairedWith = "Other"
                pairsDict[person][pairedWith] += 1
                if pairedWith not in pairsDict:
                    pairsDict[pairedWith] = Counter()
                pairsDict[pairedWith][person] += 1
                break;

    return pairsDict

def print_table():
    pairsList = list + ["Solo", "Other"]
    pairsDict = build()
    str = ""
    for index,person in enumerate(pairsList):
        if (index == 0):
            str += '|'.rjust(8) + person.ljust(7) + '\n'
        else:
            str += person.ljust(7) + '|'
            for paired in pairsList[:index]:
                count  = pairsDict[person][paired]
                str += '{:<7}|'.format(count)
            str +=  person.ljust(7)+'\n'
    print str
    return str

if __name__ == "__main__":
    print_table();

The scripts parses the git logs using GitPython, where a commit message is expected to look like this:

  "Adam/David - Refactored app to be more polyglot-y"

From there it constructs a HashMap of Counters to keep track of who has paired with whom. I'm going to eventually feed this data structure into a simple Django web-app so people can view it in a browser.

Do you have any suggestions for this script?  Could it be more "pythonic"?  Is there anything I could do to refactor it to be simpler to read, or better performance-wise?


texts:
I have created the following function which filters a linked list in place
(here it removes all instances of the element k), but it could easily be modified to take a function pointer as an argument and filter on something else.
Any ideas on how to improve the code?
typedef struct list_integer {
    type value;
    struct list_integer *next;
} list_integer;

list_integer *removeKFromList(list_integer * l, int k)
{

    if (!l)
    return l;
    while (l && l->value == k)
    l = l->next;
    if (!l)
    return l;

    list_integer *p = l;
    list_integer *q = l->next;

  scan_in:
    if (q) {
    if (q->value != k) {
        list_integer *t = q;
        q = q->next;
        p = t;
        goto scan_in;
    } else {
        goto scan_out;
    }
    }

  scan_out:
    if (q) {
    if (q->value != k) {
        p->next = q;
        p = q;
        q = q->next;
        goto scan_in;
    } else {
        q = q->next;
        goto scan_out;
    }
    } else {
    p->next = q;
    }
    return l;

}


texts: Join a collection of strings until character limit is reached

texts:
Question

I wrote a function which will take a collection of strings — and return a comma-separated string which doesn't exceed the specified character limit.

It essentially works by joining the collection of strings over and over again, and removing the last item in the collection each time, until the comma-separated string doesn't exceed the specified character limit.

private static string Join(IEnumerable<string> collection, int characterLimit)
{
    var values = new List<string>(collection);
    var joined = string.Join(", ", values);
    while (joined.Length > characterLimit)
    {
        values.RemoveAt(values.Count - 1);
        joined = string.Join(", ", values);
    }
    return joined;
}

I feel like there must more efficient way of doing this ... and that's what I'd love some help with.

Example

private string[] words =
{
    "able", "acid", "angry", "automatic", "awake", "bad", "beautiful", "bent", "bitter",
    "black", "blue", "boiling", "bright", "broken", "brown", "certain", "cheap", "chemical", "chief", "clean",
    "clear", "cold", "common", "complete", "complex", "conscious", "cruel", "cut", "dark", "dead", "dear",
    "deep", "delicate", "dependent", "different", "dirty", "dry", "early", "elastic", "electric", "equal",
    "false", "fat", "feeble", "female", "fertile", "first", "fixed", "flat", "foolish", "free", "frequent",
    "full", "future", "general", "good", "gray", "great", "green", "hanging", "happy", "hard", "healthy", "high",
    "hollow", "ill", "important", "kind", "last", "late", "left", "like", "living", "long", "loose", "loud",
    "low", "male", "married", "material", "medical", "military", "mixed", "narrow", "natural", "necessary",
    "new", "normal", "old", "open", "opposite", "parallel", "past", "physical", "political", "poor", "possible",
    "present", "private", "probable", "public", "quick", "quiet", "ready", "red", "regular", "responsible",
    "right", "rough", "round", "sad", "safe", "same", "second", "secret", "separate", "serious", "sharp",
    "short", "shut", "simple", "slow", "small", "smooth", "soft", "solid", "special", "sticky", "stiff",
    "straight", "strange", "strong", "sudden", "sweet", "tall", "thick", "thin", "tight", "tired", "true",
    "violent", "waiting", "warm", "wet", "white", "wide", "wise", "wrong", "yellow", "young"
};

private void joinButton_Click(object sender, EventArgs e)
{
    var characterLimit = 500; // the joined string's length will be <= 500
    var joined = Join(words, characterLimit); // the joined string
    Console.WriteLine("joined: " + joined);
    Console.WriteLine("joined.Length: " + joined.Length);
}

Output

joined: able, acid, angry, automatic, awake, bad, beautiful, bent, bitter, black, blue, boiling, bright, broken, brown, certain, cheap, chemical, chief, clean, clear, cold, common, complete, complex, conscious, cruel, cut, dark, dead, dear, deep, delicate, dependent, different, dirty, dry, early, elastic, electric, equal, false, fat, feeble, female, fertile, first, fixed, flat, foolish, free, frequent, full, future, general, good, gray, great, green, hanging, happy, hard, healthy, high, hollow, ill
joined.Length: 495


texts: How to refactor the following sql statement?

texts:
Declare @IsExistRoleAR As bit
Declare @IsExistRoleEN As bit
Declare @IsExist AS bit
set @IsExistRoleAR=(SELECT CASE WHEN COUNT(RoleID) > 0 THEN 1 ELSE 0 END AS isExists
                    FROM Roles
                    WHERE RoleDescAR='Arabic Name')

set @IsExistRoleEN=(SELECT CASE WHEN COUNT(RoleID) > 0 THEN 1 ELSE 0 END AS isExists
FROM Roles
WHERE RoleDescEN='English Name')

set @IsExist=(@IsExistRoleAR | @IsExistRoleEN)
select @IsExist


texts: How to make this code of shortest Path Finder more maintainable,extendable and get better static code analysis result?

texts:
I have the below code for finding the shortest path between a source node and destination node in a BiDirectional graph.It is working alright.
However, when I am running Static Code Analysis (VS2017), it is giving poor score (42) on Maintainability Index.
My questions are:

How to improve the overall code quality?
How can I make it more extendable or maintainable?
Will employing some specific Design Pattern here would have mad more sense?If yes, which one and how, can you please guide?

Here is the code below:

interface IRouter
  {
    void AddNode(string name, Dictionary<string, int> node);
    List<string> GetShortestPath(string source, string destination);
  }
public  class BaggageRouter: IRouter
  {
    Dictionary<string, Dictionary<string, int>> vertices = new Dictionary<string, Dictionary<string, int>>();

    public void AddNode(string name, Dictionary<string, int> node)
    {
      vertices[name] = node;
    }

    public List<string> GetShortestPath(string start, string finish)
    {
      #region SettingUp
      var previous = new Dictionary<string, string>();
      var distances = new Dictionary<string, int>();
      var queue = new List<string>();// the set of all nodes in Graph   - all nodes in the graph are unoptimized - thus are in Q

      List<string> path = null;

      foreach (var vertex in vertices)
      {
        if (vertex.Key == start)
        {
          distances[vertex.Key] = 0;//setting Source Node Distance=0
        }
        else
        {
          distances[vertex.Key] = int.MaxValue;//remaining all nodes are set at max distance
        }
        queue.Add(vertex.Key);
      }
      #endregion

      while (queue.Count != 0)
      {
        queue.Sort((x, y) => distances[x] - distances[y]);

        var smallest = queue[0];
        queue.Remove(smallest);//Removing the optimized Node at every Iteration

        if (smallest == finish)//Meaning we have calculated the shortest path upto destination node, so no need to calculate shortest path for remaining nodes like in original Dijkstra
        {
          path = new List<string>();
          while (previous.ContainsKey(smallest))
          {
            path.Add(smallest);
            smallest = previous[smallest];
          }
          path.Add(start);
          path.Reverse();
          path.Add(": " + distances[finish].ToString());//Adding the shortest path distance as last element
          break;
        }

        if (distances[smallest] == int.MaxValue)
        {
          break;//This corner-case scenario can happen if the remaining nodes are Un-reachable.
        }

        foreach (var neighbor in vertices[smallest])
        {
          var alt = distances[smallest] + neighbor.Value;
          if (distances.ContainsKey(neighbor.Key))
          {
            if (alt < distances[neighbor.Key])
            {
              distances[neighbor.Key] = alt;
              previous[neighbor.Key] = smallest;
            }
          }
        }
      }

      return path;
    }
  }


texts:
The basic idea is not to allow the same text and add +1 at the end.

Imagine that I have a datagrid (WPF) with names, and every time I click the add button, I will put a new name on the list automatically by running this method to ensure that no two names are alike.

My standard used: if there is repeated text, add to the end "(" + count + ")", similar to Windows Explorer.

Are there ways to make this using LINQ or Regex?

private void Test()
{
    var result = CreateText("t", new string[] { "t", "t(1)", "t(2)", "t(3)", "t(4)", "t(5)", "t(6)", "t(7)", "t(8)", "t(9)", "t(10)" });
    Assert.IsTrue(result == "t(11)");
}

public static String CreateText(string newText, String[] texts)
{
    int addCount = 0;
    foreach (String text in texts)
    {
        if (text.IndexOf(newText) == 0)
        {
            if (text == newText && addCount == 0)
            {
                addCount = 1;
                continue;
            }
            else
            {
                if (text.LastIndexOf('(') == newText.Length && text.LastIndexOf(')') == text.Length - 1)
                {
                    try
                    {
                        var initial = text.LastIndexOf('(') + 1;
                        var size = text.LastIndexOf(')') - initial;
                        int count = Int16.Parse(text.Substring(initial, size));
                        if (addCount <= count)
                        {
                            addCount = count + 1;
                        }
                    }
                    catch (Exception)
                    {
                        addCount = 0;
                    }
                }
            }
        }
    }
    if (addCount > 0)
    {
        newText += "(" + addCount + ")";
    }
    return newText;
}


texts: Deleting object properties if they are not found in another object. (javascript)

texts:
Let's take these two objects as an exemple:

let objA = {
    key1 : "whatever",
    key2 : "whatever",
    key3 : "whatever",
    key4 : "whatever",
    key5 : {
        subKey1: "whatever",
        subKey2: "whatever"
    }
}
let objB = {
    key1 : "whatever",
    key2 : "whatever",
    key3 : "whatever",
    key5 : {
        subKey1: "whatever"
    }
}

I want to delete all the properties of objA if they are not present in objB. The values of the properties do not matter, only the keys themselves. The challenge, of course, is for it to work with any object, no matter how deeply nested they can be.

I came up with this solution based on this answer to a similar question.

let objA = {
    key1 : "whatever",
    key2 : "whatever",
    key3 : "whatever",
    key4 : "whatever",
    key5 : {
        subKey1: "whatever",
        subKey2: "whatever"
    }
}
let objB = {
    key1 : "whatever",
    key2 : "whatever",
    key3 : "whatever",
    key5 : {
        subKey1: "whatever"
    }
}

const deepSameKeys = (o1, o2) => {
    const o1keys = Object.keys(o1).sort();

    return o1keys.every(key => {
        const v1 = o1[key];
        const v2 = o2[key];

        let goDeeper = true;
        if (o2[key] == undefined) {
            console.log('@found a key to delete: ', key);
            delete o1[key];
            goDeeper = false;
        }
        const t1 = typeof v1;
        return t1 === "object" && goDeeper ? deepSameKeys(v1, v2) : true;
    });
};

let result = deepSameKeys(objA, objB)
console.log(result)
console.log(objA) // no more key4 nor subKey2

So far so good, but I wonder if someone can come up with something better or   a situation where my solution would fail.


texts: Parsing XML and prepend HTML every 3 elements

texts:
I'm working on a 3 columns photo website (responsive), and I'm parsing the img src from XML. I need to prepend HTML code every 3 elements so my photo wall respects my responsive class.

I just found a cheap solution, repeating the XML loop (for). Do you have an advice to give me, to do it right, to improve my code?

$(document).ready(function(){
 xmldata=new Array();      //initialise array for XML data
 $.ajax({                      //get the XML data
  url: "xml/gallery.xml",             //URL to get the data from
 success: function(data) {         //if we succeed, set everything up. We don't expect    failure.
  $(data).find("image").each(function()
 {
  xmldata.push($(this));        //add item into array
 });

 totalNum = xmldata.length;

 gallery_images();

}

 });

});

 function gallery_images(){

 for (var i = 0; i <= 2; i++) {

 data=xmldata[i];

 img_src=$(data).attr("src");
 href=$(data).attr("href");
 title1=$(data).attr("title1");
 client=$(data).attr("client");

  var video_gallery_html = '';
  video_gallery_html += '

';
  video_gallery_html += '  ';
  video_gallery_html += '
DENIS ROVIRA
';
  video_gallery_html += '
See all projects

';
  video_gallery_html += '    ';
  video_gallery_html += '
Nescafe Gold

';

   $(".videos_container").prepend(video_gallery_html);

 };

 for (var i = 3; i <= 5; i++) {

 data=xmldata[i];

 img_src=$(data).attr("src");
 href=$(data).attr("href");
 title1=$(data).attr("title1");
 client=$(data).attr("client");

 var video_gallery_html2 = '';
 video_gallery_html2 += '

';
 video_gallery_html2 += '  ';
 video_gallery_html2 += '
DENIS ROVIRA
';
 video_gallery_html2 += '
See all projects

';
 video_gallery_html2 += '    ';
 video_gallery_html2 += '
Nescafe Gold

';

  $(".videos_container2").prepend(video_gallery_html2);

 };

 }


texts: Python use glob to search for files by extension

texts:
This code works, but I feel bad about it. Did I achieve Python Zen or create a terrible monster?
Note: it doesn't have to be super-fast or work on super-huge directory trees.
import glob
from typing import List

# Provide pathname without a trailing /
def find_files_with_extension(pathname: str, extension: str) -> List[str]:
    return list({item for sublist in [glob.iglob(s + "**." + extension) for s in glob.iglob(pathname + "/**/", recursive=True)] for item in sublist})


texts:
I am trying to learn modular pattern in javascript right now i am refactoring my previous side project a tasks app from jquery to plain js. I wish to know if what i'm doing here is right because i feel like i am over using the pattern here

(function(){
    const nameSetBtn = document.querySelector('#name-setting-btn');
    const nameSetModalParent = document.querySelector('.modal-parent');
    const nameSetModalMain = document.querySelector('.modal');
    const nameSetModalInput = document.querySelector('#name-setting-input');
    const mainInterface = document.querySelector('.main-interface');
    const createSetBtn = document.querySelector('#create-set-btn');

    const NameSetting = (function(){
        function animateModal(){
            nameSetModalMain.style.width = '30%';
            nameSetModalMain.style.opacity = '0';
            nameSetModalParent.style.opacity = '0';
            delayHide = setTimeout(function(){
                nameSetModalParent.style.display = 'none';
            }, 500)
            MainUI.setUI();
        }
        return {
            validate : function(){
            const nameValue = nameSetModalInput.value;
            const nameLength = nameValue.length;
            if(nameValue === '' || nameLength < 5){
                    alert("You're name should be at least 5 characters to 10 characters long");
                } else if(nameLength > 10) {
                    alert("You're name must only be at least 10 characters long");
                } else {
                    localStorage.setItem('username', nameValue);
                    console.log(this)
                    return animateModal();
                }
            }
        };
    })();

    const MainUI = (function(){
        function show() {
            const greeting = document.querySelector('#greet');
            greeting.innerText = 'Welcome!, ' + localStorage.getItem('username');
            mainInterface.style.display = 'block';
        }
        return {
            checkUser : function(){
                if(localStorage.getItem('username')){
                    nameSetModalParent.style.display = 'none';
                    this.setUI();
                }
            },
            setUI : function(){
                const currentDate = new Date();
                const dateStringHolder = document.querySelector('#date-string');
                dateStringHolder.innerText = currentDate.toDateString();
                const dateTimeHolder = document.querySelector('#date-time');
                const tickTime = setInterval(function () {
                        dateTimeHolder.innerText = new Date().toLocaleTimeString();
                }, 1000)

                return show();
            }
        }
    })();

// The tasks model not done yet
    function SetModel(setName){
        this.setName = setName;
        this.tasks = [];
    }

    SetModel.prototype.nameOfSet = function(){
        console.log(this.setName);
    }

    createSetBtn.addEventListener('click', () => {
        const newset = new SetModel('Name this set');

    })

    MainUI.checkUser();
    nameSetBtn.addEventListener('click', () => {
            NameSetting.validate();
    })

})();


texts: Using Token Bucket to rate limit function calls

texts:
This program is my attempt at solving the below problem:
We have a function which is going to be called by multiple threads. The problem is to find a way to limit the number of times this function is executed per second given that we don't have a control over:
a) The number of threads calling this function.
b) The number of times per second this function will be called by any thread.
We need to somehow limit its rate of execution.
This program is my attempt at solving this kind of problem. I've tried to use the Token Bucket Algorithm for this.
The usage is simple. It consists of a header file "tokenBucket.hpp". You need to include this in your program. Suppose you want to limit the execution rate of the function given below:
void printHelloWorld();

You need to do 2 things:
You need to create a tokenBucket object constructed with the required rate you want your function to be executed per second. e.g. tokenBucket aBucket(500);
When calling your function, then instead of: printHelloWorld();
you have to do:
if(aBucket.areTokensAvailable()) {
printHelloWorld();
}

Given below is my header only program:
#ifndef __TOKEN_BUCKET_HPP__
#define __TOKEN_BUCKET_HPP__

#include <chrono>
#include <mutex>
#include <iostream>

class tokenBucket{

  public:

    /* Constructor */
    tokenBucket(uint64_t fa_tokenFillRatePerSec): m_tokenFillRatePerSecond(fa_tokenFillRatePerSec),m_bucketSize(fa_tokenFillRatePerSec),m_availableTokens(fa_tokenFillRatePerSec),m_lastRefillTime(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count()),m_timeIntervalPerRequestInMicroSeconds(NUMBER_OF_MICROSECONDS_IN_A_SECOND/fa_tokenFillRatePerSec){
      fprintf(stdout,"\nToken Bucket initialised with the following values\nm_bucketSize(%lu)\nm_tokenFillRatePerSecond(%lu)\nm_availableTokens(%lu)\nm_lastRefillTime(%lu)\nm_timeIntervalPerRequestInMicroSeconds(%lu)\n",m_bucketSize,m_tokenFillRatePerSecond,m_availableTokens,m_lastRefillTime,m_timeIntervalPerRequestInMicroSeconds);
    }

    /* always called to check if sufficient number of tokens are available to server the request*/
    bool areTokensAvailable(int fa_numberOfRequestedTokens = 1){
      std::lock_guard<std::mutex> lg(m_mu);
      uint64_t now = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
      refill_tokens(now);

      if(m_availableTokens < fa_numberOfRequestedTokens){
        return false;
      }
      else{
        m_availableTokens -= fa_numberOfRequestedTokens;
        return true;
      }
    }

  private:
    static constexpr int NUMBER_OF_MICROSECONDS_IN_A_SECOND = 1000000;
    std::mutex m_mu;
    uint64_t m_bucketSize; //Currently I'm taking Bucket Size = token fill rate per second.
    uint64_t m_tokenFillRatePerSecond;
    uint64_t m_availableTokens; //current number of tokens available in the bucket
    uint64_t m_lastRefillTime;
    uint64_t m_timeIntervalPerRequestInMicroSeconds; // = (pow(10,6)/m_tokenFillRatePerSecond)

    /* to refill the tokens as per time diff */
    void refill_tokens(const uint64_t& fa_currentRequestTime) {
      /*calculate tokens added in particular time difference */
      if (fa_currentRequestTime >= m_lastRefillTime + m_timeIntervalPerRequestInMicroSeconds) {

        uint64_t l_newTokens = (fa_currentRequestTime - m_lastRefillTime)/m_timeIntervalPerRequestInMicroSeconds;

        if(m_availableTokens + l_newTokens < m_bucketSize) {
          m_availableTokens += l_newTokens;
        }
        else {
          m_availableTokens = m_bucketSize;
        }
        m_lastRefillTime = fa_currentRequestTime;
      }
    }
};

#endif

Comments/Criticisms are welcome.


texts: capturing counts of open items between dates

texts:
DB version is: Oracle 12c. Restricted to the use of inline PL/SQL.

The end goal here is to get a count of open items by day, inclusive of created date, exclusive of the end date.

The data structure is approximately:

| id | open_date  | close_date |
|----|------------|------------|
| a  | 01/01/2020 | 01/04/2020 |
| b  | 01/02/2020 | 01/05/2020 |

The end result would be something like:

| date       | open_item |
|------------|-----------|
| 01/01/2020 | 1         |
| 01/02/2020 | 2         |
| 01/03/2020 | 2         |
| 01/04/2020 | 1         |
| 01/05/2020 | 0         |

the start date in all this is user input, but that's not terribly relevant.

What I had done is generate a table of dates using that user input date in a cte like so:

with caledar_dates as (
select user_input_date + rownum-1 dates

from dual connect by rownum < sysdate-user_input_date+1
)

Then joined the items table to the calendar_dates table in another CTE like so:

item_list as (
    select
    a.dates,
    b.id

    from calendar_dates a

    left join ticket_table b on a.dates>=b.created_date-1 and a.dates<b.closed_date

)

Finally, I then simply

select count(b.id), dates from item_list group by dates

There may be a few syntax errors above since I am truncating the actual code. This query works; however, it seems like an inefficient, wordy, ugly approach to the problem and if the user inputs a date a few years back, the query takes a few minutes to run.

Looking for an alternative and hopefully more efficient approach.

Not sure if this went on SO or here so happy to post over there if that seems the better venue.

Mahalo's in advance.


texts:
I am using this script to detect the most prefered language by the user.

function Get_Client_Prefered_Language ($getSortedList = false, $acceptedLanguages = false)
{

    if (empty($acceptedLanguages))
        $acceptedLanguages = $_SERVER["HTTP_ACCEPT_LANGUAGE"];

    preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})*)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $acceptedLanguages, $lang_parse);
    $langs = $lang_parse[1];
    $ranks = $lang_parse[4];

        // (create an associative array 'language' => 'preference')
    $lang2pref = array();
    for($i=0; $i<count($langs); $i++)
        $lang2pref[$langs[$i]] = (float) (!empty($ranks[$i]) ? $ranks[$i] : 1);

        // (comparison function for uksort)
    $cmpLangs = function ($a, $b) use ($lang2pref) {
        if ($lang2pref[$a] > $lang2pref[$b])
            return -1;
        elseif ($lang2pref[$a] < $lang2pref[$b])
            return 1;
        elseif (strlen($a) > strlen($b))
            return -1;
        elseif (strlen($a) < strlen($b))
            return 1;
        else
            return 0;
    };

        // sort the languages by prefered language and by the most specific region
    uksort($lang2pref, $cmpLangs);

    if ($getSortedList)
        return $lang2pref;

        // return the first value's key
    reset($lang2pref);
    return key($lang2pref);
}

Example:

print_r(Get_Client_Prefered_Language(true, 'en,en-US,en-AU;q=0.8,fr;q=0.6,en-GB;q=0.4'));

Output:

Array
    (
        [en-US] => 1
        [en] => 1
        [en-AU] => 0.8
        [fr] => 0.6
        [en-GB] => 0.4
    )

Is this reliable? How about performance, this script will get called many times per seconds.


texts:
I'm studying Common Lisp on my own. Coming from C++, Common Lisp feels kind of strange sometimes. I'd like to get some feedback on what I understood so far.

For learning purposes, I wrote this simple vector class package. The only requirements apart from correctness are non-destructiveness and performance. I want it to be as fast as possible. Is this the way to do it? Are there any serious flaws?

(in-package :cl-user)
(defpackage math
  (:use :cl)
  (:export :vector3
       :create-vector3
       :vector3-x
       :vector3-y
       :vector3-z
       :neg
       :mul
       :div
       :add
       :sub
       :dot
       :len
       :norm))
(in-package :math)

(defclass vector3 ()
  ((x :accessor vector3-x
      :initarg :x
      :initform 0
      :type double-float)
   (y :accessor vector3-y
      :initarg :y
      :initform 0
      :type double-float)
   (z :accessor vector3-z
      :initarg :z
      :initform 0
      :type double-float)))

(defun create-vector3 (x y z)
  (make-instance 'vector3 :x x :y y :z z))

(defmethod neg ((v vector3))
  (create-vector3 (- (vector3-x v))
          (- (vector3-y v))
          (- (vector3-z v))))

(defmethod mul ((s double-float) (v vector3))
  (create-vector3 (* s (vector3-x v))
          (* s (vector3-y v))
          (* s (vector3-z v))))

(defmethod div ((v vector3) (s double-float))
  (create-vector3 (/ (vector3-x v) s)
          (/ (vector3-y v) s)
          (/ (vector3-z v) s)))

(defmethod add ((a vector3) (b vector3))
  (create-vector3 (+ (vector3-x a) (vector3-x b))
          (+ (vector3-y a) (vector3-y b))
          (+ (vector3-z a) (vector3-z b))))

(defmethod sub ((a vector3) (b vector3))
  (create-vector3 (- (vector3-x a) (vector3-x b))
          (- (vector3-y a) (vector3-y b))
          (- (vector3-z a) (vector3-z b))))

(defmethod dot ((a vector3) (b vector3))
  (+ (* (vector3-x a) (vector3-x b))
     (* (vector3-y a) (vector3-y b))
     (* (vector3-z a) (vector3-z b))))

(defmethod len ((v vector3))
  (sqrt (+ (* (vector3-x v) (vector3-x v))
       (* (vector3-y v) (vector3-y v))
       (* (vector3-z v) (vector3-z v)))))

(defmethod norm ((v vector3))
  (let ((l (len v)))
    (if (> l 0)
    (let ((inv (/ 1.0 l)))
      (create-vector3 (* (vector3-x v) inv)
              (* (vector3-y v) inv)
              (* (vector3-z v) inv)))
    (create-vector3 (vector3-x v)
            (vector3-y v)
            (vector3-z v)))))


texts:
I have the following snippet of code that redirects a user to a specific page on successful login to the application.

if(isset($this->params['url']['next'])) {
    $url = parse_url(urldecode($this->params['url']['next']), PHP_URL_HOST);
    if( $_SERVER['SERVER_NAME'] != $url || $url == false ) {
        $pathtoredirect = $this->Auth->redirect();
    } else {
        $pathtoredirect = urldecode($this->params['url']['next']);
    }
} else {
    $pathtoredirect = $this->Auth->redirect();
}
$this->redirect($pathtoredirect);

The idea is that if a query string named 'next' exists and has a valid hostname that matches the actual sever hostname then send the user to that location otherwise send them to the default location. It should also handle really bad formatted urls by the parse_url method returning false.

Can anyone see any issues with the above code? Or offer improvements?

Thanks

EDIT

The next parameter can be added manually for example on a login link, but is also created automatically on the redirect when a user tries to access a protected action.

The reason for adding the FULL_BASE_URL is because the session also contains the app url, so if your app is on a subdirectory e.g. domain.com/myapp/ and you try and access domain.com/myapp/protectedlocation you will get redirected to the login form with domain.com/myapp/login?next=/myapp/protectedlocation which will then send you off to: domain.com/myapp/myapp/protectedlocation adding /myapp twice! Doing the full url instead STOPS this from ever happening and doing the parse url prevents a malicious user from creating a login link with their own url as the return.

public function redirect($url, $status = null, $exit = true)
    {
        if($this->Session->read('Auth.redirect'))
        {
            $url.= '?next=' . urlencode(FULL_BASE_URL.$this->Session->read('Auth.redirect'));
        }
        $this->Session->delete('Auth.redirect');
        return parent::redirect($url, $status, $exit);
    }


texts:
I'm trying to implement a memory scanner in python.
The problem is, it's too slow.
What it does it gets a number from the command line and compares it to every address, then writes it to an output file.
How can I improve my algorithm?

import ctypes as c
from ctypes import wintypes as w
from struct import *
from time import *
import datetime
import sys

pid = 1234

k32 = c.windll.kernel32

OpenProcess = k32.OpenProcess
OpenProcess.argtypes = [w.DWORD,w.BOOL,w.DWORD]
OpenProcess.restype = w.HANDLE

ReadProcessMemory = k32.ReadProcessMemory
ReadProcessMemory.argtypes = [w.HANDLE,w.LPCVOID,w.LPVOID,c.c_size_t,c.POINTER(c.c_size_t)]
ReadProcessMemory.restype = w.BOOL
PAA = 0x1F0FFF
address = 0x4000000
ph = OpenProcess(PAA,False,int(pid)) #program handle

buff = c.create_string_buffer(4)
bufferSize = (c.sizeof(buff))
bytesRead = c.c_ulonglong(0)

addresses_list = xrange(address,0x9000000,0x4)
log=open(r'out.txt.','wb',0)
for i in addresses_list:
    ReadProcessMemory(ph, c.c_void_p(i), buff, bufferSize, c.byref(bytesRead))
    value = unpack('I',buff)[0]
    if value == int(sys.argv[1]):
        log.write('%x\r\n' % (i, ))


texts: Implementation of static_for to iterate over elements of std::tuple using C++17 features

texts:
I have implemented a static_for loop to iterate over the elements of an std::tuple using C++17 features. Here is what I have currently:

#include <iostream>
#include <utility>
#include <tuple>

template <std::size_t I>
struct wrapper
{
    static constexpr std::size_t n = I;
};

template <class Func, std::size_t ...Is>
constexpr void static_for_impl( Func &&f, std::index_sequence<Is...> )
{
    ( f( wrapper<Is>{} ),... );
}

template <std::size_t N, class Func>
constexpr void static_for( Func &&f )
{
    static_for_impl( f, std::make_index_sequence<N>{ } );
}

int main()
{
    auto t = std::make_tuple( 1, 22, 3, 4 );

    std::size_t weighted = 0;
    static_for<4>( [&](auto w)
    {
        weighted += ( w.n + 1 ) * std::get<w.n>( t );
    });

    std::cout << "Weighted: " << weighted << std::endl;

    return 0;
}

Demo

My questions are:

Is there a more standard way that this can be implemented (like maybe using std::apply or invoke)?
Is there another idiom that would be better than the ugly wrapper struct that can be used to access the index at compile time from within a lambda?

Accepted modification:
Incorporated all the suggested modifications here.


texts: A basic calculator in C that uses a loop

texts:
I have created a program that forms a basic calculator in C which includes the basic operations like addition, subtraction, multiplication and division. But in this case I decided to use a Do-While loop. It is working.

I would appreciate to be pointed out some mistakes and opinions to make the code more presentable.

I have only one question which is:

instead of using a single character like:

while( choice == 'y' || choice == 'Y' );

why can't I use a string? ie.

printf("would you like to try again? \"yes or no\"\n");
scanf(" %s", &choice);
}
while ( choice == 'yes' || choice == 'YES' );

My code is as given as below...

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

 int main()
 {
     float a, b, c;
     int n;
     char choice = 'y' ;

     do
     {
         printf("Please enter any number:\n");
             if (scanf("%f", &a)!=1){
                 fprintf(stderr, "error: first input must be a number\n");
                     return EXIT_FAILURE;}

         printf("Please choose any of the operator:\n");
         printf(" 1.addition\n 2.subtraction\n 3.multiplication\n 4.division\n");
             scanf(" %d", &n);

         printf("Please enter any number:\n");
             if (scanf("%f", &b)!=1){
                 fprintf(stderr, "error: second input must be a number\n");
                     return EXIT_FAILURE;}

         switch(n)
         {
             case 1 :
                 c = a + b;
                     printf("The answer is:%f\n", c);
             break ;

             case 2 :
                 c = a - b;
                     printf("The answer is:%f\n", c);
             break;

             case 3 :
                 c = a * b;
                     printf("The answer is:%f\n", c);
             break;

             case 4 :
                 c = a / b;
                     printf("The answer is:%f\n", c);
             break;

             default :
                     printf("You have not chosen the given operators\n");
             }

                     printf("would you like to try again? (y/n)\n");
                         scanf(" %c", &choice);
     }

     while( choice == 'y' || choice == 'Y');
         getch();

     return 0;
 }


texts:
I am attempting to create a fast & robust object management system that allows adding, removing and retrieving objects from a "scene". I am trying to wrap my head around the best way to do this regarding ownership and object lifecycle. Code:

main.cpp:

int main()
{
    r3d::scene main_scene;

    game_object& obj = main_scene.create_object("obj", glm::vec3(0, 0, 0), glm::vec3(-90, 0, -90), glm::vec3(1, 1, 1));

    main_scene.remove_object("obj");

    return 0;
}

scene.hpp:

namespace r3d
{
    class scene
    {
    public:
        scene::scene() { }

        game_object& create_object(std::string name,
                                glm::vec3 position = glm::vec3(0, 0, 0),
                                glm::vec3 euler_angles = glm::vec3(0, 0, 0),
                                glm::vec3 scale = glm::vec3(1, 1, 1));

        void remove_object(std::string);

        game_object& get_object(std::string);

    private:
        std::map<std::string, r3d::game_object> game_objects;
    };
}

scene.cpp:

game_object& scene::create_object(std::string name, glm::vec3 position, glm::vec3 euler_angles, glm::vec3 scale)
{
    game_objects.emplace(name, game_object { name, position, euler_angles, scale });

    return game_objects[name];
}

void scene::remove_object(std::string name)
{
    game_objects.erase(name);
}

game_object& scene::get_object(std::string name)
{
    return game_objects[name];
}

game_object.hpp

namespace r3d
{
    class game_object
    {
    public:
        std::string name;

        game_object() {}

        // constructor
        game_object(std::string name, glm::vec3 position, glm::vec3 euler_angles, glm::vec3 scale)
            : name(name),
            position(position),
            euler_angles(euler_angles),
            scale(scale)
        {
            printf("New game_object: %s [address: %p]\n", name.c_str(), this);
        }

        // destructor
        ~game_object()
        {
            printf("Delete game_object: %s [address: %p]\n", name.c_str(), this);
        }

        // copy constructor
        game_object(const game_object& source)
            : name { source.name },
            position { source.position },
            euler_angles { source.euler_angles },
            scale { source.scale }
        {
            printf("Copy game_object: %s [from: %p  to: %p]\n", source.name.c_str(), &source, this);
        }

        // move constructor
        game_object(game_object&& source)
            : name { source.name },
            position { source.position },
            euler_angles { source.euler_angles },
            scale { source.scale }
        {
            printf("Move game_object: %s [from: %p  to: %p]\n", source.name.c_str(), &source, this);
        }

    protected:
        glm::vec3 position;
        glm::vec3 euler_angles;
        glm::vec3 scale;
    };
}


texts: Use optional to check Null pointer exception

texts:
I currently have something like this:

Price price = new Price();
ActualValue actualValue = new ActualValue();
actualValue.setValue(price.getPreviousPrice().getRegion().getValue());

I want to make sure when calling getRegion() and getValue(), no NPE is thrown, trying to make it write in one line so I thought about using Optional

Currently what I have is this:

Optional.of(price)
            .flatMap(d -> Optional.ofNullable(d.getPreviousPrice())
            .flatMap(p -> Optional.ofNullable(p.getRegion())
                    .flatMap(m -> Optional.ofNullable(m.getValue()))))
            .ifPresent(v -> actualValue.setValue(v));

Looks ugly, how can I improve?


texts:
I am learning Vue after working for some time with Angular and I'd like to hear experienced programmers concerning the implementation of my Progressive Bar service (in Vue it's called Plugin).

The idea behind it is to have a solid service which is responsible for the progress bar indicator.

I've got there a component with the logic for displaying and hiding and CSS with HTML Mark-up. And the core which serves as a middleware (or a service in Angular) between the component and Providers (vueRouter and Apollo).

I wasn't sure if it's a good practice to use RxJS in Vue. I've always thought that it's reactive itself but here I found it useful to have it. Is it a good practice?

It's still raw. Later on I'd like to make it customizable with options, but for now I'd like to know if I'm on the right way.

main.js

import Vue from "vue";
import VueRx from 'vue-rx'
import App from "./App.vue";
import router from "./router";
import store from "./store";
import { createProvider } from './vue-apollo'

import ProgressBar from '@/plugins/progressBarPlugin';

Vue.use(ProgressBar);
Vue.use(VueRx)

Vue.config.productionTip = false;

export default new Vue({
  router,
  store,
  apolloProvider: createProvider(),
  render: h => h(App)
}).$mount("#app");

index.js (progressBarPlugin)

import ProgressBarComponent from './progress-bar/progress-bar.vue';
import apolloHook from './apolloHook.js';
import vueRouterHook from './vueRouterHook.js';

import { Subject } from 'rxjs'
import { distinctUntilChanged } from 'rxjs/operators'

export const state = new Subject().pipe(distinctUntilChanged());

const ProgressBarPlugin = {
    install(Vue) {
        Vue.component(ProgressBarComponent.name, ProgressBarComponent);

        Vue.mixin({
            created() {
                if (this.$options.name === ProgressBarComponent.name) {
                    apolloHook(state, this.$apolloProvider);
                    vueRouterHook(state, this.$router)
                }

            }
        })
    },

    request() {
        state.next('request');
    },

    response() {
        state.next('response');
    },

    done() {
        state.next('done');
    }
};

export default ProgressBarPlugin;

apolloHook

export default function apollo(state, apolloProvider) {
    if (apolloProvider) {

        apolloProvider.watchLoading = function (loading) {
            // This function can also accept param counter: -1 / 1

            (loading) ? state.next('request') : state.next('done');

        };

    }
}

vueRouterHook

export default function vueRouter(state, router) {
    if (router) {
        router.beforeEach((to, from, next) => {
            state.next('request');
            next();
            state.next('response');
        })

        router.afterEach(() => {
            state.next('done');
        })

    }
}
```