texts: Replace keys in values with key->values from same dictionary

texts:
I have a dictionary whose values may contain keys that are already in the dictionary. What we are actually talking about are parameters. Sometimes a parameter is defined by a number plus another parameter, etc.

It looks something like this:

paramDict = {'ad': '2*dmcg/factor*(xw/factor)',
'dmcg': 2.05e-07,
'dxwn_3vna': 10.0,
'factor': 1,
'xw': '0+dxwn_3vna'}

If there is another parameter in the value it is of type string, otherwise it is an int or a float. After the replacing I want the value to be a float.

The code I wrote to solve this problem is this:

    for _ in range(10):
        for key, value in paramDict.items():
            if type(value) is str:
                matchList = re.findall('[a-z]\w*', value)
                matchList = [match for match in matchList if match != 'e']
                for match in matchList:
                    param = paramDict[match]
                    paramDict[key] = value.replace(match, str(param))
                try:
                    paramDict[key] = eval(paramDict[key])
                except:
                    pass

It works as far as I can tell, but it just doesn't feel right to just repeat the whole process a finite number of times and hope that all the strings have been replaced. Is there a safer way?


texts: Batch bash installer script for clean Ubuntu GNOME installation

texts:
I just finished (I think) writing a bash script to install all my essential software to Ubuntu GNOME. I'll be making more for different distributions but once I have one to go off of, I can do the rest fine.

I am very new to it all, however, and have barely gotten into using the cli so I'm sure that there are a ton of errors below. If you could just read through it and let me know what I can fix/improve, that would be wonderful! This is meant to run a nearly clean install; I'll have to open Firefox and download two files; the script and the extensions list. Other than that, everything is still set to default.

#!/bin/bash
sudo apt-get install -y gnome-tweak-tool
sudo apt-get install -y variety
sudo apt-get install -y hunspell-en-gb
sudo apt-get install -y gdebi
sudo apt-get install -y gparted
sudo apt-get install -y libreoffice-style-breeze
sudo apt-get install -y evolution
sudo apt-get install -y evolution-indicator
sudo apt-get install -y cairo-dock
cd
cd Downloads
mkdir Programs
cd Programs
wget https://steamcdn-a.akamaihd.net/client/installer/steam.deb
sudo dpkg -i steam.deb
sudo apt-get install -f
wget https://atom.io/download/deb
sudo dpkg -i atom*
sudo apt-get install -f
wget https://www.realvnc.com/download/file/vnc.files/VNC-Server-6.2.0-Linux-x64.deb
sudo dpkg -i VNC-Server*
sudo apt-get install -f
wget https://www.realvnc.com/download/file/viewer.files/VNC-Viewer-6.17.731-Linux-x64.deb
sudo dpkg -i VNC-Viewer*
sudo apt-get install -f
sudo cd /usr/share/icons
wget https://dl.opendesktop.org/api/files/download/id/1464728434/164587-bridge.tar.gz
tar -xvzf 164587-bridge.tar.gz
sudo add-apt-repository ppa:papirus/papirus
sudo apt update
sudo apt-get install papirus-icon-theme
sudo apt install numix-gtk-theme
xterm -e "echo Make sure you select Bridge as the cursor, Papirus as the icon theme, and Numix as the GTK+ theme && gnome-tweak-tool"
cd
xterm -e "echo Replace whatever is there with Bridge && sudo gedit /usr/share/icons/default/index.theme"
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-key FDC247B7
echo 'deb https://repo.windscribe.com/ubuntu zesty main' | sudo tee /etc/apt/sources.list.d/windscribe-repo.list
sudo apt-get update
sudo apt-get install windscribe-cli
xterm windscribe login && windscribe start && echo Connect to Windscribe with windscribe connect best
echo All thats left is to do is, if youre using GNOME, enable all of your chosen extensions at extensions.gnome.org
cd
echo Use gedit /Documents/Scripts/Extension_Links to view my links to GNOME Shell Extensions


texts: Read from csv file, transform to dictionnary

texts:
First of all, here's the code I'm working on:

def get_data(filename, cols):
    with codecs.open(filename, 'r') as csvFile:
        for row in csv.reader(csvFile):
            # build data dictionnary
            data = {}
            for i in range(len(cols)):
                key = cols[i]

                # update
                value = row[i].strip()

                # because some columns are splited in the csv file
                if key in data:
                    data[key] += value
                else:
                    data[key] = value

            # yield data, for each row
            yield data

So, depending of the size of the file, the time to process can be very long.

I tried testing csv.reader with custom dictionnary construction VS basic csv. DictReader, and for some reason, the first one is faster...

I have some long csv files with rows like this one:

"152Q694     ","892-000357          ",       0,       0,"        "

In some files, I have this (see the product name split in two columns?):

"A","COMPANY NAME         ","1234","987654321     ","I AM A PRODUCT NAME     ","WITH SOME EXTRA INFO          ","AB    ","12345               ",0000000000000001.23,0000000000000003.45,"A","            ","Z","01234567891234058","1234","EN",000000.01,"ABC","D","        ","        ",000000,000000,"            "

All in all, there will always be n rows and x columns, so the time of the process is a multiple of n*x.  Am I wrong?

What can I do to speed things up?


texts:
/*
 * The following iterative sequence is defined for the set of positive
 * integers:
 *
 * n -> n/2 (n is even) n -> 3n + 1 (n is odd)
 *
 * Using the rule above and starting with 13, we generate the following
 * sequence:
 *
 * 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 It can be seen that
 * this sequence (starting at 13 and finishing at 1) contains 10 terms.
 * Although it has not been proved yet (Collatz Problem), it is thought that
 * all starting numbers finish at 1.
 *
 * Which starting number, under one million, produces the longest chain?
 *
 * NOTE: Once the chain starts the terms are allowed to go above one
 * million.
 */
public static int get14() {
    int max = 1;
    int ans = 1;
    // Map<Integer, Integer> t_cache = new HashMap<Integer, Integer>();
    for (int i = 2; i < 1000000; i++) {
        long n = i;
        int t = 0;
        do {
            // if (t_cache.containsKey(n)) {
            // t += t_cache.get(n);
            // break;
            // }
            ++t;
            if (n % 2 == 0) {
                n /= 2;
            } else {
                n = 3 * n + 1;
            }
            // t_cache.put(i, t);
        } while (n != 1);
        // System.out.println(i + "->" + t);
        if (t > max) {
            max = t;
            ans = i;
        }
    }
    return ans;
}

Using no cache I get:

  Answer is 837799, Time taken 22.08799153 seconds

Using cache I get:

  Answer is 837799, Time taken 90.002679307 seconds {really?}

I need improvements for this.


texts: method to get finger mask based on finger position

texts:
Is there a more graceful way to structure the code below?

The fingerPosition values are increments of 1.

The fingerMask values start at 1, then 2 and then increment in multiples of 2.

    private int getFingerMask(int fingerPosition)
    {
        int fingerMask = 0;

        if (fingerPosition == 0)
        {
            fingerMask = 1;
        }
        else if (fingerPosition == 1)
        {
            fingerMask = 2;
        }
        else if (fingerPosition == 2)
        {
            fingerMask = 4;
        }
        else if (fingerPosition == 3)
        {
            fingerMask = 8;
        }
        else if (fingerPosition == 4)
        {
            fingerMask = 16;
        }
        else if (fingerPosition == 5)
        {
            fingerMask = 32;
        }
        else if (fingerPosition == 6)
        {
            fingerMask = 64;
        }
        else if (fingerPosition == 7)
        {
            fingerMask = 128;
        }
        else if (fingerPosition == 8)
        {
            fingerMask = 256;
        }
        else if (fingerPosition == 9)
        {
            fingerMask = 512;
        }

        return fingerMask;
    }


texts:
I'm a UI / UX Designer trying to sharpen my JS skills.  I wanted someone else to check this code snippet and maybe have a Pro tip to improve or shorten it.

Javascript:

var formContainer = $('.contact-form-container');
var formError = $('.form-error');
var tosLabel = $('.tos-label');
var tosCheckbox = $('.tos-checkbox');

function checkBoxValidation(tosLabel, tosCheckbox, formError) {
    if (!tosCheckbox.is(':checked')) {
        tosLabel.removeClass('tos-is-checked');
        formError.addClass('tos-error');
    } else if (tosCheckbox.is(':checked')) {
        tosLabel.addClass('tos-is-checked');
        formError.removeClass('tos-error');
    }
}

tosCheckbox.change(function() {
    checkBoxValidation(tosLabel, tosCheckbox, formError);
});

formContainer.submit(function () {
    checkBoxValidation(tosLabel, tosCheckbox, formError);
});

HTML:

    <form data-abide novalidate method="post" action="{{ path(route) }}" class="contact-form-container">
        {% if contact.error %}

{{ contact.error }}

        {% elseif contact.success %}

{{ contact.success }}

        {% endif %}

            Vor- und Nachname
                <input type="text" required pattern="[a-zA-Z]+" name="name" value="{{ contact.name }}">
                Vor- und Nachname angeben.

            Ihre E-Mail Adresse
                <input type="email" required name="email" value="{{ contact.email }}">
                Ihre E-Mail Adresse ist nicht korrekt.

            Ihre Nachricht
                <textarea placeholder="Schreiben Sie eine Nachricht" name="message" required>{{ contact.message }}</textarea>
                Ihre Nachricht angeben.

                <input id="checkbox1" class="tos-checkbox" type="checkbox" name="privacy" {{ contact.privacy?'checked' }} required>
                Ich akzeptiere die Bestimmungen für den Datenschutz.

                Akzeptieren Sie die Bestimmungen zum Datenschutz.

        <input type="submit" class="button" value="Senden">
    </form>


texts: Simulating coin flips and plotting a histogram

texts:
I started playing around recently with F# and I find it quite elegant and succinct language.

A common problem I like to solve in every language I start to learn is the coin flip problem, with the code below being the solution to this particular problem.
What the code does is to flip a coin N times and perform M tests for each flip series. Finally, it prints in console a binomial distribution visual.

I am new to F# and I might being hasty here, I probably will learn this myself much later, but is anybody that can suggest a refactoring? Is it possible to make this even more succinct?

I solved the problem with code very similar to imperative style and I refactored my way to the following code, trying keep it as much as declarative as I could.

open System

let heads (random: Random) =
    random.Next(0, 2) = 1

let add x y = x + y

let rec calculateHeads n random =
    match n with
    | 0 -> 0
    | _ ->
        let result = calculateHeads (n - 1) random
        let addToResult v = add v result
        match heads (random) with
        | true -> addToResult 1
        | false -> addToResult 0

let rec fill frequency n m random =
    match m with
    | v when v < 0 -> frequency
    | _ ->
        let count = calculateHeads n random
        Array.set frequency count (frequency.[count] + 1)
        fill frequency n (m - 1) random

let getFrequencies n m =
    let random = new Random()
    let frequency = Array.create (n + 1) 0
    fill frequency n m random

let rec displayAsterisk length =
    match length with
    | v when v = 1 -> "*"
    | v when v < 1 -> ""
    | _ -> "*" + (displayAsterisk (length - 10))

let rec displayRecursive list =
    match list with
    | [] -> ()
    | head::tail ->
        displayRecursive tail
        printfn "%d%s -- (%d)" head (displayAsterisk (head)) head

let displayCoin (frequency:int[]) =
    displayRecursive (frequency |> Array.toList)

[<EntryPoint>]
let main argv =
    let frequency = getFrequencies 32 1000
    displayCoin frequency
    0


texts: Wrapping an IntPtr in a Struct for safer Interop

texts:
Consider the following C#/C interop scenario:

public static extern IntPtr lua_newstate();
public static extern void lua_close(IntPtr state);

IntPtr luaState = lua_newstate();
// use lua ...
lua_close(luaState)

Obviously this works well enough, however there's a fringe possibility that an IntPtr not pointing to a lua state could be passed to lua_close, since it accepts any IntPtr.

I realized that it's possible to use the behavior of struct marshaling to make this interop a bit more type-safe

[StructLayout(LayoutKind.Sequential)]
public struct LuaState
{
    public readonly IntPtr Pointer;
}

public static extern LuaState lua_newstate();
public static extern void lua_close(LuaState state);

LuaState luaState = lua_newstate();
// use lua ...
lua_close(luaState)

Since LuaState contains only an IntPtr, the marshaler happily converts the native pointer returned by lua_newstate to an instance of LuaState, and will also quite happily convert a LuaState struct to a native pointer when passed back to a native function.

This essentially creates a typed pointer. There is a cost associated with passing LuaState though the Marshaling system instead of passing IntPtr directly to the native side, but in testing the cost appears to be negligible.

Questions: Does using LuaState to create a typed wrapper for IntPtr in this way raise any red flags? Has anyone done something similar and run into issues?


texts: JQuery Promise Interface for a (very) simple JSON Parser

texts:
I have written a parser function that returns a JQuery Promise.  You can see from the code that this is the top level parser and it delegates out to two other more specific parsers.

At the minute it feels a little scattered about with the promise being rejected and resolved all over the place.  perhaps it would be better with a try and catch and an error handler that rejected the promsie?  how would others approach this?

/**
 * Inspects JSON and delegates to either the sourceParser or the dataParser.
 *
 * @constructor
 * @param {Object} json
 *
 * @returns JQuery Promsise
 *      done:       -
 *      fail:       error message
 *      progress:   Progress message
 */
function Parser(json)
{
    var dfd = $.Deferred();

    dfd.notify("Parsing");

    if (json && typeof json === "object")
    {
        if (json.hasOwnProperty("GetDataSources"))
        {
            var dataSource = json.GetDataSources;

            if (this.isSuccessfulResponse(dataSource.Response))
            {
                // Notify the caller of any progress
                dfd.notify("Parsing Source");

                // Create a new Source Parser
                var sourceParser =  new SourceParser(dataSource);
                sourceParser.done(dfd.resolve);
                sourceParser.fail(dfd.reject);
            }
            else
            {
                dfd.reject("Parsing Source Failed");
            }
        }
        else if (json.hasOwnProperty("GetData"))
        {
            var data = json.GetData;

            if (this.isSuccessfulResponse(data.Response))
            {
                // Notify the caller of any progress
                dfd.notify("Parsing Data");

                // Create a new Data Parser
                var dataParser = new DataParser(data);
                dataParser.done(dfd.resolve);
                dataParser.fail(dfd.reject);
            }
            else
            {
                // Pass back an error message?
                dfd.reject("Parsing Data Failed");
            }
        }
    }
    else
    {
        dfd.reject("There was a problem reading the JSON")
    }

    return dfd.promise();
}


texts: Using an instance of PDO class as global variable inside 'query' methods

texts:
I have one PHP file named database.php:

 try {
     $connection= new PDO(DB_DNS, DB_USER, DB_PASS);
     $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e) {
     echo "Error: ".$e->getMessage();
     die();
}

and I have a user.php with class Users:

require_once(__DIR__."/../includes/config.php");
require_once(__DIR__."/../includes/database.php");

class User
{
    public function pronadjiSveUsere() {
        global $connection;
        $upit = $konekcija->prepare("SELECT * FROM users");
        $rezultat_upita = $upit->execute();
        return $rezultat_upita;
    }

    public function find_by_id($id = 0) {
        try {
            global $connection;
            $upit = $konekcija->prepare("SELECT * FROM users WHERE id = :id");
            $rezultat_upita = $upit->execute(array($id));
            return $rezultat_upita->fetch(PDO::FETCH_OBJ);
        } catch (Exception $e) {
            echo $e->getMessage();
            die();
        }
    }
}

So, you can see that there is a global $connection in each of the methods. Is this bad and why? If so, what would you do, as parameter passing, or with a constructor?


texts: A tiny switcher for arbitrary types in C++11

texts:
I was about to use the awful enum+map trick to switch on std::strings when I thought to see if I could let some variadic templates do the job for me and I started to play...

#include <string>
#include <iostream>
#include <functional>
#include <unordered_map>

template<typename Key = std::string, typename Fun = std::function<void(void)> >
class Switcher {
  std::unordered_map<Key,Fun> map;
  Fun fdefault;
 public:
  template<typename... O>
  Switcher(const Fun& f, const Key& k, const Fun& f2, const O&... o):
    Switcher(f2, o...) { map.emplace(k,f); }
  template<typename... O>
  Switcher(const Fun& f, const Key& k, const Key& k2, const O&... o):
    Switcher(f, k2, o...) { map.emplace(k,f); }

  Switcher(const Fun & f, const Key & k) { map.emplace(k,f); }
  Switcher(const Fun & f) { fdefault=f; }

  Switcher & operator()(const Key & k) {
    if (map.count(k)) map.at(k)();
    else if (fdefault) fdefault();
    return *this;
  }
};

int main() {
  std::string s1("hi");
  std::string s2("dear");
  Switcher<> switcher ( //whatever std::function here , all the keys here
                        [](){std::cout << "Hello ";  }, "hi",
                        [](){std::cout << "World ";  }, "dear", "buddy",
                        [](){std::cout << "Default ";}
                      );
  switcher(s1);
  switcher(s2);
  switcher("hi")("buddy")("?");
  return 0;
}

Of course is not the same as a switch statement, but it looks handy and for simple purposes it goes quite close, doesn't it?


texts:
Just wondering if this is okay to do? I have to store some PHP variable values into LocalStorage.

if($res->status == "success"){

            echo '<script>alert("alrighty sparky! lets get you in...");</script>';
            echo '<script>localStorage.setItem("token", JSON.stringify({"token": "'.$res->token.'" }))</script>';
            echo '<script>localStorage.setItem("username", JSON.stringify({"username": "'.$data->username.'" }))</script>';
            echo '<script>localStorage.setItem("id", JSON.stringify({"id": "'.$data->id.'" }))</script>';

            $boarding_url =  base_url() . 'index.php/boarding/teddies';
            redirect($boarding_url);
        }


texts:
I have the following piece of Perl script for updating an Oracle database. It's working perfectly fine, but I want to know how I can simplify this script.

use DBI;
my $dbh;
my $bad_form = "text.txt";

open (OUT, $bad_form) or die "Could not open $bad_form";
while (<OUT>){
   chomp $_;
   my ($item_id, $description, $form_id_1, $form_id_3) = split(/\|/, $_);

   my $new_form_id_1 = form_1($form_id_1);
   my $new_form_id_3 = form_3($form_id_3);

   if ( $new_form_id_1 ne 'null' ){
        my $sql = "update item_table set form_id_1 = '$new_form_id_1' where item_id = '$item_id'";
        my $item = $dbh->prepare($sql) or (log_error("Couldn't prepare statement: " . $dbh->errstr) and return 2);
        $item->execute() or (log_error("Couldn't execute statement: " . $item->errstr) and return 2);
   }else{
        $form_id_1 = "correct value";
        $new_form_id_1 = "no updated";
}

   if ( $new_form_id_3 ne 'null' ){
        my $sql = "update item_table set form_id_3 = '$new_form_id_3' where item_id = '$item_id'";
        my $item = $dbh->prepare($sql) or (log_error("Couldn't prepare statement: " . $dbh->errstr) and return 2);
        $item->execute() or (log_error("Couldn't execute statement: " . $item->errstr) and return 2);

   }else{
        $form_id_3 = "correct value";
        $new_form_id_3 = "no updated";
   }
}


texts: Particle in Cell: efficient data structure handling

texts:
I am building a simulation where you have 'Agents' distributed over a rather large landscape. Because the number of Agents is small, compared to the size of the landscape, I use the PIC approach where the landscape is divided into rather large cells and every cell can contain multiple agents - in contrast to a classical grid based approach. This should speed up spatial analysis.

I am asking whether there is a way to improve the code I came up with:

Agents contain an iterator to the node in the cell and a ptr to the cell containing the node

class Agent;

typedef std::list <Agent*> CELL;

class Agent {
  public:
  //...stuff...
    CELL::iterator cell_iter;
    CELL*cell_ptr;
};

class Grid {
  public:
    Grid(int dimx,int dimy,int cellsize);
    CELL *GetCell(double x,double y);
 private:
    std::vector <std::vector<CELL>> grid_;
    int dimx_,dimy_,cellsize_,ncellx_,ncelly_;
};

To add a new individual:

std::list <Agent> population;
//..stuff...
Agent seed(pos_x,pos_y,seed_type,10.1); // create a local agent
population.push_back(std::move(seed));
Agent *agent=&population.back()
CELL *cell=GetCell(agent->x_,agent->y_); // get the cell for the agents pos
cell->push_back(agent); // add the agents ptr to the cell
agent->cell_ptr=cell; // save the agents cell to the agent
agent->cell_iter=--cell->end(); // save an iterator to the actual node

To delete an individual

auto iter=population.begin();
//...stuff...
(*iter).cell_ptr->erase((*iter).cell_iter); // erase the ptr to the agent from the cell
iter=population.erase(iter);


texts: Refactored calls to an api using Ramda.js

texts:
This is the original code for accessing a service endpoint that returns information about a product. The exported methods of this module each take a single param of "id" and returns a Promise.

I've attempted to refactor this code using curry and compose with ramda.js and would like feedback and possibly a better solution.

Original:

import {client} from '@core/GraphQLProvider';
import {CatalogItem, CatalogItemFullDetail, CatalogItemAccessories} from './query.graphql';

const locale = 'en-US';

const formatSku = id => /-/.test( id ) ? id : id + '-';

const fetch = async ( query ) => {
    const resp = await client.query( query );
    return resp.data.product;
};

export default {

    async getDetail ( id ) {
        const skuValues = formatSku( id );

        return fetch( {
            query: CatalogItem,
            variables: {skuValues, locale}
        } );
    },

    async getFullDetail ( id ) {
        const skuValues = formatSku( id );

        return fetch( {
            query: CatalogItemFullDetail,
            variables: {skuValues, locale}
        } );
    },

    async getPurchaseDetail ( id ) {
        const skuValues = formatSku( id );

        return fetch( {
            query: CatalogItem,
            variables: {skuValues, locale, withPrice: true}
        } );
    },

    async getDetailWithAccessories ( id ) {
        const skuValues = formatSku( id );

        return fetch( {
            query: CatalogItem,
            variables: {skuValues, locale, withAccessories: true}
        } );
    },

    async getAccessories ( id ) {
        const skuValues = formatSku( id );

        const resp = await client.query( {
            query: CatalogItemAccessories,
            variables: {skuValues, locale}
        } );

        return resp.data.product.accessories;
    }
};

Refactored:

import {client} from '@core/GraphQLProvider';
import {CatalogItem, CatalogItemFullDetail, CatalogItemAccessories} from './query.graphql';
import curry from 'ramda/src/curry';
import compose from 'ramda/src/compose';
import pCompose from 'ramda/src/composeP';
import prop from 'ramda/src/prop';

const locale = 'en-US';
const DEFAULT_OPTIONS = {
    withAccessories: false,
    withPrice: false
};
const formatSku = id => /-/.test( id ) ? id : id + '-';
const buildQuery = curry(
    ( locale, query, withOptions, skuValues ) => ({
            query,
        variables: {
            locale,
            ...withOptions,
            skuValues: formatSku( skuValues )
        }
    })
);
const buildQueryWithLocale = buildQuery( locale );
const queryProp = propName => pCompose( prop( propName ), prop( 'data' ), client.query );
const queryProductWithOptions = curry( compose( queryProp( 'product' ), buildQueryWithLocale ) );

export default {
    getDetail: queryProductWithOptions( CatalogItem, DEFAULT_OPTIONS ),
    getDetailWithAccessories: queryProductWithOptions( CatalogItem, {withAccessories: true} ),
    getPurchaseDetail: queryProductWithOptions( CatalogItem, {withPrice: true} ),
    getFullDetail: queryProductWithOptions( CatalogItemFullDetail, DEFAULT_OPTIONS ),
    getFullDetailWithAccessories: queryProductWithOptions( CatalogItemFullDetail, {withAccessories: true} ),

    async getAccessories ( id ) {
        const product = await queryProductWithOptions( CatalogItemAccessories, DEFAULT_OPTIONS, id );
        return product.accessories;
    }
};


texts:
Create folder on ftp if possible.

public async Task<bool> CreateFolder(string path)
{
    FtpWebRequest ftpRequest = null;
    try
    {
        ftpRequest = ftpBuilder.Create(path, WebRequestMethods.Ftp.MakeDirectory);
        using (var ftpResponse = (FtpWebResponse)await ftpRequest.GetResponseAsync())
        using (var ftpStream = ftpResponse.GetResponseStream())
        {
            return true;
        }
    }
    catch
    {
        return false;
    }
}

This is my solution but I have two doubts

Is it ok in this case to have return statement in catch?
Is it ok to have just return true in using?


texts: PHP class design with methods requiring database access

texts:
I've been a procedural PHP programmer for a long time but I'm getting to learn OOP and would like some advice. I'm designing a class which currently is composed mainly of simple getters/setters, but I'm not quite sure if I'm designing my class in the best way possible.

The getters require accessing a database to pull the requested information, so I'm checking if a property has been set first before running the query which seems like a good idea to me but I'm not sure.

I think I could make use of DI by type hinting the $connect parameter and using a DAL but this is not a public facing API and we're never going to use a different database engine so I'm not sure it's worth the trouble. I'm using a proprietary database engine which has a bug preventing me using PDO and parametrised queries. I'm also not sure if I should be try/catching/throwing exceptions inside class methods.

Here is a sample of the code below, there are more methods/properties but they all follow the same basic structure. I would very much appreciate any and all commentary.

class Patient {
  // Database connector
  private $connect;
  protected $_connection;

  public $dmg_ID;
  public $LNK_ID;
  public $dailyLNK_ID;

  public function __construct($connect, $lnkid, $dlkid = NULL) {
      $this->_connection = $connect;
      unset($connect);

      // Patient requires a LNK_ID but not always a daily link ID
      $this->LNK_ID = $lnkid;

      if (!is_null($dlkid) && is_numeric($dlkid)) {
        $this->dailyLNK_ID = $dlkid;
      }
  }

  public function getDmgID() {

      if ($this->dmg_ID) return $this->dmg_ID;

      $sql = "SELECT lnk_dmgID FROM LINK WHERE lnk_ID=".$this->LNK_ID;
      try {
          $result = odbc_exec($this->_connection,$sql);
          if($result) {
              $dmgID = odbc_fetch_array($result);
          }
          else {
              throw new RuntimeException("Failed to connect.");
          }
      }
      catch (RuntimeException $e) {
          print("Exception caught: $e");
      }

      return $this->dmg_ID = $dmgID['LNK_DMGID'];
  }

  public function setDmgID() {

      if (!$this->dmg_ID) return false;

      $sql = "UPDATE LINK SET lnk_dmgID=".$this->dmg_ID." WHERE lnk_ID=".$this->LNK_ID;
      try {
          $result = odbc_exec($this->_connection,$sql);
          if(!$result) {
              throw new RuntimeException("Failed to connect.");
          }
      }
      catch (RuntimeException $e) {
          print("Exception caught: $e");
      }

      return true;
  }
...


texts: Build a time struct for current time in UTC

texts:
I'm learning about time structs. Without assigning either in code or input routines I want the current time. Please help me refactor this, if it should be.

This code just tries to make a time struct with the current UTC time. How am I doing?

// better_current_gmtime_struct_builder.c
// compile with :
// gcc -Wall -g better_current_time_struct_builder.c -o better_current_time_struct_builder

#include <time.h>
#include <stdio.h>

/* function declarations */
void print_struct_parts(struct tm* t);

int main()
{

    time_t now;

    /* set the time for now */
    now = time( NULL ); /* NULL is a control character */

    /* set up time ponter */
    struct tm *tp;
    tp = gmtime(&now);

    /* quick check of time expected */
    printf("%s\n", asctime(tp));

    /* assign the current time struct from the time pointer */
    struct tm t = *tp;

    /* print the parts */
    print_struct_parts(&t);
    return 0;
}

/* check the struct parts */
void print_struct_parts(struct tm* t)
{
    printf ("%i\n", t->tm_wday);
    printf ("%i\n", t->tm_mon);
    printf ("%i\n", t->tm_mday);
    printf ("%i\n", t->tm_hour);
    printf ("%i\n", t->tm_min);
    printf ("%i\n", t->tm_sec);
    printf ("%i\n", t->tm_year);
}


texts:
This code is for part of my first major contribution to open-source, for the socli project. The purpose is to allow the user to select a site from the stack exchange network to browse and fill two variables with the appropriate urls (used through the rest of the program). Since the stack exchange network is adding new sites all the time, I wanted to make it decently easy to update the stored list. Also, I'm lazy, and didn't want to manually create a dictionary =) So I use a text file with the list of sites copy-pasted into it and the code takes care of the rest.
Approach
The purpose of the code is to go through a text file named sites.txt filled with urls in a format like
https://codereview.stackexchange.com
https://physics.stackexchange.com

Taking the above, it would then produce a dictionary looking like
{'codereview':'https://codereview.stackexchange.com', 'physics':'https://physics.stackexchange.com'}

It would also print
Sites: codereview, physics

and allow the user to select one of the above, storing the url and a modified version of the url in a variable. I'd like to know if I've done this in the best possible way, and also get general feedback.
Code
import re
siteslst = {}
with open('sites.txt', 'r') as s:
    data = s.read()
    data = data.splitlines()
    for i in data:
        keyVal = re.search(r'(\w+)\.',str(i)).group(1)
        siteslst[str(keyVal)] = str(i)
testInput = siteslst.keys()
print('Sites: ', ', '.join(testInput), '\n')
validInput = False
while validInput == False:
    searchSite = input("which site would you like to search? ")
    if searchSite in testInput:
        url = siteslst[searchSite]
        urlSearch = siteslst[searchSite]+'/search?q='
        validInput = True
    else:
        validInput = False


texts: Extracting country data from HTML tables

texts:
I am trying to optimize/improve my coding skills in python

The rationale behind this code is to extract some data from files and store them in a dictionary.

I tried to comments lines to improve readability.
I suppose I may use functions or (x for x in list) in place of [x for x in list] at some point to improve performance.

Country=['usa','germany','spain','brazil','russia']#country list
Demofiles=os.listdir('E:/CtryData/capital/')#files locations
Incfiles=os.listdir('E:/CtryData/income/')#files locations

Append MissDataLst list if Country file has empty data:

MissDataLst=[]

for indices,ticker in enumerate(Country):
    if ticker.lower() not in (Demofiles or Incfiles):
        #file does not exist
        continue
    IncDirLocation='C:/CtryData/income/'+ticker[0].lower()
    CapitalDirLocation='C:/CtryData/capital/'+ticker[0].lower()
    if 'There is currently no data for this country' in (open(IncDirLocation).read() or open(CapitalDirLocation).read()):
        #file exist but no data
        MissDataLst.append(indices)

Append a data dictionnary with extracted data from files in the form of:

'country':
    {
    'investments':
            {2009:100,2010:150,2011:200},
    'Debt':
            {2009:1000,2010:1500,2011:2000},
    'gdp':
            {2009:10000,2010:15000,2011:20000}
    }

#empty dictionary to append with data
DataDic={}

for indices,ticker in enumerate(country):
    if indices in MissDataLst:
        continue
    if ticker.lower() not in (Demofiles or Incfiles):
        continue
    IncDirLocation='C:/CtryData/income/'+ticker[0].lower()
    inc_read=BeautifulSoup(open(IncDirLocation).read())
    #find existing tables
    tbl=inc_read.findAll('td',{'class':'td_genTable'})
    #extract tables title
    inc_titles=[x.findPrevious().getText() for x in tbl]
    if 'GDP' not in inc_titles:
        continue
    #replace (456) digit format by -456 format and clean empty cells: re.sub(r',|\$','',x.getText())) and re.sub('^0$','',x)
Gdp=[re.sub('\((.*)\)','-\\1',re.sub(r',|\$','',x.getText())) for x in inc_read.findAll('td',{'class':'td_genTable'})[inc_titles.index('GDP')].findNextSiblings()]
    #convert to integer if not empty
    Gdp=[int(x) for x in gdp if x]
    #################same process as above for debt and investments data#########
    capitalDirLocation='C:/CtryData/capital/'+ticker.lower()
    bs_read=BeautifulSoup(open(capitalDirLocation).read())
    tblbs=bs_read.findAll('td',{'class':'td_genTable'})
    #if no debt or investments data
    if tblbs==[]:
            continue
    bs_titles=[x.findPrevious().getText() for x in tblbs]
    if 'Debt' not in bs_titles:
            continue
    Years=[x.getText().split('/')[-1] for x in inc_read.body.findAll('th') if '/20' in x.getText()]
    Debt=[re.sub('\((.*)\)','-\\1',re.sub(r',|\$','',x.getText())) for x in bs_read.findAll('td',{'class':'td_genTable'})[bs_titles.index('Debt')].findNextSiblings()]
    #convert to integer if not empty
Debt=[int(x) for x in Debt if x]
 #replace (456) format by -456 format and clean empty cells: re.sub(r',|\$','',x.getText())) and re.sub('^0$','',x)
    Investments=[re.sub('\((.*)\)','-\\1',re.sub(r',|\$','',x.getText())) for x in bs_read.findAll('td',{'class':'td_genTable'})[bs_titles.index('Total investments')].findNextSiblings()]
    Investments=[re.sub('^0$','',x) for x in investments ]
    #append DataDic in the form:{'country':{'investments':{2009:100,2010:150,2011:200},'Debt':{2009:1000,2010:1500,2011:2000},'Gdp':{2009:10000,2010:15000,2011:20000}}
    DataDic[ticker]={'investments': {y:Investments[x] for x, y in enumerate(Years)},'Debt':{y:Debt[x] for x, y in enumerate(Years)},'gdp':{y:Gdp[x] for x, y in enumerate(Years)}}


texts: Find the smallest subarray with sum greater than a given value

texts:
Given some array, find the smallest subarray with a sum that is greater than a value given.

So for instance, given this array:

{1, -4, -45, 6, 0, 19, 16, 17}

and the give value of 51, the smallest subarray with a sum greater than 51 would be {19, 16, 17}

The idea is to use a window to scan over the elements, expanding it on the right and contracting it on the left as needed.

public class SmallestSubarray {

    static int[] smallestSub(int[] arr, int targetSum) {
        int winnerL = 0, winnerR = Integer.MAX_VALUE;
        int currentSum = 0;
        int leftI = 0;
        //widen the window from the right side
        for (int rightI = 0; rightI < arr.length; rightI++) {
            currentSum += arr[rightI];

            //handle negatives, collapse the window
            if (currentSum < 0) {
                //move L past R because R is going to increment next... otherwise left will be sitting on the wrong value
                leftI = rightI + 1;
                if (leftI == arr.length) {
                    return new int[0];
                }
                currentSum = 0;
                continue;
            }
            // now we've built up a sum greater than target.  trim it down if possible
            while (currentSum > targetSum && leftI <= rightI) {
                // if current window is smaller than the last smallest window
                if (rightI - leftI  < winnerR - winnerL) {
                    winnerL = leftI;
                    winnerR = rightI;
                }
                //chip away at current sum and shrink window from left.
                currentSum -= arr[leftI++];
            }
        }
        if (winnerR == Integer.MAX_VALUE) {
            return new int[0];
        }
        return Arrays.copyOfRange(arr, winnerL, winnerR +1);
    }

    public static void main(String[] args) {
        int[] arr2 = {1, -4, -45, 6, 0, 19, 16, 17};
        int[] result = smallestSub(arr2, 51);
        System.out.println("Arrays.toString(result) = " + Arrays.toString(result));
    }
}


texts:
Problem Statement

  Find the max sequence finder.

  findMaxSequence([3, 2, 3, 4, 2, 2, 4]);

  findMaxSequence([3, 5, 4, 6, 1, 2, 3, 6, 10, 32]);

  findMaxSequence([3, 2, 1]);

  Expected Output

  [ 2 , 3 , 4 ]

  [1, 2, 3, 6, 10, 32]

  no

Solution

            function findMaxSequence(array, start = -1, end = -1, i = 0, results=[]){
                if((array.length == 1) || (array.length == 0)){
                        return "[ " + array + " ]";
                }
                else if(i >= array.length-1){
                       if(start != -1){
                            results.push(array.slice(start, end+1));
                       }
                       if(results.length > 0){
                         results.sort(
                            function(a, b){
                                return a.length < b.length;
                            }
                         );
                         return "[ " + results[0].toString() + " ]";
                       }else{
                         return "no";
                       }
                }else if(array[i] < array[i+1]){
                       if (start == -1){
                            start = i;
                       }
                       return findMaxSequence(array, start, i+1, ++i, results);
                }else if(array[i] >= array[i+1]){
                      if(start != end){
                        results.push(array.slice(start, end+1))
                      }
                      return findMaxSequence(array, -1, -1, ++i, results);
                }

            }
            console.log(findMaxSequence([3,2,3,4,2,2,4]));
            console.log(findMaxSequence([3, 5, 4, 6, 1, 2, 3, 6, 10, 32]));
            console.log(findMaxSequence([3,2,1]));
            console.log(findMaxSequence([1]));
            console.log(findMaxSequence([2, 2, 2, 2]));
            console.log(findMaxSequence([1, 2, 2, 3, 3, 4]));

Actual output

[ 2,3,4 ]
[ 1,2,3,6,10,32 ]
no
[ 1 ]
no
[ 1,2 ]

A per the above solution, Did I understand the problem statement? Wrt two elements being equal in an array? Did I handle two equal size sequences correctly?
Can we make the code more elegant? I see lot of nested conditions, which makes it less readable.
Is it an elegant approach of using results array? Please let me know, if there is any better approach.

Note: Above problem is pulled from here. Tested on firefox browser, Chrome could not support default argument syntax


texts: Any recommendations to improve this logging framework? Or is it overkill?

texts:
So I've been kind of irritated with my logging recently as I find myself copying and pasting the same kinds of generic messages around to lots of different methods or retyping them ever so slightly differently (when they ought to be identical).

Hence, I created this kind of framework:

public class Log {

// other logging utility methods truncated

    public enum Message {

        //Main
        PROGRAM_EXIT ("Exiting program, return code = {0}"),
        THREAD_INTERRUPTED ("Thread interrupted while {0}"),
        FATAL_TERMINATING_ERROR ("Fatal exception thrown through entire stack: {0}"),
        SHUTDOWN_HOOK_EXCEPTION ("Exception while attempting to gracefully exit: {0}"),
        IO_READ_ATTEMPT ("Attempting to read file: {0}"),
        IO_READ_FAILURE ("Unable to read from file: {0}"),
        IO_WRITE_ATTEMPT ("Attempting to write to file: {0}"),
        IO_WRITE_FAILURE ("Unable to write to file: {0}"),
        IOEXCEPTION ("IOException while {0} to {1} : {2}"),

        private final String text;

        private Message(String text) {
            this.text = text;
        }

            @Override
            public String toString() {
                return text;
            }

        public String format(Object ... args) {
            String returnValue = toString();
            for(int i = 0; i < args.length; i++) {
                String placeholder = "{" + i + "}";
                if(!returnValue.contains(placeholder)) {
                    LOGGER.error("Too many arguments supplied to generateMessage() from " + getCallingMethodName());
                    LOGGER.error(" -- " + name());
                    break;
                }
                returnValue = returnValue.replace("{" + i + "}", args[i] == null ? "null" : args[i].toString());
            }
            return returnValue;
        }
    }
}

It's then invoked like the following:

private static final String FILE_PATH = "resources/something.txt";
//...
LOGGER.error(Log.Message.IO_READ_FAILURE.format(FILE_PATH));

... which would log ...

  Unable to read from file: resources/something.txt

It all works fine, but it feels a little too verbose at times for what I'm trying to accomplish, like I've tacked on a bit too many nuts and bolts.  Like I've gone deer hunting with a .50 cal or something.

Any suggestions to improve this?  The same messages are used redundantly in several places, so I am seeing some value out of it, but I'm not sure if there's a good way to make this still more clean or otherwise accomplish what I'm trying to do in a more succinct way.

If it's relevant, I'm using log4j.


texts: Calculate mean of vector primitive numerical values generically

texts:
I'm trying to write a generic mean function for all values within an Vector of generic numerical primitive type.

Could the following implementation be possible more efficient, yet still generic enough for all the possible numerical primitives?

Is the num crate really needed?

extern crate num;
use std::iter::Sum;
use std::ops::Div;

fn mean<'a, T, U>(values: &'a [T]) -> U::Output
    where T: Sum<&'a T> + num::ToPrimitive,
          U: num::NumCast + Div
{
    U::from(values.iter().sum::<T>()).unwrap() / U::from(values.len()).unwrap()
}

fn main() {
    let arr_i32: Vec<i32> = vec![1, 2, 5];
    let arr_f32: Vec<f32> = vec![1.1, 2.2, 5.5];
    println!("Mean of ({:?}) is: {}", arr_i32, mean::<_, f32>(&arr_i32));
    println!("Mean of ({:?}) is: {}", arr_f32, mean::<_, f32>(&arr_f32));
}


texts: How to sort two array of objects using Underscore.js?

texts:
I am sorting 2 arrays of object like this, but I know this is very bad.  Any good approach, like using each method like so? ( I tried, but using each, I am unable to return the object )

var O1 = [{'name':'one'}, {'name':'two'}, {'name':'three'}, {'name':'four'}, {'name':'five'}, {'name':'six'}];
var O2 = [{'name':'rat'}, {'name':'cat'}, {'name':'lion'}, {'name':'tiger'}, {'name':'dog'}, {'name':'horse'}];

var sorted1 = _.sortBy(O1, function(item){
    return item.name;
})

var sorted2 = _.sortBy(O2, function(item){
    return item.name;
})

console.log(sorted1, sorted2);

Demo


texts:
Building out a React component that is supposed to hold the following information and display it in a feed-like page. The idea is to later map over the individual entries in an array.

Author
Timestamp
Message Title
Message body

Currently, I have the following code in one file (BuildingUpdateBox.js):

import React from 'react';
import "./BuildingUpdateBox.css"

const BuildingUpdateBoxHeader = (props) => {
const author = props.author ? `Author: ${props.author}` : 'No Author'
return (

    {author}
    Timestamp: {props.timestamp}

)
}

const BuildingUpdateBoxBody = (props) => {
return (

{props.title}

{props.message}

)
}

const BuildingUpdateBox = (props) => {
return (

      <BuildingUpdateBoxHeader
        author={props.content.author}
        timestamp={props.content.timestamp}
      />
      <BuildingUpdateBoxBody
        title={props.content.title}
        message={props.content.message}
      />

)
}

export default BuildingUpdateBox;

And in App.js (I currently use create-react-app):

const message = {
  author: 'Joe Smith',
  timestamp: '2018/12/22',
  title: 'Broken Heater',
  message: 'Dear tenants, we will have a plumber onsite tomorrow, who will replace the broken boiler. We apologize for the inconvenience. If you have any questions, please feel free to reach out to 123-456-7890.'
};

class App extends Component {
  render() {
    return (

        <BuildingUpdateBox content={message} />

    );
  }
}

I'm looking to hear if I should:

Place the functional components into their own files (with reasoning)
Even use 3 separate functions, since I don't ever see the Header or Body being used without the Box and vice versa
Do anything with the way I import the CSS


texts: Calculating "element-wise" the angles between two lists of vectors

texts:
Let's say you have two lists of vectors:

v1s = [a, b, c]

v2s = [d, e, f]

I am interested in generating the following result:

angles = [angleBetween(a, d), angleBetween(b, e), angleBetween(c, f)]

Here is my function to do this (it uses vector dot products in order to calculate the angles):

import numpy as np

def findAnglesBetweenTwoVectors(v1s, v2s):
    dot_v1_v2 = np.einsum('ij,ij->i', v1s, v2s)
    dot_v1_v1 = np.einsum('ij,ij->i', v1s, v1s)
    dot_v2_v2 = np.einsum('ij,ij->i', v2s, v2s)

    return np.arccos(dot_v1_v2/(np.sqrt(dot_v1_v1)*np.sqrt(dot_v2_v2)))

I call this function a lot, so optimizing it would be very helpful for me.  Is this possible?


texts:
I have recently started studying JavaScript, nodeJS, and reactJS on the front-end, and I have some questions about best practices to apply in this JavaScript world. I would like to ask for opinions regarding how I could improve my code.
Starting with an example: I have 2 functions, with different ways of handling promises
Here I have a route to add a user:
 addUsers(req,res,next) {
    try {
        const {name,email,login} = req.body;
        User.existLogin(req.body.login)
        .then(async result => {
            if(!result){
                const password = await bcrypt.hashSync(req.body.password, 10);
                User.create({
                    name, email, login, password }).then(result => {
                    res.status(201).json({Results: result.dataValues})
                })
            }else{
                return res.status(409).json({message: 'Login already exists'});
            }
        })
    } catch (error) {
        res.status(500).json({error: error})
    }
}

And here I have another function to login:
async login(req,res){
    const  user  = await User.existLogin(req.body.login);
    if (!user) { return res.status(400).json({result: 'Login is wrong '});}
    const isPassword = await User.isPassword(user.dataValues.password, req.body.password);
    if (!isPassword) { return res.status(400).json({result: 'Password is wrong '}); }
    const jwt = auth.signjwt(auth.payload(user));
    console.log(jwt);
    res.status(200);
    res.json(jwt);
}

Looking at this the login function seems to me to be cleaner, but I have doubts if really yours I could improve in one of two (I follow different logics to do both).
I have an auth folder, where I export functions, such as my payload, my sign, my middlware to validate my jwt, but I don't know if this is a correct decision.
const jwt = require('jsonwebtoken');
const User = require('../models/User')
const config= require('../config/dbconfig');
const moment = require('moment');

module.exports = {
    signjwt (payload) {
        return jwt.sign(payload,
            config.secretToken
                   )
    },
    payload (usuario) {
        return {
            sub: usuario.id,
            name: usuario.nome,
            email: usuario.email,
            login: usuario.username,
            admin: true,
            iat: Math.floor(moment.now()/1000), // Timestamp de hoje
            exp: moment().add(10, 'minutes').unix() // Validade de 2 dias
        }
    },
    async auth(req,res,next){
        const token = req.header('Authorization');
        console.log(token);
        if(!token) return res.status(401).json('Unauthorized');
        try{
            const decoded = jwt.verify(token,config.secretToken);
            const user = await User.findByPk(decoded.sub);
            console.log(user);
            if(!user){
                return res.status(404).json('User not Found');
            }
            res.json(user);
            next();
        }catch(error){
            console.error(error);
            res.status(400).json('Invalid Token');
        }
    }
}


texts: Calculate highscores based on sales data

texts:
The background is my question is SO How to create a list of totals for durations?
where I found a recursive solution that I want to review. I could not test it for higher levels than 1 but to the best of my knowledge it should work.

What I'm trying to do is calculate a kind of "highscore", i.e. a level based on sales during the two historical months where sales where the most. So I find the oldest purchase, use the helper methods to calculate the bonus for that period and then check to see whether that period is the entitling to a level upgrade. It's basically going through all the historical orders.

Is my recursion written correctly?

def level(self):
    startdate = model.Order.all().filter('status =', 'PAID'
            ).filter('distributor_id =',
                     self._key.id()).get().created.date()
    last_day_nextmonth = startdate + relativedelta(months=2) \
        - timedelta(days=1)
    total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)
    if total >= 125:
        level = 5
    elif total >= 75:
        level = 4
    elif total >= 25:
        level = 3
    elif total >= 2:
        level = 2
    else:
        level = 1
    return self.levelHelp(level, last_day_nextmonth + timedelta(days=1))

def levelHelp(self, level, startdate):

    last_day_nextmonth = startdate + relativedelta(months=2) \
        - timedelta(days=1)
    total = self.personal_silver(startdate, last_day_nextmonth) + self.non_manager_silver(startdate, last_day_nextmonth)
    if total >= 125:
        newlevel = 5
    elif total >= 75:
        newlevel = 4
    elif total >= 25:
        newlevel = 3
    elif total >= 2:
        newlevel = 2
    else:
        newlevel = 1

    maxlevel = level if level > newlevel else newlevel

    nextstart = last_day_nextmonth + timedelta(days=1)
    now = datetime.now().date()
    if nextstart > now: #next start in is the future
        return maxlevel
    else: return self.levelHelp(maxlevel, nextstart)

The helper functions are

def non_manager_silver(self, startdate, enddate):
    silver = 0
    timeline = date(startdate.year, startdate.month, 1)
    downline = User.query(User.sponsor == self._key).fetch()
    distributor = self
    while distributor.has_downline():
        downline = User.query(User.sponsor
                              == distributor.key).fetch()
        for person in downline:
            orders = model.Order.all().filter('distributor_id =',
                    person.key.id()).filter('created >',
                    startdate).filter('created <',
                    enddate).filter('status =', 'PAID'
                    ).fetch(999999)
            for order in orders:
                for (idx, item) in enumerate(order.items):
                    purchase = model.Item.get_by_id(long(item.id()))
                    amount = int(order.amounts[idx])
                    silver = silver + amount * purchase.silver \
                        / 1000.000
            distributor = person
    return silver

def personal_silver(self, startdate, enddate):
    p_silver = 0
    timeline = date(startdate.year, startdate.month, 1)  # first day of month
    orders = model.Order.all().filter('distributor_id =',
            self._key.id()).filter('created >',
            timeline).filter('created <', enddate).filter('status ='
            , 'PAID').fetch(999999)
    for order in orders:
        for (idx, item) in enumerate(order.items):
            purchase = model.Item.get_by_id(long(item.id()))
            amount = int(order.amounts[idx])
            p_silver = p_silver + amount * purchase.silver \
                / 1000.000  # remember amounts
    return p_silver


texts: Kotlin extension functions with null checks

texts:
Kotlin defines extension functions like also but they are not null checked. That's fine because you might not need the check. In case you do though, do you see any issue with the solution below?

inline fun <T> T?.ifNotNull(block: (T) -> Unit): T? {
    return this?.also {
        block(it)
    }
}

inline fun <T> T?.otherwise(block: () -> Unit) {
    this?: run {
        block()
    }
}

fun main(args: Array<String>) {
    "it".ifNotNull {
        println("You can use $it")
    }.otherwise {
        // will not happen
    }

    null.ifNotNull {
        // will not happen
    }.otherwise {
        println("You don't see it")
    }

}


texts:
I am doing Java exercises from HackerRank.com and bit confused about this problem.

Here is my code that pass the test case.

import java.io.*;
import java.util.*;

public class Solution {

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

     // String input = in.nextLine();

        int counter = 1;
        while (in.hasNext()) {
            System.out.println(counter + " " + in.nextLine());
            counter++;
        }
    }
}

We are suppose to print number of lines of input from Scanner, until line of input contains a empty String. The line of inputs are automatically generated by the HackerRank website. For test case, three lines of input will be generated.

  Test case input

    Hello World

    I am a file

    Read me until end-of-file.

  Expected output

    1 Hello World

    2 I am a file

    3 Read me until end-of-file.

However, whenever I uncomment out the

String input = in.nextLine();

My output only shows first 2 lines instead of all 3. I thought I need that line of code in order to type a line of input. For example,

Scanner sc = new Scanner(System.in);
System.out.println("Enter your name.");
String name = sc.nextLine();

Also when I write

String input = in.next();

instead of nextLine() code, my output shows all 3 lines but first word "Hello" is omitted.

  in.next(); output

    1   World

    2 I am a file

    3 Read me until end-of-file.

What I want to know is why I don't need String input = in.nextLine(); to pass the test case.


texts: Python classes to grab HTTP response from website entities

texts:
I am trying to implement a parent WebContent class and child classes to grab HTTP responses from the actual website entities. There are highlevel codes below and I am wondering what are people's perspectives in terms of the neatest way to implement this in a OOP manner.

import requests
from onelogin.api.client import OneLoginClient

class WebContent(object):

    def __init__(self, client_id, client_secret, login, password, sub_domain, app_id, app_url):

        self.client_id = client_id
        self.client_secret = client_secret
        self.app_id = app_id
        self.app_url = app_url
        self.login = login
        self.password = password
        self.sub_domain = sub_domain

    def _login(self):
        client = OneLoginClient(self.client_id, self.client_secret)
        saml = client.get_saml_assertion(self.login,
                                         self.password,
                                         self.app_id,
                                         self.sub_domain)
        saml_data = saml.saml_response

        session = requests.Session()
        saml_payload = {'SAMLResponse': saml_data}
        session.post("{}/sso/response".format(self.app_url), saml_payload)
        return session

    def get_content(self, endpoint, time_out=30):
        if endpoint:
            session = self._login()
            result = session.get(endpoint, timeout=time_out)
            session.close()
            return result.content

class WebMarketingContent(WebContent):
    def get_endpoint(self, entity_id):
        base_url = "{app_url}/{entity_id}?{query_params}"
        params = '&entity_id={}'.format(entity_id)
        return base_url.format(app_url=self.app_url, query_params=params)

class WebEducationContent(WebContent):
    def get_endpoint(self, entity_id):
        base_url = "{app_url}/category/adhoc_element/{entity_id}?{query_params}"
        params = '&entity_id={}'.format(entity_id)
        return base_url.format(app_url=self.app_url, query_params=params)

if __name__ == '__main__':
    web_marketing_content = WebMarketingContent('client_id',
                                                'client_secret',
                                                'email',
                                                'password',
                                                'sub_domain',
                                                'app_id',
                                                'app_url')

    endpoint = web_marketing_content.get_endpoint(123)
    result = web_marketing_content.get_content(endpoint)


texts:
I've implemented the GroupBy extension method for IEnumerable<T> type as an excersise to deep a little more into LINQ.

What do you think about the source code?

Code:

static IEnumerable<IGrouping<TKey,TElement>> GroupBy<TKey,TElement>(this IEnumerable<TElement> source, Func<TElement,TKey> keySelector)
{
    //Grouping elements in the dictionary according to the criteria
    var dict = new Dictionary<TKey, List<TElement>>();

    //Filling the dictionary. It will contain: [Key -> List<Values>]
    foreach (var x in source)
    {
        var key = keySelector(x);
        if (dict.Keys.Contains(key))
        {
            dict[key].Add(x);
        }
        else
        {
            dict.Add(key, new List<TElement> { x });
        }
    }

    //For each group...
    foreach (var x in dict)
    {
        yield return new Grouping<TKey, TElement>(x.Key, x.Value);
    }
}

class Grouping<TKey, TElement> : IGrouping<TKey, TElement>
{
    private TKey _key;
    private IEnumerable<TElement> _elements;

    public Grouping(TKey key, IEnumerable<TElement> elements)
    {
        _key = key;
        _elements = elements;
    }

    public IEnumerator<TElement> GetEnumerator()
    {
        return _elements.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public TKey Key
    {
        get { return _key; }
    }
}


texts:
I wanted to take a stab at implementing a binary search, and here's what I came up with. Is there anything I could have done better, from  a code clarity perspective, or code optimization perspective? Any and all criticism would be appreciated:

import random
# implement a binary search

def binary_search(alist, item):
    first = 0
    last = len(alist)-1
    found = False
    midpoint = None
    while True:
        midpoint = first + ((last-first) // 2)
        if alist[midpoint] == item:
            return midpoint
        elif alist[midpoint] < item:
            first = midpoint
        elif alist[midpoint] > item:
            last = midpoint

def _create_search_criteria(cap=10000):
    # choose a target to search for
    choice = random.randrange(0, cap/2)
    # create some data full of random numbers
    data = [random.randrange(0, cap/2) for i in xrange(cap)]
    # ensure the choice is nowhere in the data
    data = [d for d in data if d != choice]
    # put a single of instance of choice back into the data
    data[random.randrange(0, cap)] = choice
    # sort the data
    data = sorted(data)
    return data, choice

def test_binary_search():
    data, choice = _create_search_criteria()
    print 'Searching for: ' + str(choice)
    index =  binary_search(data, choice)
    print 'Found it at index: ' + str(index)
    assert data[index] == choice

for x in xrange(1000):
    test_binary_search()


texts:
I am running through an app idea to help improve my knowledge of Javascript. The code attached performs the following:

Performs a regex on the input field to check it is value 0-9 If not,
it clears the field and shows a warning (Although this only seems to work on FF)
If it passes, updates the styles of the preview box on keyup
Adds the styles to a text area that the user can copy when selecting the
button

I am looking for suggestions where I can improve in terms of writing more efficient code. Or pointers where I have possibly used the wrong method to perform a task. One area where I struggled was getting the value of the input field.

This is the first stage for this application as in the near future I plan to add in the ability modify each corner.

Feedback is welcomed

"use strict"

const masterField = document.getElementById('masterField');
const box = document.getElementById('box');
const warn = document.getElementById('warn');
const styleSheet = document.getElementById('styleSheet');

const WARNING_TIME = 2000;
var warningTimer;

masterField.addEventListener('keyup', updateCss);

function updateCss() {
    let inputVal = this.value;
    console.log(this.value);
    const expCase = /[0-9]/;

    if (expCase.test(inputVal)) {
        box.style.borderRadius = inputVal + 'px';
        styleSheet.textContent = 'border-radius: ' + inputVal + 'px';
    } else {
        this.value = '';
        showWarning();
    }
}

function hidewarning() {
    warn.classList.add('hide-warning');
}

function showWarning() {
    clearTimeout(warningTimer);
    warningTimer = setTimeout(hidewarning, WARNING_TIME);
    warn.classList.remove('hide-warning');
}

function copyStyles() {
    styleSheet.select();
    document.execCommand('copy');
}
#box {
            width: 300px;
            height: 175px;
            background-color: red;
        }

        #warn {
            display: block;
        }

        #warn.hide-warning {
            display: none;
        }

        All Corners
        <input id="masterField" class="radius-field" type="number">
        Only numbers 0 - 9 are allowed

    <button onclick="copyStyles()">Copy Styles</button>

    <textarea id="styleSheet"></textarea>


texts:
This code snippet is about asking Windows for the highest possible execution priority. Basically, we have to ask for real-time priority class for the entire process, after which each thread has to ask for real-time thread priorities. However, since Windows Vista, whatever is the program that needs the real-time priority, it must be asked to be run in administrator privilege level.

The demonstration program I provide simply loops for 7 seconds. During that period, your system should be frozen (try pressing Caps Lock; should not switch the Caps Lock light). Also, if you put on some audio, the sound card will repeat its contents of the sound buffer over and over again.

rtprio.h:

#pragma once
#include <Windows.h>

BOOL RealTimePriorityClass()
{
    return SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
}

BOOL RealTimeThreadPriority()
{
    return SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
}

main.cpp:

#include <windows.h>
#include "rtprio.h"

static const DWORD dwInterval = 7000; // millseconds.

DWORD WINAPI ThreadProc(LPVOID lpParams);

int WINAPI WinMain(HINSTANCE hInst,
    HINSTANCE hPrev,
    LPSTR lpCmdLine,
    int nShowCmd)
{
    DWORD       i;
    DWORD       dwInitTicks;
    DWORD       dwCores;
    SYSTEM_INFO sysInfo;

    GetSystemInfo(&sysInfo);
    dwCores = sysInfo.dwNumberOfProcessors;

    // Ask real-time priority class for the entire process.
    RealTimePriorityClass();

    for (i = 0; i < dwCores - 1; i++)
    {
        CreateThread(NULL,
                     0,
                     ThreadProc,
                     NULL,
                     0,
                     NULL);
    }

    RealTimeThreadPriority();

    dwInitTicks = GetTickCount();

    while (GetTickCount() - dwInitTicks < dwInterval);

    return 0;
}

DWORD WINAPI ThreadProc(LPVOID lpParams)
{
    // Ask for real-time priority for this thread.
    RealTimeThreadPriority();

    // Freeze the system for dwInterval milliseconds.
    while (TRUE) {}

    return 0;
}


texts: Soccer winning probabilies from ELO strength indicator

texts:
What can I do to improve this function, which calculates the win expectancy of a soccer team, given their strength:

def winning_prob(first, second, first_at_home=False, second_at_home=False):
    """ Return winning probability, given ELO ratings of two soccer teams

    Args:
        first: ELO rating of first team
        second: ELO rating of second team
        first_at_home: is first team playing at home?
        second_at_home: is second team playing at home?

    Returns:
        Winning probability of first team against second team
    """
    if first_at_home:
        first = first + 100
    if second_at_home:
        second = second + 100

    difference = (first - second) / 400.0
    return 1.0 / (10**(-difference) + 1.0)

Especially the two boolean switches look clunky to me, but the explanation is simpler that way. What improvements do you see?


texts: Iterating pattern (1-10 then 10-1) with only 1 loop

texts:
I want to obtain the following output:

1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10

The code am running is as follows:

#include <stdio.h>

int main(void) {
    int i=1,flag=0,lines=0;  //0 for forward, 1 for reverse
    while(i!=0 && lines<3){
        if(!flag){
            printf("%d ",i);
            if(i==10){
                flag=1;
                printf("\n");
                lines++;
            }
            else
                i++;
        }
        else if(flag){
            printf("%d ",i);
            if(i==1){
                lines++;
                flag=0;
                printf("\n");
            }
            else
                i--;
         }
    }
    return 0;
}

Am getting the desired output from the above code but not sure if it's an optimal code. Any other method/suggestion? Considering unlimited space but time complexity should be kept minimum.

Condition: Use only one loop


texts:
The task

is taken from leetcode

  Given a non-empty array of digits representing a non-negative integer,
  plus one to the integer.

  The digits are stored such that the most significant digit is at the
  head of the list, and each element in the array contain a single
  digit.

  You may assume the integer does not contain any leading zero, except
  the number 0 itself.

  Example 1:

  Input: [1,2,3]

  Output: [1,2,4]

  Explanation: The array represents the integer 123.

  Example 2:

  Input: [4,3,2,1]

  Output: [4,3,2,2]

  Explanation: The array represents the integer 4321.

My solution

/**
 * @param {number[]} digits
 * @return {number[]}
 */
var plusOne = function(digits) {
  let i = digits.length;
  let carry = 1;
  let tmp;
  const res = [];
  while(i > 0 || carry) {
    tmp = (--i >= 0 ? digits[i] : 0) + carry;
    carry = tmp / 10 | 0;
    res.unshift(tmp % 10);
  }
  return res;
};


texts: "Increment" a string of uppercase characters

texts:
Given a string of uppercase characters, return a string corresponding to the next item in the following series:

A, B, ..., Z, AA, AB, ..., AZ, BA, ..., BZ, ..., ZZ, AAA, ...

My code:

def increment_char(c):
    """
    Increment an uppercase character, returning 'A' if 'Z' is given
    """
    return chr(ord(c) + 1) if c != 'Z' else 'A'

def increment_str(s):
    lpart = s.rstrip('Z')
    if not lpart:  # s contains only 'Z'
        new_s = 'A' * (len(s) + 1)
    else:
        num_replacements = len(s) - len(lpart)
        new_s = lpart[:-1] + increment_char(lpart[-1])
        new_s += 'A' * num_replacements
    return new_s

Proof my code works according to the specification I gave above:

In [4]: increment_str('A')
Out[4]: 'B'

In [5]: increment_str('Z')
Out[5]: 'AA'

In [6]: increment_str('AA')
Out[6]: 'AB'

In [7]: increment_str('AZ')
Out[7]: 'BA'

In [8]: increment_str('ZZ')
Out[8]: 'AAA'

One thing I would ask you ignore is whether or not you think s and new_s (but only those two) are good names for identifiers, because they are not present in the real code (only the trimmed down version for here). All other suggestions, bug reports, etc., are welcome.


texts: Project Euler 10: Summation of primes in Go

texts:
Here is my first try at Google's Go language, trying to solve Project Euler Problem 10:

  The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

  Find the sum of all the primes below two million.

Any suggestions on the style and usage (best practice) of Go?

package main

import "fmt"

var primes = []uint64{2, 3}

func CheckIfIsNewPrime(number uint64) bool {
    check_if_number_is_new_prime := false
    var remainder uint64 = 0

    for i := range primes {
        remainder = number % primes[i]
        if remainder == 0 {
            check_if_number_is_new_prime = false
            break
        } else {
            check_if_number_is_new_prime = true
        }
    }
    return check_if_number_is_new_prime
}

func FindNewPrime() uint64 {
    for counter := primes[len(primes)-1]; ; counter += 2 {
        if CheckIfIsNewPrime(counter) == true {
            return counter
        }
    }
    return 0
}

func main() {
    limit := 2000000
    var sum uint64
    sum = 5

    for i := 2; i < limit; i++ {
        primes = append(primes, FindNewPrime())
        sum += primes[len(primes)-1]
    }

    fmt.Println("sum: ", sum)

}


texts: Extracting book information from a web page, with possible missing attributes

texts:
I'm just starting to code and I found a solution to first check if a div class exist before to try to get_text (and avoid an error if it doesn't). But the code doesn't looks really nice repeating the same parameters.

The code is working but if there is something I could learn, it would be better.

headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url_book, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')

book_info = soup.find_all('div', {'class': 'jr_pgContainer jr_itemDetail hReview-aggregate'})

for content in book_info:
    title = content.find('span', {'class': 'fn'}).get_text()
    if content.find('div', {'class': 'fieldRow jr_autorestr'}):
        author = content.find('div', {'class': 'fieldRow jr_autorestr'}).get_text().replace("Autore","")
    else:
        author = 'None'
    if content.find('div', {'class': 'fieldRow jr_editore'}):
        editor = content.find('div', {'class': 'fieldRow jr_editore'}).get_text().replace("Casa editrice","")
    else:
        editor = 'None'
    if content.find('div', {'class': 'fieldRow jr_narrstrcontinente'}):
        classification = content.find('div', {'class': 'fieldRow jr_narrstrcontinente'}).get_text().replace("Classificazione","")
    else:
        classification = 'None'
    if content.find('div', {'class': 'contentFulltext'}):
        description =  content.find('div', {'class': 'contentFulltext'}).get_text().replace("\t","").replace("\n","")
    else:
        description = 'None'
    if content.find('h4', {'class': 'jr_reviewTitle'}):
        title_review = content.find('h4', {'class': 'jr_reviewTitle'}).get_text()
    else:
        title_review = 'None'
    if content.find('div', {'class': 'jr_reviewComment'}):
        review = content.find('div', {'class': 'jr_reviewComment'}).get_text().replace("\t","").replace("\n\n","")
    else:
        review = 'None'

#CREATE AND PRINT DICTIONARY
book_detail = {'title: ': title, 'author: ': author, 'editor: ': editor, 'classification: ': classification, 'description: ': description, 'revew title: ': title_review, 'review: ': review }

for keys,values in book_detail.items():
    print(keys)
    print(values)
    print("************************************")


texts:
I am trying to create a dynamic Treeview in HTML using jQuery with following code,

Code with data and working example : https://jsfiddle.net/8jt0crv7/

var Menu = function(data) {
    this.data = data;
};

Menu.prototype.render = function(root) {
    var ul = $("

");
    var li = $("

");
    li.append($("", {
        href: this.data.url,
        text: this.data.title
    })).appendTo(ul);
    ul.appendTo(root);
    if (this.data.menu) {
        Menu.renderMenus(this.data.menu, $("

").appendTo(ul));
    }
};

Menu.renderMenus = function(menus, root) {
    $.each(menus, function(key, val) {
        var m = new Menu(val);
        m.render(root);
    });

console.time("Tree");

Menu.renderMenus(children, $("#container"));

console.timeEnd("Tree");

Some tests I ran on latest Chrome on Windows 10 are followings :

Tree: 129.593ms
Tree: 145.519ms
Tree: 179.777ms
Tree: 146.314ms
Tree: 174.272ms

Is there anyway I could improve performance of this code as I have trimmed it from a very big setup into example code. I am open to not use jQuery or any other plugin to make it faster.


texts:
I wrote an algorithm to solve this challenge but would love some feedback on its efficiency and, if you were an interviewer, what your opinion would be on my solution. I believe my time complexity is \$O(N)\$. Is this correct?

The Task:

  Given a sorted array nums, remove the duplicates in-place such that
  each element appear only once and return the new length.

  Do not allocate extra space for another array, you must do this by
  modifying the input array in-place with O(1) extra memory.

    Example:
    Given nums = [0,0,1,1,1,2,2,3,3,4]

    Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

    It doesn't matter what values are set in the array beyond the returned length.

My Solution:

def removeDuplicates(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    if(nums):
        IndFirstKind = IndCompare = 0
        lengthArray = len(nums)
        while(IndCompare < lengthArray):
            if nums[IndFirstKind] == nums[IndCompare]:
                IndCompare = IndCompare + 1
            else:
                if(IndFirstKind + 1 != IndCompare):
                    temp = nums[IndCompare]
                    nums[IndCompare] = nums[IndFirstKind + 1]
                    nums[IndFirstKind + 1]= temp
                IndFirstKind = IndFirstKind +1
                IndCompare = IndCompare + 1
        return IndFirstKind + 1
    return 0


texts: Calculating the distance between one point, and many others

texts:
In my program, I have entities that I call "blobs", because they have a blobby shape. Blobs are polygons. If I have two blobs, then their information array would look like:

>>> blobs
np.array([ [ [x1, y1], [x2, y2], [x3, y3] ], [ [x1, y1], [x2, y2], [x3, y3] ] ])

Each entry along axis 0 represents one blob. Each entry along axis 2 represents the x,y coordinates of the vertex of a blob. In the above case, there are 2 blobs, each with three vertices.

There could be other information in each

We can assume that all blobs will always have the same number of vertices.

I sometimes need to find which blobs are within a certain distance from another blob.

Here are the two functions I use:

def returnBlobIndicesOfRelevantBlobs(minimumDistanceFromFocusVertex, blobs, focusVertexBlobIndex, focusVertexIndex):
    focusVertexCoords = blobs[focusVertexBlobIndex, focusVertexIndex, :2]

    # get the coordinate of the zeroth vertex for all blobs
    vertexCoordsForAllRelevantBlobs = blobs[:, 0, :2]

    distanceVectors = (vertexCoordsForAllRelevantBlobs - focusVertexCoords)
    distances = np.sqrt(np.einsum('ij,ij->i', distanceVectors, distanceVectors))

    mask = (distances <= minimumDistanceFromFocusVertex)
    return np.arange(len(blobs))[mask]

def returnBlobVertexIndicesOfRelevantBlobs(minimumDistanceFromFocusVertex, blobs, focusVertexBlobIndex, focusVertexIndex):
    # trying to reduce the number of calculations by only executing calculations on the closest blobs
    relevantBlobIndices = returnBlobIndicesOfRelevantBlobs(4*minimumDistanceFromFocusVertex, blobs, focusVertexBlobIndex, focusVertexIndex)

    # can the generation of this list be improved perhaps?
    relevantBlobVertexIndices = np.array(list(itertools.product(relevantBlobIndices, range(len(blobs[0])))))

    focusVertexCoords = blobs[focusVertexBlobIndex, focusVertexIndex, :2]

    # can the generation of this list be improved perhaps?
    blobVertexCoords = np.array([blobs[x[0], x[1], :2] for x in relevantBlobVertexIndices ])

    distanceVectors = (blobVertexCoords - focusVertexCoords )
    distances = np.sqrt(np.einsum('ij,ij->i', distanceVectors, distanceVectors))

    mask = (distances <= minimumDistanceFromFocusVertex)
    return relevantBlobVertexIndices[mask]

What improvements could I make?


texts:
I am trying to implement a live chat for my websites visitors. I am currently using a PHP script that processes in background and that is called by AJAX. I am not familiar with sockets and node.js that also allow to create a live chat so I tried to make one longpolling-like code upon my possibilities. What I am hoping for is to hear your ideas about this code, how I can improve it and what are the pros and cons for using my code.

PHP script (used for getting all the latest messages):

require ($_SERVER['DOCUMENT_ROOT'].'/includes/config.php');
$time = $_POST['time'];
$x = 0;
$allowloop = true;
while (($x < 99) && ($allowloop))
{
    if ($time == 0)
    {
        $query = mysqli_query($con, 'SELECT * FROM (SELECT * FROM chat_messages WHERE send_time > "'.$time.'" ORDER BY chat_message_id DESC LIMIT 30) T1 ORDER BY chat_message_id ASC');
    } else {
        $query = mysqli_query($con, 'SELECT * FROM chat_messages WHERE send_time > "'.$time.'"');
    }

    if ((!$query) && ($time == 0))
    {
        $allowloop = false;
    } elseif (mysqli_num_rows($query) == 0) {
        usleep(200000);
        $x = $x + 1;
    } else {
        $allowloop = false;
    }
}

if (!$allowloop)
{
    while ($messages = mysqli_fetch_assoc($query))
    {
        echo
    '

'.$messages['chat_message_text'].'

                    '.date('G:i:s', $messages['send_time']).'
                    '.$messages['send_time'].'

    ';
    }
}
}

JS function that calls the code above in the background:

$('#world_chat_input').focus();
var time = 0;
var data = '';
(function chat_get() {
    time = $('table#w_messages_t tr:last td#time').html();
    data = {time: time};
    $.ajax({
        type: 'POST',
        url: '/guild/character/guild/home/chat_get.php',
        data: data,
        async: true,
        success: function (data) {
            $('#w_messages_t tbody').append(data);
            if (data) {
                $('#w_m_table_wrap').animate({
                    scrollTop: $('#w_m_table_wrap').prop('scrollHeight')
                }, 1000);
            }
            setTimeout(chat_get);
        }
    });
})();

HTML chat table:

            Welcome to World chat	0


texts: Hamming distance between numbers in JavaScript

texts:
In Leetcode it states that my runtime is only faster than 38% all of submitted JavaScript solutions. Is there anything I can change to make it more efficient?

/**
 * @param {number} x
 * @param {number} y
 * @return {number}
 */
var hammingDistance = function(x, y) {
    var resultStr =( x^y);
    let count =0;
    while(resultStr>0){
       resultStr =(resultStr&resultStr-1) ;
       count++;
    }
     return count;
};


texts: Method to replace all spaces in a String with '%20'

texts:
Problem statement (extracted from cracking the coding interview):

Write a method to replace all spaces in a string with'%20'. You may assume that
the string has sufficient space at the end of the string to hold the additional
characters, and that you are given the "true" length of the string. (Note: if implementing
in Java, please use a character array so that you can perform this operation
in place.)

EXAMPLE
Input: "Mr John Smith

Output: "Mr%20Dohn%20Smith"

My Solution:

public class InterviewMain {

    public static void main(String[] args){

        //Q 1.4
        String str = "Example String with spaces           ";
        replaceSpaces(str);
    }

    public static void replaceSpaces(String str){

        int trueLength = getTrueLength(str);

        char[] strChar = str.toCharArray();
        int spaceCount = 0;
        int finalLength;

        //count the number of spaces in the original string
        for (int i=0; i<trueLength; i++){
            if (strChar[i]== ' ')spaceCount++;
        }

        //get the length of final char array
        finalLength = trueLength + spaceCount*2;
        char[] finalArr = new char[finalLength];

        //update final array here
        int spaces = 0;
        char temp;
        int index;

        for (int i=0; i < trueLength; i++){
            temp = strChar[i];

            if (temp==' '){
                finalArr[getInsertIndex(i,spaces)]= '%';
                finalArr[getInsertIndex(i+1,spaces)] = '2';
                finalArr[getInsertIndex(i+2,spaces)] = '0';
                spaces++;
                continue;
            }

            index = getInsertIndex(i,spaces);
            finalArr[index] = temp;
        }

        //print results here
        for (int i=0; i < finalLength; i++){
            System.out.print(finalArr[i]);
        }
    }

    private static int getTrueLength(String str) {
        int count=0;
        int length = str.length();
        char[] strChar = str.toCharArray();

        //backtrack from end of string to count padding
        for (int i=length-1; i >=0; i--){
            if (strChar[i]!= ' ')break;
            count++;
        }
        return length-count;
    }

    private static int getInsertIndex(int i, int spaces){
        return (i + spaces*2);
    }
}

I was wondering if someone could review this and point out what I have done right and where I can improve upon. Thank you


texts: PHP function to obtain model_name from Namespace\To\ModelName

texts:
Would there be a more clear/efficient way to write

public function getModelName()
{
    return substr(strtolower(substr(strrchr(preg_replace('/(?<!\ )[A-Z]/', '_$0', __CLASS__), "\\"), 1)), 1);
}

for example:

__CLASS__: Namespace\To\SettingOption

Output: setting_option


texts: C++ Solution for ProjectEuler Problem #5

texts:
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Is there a more elegant solution in C++?

#include <iostream>
using namespace std;

int main(){
    long long num = 1;
    int divMin = 1;
    int divMax = 20;
    int tempDivMax = divMax;

    while(true){
        if(num % tempDivMax == 0)
        {
            tempDivMax--;
            if(tempDivMax == divMin){
                cout << num << endl;
                break;
            }
        }else{
            tempDivMax = divMax;
            num++;
        }
    }
    return 0;
}


texts: merge list of strings into one sorted string

texts:
So I was tasked the following:

  Given a list of strings, output a sorted string that consists of all
  lowercase characters  (a-z) from each string in the list.

  Example

  [aba, xz] -> aabxz

I tried this:

from collections import Counter
from string import ascii_lowercase
def merge(strings):
    counter = Counter()
    for string in strings:
        for char in string:
            counter[char] +=1

    result = []
    for c in ascii_lowercase:
        if c in counter:
            for _ in range(counter[c]):
                result.append(c)
    return "".join(result)

This works on most test cases, but times out on a couple test cases. I am extremely frustrated. How can I  improve the time complexity of this solution?


texts:
This was actually asked in an interview. I have made it in the best possible way I could and would like to optimize it if there is any chance of doing it.

The input is:

a(b(cd)e(fg))

The output should be:

                            a
                           / \
                          b   e
                         / \ / \
                        c  d f  g

My current code is:

#include<stdio.h>
#include<malloc.h>
#include<string.h>

struct node
{
    char x;
    struct node *left;
    struct node *right;
}*root;

char a[30];
int i=0,n;

void tre(struct node * p) //function that I am using to convert the string to a tree
{
        if(a[i]=='(')
        {
            i++;
            struct node *temp=malloc(sizeof(struct node));
            temp->x=a[i];
            temp->left=temp->right=NULL;
            i++;
            if(p->left==NULL)
            {
                p->left=temp;
                tre(p->left);
            }
            if(a[i]!='('&&a[i]!=')')
            {
                struct node *tempp=malloc(sizeof(struct node));
                tempp->x=a[i];
                i++;
                p->right=tempp;
                tre(p->right);
            }
        }
        else
        if(a[i]==')')
        {
            i++;
        }

}

void inorder(struct node *p)//inorder traversal of the tree made
{
    if(p!=NULL)
    {
        inorder(p->left);
        printf("%c ",p->x);
        inorder(p->right);
    }
}

main()
{
    printf("Enter the string : ");
    scanf("%s",a);
    struct node *temp=malloc(sizeof(struct node));
    temp->x=a[i];
    temp->left=temp->right=NULL;
    i++;
    root=temp;
    tre(root);
    inorder(root);
}


texts: Capitalize the first letter of all words in a String

texts:
A rags-to-riches of A method to capitalize the first letter of all words in a String.

To recap the requirements:

  Please implement this method to capitalize all first letters of the words in the given String. All other symbols shall remain intact. If a word starts not with a letter, it shall remain intact too. Assume that the parameter String can only contain spaces and alphanumeric characters.

  NOTE: please keep in mind that the words can be divided by single or multiple spaces.The spaces also can be found at the beginning or the end of the parameter string,and you need to preserve them.

And the code:

public class Main
{
    public static void main(String... args) {
        for(String arg : args) {
            System.out.println(titleize(arg));
        }
    }

    /**
     * Titleize a string. Takes a string and returns a new string where all words
     * have had their first letter title cased. If the letter is already title case
     * or is not a cased letter (like a number), it will be passed through.
     * Leading, trailing, and all other whitespace is preserved.
     *
     * This method is not as robust as titleize in Rails. It does not do any magic
     * like breaking up MashedTogetherWords or replacing_underscores.
     *
     * This will blow up if null is passed in.
     */
    public static String titleize(final String input) {
        // Initialize the output to the length of the input since we know it and the
        // output and input will be the same size.
        StringBuilder output = new StringBuilder(input.length());
        // This defaults to true because we assume the beginning of the
        // string also counts as whitespace. This is to make sure the
        // first word gets capitalized as well.
        boolean lastCharacterWasWhitespace = true;

        for(int i = 0; i < input.length(); i++) {
            char currentCharacter = input.charAt(i);

            if(lastCharacterWasWhitespace && Character.isLowerCase(currentCharacter)) {
                currentCharacter = Character.toTitleCase(currentCharacter);
            }

            output.append(currentCharacter);

            lastCharacterWasWhitespace = Character.isWhitespace(currentCharacter);
        }

        return output.toString();
    }
}

The original code tried to use regular expressions and splitting words to accomplish the task. This does neither. It was partially inspired by the accepted answer, by treating the String as a stream of characters.

This is Java 7. I'm sure there's some Java 8 stream fanciness that can do this in half the lines.


texts:
This is the Haskell version of my recursive Fisher-Yates shuffle in JS.

import System.Random

pick :: Int -> [a] -> ([a],[a])
pick _ []     = ([],[])
pick 0 (x:xs) = ([x],xs)
pick i (x:xs) = (,) <$> fst <*> ((x:) . snd) $ pick (i-1) xs

shuffle :: [a] -> IO [a]
shuffle = runner =<< length
          where
          runner :: Int -> [a] -> IO [a]
          runner 0 xs = return xs
          runner i xs = randomRIO (0, i-1) >>= \r -> let (y,ys) = pick r xs
                                                     in (y ++) <$> runner (i-1) ys

The pick function fetches the i'th item in a the list as a singular list alongside a list with the remaining items. ie pick 3 [1,2,3,4,5,6,7] = ([4],[1,2,3,5,6,7]).

Although the above code is a version of the modern method which is claimed to work in O(n) this pretty fast shuffle code still seems to work in exponential time (i think).

Prelude Main> take 10 <$> shuffle [1..100000]
[20141,12487,79977,44600,14825,86744,65941,84737,97850,21214]
(0.57 secs, 334,790,152 bytes)

Prelude Main> take 10 <$> shuffle [1..1000000]
[698377,452503,263121,737622,550957,927399,453318,657374,728367,775039]
(6.81 secs, 3,782,234,776 bytes)

I have two questions.

Can the time complexity improved while using the List type?
I am not fully in control of Haskell's performance gimmicks like unboxed types and such. Can it's performance boosted by means of such Haskell tools or what data type would be the best?


texts:
This little program is self-explanatory. I count letters in a string (can be any string), using a for loop to iterate through each letter. The problem is that this method is very slow and I want to avoid loops.

Any ideas? I thought that maybe if I remove checked letters from the string after each loop, then in some cases, where many letters repeat, that would make a difference.

def count_dict(mystring):
    d = {}
# count occurances of character
    for w in mystring:
        d[w] = mystring.count(w)
# print the result
    for k in sorted(d):
        print (k + ': ' + str(d[k]))

mystring='qwertyqweryyyy'
count_dict(mystring)

The output:

e: 2
q: 2
r: 2
t: 1
w: 2
y: 5


texts: How to reduce runtime of gene data processing program?

texts:
This program takes a huge data set as input, processes it, calculates and then writes the output to an array.  Most calculations may be quite simple, such as summation. In the input file, there are about 100 million rows and 3 columns.

first column is the name of the gene (total 100 millions)
second column is the specific value
third column is another value of each gene

The problem I face is a long runtime. How can I reduce it?

I need to write all new values (from GenePair to RM_pval with header) I calculated from the new file.

fi = open ('1.txt')
fo = open ('2.txt','w')

import math
def log(x):
    return math.log(x)

from math import sqrt

import sys
sys.path.append('/tools/lib/python2.7/site-packages')
import numpy
import scipy
import numpy as np
from scipy.stats.distributions import norm

for line in fi.xreadlines():
    tmp = line.split('\t')

    GenePair = tmp[0].strip()

    PCC_A = float(tmp[1].strip())
    PCC_B = float(tmp[2].strip())

    ZVAL_A = 0.5 * log((1+PCC_A)/(1-PCC_A))
    ZVAL_B = 0.5 * log((1+PCC_B)/(1-PCC_B))

    ABS_ZVAL_A = abs(ZVAL_A)
    ABS_ZVAL_B = abs(ZVAL_B)

    Var_A = float(1) / float(21-3) #SAMPLESIZE - 3
    Var_B = float(1) / float(18-3) #SAMPLESIZE - 3

    WT_A = 1/Var_A #float
    WT_B = 1/Var_B #float

    ZVAL_A_X_WT_A = ZVAL_A * WT_A #float
    ZVAL_B_X_WT_B = ZVAL_B * WT_B #float

    SumofWT = (WT_A + WT_B) #float
    SumofZVAL_X_WT = (ZVAL_A_X_WT_A + ZVAL_B_X_WT_B) #float

    #FIXED MODEL
    meanES = SumofZVAL_X_WT / SumofWT #float
    Var = float(1) / SumofWT #float
    SE = math.sqrt(float(Var)) #float
    LL = meanES - (1.96 * SE) #float
    UL = meanES - (1.96 * SE) #float
    z_score = meanES / SE #float
    p_val = scipy.stats.norm.sf(z_score)

    #CAL
    ES_POWER_X_WT_A = pow(ZVAL_A,2) * WT_A #float
    ES_POWER_X_WT_B = pow(ZVAL_B,2) * WT_B #float
    WT_POWER_A = pow(WT_A,2)
    WT_POWER_B = pow(WT_B,2)
    SumofES_POWER_X_WT = ES_POWER_X_WT_A + ES_POWER_X_WT_B
    SumofWT_POWER = WT_POWER_A + WT_POWER_B

    #COMPUTE TAU
    tmp_A = ZVAL_A - meanES
    tmp_B = ZVAL_B - meanES
    temp = pow(SumofZVAL_X_WT,2)

    Q = SumofES_POWER_X_WT - (temp /(SumofWT))
    if PCC_A !=0 or PCC_B !=0:
        df = 0
    else:
        df = 1

    c = SumofWT - ((pow(SumofWT,2))/SumofWT)
    if c == 0:
        tau_square = 0
    else:
        tau_square = (Q - df) / c

    #calculation
    Var_total_A = Var_A + tau_square
    Var_total_B = Var_B + tau_square

    WT_total_A = float(1) / Var_total_A
    WT_total_B = float(1) / Var_total_B

    ZVAL_X_WT_total_A = ZVAL_A * WT_total_A
    ZVAL_X_WT_total_B = ZVAL_B * WT_total_B

    Sumoftotal_WT = WT_total_A + WT_total_B
    Sumoftotal_ZVAL_X_WT= ZVAL_X_WT_total_A + ZVAL_X_WT_total_B

    #RANDOM MODEL
    RM_meanES = Sumoftotal_ZVAL_X_WT / Sumoftotal_WT
    RM_Var = float(1) / Sumoftotal_WT
    RM_SE = math.sqrt(float(RM_Var))
    RM_LL = RM_meanES - (1.96 * RM_SE)
    RM_UL = RM_meanES + (1.96 * RM_SE)
    RM_z_score = RM_meanES / RM_Var
    RM_p_val = scipy.stats.norm.sf(RM_z_score)


texts:
This is a simple circular progress with Canvas. Is there any way to make it shorter and easier to read? Another concept for a better performance? I guess clear and re-draw the whole canvas in every input change is not a good thing. I might be wrong.

var canvas = document.getElementById('canvas'),
  ctx = canvas.getContext('2d'),
  halfW = canvas.width / 2,
  halfH = canvas.height / 2,
  range = document.getElementById('range'),
  radius = 75,
  bColor = '#9575CD';

ctx.lineWidth = 7;
ctx.lineCap = 'round';
ctx.textAlign = 'center';

ctx.translate(halfW, halfH);
ctx.rotate((-1 / 2) * Math.PI);
ctx.translate(-halfW, -halfH);

ctx.beginPath();
ctx.strokeStyle = '#ECEFF1';
ctx.arc(halfW, halfH, radius, 0, Math.PI * 2, false);
ctx.stroke();

function draw() {

  ctx.clearRect(0, 0, 400, 400);
  ctx.beginPath();
  ctx.strokeStyle = '#ECEFF1';
  ctx.arc(halfW, halfH, radius, 0, Math.PI * 2, false);
  ctx.stroke();
  ctx.beginPath();
  ctx.strokeStyle = bColor;
  ctx.arc(halfW, halfH, radius, 0, Math.PI * 2 * (range.value * 0.01), false);
  update();
  ctx.stroke();
}

function update(value) {

  ctx.save();
  ctx.translate(halfW, halfH);
  ctx.rotate((1 / 2) * Math.PI);
  ctx.translate(-halfW, -halfH);
  ctx.fillText(range.value + '%', halfW, halfH);
  ctx.restore();
}
setTimeout(draw, 10);
range.addEventListener('input', draw);
div {
  display: flex;
  justify-content: center;
}
  <div>
    <input type="range" id="range" min="0" max="100" value="50" />
    <canvas id="canvas" width="400" height="400"></canvas>
  </div>


texts:
I asked this question on Stackoverflow, but thought it might be a better fit here.

I'm playing around with the titanic dataset, and wanted to create a custom imputer to fill in missing age values with predictions from a LinearRegression model.  Please find the code below:

import seaborn as sns
import pandas as pd

from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LinearRegression
from sklearn.base import BaseEstimator, TransformerMixin

titanic = sns.load_dataset('titanic')

class AgeImputer(TransformerMixin, BaseEstimator):
    def fit(self, x, y=None):
        self.model = LinearRegression()

        # just use two columns for this example
        self.independent_columns = ['fare', 'pclass']

        # split the null age values from rest of data
        self.null_age_data = x[pd.isnull(x['age'])]
        self.age_data = x[pd.isnull(x['age'])==False]

        # fit the model on age_data
        self.model.fit(self.age_data[self.independent_columns], self.age_data['age'])

        return self

    def transform(self, x):
        """ make predictions and return the whole dataframe """
        self.null_age_data['age'] = self.model.predict(self.null_age_data[self.independent_columns])

        return self.null_age_data.append(self.age_data)

age_imputer = make_pipeline(
    AgeImputer()
)

age_imputer.fit_transform(titanic)

The code does the following:

during the fit phase, it saves the entire dataframe as a variable (after splitting it on whether or not the age column is null or not)
Fits a linear regression model on the dataset where age is not null
During the transform phase, it predicts the null values.
Finally, concatenates the two dataframe and output the result.

I'm wondering if this is the best way to create an imputer like this.  The reason being, passing in the whole dataframe and saving it as a class variables feels like a waste of memory.  Is there a simpler solution than this where the memory usage might be more efficient?  Thanks in advance!