texts: Reverse double linked list in python 2.7

texts:
Problem is straightforward, reverse a double linkedlist, any advice on functional bug, performance in terms of algorithm time complexity and code style are highly appreciated.

Code written in Python 2.7.

class DoubleLinkedListNode:
    def __init__(self, value, next_node):
        self.value = value
        self.pre_node = None
        if next_node:
            next_node.pre_node = self
        self.next_node = next_node
    def reverse_list(self):
        new_list = self
        cur = new_list.next_node
        new_list.next_node = None
        new_list.pre_node = None
        while cur:
            node = cur.next_node
            new_list.pre_node = cur
            cur.next_node = new_list
            new_list = cur
            cur = node
        return new_list
    def print_list(self):
        cur = self
        result = []
        while cur:
            result.append(cur.value)
            cur = cur.next_node
        return result

if __name__ == "__main__":
    head = DoubleLinkedListNode(1, DoubleLinkedListNode(2, DoubleLinkedListNode(3, DoubleLinkedListNode(4, DoubleLinkedListNode(5, None)))))
    print head.print_list()
    new_head = head.reverse_list()
    print new_head.print_list()


texts: Replacing the vowels of a string with the letter "X"

texts:
This code replaces every vowel of the string with "X":

def vowel_censor(sentence)
    vowels = "aeiou".chars
    result = []
    sentence.chars.each do |charachter|
      if vowels.include?(charachter)
        result << "X"
      else
        result << charachter
      end
    end
    result.join("")
end

puts "---------Vowel Censor----------"
puts vowel_censor("Let's order a pizza") == "LXt's XrdXr X pXzzX"
puts vowel_censor("Nitwit, blubber, oddment, tweak") == "NXtwXt, blXbbXr, XddmXnt, twXXk"
puts vowel_censor("Supercalifragilisticexpialidocious") == "SXpXrcXlXfrXgXlXstXcXxpXXlXdXcXXXs"


texts: Google Analytic Webcrawler for every country code

texts:
At the moment I'd like recommendation where I can change and what I can use to improve on simplicity and modularity. If I'm practicing good naming conventions as to provide clean readable code. Any critique is much appreciated.

import time
import re
import requests
from bs4 import BeautifulSoup, SoupStrainer
import pandas as pd
import time

SESSION = requests.Session()

""" This is the Google Analytics Selector Section """

class myGoogleSession:

    def fetch_google_xml(self, URL, country_code):
        format_url = f"{URL}{country_code}"
        response = SESSION.get(format_url)
        soup = BeautifulSoup(response.text, 'xml',
                             parse_only=SoupStrainer('channel'))
        return soup

google_session = myGoogleSession()

def google_trends_retriever(URL, country_code):
    xml_soup = google_session.fetch_google_xml(URL, country_code)
    print(country_code)
    return[(title.text, re.sub("[+,]", "", traffic.text))
           for title, traffic in zip(xml_soup.find_all('title')[1:],
                                     xml_soup.find_all('ht:approx_traffic'))]

def create_pdTrend(data):
    check_panda = pd.DataFrame(
        google_trends_retriever(GoogleURL, data),
        columns=['Title', 'Score']
    )
    if len(check_panda) == 0:
        print('No available data')
    else:
        return check_panda

""" This is the Country Code Selector Section """

country_code_list = []

class myCountryCodeSession:
    def fetch_countrycode_html(self, URL):
        response = SESSION.get(URL)
        soup = BeautifulSoup(response.text, 'html.parser',
                             parse_only=SoupStrainer('table'))
        return soup

countryCode_session = myCountryCodeSession()

def parse_row(url):
    rows = countryCode_session.fetch_countrycode_html(url)
    _rows = rows.findChildren(['td', 'tr'])
    for row in _rows:
        cells = row.findChildren('td')[2:3]
        for cell in cells:
            value = cell.string
            country_code_list.append(value[:2])
    return None

def create_pdCountryCode(country_code):
    return pd.DataFrame({'Country_Code': country_code})

def iterate_List(data):
    i = 1
    while i <= 239:
        selected_CountryCode = get_data_fromList(i)
        print(create_pdTrend(selected_CountryCode))
        i += 1
    else:
        print('Has reach the end of i ' + str(i))

def get_data_fromList(num):
    key = num-1
    for i in country_code_list[key:num]:
        return str(i)

if __name__ == '__main__':
    """ URL Section """
    GoogleURL = "https://trends.google.com/trends/trendingsearches/daily/rss?geo="
    CountryCodeURL = "https://countrycode.org/"
    """-------------"""
    start = time.time()
    print("hello")

    """Country Code Section """
    parse_row(CountryCodeURL)
    """---------------------"""

    """Google Analytics Section """
    iterate_List(country_code_list)
    """-------------------------"""
    end = time.time()
    print(end - start)


texts:
Regarding these two functions, which do the same thing...

Large and confusing:

var fade = function(flag){

    if (volumeIntervalId)
        clearInterval(volumeIntervalId);

    switch (flag){
        case 'in':
            volumeIntervalId = setInterval(function(){
                var vol = songInstance.getVolume();
                if (vol < 1){
                    songInstance.setVolume( vol + volumeIncrement );
                }else{
                    clearInterval(volumeIntervalId);
                }
            }, volumeIntervalDelay);
            break;
        case 'out':
            volumeIntervalId = setInterval(function(){
                var vol = songInstance.getVolume();
                if (vol > 0){
                    songInstance.setVolume( vol - volumeIncrement );
                }else{
                    clearInterval(volumeIntervalId);
                    songInstance.stop();
                }
            }, volumeIntervalDelay);
            break;
        default:
            clearInterval(volumeIntervalId);
            break;
    }

},

Slighty smaller but maybe more confusing:

var fade = function(flag){

    if (volumeIntervalId)
        clearInterval(volumeIntervalId);

    volumeIntervalId = setInterval(function(){
        var vol = songInstance.getVolume();
        if (flag === 'in'){
            if (vol < 1) {
                songInstance.setVolume( vol + volumeIncrement );
                return;
            }
        } else if (flag === 'out'){
            if (vol > 0) {
                songInstance.setVolume( vol - volumeIncrement );
                return;
            }else{
                songInstance.stop();
            }
        }
        clearInterval(volumeIntervalId);
    }, volumeIntervalDelay);

},

How could I make that simpler/cleaner/easier to read? Maybe split into more functions?

It's interesting how the 2nd function's setInterval anonymous function keeps the value of 'flag' due to the closure. Is there any risk? Should I avoid that?

Maybe (the obvious) use two functions (fadeIn and fadeOut)? Why do people (like me) tend to complicate things like that?

Update

I guess this is better:

fadeIn: function(){
    if (volumeIntervalId) clearInterval(volumeIntervalId);

    volumeIntervalId = setInterval(function(){
        var vol = songInstance.getVolume();
        if (vol < 1){
            songInstance.setVolume( vol + volumeIncrement );
        }else{
            clearInterval(volumeIntervalId);
        }
    }, volumeIntervalDelay);
},

fadeOutAndStop: function(){
    if (volumeIntervalId) clearInterval(volumeIntervalId);

    volumeIntervalId = setInterval(function(){
        var vol = songInstance.getVolume();
        if (vol > 0){
            songInstance.setVolume( vol - volumeIncrement );
        }else{
            songInstance.stop();
            clearInterval(volumeIntervalId);
        }
    }, volumeIntervalDelay);
},


texts: Capture Min() And Max() Of Numbers Input

texts:
I have two text boxes where a user inputs a start and a end, that is how it is supposed to work at least.  Rather than throwing an error if end < start, I was thinking I could use the built in functions Min() & Max() to capture which value is actually which.

Is this the most efficient way of capturing the Min() & Max() value of text box input?

int start = Math.Min(Convert.ToInt32(txtStart.Text), Convert.ToInt32(txtEnd.Text));
int end = Math.Max(Convert.ToInt32(txtStart.Text), Convert.ToInt32(txtEnd.Text));


texts:
I often need to parse tab-separated text (usually from a huge file) into records. I wrote a  generator to do that for me; is there anything that could be improved in it, in terms of performance, extensibility or generality?

def table_parser(in_stream, types = None, sep = '\t', endl = '\n', comment = None):
  header = next(in_stream).rstrip(endl).split(sep)
  for lineno, line in enumerate(in_stream):
    if line == endl:
      continue # ignore blank lines
    if line[0] == comment:
      continue # ignore comments
    fields = line.rstrip(endl).split(sep)
    try:
      # could have done this outside the loop instead:
      # if types is None: types = {c : (lambda x : x) for c in headers}
      # but it nearly doubles the run-time if types actually is None
      if types is None:
        record = {col : fields[no] for no, col in enumerate(header)}
      else:
        record = {col : types[col](fields[no]) for no, col in enumerate(header)}
    except IndexError:
      print('Insufficient columns in line #{}:\n{}'.format(lineno, line))
      raise
    yield record


texts:
I want my entire node application to use one single mongodb connection, at least that's what I think is better. I wrote this little script and want some feedback on it. Especially if what I'm doing makes sense.

This is my mongodb.js file

'use strict';

// Mongodb module.
var MongoClient = require( 'mongodb' ).MongoClient;

// Database.
var db;

// Working variable.
var working;

// Callbacks array.
var arr = [];

// Exported variable.
module.exports = function( callBack ) {
    if ( db ) {
        callBack( db );
        return;
    }

    arr.push( callBack );

    if ( working ) return;

    working = true;

    var MongoDB = MongoClient.connect( 'mongodb://127.0.0.1:27017/test',
        function( err, res ) {
            if( err ) throw err;

            console.log( "Connected to MongoDB!" );

            db = res;

            for ( var i = 0; i < arr.length; i++ ) {
                arr[i]( res );
            }

            arr = [];
        }
    );
}

This is a file where I include the mongodb.js

var collection;
new require( 'mongodb.js' )(
    function( db ) {
        collection = db.collection( 'test' );
    }
);


texts: disable other default row- Entity framework

texts:
I have a table that name is Store  , In Store Table , just one row can IsDefault=true at time . when I insert new Row , I check If user selected IsDefault , I  update other row whice isDefault=true . I use this code :

public AddStatus Add(AddStoreViewModel storeViewModel)
    {
        if (Exists(storeViewModel.Name)) return AddStatus.Exists;
        var storeModel = Mapper.Map(storeViewModel, new StoreEntity.Store());
        if (storeModel.IsDefault)
        {
            var defaultStore = GetDefault();
            if (defaultStore != null)
            {
                defaultStore.IsDefault = false;
                _uow.MarkAsBaseChanged(defaultStore); // update
            }
        }
        _uow.MarkAsBaseAdded(storeModel);
        return AddStatus.Successfull;
    }

and in controller I call Above Method like belowe and Call SaveAllChanges :

 _storeService.Add(storeViewModel);
 await _uow.SaveChangesAsync();

and  MarkAsBaseChange like belowe :

  public void MarkAsBaseChanged<TEntity>(TEntity entity) where TEntity : BaseEntity
    {
        Entry(entity).Entity.Action = Enums.AuditAction.Update;
}

is this code ok ?


texts: Searching for a substring in a ring queue

texts:
I am implementing a function which searches through a ring queue for a given substring. The function returns true if the substring is found, otherwise false. There is a cell containing null between the tail and head to signify the end of string. Please give feedback on this implementation.

bool SoftwareSerial::contains(const char *substr){
    char *pBuffer =_receive_buffer + _receive_buffer_head;
    char *pSubstr = substr;

    for(; *pBuffer != 0 && *pSubstr != 0; ++pBuffer ){
        if(pBuffer == (_receive_buffer + _SS_MAX_RX_BUFF)){
            pBuffer = _receive_buffer + _receive_buffer_head;
        }
        if(*pBuffer != *pSubstr){
            pSubstr = substr;
            continue;
        }
        ++pSubstr;
    }
    return (*pSubstr == 0);
}


texts: Sugestion on a better way to code this EF update?

texts:
I have a block of code that pulls the current menu position and compares it to what users selected, if the selection is different the database is updated with the new selection. As I am still new with EF I was hoping for a general code review for suggestions on a possible better, more efficient, and/or easier way to code this. Here is my existing code:

using (var db = new SectionInfoAdmin())
{
    var dtCategories = (from n in db.Navigation
    where n.SectionID == SectionID
    select new
    {
       n.Category
    }).ToList();

 string PrimaryCategory = dtCategories[0].Category.ToString();

 if (ddlPrimaryCategory.SelectedValue != PrimaryCategory)
 {
    var Category = (from n in db.Navigation
    where n.Category == PrimaryCategory && n.SectionID == SectionID
       select n).First();

    Category.Category = PrimaryCategory;
 }

 if (dtCategories.Count > 1)
 {
    string SecondaryCategory = dtCategories[1].Category.ToString();
    if (ddlSecondaryCategory.SelectedValue == SecondaryCategory)
    {
       var Category = (from n in db.Navigation
       where n.Category == SecondaryCategory && n.SectionID == SectionID
          select n).First();
       Category.Category = SecondaryCategory;
    }
 }
 db.SaveChanges();
 lblResults.Text = "Information updated.";
}


texts:
I have the following code that takes a Point and a given tolerance value and looks for all other Points that fall within the tolerance from a Point array. Now this code is quite slow, does anyone know a faster way of doing this?

Also if you have any tips on how I can improve my coding style, if needed, that would be great.

private Point[] FindNearbyPoints(Point[] points, Point initialPoint, int tolerance)
{
    return points.Select(p => p)
                 .Where(p => (p.X >= initialPoint.X - tolerance && p.X <= initialPoint.X + tolerance) &&
                             (p.Y >= initialPoint.Y - tolerance && p.Y <= initialPoint.Y + tolerance))
                 .ToArray();
}


texts: C++ split function (equivalent to python string.split())

texts:
I wrote the equivalent to the split() in python for C++.  I would like to know how I can make it better:

static constexpr auto whitespace = " \t\v\r\n\f";
static constexpr auto npos = std::string::npos;

std::vector<std::string> split(std::string_view str, std::string_view sep = "", std::size_t maxsplit = std::numeric_limits<std::size_t>::max())
{
    std::vector<std::string> result;
    if (sep.empty())
    {
        for (std::size_t start = str.find_first_not_of(whitespace), splits = 0; start != npos; ++splits)
        {
            if (auto end = str.find_first_of(whitespace, start); end != npos && splits < maxsplit)
            {
                result.emplace_back(str.substr(start, end - start));
                start = str.find_first_not_of(whitespace, end);
            }
            else
            {
                result.emplace_back(str.substr(start));
                break;
            }
        }
    }
    else
    {
        for (std::size_t start = 0, splits = 0; start < str.size(); ++splits)
        {
            if (auto end = str.find(sep, start); end != npos && splits < maxsplit)
            {
                result.emplace_back(str.substr(start, end - start));
                start = end + sep.size();
            }
            else
            {
                result.emplace_back(str.substr(start));
                break;
            }
        }
    }
    return result;
}

I tried to keep all variables as local as possible and use standard algorithms.


texts:
I have a pretty functional JavaScript based graphing calculator.

Functions like \$\space tan(x)\$, \$\space\frac{1}{tan(x)}\space\$ and \$\space x^{high\space number}\space\$ look weird, however because the interval it graphs isn't small enough. If I make that interval any smaller to fix the gaps though, it severely impacts its performance.

Is there a more efficient way to do the plotting?

Here is the pertinent code. It draws rectangles on an HTML canvas. The page of the complete version can be found here.

var mathjs = require('mathjs');
//JavaScript parser that evaluates the user input
var canvas = document.getElementById("graph");
var ctx = canvas.getContext("2d");

var width = canvas.width;
var height = canvas.height;
var center = width/2;

function plot(){
    var f = mathjs.eval('f(x) = '+($("#function").val()));
    try{
        for(var x = -250;x<250;x+=0.001){
            //"x+=0.001" is the interval in question
            ctx.fillRect(center+x,center-f(x),0.1,0.1);
        }
    }
    catch(e){
        throw new Error("Syntax error or invalid function sent to mathjs.");
    }
}


texts: Project Euler 8: find the maximum product of 13 consecutive digits

texts:
I'm doing Project Euler problems as a learning platform for Forth. Currently I'm solving Project Euler Problem 8 which involves a 1000-long string, which I entered directly in the source code.
My questions are:

What options are common for dealing with input?
If I put the locals on the stack, won't that make the loop too full of (otherwise unneeded) stack manipulation words?
Suggestions, criticism, nitpicks are welcome...

: e008-multNdigits ( a n -- p )
    1 swap 0 do swap dup i + c@ [char] 0 - rot * loop nip ;

: euler008
    0 13 locals| length maxproduct |
    s" 731671765313306249192...450"
    ( a 1000 )
    length - 0 do
        dup i + length e008-multNdigits
        dup maxproduct > if to maxproduct else drop then
    loop maxproduct . ;


texts:
I am trying to teach myself about repository pattern in ruby. Could you please review my code.

adapter.rb

module Adapter
  class Main
    def prebuild(obj)
      self.set_table_name = obj.table_name.to_s
      variables = obj.instance_variables
      @values = []
      @keys = []

      variables.reject! { |c| c.to_s == '@table_name' }.map do |key, value|
        @keys.push(key.to_s.gsub('@', ''))
        @values.push(obj.send(@keys.last))
      end
    end

    def get_table_name
      @table_name
    end

    def get_keys
      @keys
    end

    def get_values
      @values.map { |value| "'#{value}'" }
    end

    def set_table_name=(table_name)
      @table_name = table_name
    end
  end

  class Sqlite < Main
    require 'sqlite3'

    def initialize
      @db = SQLite3::Database.new 'file.db'
    end

    def persist(obj)
      prebuild(obj)
      sql_string = "INSERT INTO #{get_table_name} (#{get_keys.join(', ')}) VALUES (#{get_values.join(', ')})"
      @db.execute sql_string
      obj.id = @db.execute "SELECT last_insert_rowid()"
      obj
    end

    def retrieve(entity, id)
      self.set_table_name = entity.table_name
      rows = @db.execute "SELECT * FROM #{get_table_name} WHERE id=#{id}"
      fields = get_fields
      new_entity = entity.new

      for i in (0..fields.size-1)
        new_entity.send("#{fields[i]}=", rows[0][i])
      end
      new_entity
    end

    def get_fields
      rows = @db.execute "PRAGMA TABLE_INFO (#{get_table_name});"

      rows.map { |name| name[1] }
    end

    def delete(obj)
      prebuild(obj)
      @db.execute "DELETE FROM #{get_table_name} WHERE id=#{obj.id}"
    end
  end
end

entity.rb

module Entity
  class Member
    attr_reader :table_name

    attr_accessor :username
    attr_accessor :email
    attr_accessor :password
    class << self
      def table_name
        @table_name ||= 'members'
      end
    end
    def table_name
      @table_name ||= 'members'
    end

    def id=(new_id)
      @id = new_id
    end

    def id
      @id
    end

    def username=(new_username)
      @username = new_username
    end

    def username
      @username
    end

    def email=(new_mail)
      @email = new_mail
    end

    def email
      @email
    end

    def password=(new_password)
      @password = new_password
    end

    def password
      @password
    end
  end
end

repository.rb

module Repository
  class Member
    def initialize(adapter)
      @adapter = adapter.new
    end

    def save(member)
      @adapter.persist(member)
    end

    def get(id)
      @adapter.retrieve(Entity::Member, id)
    end

    def delete(member)
      @adapter.delete(member)
    end
  end
end

test.rb

require './lib/entity'
require './lib/adapter'
require './lib/repository'

member = Entity::Member.new
member.username = 'ahmet'
member.email = 'ahmet@kapikiran.com'
member.password = '12345'
repository = Repository::Member.new(Adapter::Sqlite)
repository.save(member)

member = repository.get(5)

repository.delete(member)


texts: A routing heuristic: improving function speed

texts:
I am currently constructing a heuristic to solve a routing problem. Routes are represented by vector<int> of customer ID's, which are stored in the class Solution (which also contains other relevant information). The class Instance contains instance-specific information, i.e. distances between customers and pickup and delivery quantities of the customers and cost parameters.

I use a Large Neighborhood Search approach, where I destroy a solution after which it needs to be repaired. After destroying a solution, certain customers get placed in a customer pool (part of Solution). Below is my script of placing each customer currently in the pool at their best insertion place, so it examines all possible insertion locations and saves the best option. Costs are made up of two parts: routing costs and handling costs. The function should change the solution with the pre-specified functions. Feasibility is determined by checking the load in the vehicle. It should not exceed its capacity. At every customer, a delivery is made and goods are picked up.

This function works as it should, but I am wondering if it could be made faster/more efficient. Since I am fairly new to C++, I can not think of things that would improve the speed of this script, but since it is called many times, efficiency is important. All suggestions or improvements are welcome!

Note: some external functions are used in the function below. I believe their names are self-explanatory. The get_...() functions return a value of the relevant class.

Note 2: apologies if this is a too general question.

void best_insert_repair(const Instance& inst, Solution& sol){
while (sol.get_customer_pool().size()!=0) {
double best_cost = INFINITY;
int best_r = -1;
int best_ind = -1;

//determine random customer in pool
int r_ind = unif_rand_int(0, (int)sol.get_customer_pool().size()-1);
int cust = sol.get_customer_pool()[r_ind]+1;
double routing_cost = 0.0;
double handling_cost = 0.0;
double total_cost = 0.0;
bool add_route = false;

//loop over all existing routes
for (int r = 0; r!=sol.get_routes().size(); r++) {

    //and over all elements
    for(int i = 1; i!=sol.get_routes()[r].size(); i++){

        //copy route and insert
        route r_temp = sol.get_routes()[r];
        r_temp.reserve(inst.get_nr_cust());
        insert_in_route(r_temp, i, cust);

        //only calculate if route is feasible
        if (compute_feasible(inst, r_temp)) {
            routing_cost = inst.get_distances()[r_temp[i-1]][cust] + inst.get_distances()[cust][r_temp[i+1]];
            handling_cost = calc_handling_cost(inst, r_temp) - sol.get_handling_cost(r);
            total_cost = routing_cost + handling_cost;
            if (total_cost<best_cost) {
                best_cost=total_cost;
                best_r = r;
                best_ind = i;
            }
        }
    }
}
//also check insertion in new route
route new_route = {0, cust, 0};
new_route.reserve(inst.get_nr_cust()+2);
total_cost = calc_handling_cost(inst, new_route) + calc_routing_cost(inst, new_route);
if (total_cost<best_cost) {
    add_route = true;
}

//insertion at best place
if(!add_route){
    //insert customer at best_r best_ind
    sol.insert_in_route(best_r, best_ind, cust);
    sol.set_route_cost(inst, best_r);

} else {
    //add new route with customer
    sol.add_route(new_route);
    sol.set_route_cost(inst, (int)sol.get_routes().size()-1);
}

//remove inserted customer from the customer pool
sol.remove_from_cust_pool(r_ind);
}

A function that may be important for performance is the following:

void insert_in_route(route& r, const int& index, const int& customer){
r.insert(r.begin() + index, customer);}


texts: LINQ queries to generate a report on accrued work time on projects

texts:
The following code fetches data from a MySql database to generate a simple report on accrued work time on projects.

I've been away from Entity Framework for a while and looking at this code you can see that the creation of ListProject is basically repeated 3 times.

Is there any way to refactor this so I can reuse the duplicate parts?

I've thought about a factory method, but that won't work because it can't be translated to SQL by the expression interpreter.

    var project = entities.Tickets
        .Where(p => p.ID == id)
        .Select(p => new ListProject
        {
            Id = p.ID,
            Name = p.ueberschrift,
            AssignedEmployee = new ListEmployee
            {
                Id = p.AssignedEmployee.ID,
                Name = p.AssignedEmployee.name
            },
            WorkUnits = p.WorkUnits
                .Select(wu => new ListProjectWorkUnit
                {
                    Duration = wu.dauer,
                    PauseDuration = wu.pauseDauer,
                    Employee = new ListEmployee
                    {
                        Id = wu.AssignedEmployee.ID,
                        Name = wu.AssignedEmployee.name
                    }
                })
                .ToList()
            })
            .Single();

    project.Tickets = entities.Tickets
        .Where(p => p.vonProjekt == id)
        .Where(p => p.phaseID == 0)
        .OrderBy(p => p.ueberschrift)
        .Select(p => new ListProject
        {
            Id = p.ID,
            Name = p.ueberschrift,
            AssignedEmployee = new ListEmployee
            {
                Id = p.AssignedEmployee.ID,
                Name = p.AssignedEmployee.name
            },
            WorkUnits = p.WorkUnits
                .Select(wu => new ListProjectWorkUnit
                {
                    Duration = wu.dauer,
                    PauseDuration = wu.pauseDauer,
                    Employee = new ListEmployee
                    {
                        Id = wu.AssignedEmployee.ID,
                        Name = wu.AssignedEmployee.name
                    }
                })
                .ToList()
        })
        .ToList();

    project.Phases = entities.projekt_phase
        .Where(p => p.projektID == id)
        .OrderBy(p => p.rang)
        .Select(p => new ListProjectPhase
        {
            Id = p.ID,
            Name = p.name,
            Tickets = p.Tickets
                .OrderBy(t => t.ueberschrift)
                .Select(t => new ListProject
                {
                    Name = t.ueberschrift,
                    Id = t.ID,
                    AssignedEmployee = new ListEmployee
                    {
                        Id = t.AssignedEmployee.ID,
                        Name = t.AssignedEmployee.name
                    },
                    WorkUnits = t.WorkUnits
                        .Select(wu => new ListProjectWorkUnit
                        {
                            Duration = wu.dauer,
                            PauseDuration = wu.pauseDauer,
                            Employee = new ListEmployee
                            {
                                Id = wu.AssignedEmployee.ID,
                                Name = wu.AssignedEmployee.name
                            }
                        })
                        .ToList()
                })
                .ToList()
        })
        .ToList();


texts: Setting the token for API client generated instances in an Angular application

texts:
I am developing an Angular application who also consumes an external REST API. I am also trying the OpenAPI generator using a TypeScript template.

The OK path is the following:

call a method that requires a username + password and get a token
set the token on a configuration object
update the generated instance API client with that configuration (which should also receive a base path)
use the instance API client to call a method

DataLakeSecurityClientCustomizationService

This takes care of initializing the API clients and setting the token when this is refreshed.

@Injectable({providedIn: "root"})
export class DataLakeSecurityClientCustomizationService {

    constructor(
        private readonly defaultService: DefaultService,
        private readonly securityTagsService: SecurityTagsService,
        /* other generated API client service instances will be here */) {
    }

    init() {
        this.defaultService.configuration.basePath = environment.dataLakeSecurityApiBasePath;
        this.securityTagsService.configuration.basePath = environment.dataLakeSecurityApiBasePath;
    }

    setToken(token: string) {
        this.securityTagsService.configuration.accessToken = token;
        // all other used services will get the token here
    }
}

app.component.ts

  private initDataLakeExtAuth() {
    this.dataLakeCustService.init();

    // trying to get a token ASAP to use for subsequent calls
    this.store.dispatch(RequestNewTokenAction());
  }

  ngOnInit(): void {
    this.initDataLakeExtAuth();
  }

Authentication effect

This handles getting the token which is happening outside of reducer's pure functions. I am using ngrx/store framework (Angular 8 version).

@Injectable()
export class DataLakeExtAuthEffects {

    constructor(
        private readonly actions$: Actions,
        private readonly dataLakeExtAuthService: DataLakeExtAuthService,
        private readonly store: Store<AppState>,
        private readonly logger: LoggingService,
        private readonly dataLakeSecurityClientCustomizationService: DataLakeSecurityClientCustomizationService
    ) { }

    getNewToken$ = createEffect(() => this.actions$.pipe(
        ofType(RequestNewTokenAction),
        switchMap(_ => {
            this.store.dispatch(LoadingStartedAction({ message: "Performing security level authentication ..."}));

            return this.dataLakeExtAuthService.getLoginToken().pipe(
                tap(() => this.store.dispatch(LoadingEndedAction())),
                catchError(err => {
                    this.store.dispatch(LoadingEndedAction());
                    this.logger.logErrorMessage("Error getting a Data Lake Security View token: " + err);

                    this.store.dispatch(NewTokenLoadCancelledAction());
                    return of<string>();
                }));
            }),
        map((token: string) => {
            this.dataLakeSecurityClientCustomizationService.setToken(token);

            return NewTokenLoadedAction({token});
        }))
    );
}

The authentication service for the external REST API

@Injectable({providedIn: "root"})
export class DataLakeExtAuthService {

    credentials = DataLakeCredentials;

    constructor(private readonly defaultService: DefaultService,
                private readonly logger: LoggingService) {
    }

    getLoginToken(): Observable<string> {
        const token$ = this.defaultService.loginTokenPost(this.credentials.username, this.credentials.password)
            .pipe(
                map((payload: { access_token: string }) => payload.access_token),
                tap((token: string) => {
                    this.logger.logTrace("Received token: ", token);
                })
            );
        return token$;
    }
}

DefaultService is an automatically generated TypeScript class that actually performs the API call.

I am looking for improvement suggestions for this pattern I am using. Also, I cannot control what code is generated through the OpenAPI generator.


texts: Find pairs in an integer array whose sum is equal to 10

texts:
I came up with 2 different solutions in Java.

First one is:

public static void main(String[] args) {

    int[] array = new int[]{10,3,4,6,1,9,10,0};
    int sum=0;

    for (int i=0;i<array.length;i++)
    {
      for (int j=i ; j<array.length;j++){

        sum = array[i] + array[j];
        if (sum==10){

          System.out.println(array[i] + " " + array[j]);

        }

      }

    }

I believe this one works in \$O(N^2)\$.

My second solution is:

  public static void main(String[] args) {
    int[] nums = new int[] {10, 3, 4, 6, 1, 9, 10, 0};
    Hashtable<Integer, Integer> reqNoList = new Hashtable<Integer, Integer>();
    int sum = 10;
    int i = 0, count = 0;

    while (i < nums.length && i < sum) {
      int key = sum - nums[i];
      if (reqNoList.containsKey(nums[i])) {
        Integer temp = reqNoList.get(nums[i]);
        System.out.println(key + " " + nums[i]);
        count++;
      } else {
        reqNoList.put(key, i);
      }
      i++;
    }
  }
}

I tried to do it in \$O(N)\$ but I have no idea.


texts:
I just tried to create a program for the N queens problem.

def print_board() -> None:
    """ Prints the board """

    length = 3 * (SIZE - 1) + SIZE + 4

    print()

    print('-' * length)

    for row in board:
        print('| ' + ' | '.join(row) + ' |')
        print('-' * length)

    print()

def isValid(row: int, col: int) -> bool:
    """ Returns if a cell index is valid """

    return 0 <= row < SIZE and 0 <= col < SIZE

def isSafe(row: int, col: int) -> bool:
    """ Checks if the given index position is safe """

    # Checks if the column is safe
    for i in range(SIZE):
        if i != row and board[i][col] != ' ':
            return False

    # Checks if the row is safe
    for j in range(SIZE):
        if j != col and board[row][j] != ' ':
            return False

    # Checks if the diagonals are safe
    for k in range(SIZE):
        if isValid(row + k, col + k) and board[row + k][col + k] != ' ' or \
           isValid(row - k, col + k) and board[row - k][col + k] != ' ' or \
           isValid(row + k, col - k) and board[row + k][col - k] != ' ' or \
           isValid(row - k, col - k) and board[row - k][col - k] != ' ':

            return False

    return True

def backtrack(row=0, total=0) -> bool:
    """ Backtracks and fills chacks for every possible combination """

    # If all rows are safely filled with queens
    if row == SIZE:
        # print_board()  # Uncomment the code to print the current solution
        # input('Enter to continue... ')

        return 1

    for col in range(SIZE):
        # If the current index is safe, check for the next row
        if isSafe(row, col):
            board[row][col] = 'Q'

            total += backtrack(row + 1)

            board[row][col] = ' '

    return total

def solve() -> None:
    """ Calls backtrack and prints number of solutions """

    total = backtrack()

    print()

    if not total:
        print('No possible solution was found')
    elif total == 1:
        print('There is a total of 1 solution')
    else:
        print(f'There are a total of {total} solutions')

if __name__ == '__main__':
    SIZE = int(input('Enter the size of the board: '))

    board = [[' '] * SIZE for row in range(SIZE)]

    solve()

Though it does work, I'm not satisfied yet.

I want to make this code as short as possible while also following Pep8 rules.

I believe there isn't a faster approach, but if there are any, please enlighten me!

Thank you!


texts: Parsing notification information from distribution lists

texts:
I'm writing am application that I've previously posted questions on here, but I'm looking for similar advice if possible. I am looking for how best to write my code, as I have a working example, but to me it feels long winded.

The application first grabs 3 tables via DataContext:-

        var contacts = db.GetTable<Contact>();
        var distributionLists = db.GetTable<DistributionList>();
        var JunctionTable = db.GetTable<ContactsDistribution>();

I then get the selected items from my listbox, which are distribution lists. A contact can be in more than one distribution list, so I first get the raw data from my database:

var listBoxItems = listBox1.SelectedItems.Cast<object>().Select(t => t.ToString());

var initialList = (from j in JunctionTable
                      where listBoxItems.Contains(j.DistributionName)
                      join c in contacts on j.ContactID equals c.ContactID
                      select new { c.ContactID,c.Surname,j.DistributionName, j.EmailFlag, j.SMSFlag}).ToList();

I then need to search the initialList collection for users who require email notifications.  I also need to remove duplicate entries, as a Contact can appear multiple times. So the list is made Distinct:-

var email = (from l in initialList
                       where l.EmailFlag.Equals(true)
                       select new { l.ContactID }).Distinct().ToList();

I then do the same search for Contacts that require SMS Notification from the selected lists:

var sms = (from l in initialList
                       where l.SMSFlag.Equals(true)
                       select new { l.ContactID }).Distinct().ToList();

Now that I have lists for both SMS & Email Notifications I need get the required email address or mobile number by doing this:

var smsMobileNumbers = (from s in sms
                        join c in contacts on s.ContactID equals c.ContactID
                        select new { c.MobileNumber }).ToList();

var emailAddresses = (from m in email
                     join c in contacts on m.ContactID equals c.ContactID
                     elect new { c.EmailAddress }).ToList();

Is there a cleaner way of writing this code or is there a better, more efficient way of achieving this?


texts:
I did another exercise, this time it simulates n games of craps(dice game) and outputs the wins and win percentage!

#craps.py -- Simulates multiple games of craps
#   and estimates the probability that the player wins.

import random

def output(wins, total):
    winrate = wins / total
    print("The player won {0} of {1} games ({2:0.2%})".format(wins, total, winrate))

def rolldies():
    dice1 = random.randint(1, 6)
    dice2 = random.randint(1, 6)
    roll = dice1 + dice2
    return roll

def simOneGame():
    initial_roll = rolldies()
    if initial_roll == 2 or initial_roll == 3 or initial_roll == 12:
        return True     # won
    elif initial_roll == 7 or initial_roll == 11:
        return False    #lost
    else:
        #Roll until roll is 7 or initial roll
        roll = rolldies()
        while roll != 7 and roll != initial_roll:
            roll = rolldies()
        if roll == 7:
            return True     #won
        else:
            #roll is inital_roll
            return False    #lost

def simNGames(games_to_sim):
    wins = 0
    for i in range(games_to_sim):
        if simOneGame():
            wins += 1
    return wins

def main():
    games_to_sim = int(input("How many games to simulate? "))
    wins = simNGames(games_to_sim)
    output(wins, games_to_sim)

if __name__ == "__main__":
    main()

Always open for suggestions on what to improve/do differently or more pythonic.


texts: Python 3 simple external sort with heapq

texts:
I've implemented a minimal external sort of text file using heapq python module.

On the few tests I did it seems to works well, but I would like to have some advice to have a cleaner and faster code. I do not know much of good practices and I want to learn (May wish to go from academics to industry one day). All remarks, advice and suggestions are warmly welcome.

There are 3 functions: one that splits the big file in smaller files,
one that does the merge, and one main function.

import os
import tempfile
import heapq
import sys
import shutil

# Algorithm based on
# https://github.com/melvilgit/external-Merge-Sort

def split_large_file(starting_file, my_temp_dir, max_line=1000000):
    """

    :param starting_file: input file to be splitted
    :param my_temp_dir: temporary directory
    :param max_line: number of line to put in each smaller file (ram usage)
    :return: a list with all TemporaryFile
    """
    liste_file = []
    line_holder = []
    cpt = 0
    with open(starting_file, 'rb') as f_in:
        for line in f_in:
            line_holder.append(line)
            cpt += 1

            if cpt % max_line == 0:
                cpt = 0
                line_holder.sort(key=lambda x: x.split(b"\t")[0])
                temp_file = tempfile.NamedTemporaryFile(dir=my_temp_dir, delete=False)
                temp_file.writelines(line_holder)
                temp_file.seek(0)
                line_holder = []
                liste_file.append(temp_file)

        if line_holder:

            line_holder.sort(key=lambda x: x.split(b"\t")[0])
            temp_file = tempfile.NamedTemporaryFile(dir=my_temp_dir, delete=False)
            temp_file.writelines(line_holder)
            temp_file.seek(0)
            liste_file.append(temp_file)

    return liste_file

def merged(liste_file, out_file, col):
    """

    :param liste_file: a list with all temporary file opened
    :param out_file: the output file
    :param col: the column where to perform the sort, being minimal the script will fail
     if one column is shorter than this value
    :return: path to output file
    """
    my_heap = []
    for elem in liste_file:
        line = elem.readline()
        spt = line.split(b"\t")
        heapq.heappush(my_heap, [int.from_bytes(spt[col], "big"), line, elem])

    with open(out_file, "wb") as out:
        while True:
            minimal = my_heap[0]
            if minimal[0] == sys.maxsize:
                break

            out.write(minimal[1])
            file_temp = minimal[2]
            line = file_temp.readline()
            if not line:
                my_heap[0] = [sys.maxsize, None, None]
                os.remove(file_temp.name)
            else:
                spt = line.split(b"\t")
                my_heap[0] = [int.from_bytes(spt[col], "big"), line, file_temp]

            heapq.heapify(my_heap)
    return out_file

def main(big_file, outfile, tmp_dir=None, max_line=1000000, column=0):

    if not tmp_dir:
        tmp_dir = os.getcwd()

    with tempfile.TemporaryDirectory(dir=tmp_dir) as my_temp_dir:
        temp_dir_file_list = split_large_file(big_file, my_temp_dir, max_line)
        print("splitted")
        merged(liste_file=temp_dir_file_list, out_file=outfile, col=column)
        print("file merged, sorting done")


texts: Finding the Euclidean distance between the vectors of matrix a, and vector b

texts:
Here is the problem,

Given a 2D numpy array 'a' of sizes  n×m  and a 1D numpy array 'b' of
size m. You need to find the distance(Euclidean) of the 'b' vector
from the rows of the 'a' matrix. Fill the results in the numpy array.
Follow up: Could you solve it without loops?

a = np.array([[1, 1],
              [0, 1],
              [1, 3],
              [4, 5]])
b = np.array([1, 1])
print(dist(a, b))
>>[0,1,2,5]

And here is my solution
import math

def dist(a, b):
    distances = []
    for i in a:
        distances.append(math.sqrt((i[0] - b[0]) ** 2 + (i[1] - b[1]) ** 2))
    return distances

a = np.array([[1, 1],
              [0, 1],
              [1, 3],
              [4, 5]])
print(dist(a, [1, 1]))

I wonder how can this be solved more elegant, and how the additional task can be implemented.


texts: Converting a 1D Array of Strings to a 2D Array in Python

texts:
I was solving this question on a site that gives you a 1d array called grid

grid = ['top left',    'top middle',    'top right',
        'middle left', 'center',        'middle right',
        'bottom left', 'bottom middle', 'bottom right']

and you're expected to write a method fire(x,y) that takes in two coordinates and gives you back where you hit the grid.

For example:

fire(0,0) # 'top left'
fire(1,2) # 'bottom middle'

Here is my solution, I used NumPy for it.

import numpy as np
def fire(x,y):
#the grid is preloaded as you can see in description

    oneDArray = np.array(grid)
    twoDArray = oneDArray.reshape(3,3)

    return twoDArray[y][x]

I'm looking to get some feedback on the answer.


texts: Circle check algorithm optimization for directed graph

texts:
Here is my two versions of code to check if there is a circle for a directed graph. Any advice on performance improvements in terms of algorithm time complexity, code bugs or code style are highly appreciated.

More specifically, I have two questions:

My v2 method (refer to check_circle_v2) is an optimization which traverse only from in-degree zero nodes, and after DFS all in-degree zero nodes, I will check if there are still remaining nodes unvisited -- if yes, there are circle. I learned this method from some forum, but I am not sure if this algorithm truly has no bugs or truly have performance improvements comparing to straightforward dfs implementation in the code (refer to check_circle)?
If there are no in-degree zero nodes, can I make a conclusion that the graph has circle? Is that always true?

from collections import defaultdict
class Graph:
    def __init__(self):
        self.out_neighbour = defaultdict(list) # key has edge to value
        self.in_neighbour = defaultdict(list) # value has edge to key
        self.visited = set()
        self.nodes = set()
        self.being_visited = set()
    def add_edge(self, from_node, to_node):
        self.out_neighbour[from_node].append(to_node)
        self.in_neighbour[to_node].append(from_node)
        self.nodes.add(from_node)
        self.nodes.add(to_node)
    def check_circle_v2(self):
        for root in self.nodes:
            if root not in self.in_neighbour:
                if self.dfs(root):
                    return True
        if len(self.visited) < len(self.nodes):
            return True
        return False
    def check_circle(self):
        for root in self.nodes:
            if root not in self.visited:
                if self.dfs(root):
                    return True
        return False
    def dfs(self, node):
        self.being_visited.add(node)
        for n in self.out_neighbour[node]:
            if n in self.being_visited:
                return True # has circle
            elif n not in self.visited:
                if self.dfs(n):
                    return True
        self.visited.add(node)
        self.being_visited.remove(node)
        return False
if __name__ == "__main__":
    g = Graph()
    edges = [(1,2),(2,3),(3,1),(3,4)] # true
    edges = [(1, 2), (2, 3), (1, 3), (3, 4)] # false
    edges = [(4,1),(1,2),(3,2),(3,1)] # false
    for e in edges:
        g.add_edge(e[0],e[1])
    print g.check_circle()
    print g.check_circle_v2()


texts:
Is this code written in a decent style? Appreciate some feedback : )

private static int Max(int a, int b)
{
    return a > b ? a : b;
}

/// <summary>
/// Returns the solution to Knapsack01 problem. Uses bottom up dynamic programming.
/// </summary>
private static int Knapsack01(int capacity, int[] values, int[] weights)
{
    int[,] table = new int[values.Length + 1, capacity + 1];

    for (int row = 0; row <= values.Length; row++)
    {
        for (int column = 0; column <= capacity; column++)
        {
            if (row == 0 || column == 0)
            {
                // base case
                table[row, column] = 0;
            }

            else if (weights[row -1] <= column)
            {
                // item fits
                int valueAbove = table[row - 1, column];
                int spareCapacity = column - weights[row - 1];
                int currentValue = values[row - 1] + table[row - 1, spareCapacity];
                table[row, column] = Max(valueAbove, currentValue);
            }

            else
            {
                // item doesn't fit so copy value from above cell
                table[row, column] = table[row - 1, column];
            }
        }
    }

    return table[values.Length, capacity];
}


texts: Industrial Practices for Time-Series Forecasting

texts:
Hi I have wrote a code here for predicting temperature across months. This is the dataset that I was using: https://www.kaggle.com/sumanthvrao/daily-climate-time-series-data
I have used a SARIMA model and looking at the predicted results, it does seem to be pretty decent.
Given that I just started learning about a month ago and most of my reference materials are based off Youtube tutorial. I would just like to seek opinions from professional data scientist/ML experts on what are some caveats which I might have missed out or done wrongly here. (For instance, I saw in a video somewhere that mentioned RSS should be low whereas mine is pretty high here)
%tensorflow_version 2.x  # this line is not required unless you are in a notebook

import tensorflow as tf
from numpy import array
from numpy import argmax
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import os

#read data and filter temperature column
df = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/Weather Parameter/DailyDelhiClimateTrain.csv')
df["date"] = pd.to_datetime(df["date"])
df.date.freq ="D"
df.set_index("date", inplace=True)
df_monthly = df['meantemp'].resample('MS').mean()
plt.figure(figsize=(30,8))
plt.plot(df_monthly)

from statsmodels.tsa.seasonal import seasonal_decompose

sd = seasonal_decompose(df_monthly, model='additive')
sd.plot()
plt.show()

#make data stationary
df_monthly_diff = np.log(df_monthly).diff(12)
plt.figure(figsize=(15,5))
plt.plot(df_monthly_diff)
print(df_monthly_diff)

from statsmodels.tsa.stattools import adfuller
adf_result = adfuller(df_monthly_diff.dropna())
print('ADF Statistic: %f' % adf_result[0])
print('p-value: %f' % adf_result[1])
print('Critical Values:')
for key, value in adf_result[4].items():
    print('\t%s: %.3f' % (key, value))

from statsmodels.tsa.stattools import acf

lag_acf = acf(df_monthly_diff.dropna())

plt.figure(figsize=(20,5))
plt.plot(lag_acf)
plt.show

from statsmodels.tsa.stattools import pacf

lag_pacf = pacf(df_monthly_diff.dropna())

plt.figure(figsize=(20,5))
plt.plot(lag_pacf)
plt.show

from statsmodels.tsa.arima_model import ARIMA
import statsmodels.api as sm

# fit model
model = sm.tsa.statespace.SARIMAX(df_monthly,order=(0, 1, 0),seasonal_order=(0,1,0,12))
model_fit = model.fit()
# summary of fit model
print(model_fit.summary())
# line plot of residuals
residuals = model_fit.resid
residuals.plot()
plt.show()
# density plot of residuals
residuals.plot(kind='kde')
plt.show()
# summary stats of residuals
print(residuals.describe())

plt.figure(figsize=(20,5))
plt.plot(df_monthly)
plt.plot(model_fit.fittedvalues, color='red')
rss = sum((model_fit.fittedvalues-df_monthly)**2)
plt.show
print(rss)

df_test = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/Weather Parameter/DailyDelhiClimateTest.csv')
df_test["date"] = pd.to_datetime(df_test["date"])
df_test.date.freq ="D"
df_test.set_index("date", inplace=True)
df_test_monthly = df_test['meantemp'].resample('MS').mean()

pred = model_fit.predict(start=48,end=61,dynamic=True)
pred_df_monthly = df_monthly.append(pred)
df_monthly = df_monthly.append(df_test_monthly)

plt.figure(figsize=(20,8))
plt.plot(pred_df_monthly)
plt.plot(df_monthly)
plt.show

This is the predicted result from my code. Would really appreciate any comments. Thanks!


texts: Successful Encoder and Decoder for messages

texts:
I recently wrote a code for a encoder and decoder that works off of a key and the only way to decode the message is with this program and the case-sensitive key. I have yet to incorporate punctuation but that will come soon. I am currently designing a GUI using the  Tkinter module. I would love any feedback.

from random import seed, shuffle
#Encoder Function
def Encoder(user_input,SEED):
    user_input = user_input.lower()
    letter = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    Letter_code = {"a":0,"b":1,"c":2,"d":3,"e":4,"f":5,"g":6,"h":7,"i":8,"j":9,"k":10,'l':11,'m':12,'n':13,'o':14,'p':15,'q':16,'r':17,'s':18,'t':19,'u':20,'v':21,'w':22,'x':23,'y':24,'z':25}
    code = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',]
    n = []
    seed(SEED)
    shuffle(code)
    for letter in user_input:
        for let in letter:
            if letter != " ":
                if letter == let:
                    first = Letter_code[let]
                    n.append(code[first])
            else:
                n.append("~")
    return ''.join(n)

#Decoder Function
def Decoder(user_input,SEED):
    user_input = user_input.lower
    key_list = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    final = ["a","b","c","d","e","f","g","h","i","j","k",'l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    seed(SEED)
    shuffle(key_list)
    key_code = {}
    z = 0
    n = []
    for key in key_list:
        key_code[key] = z
        z += 1
    for let in user_input:
        if let != "~":
            for Ke in key_list:
                if let == Ke:
                    a = key_code[Ke]
                    n.append(final[a])
        else:
            n.append(" ")
return ''.join(n)

#Prompt
encode_decode = raw_input("Would you like to encode or decode a message?(encode/decode)")
encode_decode = encode_decode.lower()
if encode_decode == "encode":
    message = raw_input("Message to encode (no puncuation):")
    SEED = raw_input("Key:")
    print Encoder(message,SEED)
elif encode_decode == "decode":
    message = raw_input("Message to decode:")
    SEED = raw_input("Key:")
    print Decoder(message,SEED)
else:
    print "!!!INVALID RESPONSE!!!"


texts:
I have written a piece of code for removing duplicated values from a string. Any suggestions on improvements?

public static String removeDuplicate(String s)
{
    char [] temp = s.toCharArray();
    int length =temp.length;
    for (int i=0;i<length;i++)
    {
        for (int j = i+1; j<length;j++)
        {
            if(temp[i]==temp[j])
            {
                int test =j;
                for(int k=j+1; k<length ; k++)
                {
                    temp[test] = temp[k];
                    test++;
                }
                length--;
                j--;
            }
        }
    }
    return String.copyValueOf(temp).substring(0,length);
}


texts: Correcting time in DST gap using Joda Time

texts:
We have a class which acts as a time interval, containing a LocalDate and two counts of minutes since midnight.
One of the methods on this class converts these values into two DateTimes.
Since DateTime has time zone information built-in this conversion might fail if the time is in the daylight savings time "gap", i.e. the hour which disappears when going from winter time to summer time.
Instead I would like any such time to be advanced to the earliest later valid time, i.e. the time where the gap ends.

To solve this problem I have created the following method.

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

public class DstCorrector {
    public static DateTime getDateTimeCorrected(LocalDate localDate, int minutes) {
        DateTimeZone timeZone = DateTimeZone.getDefault();

        //Construct a LocalDateTime(which has no timezone)
        LocalDateTime startDateTime = localDate.toLocalDateTime(LocalTime.MIDNIGHT.plusMinutes(minutes));

        //Check if this time is in the DST gap, given the current time zone
        if(timeZone.isLocalDateTimeGap(startDateTime)) {
            //correct the time by moving it to the end of the gap
            long dayStartMillis = startDateTime.toLocalDate().toDateTimeAtStartOfDay().getMillis();
            long endOfGapMillis = timeZone.nextTransition(dayStartMillis);
            return new DateTime(endOfGapMillis, timeZone);
        }

        return localDate.toDateTime(LocalTime.MIDNIGHT.plusMinutes(minutes));
    }
}

With this test demonstrating expected behavior:

@Test
public void test() throws Exception {
    DateTime dateTimeCorrected = DstCorrector.getDateTimeCorrected(new LocalDate(2017, MARCH, 26), 150);//2:30 AM
    assertEquals(new DateTime(2017, MARCH, 26, 3, 0), dateTimeCorrected);
}

Is there a better way to do this?
I dislike the snippet inside the if, specifically that I am unable to get the exact millis of the invalid time, using the start of the day instead.
I know DateTimeZone has methods for converting to and from UTC which can be used to similar effect, but that converts by subtracting an hour from any time in the DST gap, which doesn't work in our case.


texts: Complementary multiply with carry in Rust

texts:
Background and motivation

I'm a C++ developer with a passion for modern, multi-threaded and functional code. I came across Rust not so long ago and it sounded like everything I wanted my C++ code to be. Naturally, I decided to try it out.

I was working on my own C++ project that had a need for some random numbers. I thought it would be a good opportunity to use some Rust and call into it from my C++ code. After some messing about, I thought I would convert some C/C++ code to Rust from the following pages:

http://school.anhb.uwa.edu.au/personalpages/kwessen/shared/Marsaglia03.html
https://stackoverflow.com/questions/12884351/complement-multiply-with-carry-cmwc-rng-c-winmain16-compile-issue

Long story short, I ended up with the following code:

Code

#[macro_use]
extern crate lazy_static;

mod pointgen_random
{
    const CMWC_CYCLE: u32 = 4096;
    const PHI: u32 = 0x9e3779b9;

    struct ComplementaryMultiplyWithCarryGen {
        q: [u32; CMWC_CYCLE as usize],
        c: u32,
        i: usize
    }

    impl ComplementaryMultiplyWithCarryGen {

        fn new(seed: u32) -> ComplementaryMultiplyWithCarryGen {
            let mut q_init = [0; CMWC_CYCLE as usize];

            q_init[0] = seed;
            q_init[1] = seed + PHI;
            q_init[2] = seed + PHI + PHI;

            for i in 3..CMWC_CYCLE as usize{
                q_init[i] = q_init[i - 3] ^ q_init[i - 2] ^ PHI ^ seed;
            }

            return ComplementaryMultiplyWithCarryGen{q: q_init, c: 362436, i: 4095};
        }

        fn reset(&mut self, seed: u32){
            let cmwc = ComplementaryMultiplyWithCarryGen::new(seed);
            self.q = cmwc.q;
            self.i = cmwc.i;
            self.c = cmwc.c;
    }

        fn random(&mut self) -> u32{
            const A: u64 = 18782;
            const R: u32 = 0xfffffffe;

            self.i = (self.i + 1) & (CMWC_CYCLE as usize - 1);
            let t = A * self.q[self.i] as u64 + self.c as u64;

            self.c = (t >> 32) as u32;
            let mut x = (t + self.c as u64) as u32;
            if x < self.c {
                x+=1;
                self.c+=1;
            }

            self.q[self.i] = R - x;
            return self.q[self.i];
        }
    }

    use std::sync::Mutex;

    // Lazy singleton random number generator
    lazy_static!{
            static ref GLOBAL_CMWC_GEN: Mutex<ComplementaryMultiplyWithCarryGen> = Mutex::new(ComplementaryMultiplyWithCarryGen::new(0));
    }

    pub fn get_random_cmwc() -> u32
    {
        GLOBAL_CMWC_GEN.lock().unwrap().random()
    }

    pub fn set_cmwc_seed(seed: u32)
    {
        GLOBAL_CMWC_GEN.lock().unwrap().reset(seed);
    }
}

// Public exports for PointGenLib
// All prefixed with pointgen_ to avoid name conflicts
#[no_mangle]
pub extern "C" fn pointgen_set_cmwc_seed(seed: u32)
{
    pointgen_random::set_cmwc_seed(seed);
}

#[no_mangle]
pub extern "C" fn pointgen_random_cmwc() -> u32
{
    return pointgen_random::get_random_cmwc();
}

It compiles on Windows without warning and appears to give some sensible pseudo-random numbers from 0 to 2^32, but there's just a lot of things in it that I don't like or don't feel right:

In fn new(), having q_init be mut seems like a hack, is there a more functional way to do this using slices?
Is this an appropriate struct to use the Default trait? I read that it's not recommended to use that.
There's a lot of as usize around, I don't quite have the feel for casting types as I would do in C++.
fn reset() seems ridiculous, is there a better way to reassign all values at once?

Any other help/suggestions/advice you can give would be very much appreciated.


texts: Batch retrieve formatted address along with geometry (lat/long) and output to csv

texts:
I have a csv file with 3 fields, two of which are of my interest, Merchant_Name and City.
My goal was to output multiple csv files each with 6 fields, Merchant_Name, City, name, formatted_address, latitude, longitude.

For example, if one entry of the csv is Starbucks, Chicago, I want the output csv to contain all the information in the 6 fields (as mentioned above) like so-
Starbucks, Chicago, Starbucks, "200 S Michigan Ave, Chicago, IL 60604, USA", 41.8164613, -87.8127855,
 Starbucks, Chicago, Starbucks, "8 N Michigan Ave, Chicago, IL 60602, USA", 41.8164613, -87.8127855
and so on for the rest of the results.

For this, I used Text Search request of Google Maps Places API. Here is what I wrote.

import pandas as pd
# import googlemaps
import requests
# import csv
# import pprint as pp
from time import sleep
import random

def search_output(search):
    if len(data['results']) == 0:
        print('No results found for {}.'.format(search))

    else:

        # Create csv file
        filename = search + '.csv'
        f = open(filename, "w")

        size_of_json = len(data['results'])

        # Get next page token
        # if size_of_json = 20:
            # next_page = data['next_page_token']

        for i in range(size_of_json):
            name = data['results'][i]['name']
            address = data['results'][i]['formatted_address']
            latitude = data['results'][i]['geometry']['location']['lat']
            longitude = data['results'][i]['geometry']['location']['lng']

            f.write(name.replace(',', '') + ',' + address.replace(',', '') + ',' + str(latitude) + ',' + str(longitude) + '\n')

        f.close()

        print('File successfully saved for "{}".'.format(search))

        sleep(random.randint(120, 150))

API_KEY = 'your_key_here'

PLACES_URL = 'https://maps.googleapis.com/maps/api/place/textsearch/json?'

# Make dataframe
df = pd.read_csv('merchant.csv', usecols=[0, 1])

# Construct search query
search_query = df['Merchant_Name'].astype(str) + ' ' + df['City']
search_query = search_query.str.replace(' ', '+')

random.seed()

for search in search_query:
    search_req = 'query={}&key={}'.format(search, API_KEY)
    request = PLACES_URL + search_req

    # Place request and store data in 'data'
    result = requests.get(request)
    data = result.json()

    status = data['status']

    if status == 'OK':
        search_output(search)
    elif status == 'ZERO_RESULTS':
        print('Zero results for "{}". Moving on..'.format(search))
        sleep(random.randint(120, 150))
    elif status == 'OVER_QUERY_LIMIT':
        print('Hit query limit! Try after a while. Could not complete "{}".'.format(search))
        break
    else:
        print(status)
        print('^ Status not okay, try again. Failed to complete "{}".'.format(search))
        break

I want to implement next page token but cannot think of a way which woudn't make it all a mess. Another thing I wish to improve is my csv writing block. And dealing with redundancy.
I further plan to concatenate all the csv files into one(but still keeping the original separate files).

Please note that I'm new to programming, in fact this is actually one of my first programs to achieve something. So please elaborate a bit more when need be. Thanks!


texts:
I have some concerns on my refactoring for the data layer in my current Project. Just for a small info, I am currently building a CRM as "training JEE application". But enough of talk, let's talk code!

IService.java: (7 lines, 160 bytes)

public interface IService<T> {
    public void update(T update);
    public void delete(long id);
    public T getById(long id);
}

IListService.java: (8 lines, 169 bytes)

public interface IListService<T> extends IService<T> {
    public void add(T add);
    public List<T> getAll();
}

IDependentListService.java: (8 lines, 225 bytes)

public interface IDependentListService<T> extends IService<T> {
    void add(T entity, long masterRecordId);
    List<T> getAllByMasterRecordId(long masterRecordId);
}

IAddressService.java: (7 lines, 199 bytes)

public interface IAddressService extends IDependentListService<Address>{
    public void promoteToMainAddress(long addressId);
}

IContactPersonService.java: (7 lines, 167 bytes)

public interface IContactPersonService extends IDependentListService<ContactPerson>{

}

IContractService.java: (9 lines, 234 bytes)

public interface IContractService extends IDependentListService<Contract> {
    public List<Contract> getAllContractsByLoggedInUser();
}

ICustomerService.java: (9 lines, 220 bytes)

public interface ICustomerService extends IListService<Customer> {

}

IProductService.java: (10 lines, 262 bytes)

public interface IProductService extends IListService<Product> {
    public List<Product> getAllCurrentProducts();
    public List<Product> getAllArchivedProducts();
}

IProjectService.java: (9 lines, 228 bytes)

public interface IProjectService extends IDependentListService<Project>{
    public List<Project> getAllProjectsByLoggedInUser();
}

IUserService.java: (7 lines, 129 bytes)

public interface IUserService extends IListService<User>{

}

Update (Code):

The code for the IUserService changed a bit, after reviewing the implementation of the CustomerService:

IUserService.java:

public interface IUserService extends IListService<User>{
    User getLoggedInUser();
}

Questions

Does this code follow good practices, especially concerning inheritance?
Naming. Should I really prepend I before the Interfaces? (Implementations are named without I). Are the names clear enough?
Everything else you see as problematic ;)

Update (Questions):

I am currently in the process of writing Javadoc for this code after refactoring it. Currently I use the interfaces as a Platform to place the Javadoc. In the implementation I would then just @see to the Interface Javadoc. Is it okay to do this, should I instead write out the Javadoc for the Implementations too and just @see to other implementations and the interfaces?


texts: Set logged-in USER in a Form requiring Current User Credentials

texts:
Currently, I can set the the current_user in the views.py for a form, which requires the user object to validate the post (and its origin).
Is there a better way to more eloquently set the user in a form than what I've posted below? Note, this is in views.py and I have no altered forms or models to tackle this aspect.
def index(request):
    article = Article.objects.all()
    if request.method == 'POST':
        form = ArticleForm(request.POST)
        # This segment below is the focal point of my question:
        if form.is_valid() and request.user.is_authenticated:
            form_object = form.save(commit=False)
            form_object.author = request.user
            form_object.save()
            return HttpResponseRedirect('to somewhere over the rainbow')
    else:
        # stuff

The code works. It just seems gimmicky to use a non-committed form, store it in a variable, alter the form object, then ultimately save it.


texts:
I want to assign the row of a matrix the return value of a function, but the only way I can figure out how to do this is with a for-loop. I'm assuming this is bad and vectorization would be better.

I'm trying to implement the first principle of the Neural Engineering Framework for a class. The function of the code is to get activation levels of a neuron and put them into an activities matrix.

# I'm going to use a rectified linear neuron model, because it's super easy to implement
def rec_lin_neuron(x_inter, max_fire, gain_sign, x_max=1.0):
    def rec_lin(x):
        return np.minimum(
                np.maximum(
                    np.dot(gain_sign, x) * (max_fire/(x_max-x_inter))
                    - x_inter * (max_fire/(x_max-x_inter)),
                    np.zeros(x.size)
                ),
                max_fire
            )
    return rec_lin

# We're going to make 16 neurons
n_neurons = 16

# These are the neuron attributes that will be created randomly
max_firing_rates = np.random.uniform(100, 200, n_neurons)
x_cepts = np.random.uniform(-0.95, 0.95, n_neurons)
gain_signs = np.random.choice([-1, 1], n_neurons)

# Create the neurons and stick them in a list, because I don't know how else to keep track of them
neurons = []
for i in range(n_neurons):
    neurons.append(rec_lin_neuron(x_cepts[i], max_firing_rates[i], gain_signs[i]))

# Now let's calculate the response of these neurons to an input and plot it
x_vals = np.arange(-1, 1, 0.05)
A = np.zeros((n_neurons, x_vals.size))

fig = plt.figure()
for i in range(n_neurons):
    A[i,:] = neurons[i](x_vals)
    plt.plot(x_vals, A[i,:])
plt.show()


texts:
I have a fairly complicated function to decode an LZSS byte stream.
decodeLZSS :: Bits -> [GHC.Word.Word8] -> [GHC.Word.Word8]
decodeLZSS (x : xs) decoded = if length xs >= 8
    then
        if x
        then decodeLZSS (drop byteSize xs) (decoded ++ [bitsToWord $ take byteSize xs])
        else decodeLZSS (drop (lookaheadPower + bufferPower) xs)
                        (decoded ++ LZ77Common.slice startSlice endSlice decoded)
    else
        decoded
  where
    startSlice = length decoded - bitsToInt (LZ77Common.slice lookaheadPower (lookaheadPower + bufferPower) xs)
    endSlice   = startSlice + bitsToInt (take lookaheadPower xs)
decodeLZSS [] decoded = decoded

I call the function as follows
(decodeLZSS (concatMap wordToBits (B.unpack bytes)) [])

It works but I have read the you should avoid explicit recursion, in this case what I am doing kind of feels like a fold, but since my steps are variable size I'm not sure if its possible. Is it possible to express this function without recursion?


texts:
I've written a small script to calculate Collatz sequences. For background, read here about the Collatz conjecture. Largest number I've tried so far in my implementation is 93571393692802302 (which wikipedia claims is the number requiring most steps below 10e17), which needs 2091 steps. Apparently I count different from Wikipedia, as my len(collatz(93571393692802302)) is 2092 long, but I include the number itself as well as the final 1 .

A Collatz sequence takes a number, and calculates the next number in sequence as following:

If it is even, divide by two
If it is odd, triple and add one.

The Collatz Conjecture claims that all sequences created this way converge to 1. It is unproven, but it seems most mathematicians suspect it's True.

Without further ado, the code:

from typing import List

collatz_cache = {}

def _calc(number: int) -> int:
    """
    Caches this number in the collatz_cache, and returns the next in sequence.
    :param number: Integer > 1.
    :return: Integer > 0
    """
    if number % 2 == 0:
        next_number = number // 2
    else:
        next_number = number * 3 + 1
    collatz_cache[number] = next_number
    return next_number

def collatz(number: int) -> List[int]:
    """
    Returns the collatz sequence of a number.
    :param number: Integer > 0
    :return: Collatz sequence starting with number
    """
    if not isinstance(number, int):
        raise TypeError(f"Collatz sequence doesn't make sense for non-integers like {type(number).__name__}")
    if number < 1:
        raise ValueError(f"Collatz sequence not defined for {type(number).__name__}({number})")
    new_number = number
    result = [number]
    while new_number not in collatz_cache and new_number != 1:
        new_number = _calc(new_number)
        result.append(new_number)
    while result[-1] != 1:
        result.append(collatz_cache[result[-1]])
    return result

I've tried to minimize calculation time in repeated attempts by creating a mapping for each number to the next number in the sequence. First I just mapped to the full list, but that would make the dictionary a bit bigger than I really wanted.

I feel that there should be some gains to be made in the list construction, but I'm at loss as to the how.

Purpose of this code is to basically be a general library function. I want to:

Be fast
Be memory efficient with my cache
Handle multiple equal/partially overlapping sequences
Handle completely different sequences

And all of that at the same time. Any code stylistic improvements are of course welcome, but any suggestions improving the above goals without disproportional disadvantage to the others are also welcome.


texts: Creating a structured category list in F#

texts:
This takes a list of categories and organizes them into a tree-type structure based on their parentId.  This code works, but is obviously a little over-complicated. How can I optimize it?

type ValidString = | ValidString of string | NotValid

type CategoryStructure = {
    Id: ValidString;
    ParentId: ValidString;
    Name: ValidString;
    Abbreviation: ValidString;
    Description: ValidString;
    SapId: ValidString;
    Section: ValidString;
    SectionPosition: ValidString
}

type DynamicCategories = {
    Category: CategoryStructure;
    SubCategories: seq<DynamicCategories>
}

let rec private structureCategories (fullList: CategoryStructure list)
    (list: CategoryStructure list)  =

    List.fold (fun acc elem ->

                    // get all categories and details
                    let categories = fullList
                    let mainAcc =
                        [

                            for row in categories do
                                if row = elem
                                then
                                    let subs =
                                        List.fold (fun acc' elem' ->

                                                    if row.Id = elem'.ParentStructureId
                                                    then
                                                        let modifiedList = elem' :: List.empty<CategoryStructure>
                                                        let foundSubCategory =
                                                            {
                                                                Category = elem';
                                                                SubCategories = structureCategories fullList modifiedList |> Seq.ofList
                                                            }
                                                        foundSubCategory :: acc'
                                                    else acc'

                                                    ) List.empty<DynamicCategories> categories
                                        |> Seq.ofList
                                    yield{
                                        Category = elem;
                                        SubCategories = subs
                                    }

                        ]

                    mainAcc @ acc
                    ) List.empty<DynamicCategories> list

// get the initial parent categories and then call the above code to finish the organizing the list
let getStructuredCategories () =

        let categories = allCategoriesAndDetails () |> List.ofSeq
        [
            for row in categories do
                if row.ParentStructureId = NotValid
                then yield row
        ] |> structureCategories categories |> Seq.ofList


texts: Slider that increased center slide width. (Slider plugin suggestions)

texts:
I wanted to create slider when it slide center slide width must have incresed and the two slide next to it stay on normal slide.

I have tried one using slick slider.

Here is the code pen link that I have tried.

But this is not smooth and slide next to center slide not showing properly.

If anyone know some better slider for do exact kind of this please suggest me a link.

$('.slider').slick({
  slidesToShow: 3,
  centerMode: true,
  centerPadding: "0px",
  speed: 1000

});

$('.slider').on('beforeChange', function(event, slick, currentSlide, nextSlide){

  $(slick).next().css({
    'margin-left':'auto'
  });//this code not working
});
html,
body {
  background: #102131;
}
.slider {
  width: 1140px;
  margin: 20px auto;
  text-align: center;
  padding: 20px;
  color: white;
}
.slider .slide {
  padding: 0px;
}
.slider .slide .child-element {
  transition: all .2s ease;
  background: #0c1c79;
  width: 100%;
  height: 800px;
  width: 300px;
}
.slider .slide .child-element .imgWrap img {
  width: 100%;
  max-width: 100%;
}
.slider .slide .child-element .desc {
  display: none;
}
.slider .slide.slick-active:last-chid .child-element {
  margin-left: auto;
}
.slider .slide.slick-center .child-element {
  background: rebeccapurple;
  -webkit-transform: translate(-70px, 0px);
          transform: translate(-70px, 0px);
  width: calc(100% + 140px);
  max-width: initial;
}
.slider .slide.slick-center .child-element .desc {
  display: block;
}
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<link href="//cdn.jsdelivr.net/jquery.slick/1.5.0/slick.css" rel="stylesheet"/>
<link href="//cdn.jsdelivr.net/jquery.slick/1.5.0/slick-theme.css" rel="stylesheet"/>

Title1

Lorem ipsum dolor

Title2

Lorem ipsum dolor

Title3

Lorem ipsum dolor

Title4

Lorem ipsum dolor

Title5

Lorem ipsum dolor


texts:
I am new to programming and need input on how I could've written something better. Not coding on daily basis. The task was to write a script in python, bash or anything. So I mixed python with bash commands using python module os.systems. Some friends recommended lists but I wanted the output to be similar as the example in this task:

Write a script (Bash, Python etc.) that checks for files - in directory X - that have not been
modified in (older than) the last Y days.
The directory and days should be passed to the script as mandatory arguments.
The script shall only look for files in directory X,
not in sub directories. You may assume that none of the filenames contain newlines.
The output of the script should print the file names, and the time for
when the file was last modified, sorted by modification time:
./README.txt                      2019-05-09  17:19:53.193771720  +0200
./README.txt.gpg                  2019-05-09  17:20:21.331833720  +0200
./migratemost-master.zip          2019-05-20  12:52:34.867119547  +0200
./INC177759                       2019-05-23  13:29:47.014557386  +0200

Include a help option, so that if '-h' or '--help' is passed as an optional
argument, a summary of what the program does is printed to stdout.
Also try to handle user errors so the script exits gracefully with an error
message upon incorrect - or missing - input.

My solution that I need help to refactor/improve peer review on:
import os
import sys

days = raw_input("Please enter days: ")
if days.isdigit():
    print "You entered:", days
else:
    sys.exit("Exiting the program, wrong data type.")

dir = raw_input("Please enter path: ")
print "You entered:", dir

stuff_in_string = "find {} -type f -mtime -{}".format(dir, days)
print stuff_in_string

print(os.system('{} | xargs -d \'\n\' ls -lth --full-time'.format(stuff_in_string)))

The output:
$ python main.py
Please enter days: asdf
Exiting the program, wrong data type.
$
$ python main.py
Please enter days: 365
You entered: 365
Please enter path: .
You entered: .
find . -type f -mtime -365
-rw-r--r--. 1 root root 413 2020-09-21 16:43:48.608029286 +0200 ./main.py
-rw-r--r--. 1 root root   0 2020-09-21 09:36:17.072137720 +0200 ./file2.csv
-rw-r--r--. 1 root root   0 2020-09-21 09:35:28.502502950 +0200 ./file1.txt
0
$
$ python main.py
Please enter days: 9999
You entered: 9999
Please enter path: .
You entered: .
find . -type f -mtime -9999
-rw-r--r--. 1 root root 413 2020-09-21 16:43:48.608029286 +0200 ./main.py
-rw-r--r--. 1 root root   0 2020-09-21 09:36:17.072137720 +0200 ./file2.csv
-rw-r--r--. 1 root root   0 2020-09-21 09:35:28.502502950 +0200 ./file1.txt
-rw-r--r--. 1 root root   0 2012-01-01 00:00:00.000000000 +0100 ./goldenfile.xls
0


texts: just making sure this is efficient, for the null checks

texts:
This is inside a method (basically its just this), I try to get the neededValue otherwise I pass back what was passed in...

private static string GetNeededValue(string param)
    {
        string tValue = "";

        if (!string.IsNullOrEmpty(param))
        {
            var map = repo.Item(string.Format("CoverageName LIKE '{0}'",param));
            tValue = map == null ? param : map.theNeededValue;
        }

        return tValue;
    }


texts: Manual slide-in animation using delta time

texts:
I created a simple slide-in animation for my game. The box is shown at the bottom with character dialog.

The animation is as follows:

A square slides in from the left, then waits a bit, then expands to its full width.

The box is made using Unity's GUI Box. The timing is extended for debugging purposes (I need to be able to clearly see the animation).

It isn't coded spectacularly (I wrote it in 5 minutes in the first way that occurred to me), but I can't really think of another way to write it at the moment. What would you improve?

private string boxString = "Hello, world! I am sample character dialog.";

private float elapsedTime = 0.0f;

private float initialSlideInDuration = 1.333f;
private float waitBetweenSlideAndExpand = 0.666f;
private float expansionDuration;

private float boxHeightPercentage = 0.10f;
private float boxWidthPercentage = 0.95f;
private float positionFromLeft;
private float positionFromBottom;
private float boxWidth;
private float boxHeight;

// instantiate variables before any frames are drawn
void Start () {
    expansionDuration = initialSlideInDuration + waitBetweenSlideAndExpand + 3.333f;
    boxWidth = Screen.width*boxWidthPercentage;
    boxHeight = Screen.height*boxHeightPercentage;
    positionFromLeft = (Screen.width - (Screen.width * boxWidthPercentage)) / 2;
    positionFromBottom = Screen.height - (positionFromLeft + boxHeight);
}

// called once per frame
void Update () {
    elapsedTime += Time.deltaTime;
}

// render and handle GUI events
void OnGUI() {
    // slide in square
    if (elapsedTime <= initialSlideInDuration) {
        float initialLeftPadding = -positionFromLeft - boxHeight;
        float finalLeftPadding = positionFromLeft;
        float movementDistance = (2 * positionFromLeft) + boxHeight;
        float progress = elapsedTime / initialSlideInDuration;

        GUI.Box (new Rect ((progress * movementDistance) + initialLeftPadding, positionFromBottom, boxHeight, boxHeight), boxString);
    }
    // if square is ready and we have waited, animate to rectangle
    else if (elapsedTime > initialSlideInDuration+waitBetweenSlideAndExpand && elapsedTime <= expansionDuration) {
        float initialWidth = boxHeight;
        float finalWidth = boxWidth;
        float growth = finalWidth - initialWidth;
        float progress = elapsedTime / expansionDuration;

        GUI.Box(new Rect(positionFromLeft, positionFromBottom, (progress * growth) + initialWidth, boxHeight), boxString);
    }
    // stay as full width rectangle
    else if(elapsedTime > expansionDuration){
        GUI.Box (new Rect (positionFromLeft, positionFromBottom, boxWidth, boxHeight), boxString);
    }
    // we are waiting, display the square with left padding
    else {
        GUI.Box (new Rect (positionFromLeft, positionFromBottom, boxHeight, boxHeight), boxString);
    }
}


texts: ChunkerTransformStream, a transform stream to take arbitrary chunk sizes and make them consistent

texts:
I have some code to interface with a wire protocol that requires data to be inserted into a stream at regular byte intervals.  Every 8KB (or at some other definable interval), a small chunk will be inserted.  To make this easy, I decided to create a transform stream that would take a flowing stream and write fixed chunk sizes.  That is, this stream can be written to in any size (2KB here, 500KB there, 5 bytes next, etc.) and it will output chunks in 8KB of size every time.

var stream = require('stream');
function ChunkerTransformStream (chunkSize) {
    chunkSize = chunkSize || 8192;

    var buffer = new Buffer(0);

    var chunker = new stream.Transform({objectMode: true});
    chunker._transform = function (chunk, encoding, done) {
        buffer = Buffer.concat([buffer, chunk]);

        while (buffer.length >= chunkSize) {
            this.push(buffer.slice(0, chunkSize));
            buffer = buffer.slice(chunkSize);
        }

        done();
    }

    chunker._flush = function (done) {
        if (buffer.length) {
            this.push(buffer);
            done();
        }
    }

    return chunker;
}

module.exports = ChunkerTransformStream;

This transform stream will be used heavily in my code, having several megabit pushed through it per second.  Is this the most efficient way to achieve what I want?  I am most concerned about my buffer operations.  It's my understanding that Buffer.concat() is very expensive, as it allocates an entirely new buffer and copies the first two to it.

Any feedback, on performance or otherwise, is welcomed.


texts:
This code stores the last know location in the session. The location is not stored if it is one of the exceptions in the if statement.

def store_location
    if request.fullpath != '/users/sign_in' &&
     request.fullpath != '/users/sign_up' &&
     request.fullpath != '/users/password' &&
     request.fullpath != '/users/sign_out' &&
     request.fullpath != '/accounts' &&
     request.fullpath != '/accounts/new' &&
     !request.fullpath.include?('/users/confirmation') &&
     request.fullpath != '/' &&
     !request.xhr?

     session[:previous_url] = request.fullpath
   end
  end

I need to make it more simple.


texts:
Here's an excerpt from my migration script for my database for the new "remember me" login option for my web application.

Logging in with a valid username/password combination (authenticate_user) will generate a new token and a hash of it is stored in the tokens table.
When authenticating with a token (authenticate_token), the old token is removed from the database, the user is given a new one, and a session is started for them.
If the user changes their password, all tokens for that user become invalid.

The process appears to work, but is it secure enough?

/*----------------------------------------------------------------------------------------------------*\
                                                                      | New Tables
\*----------------------------------------------------------------------------------------------------*/

CREATE TABLE user_login_tokens (
    user_id INT NOT NULL,
    token TEXT NOT NULL,
    expiry TIMESTAMPTZ NOT NULL DEFAULT now() + interval '1 week',

    PRIMARY KEY (user_id, token),
    UNIQUE (token),
    FOREIGN KEY (user_id) REFERENCES users (id)
);
COMMENT ON TABLE user_login_tokens IS 'A collection authentication tokens for a given user that allows them to login without supplying a username/password';

/*----------------------------------------------------------------------------------------------------*\
                                                                      | New / Updated Functions
\*----------------------------------------------------------------------------------------------------*/

CREATE OR REPLACE FUNCTION authenticate_user(_email TEXT, _password PASSWORD, _remember BOOL) RETURNS TABLE
    (id INT, name TEXT, token TEXT, authenticated BOOL) AS $$
DECLARE
    u record;
BEGIN
    SELECT
        users.id,
        users.name,
        CASE WHEN _remember
            THEN crypt(users.id || users.password, gen_salt('bf'))
            ELSE null END AS token,
        password = crypt(_password, password) AS authenticated
    FROM users
    WHERE email = _email INTO u;

    -- only modify user data if the authentication was successful
    IF u.authenticated THEN
        UPDATE users
        SET
            reset_token_expiry = NULL
        WHERE
            users.id = u.id;

        IF _remember THEN
            INSERT INTO user_login_tokens
                (user_id, token)
            VALUES
                (u.id, crypt(u.token, gen_salt('bf')));
        END IF;
    END IF;

    RETURN QUERY SELECT u.id, u.name, u.token, u.authenticated WHERE u.id IS NOT NULL;
END;
$$ LANGUAGE plpgsql;

---------------------------------------------------------------------

CREATE OR REPLACE FUNCTION authenticate_token(_token TEXT) RETURNS TABLE
    (id INT, name TEXT, email TEXT, token TEXT) AS $$
DECLARE
    u RECORD;
BEGIN
    -- verify the validity of our token
    SELECT
        users.id,
        users.name,
        users.email,
        crypt(users.id || users.password, gen_salt('bf')) AS token,
        user_login_tokens.token AS old_token
    FROM
        users
        JOIN user_login_tokens ON user_id = users.id
    WHERE
        expiry > NOW()
        AND user_login_tokens.token = crypt(_token, user_login_tokens.token)
        AND _token = crypt(users.id || password, _token)
    INTO u;

    -- if our token is valid, we need to store a new token because the old one has been used up
    IF FOUND THEN
        INSERT INTO user_login_tokens
            (user_id, token)
        VALUES
            (u.id, crypt(u.token, gen_salt('bf')));
    END IF;

    -- then delete any expired tokens + the used up token
    DELETE FROM user_login_tokens WHERE expiry < NOW() OR user_login_tokens.token = u.old_token;

    RETURN QUERY SELECT u.id, u.name, u.email :: TEXT, u.token WHERE u.id IS NOT NULL;
END;
$$ LANGUAGE plpgsql;


texts:
Simplification of code would be appreciated.

var textarea = document.getElementById("textarea"),
  statusBar = document.getElementById("status-bar"),
  inputFile = document.getElementById("input-file"),
  appname = "notepad",
  isModified = false,
  showStatusBar = true,
  filename;

function changeDocTitle(newFilename) { // Change doc title
  filename = newFilename;
  document.title = filename + " - " + appname;
}

function dontSave() { // Confirm dont save
  if (confirm("You have unsaved changes that will be lost.")) {
    isModified = false;
    return true;
  }
}

function newNote(text, name) { // New
  if (!isModified || dontSave()) {
    textarea.value = text || "";
    changeDocTitle(name || "untitled.txt");
  }
  textarea.focus();
}

function openNote() { // Open
  if (!isModified || dontSave()) {
    inputFile.click();
  }
  textarea.focus();
}

function rename() { // Rename
  var newFilename = prompt("Name this note:", filename);
  if (newFilename !== null) {
    if (newFilename === "") {
      changeDocTitle("untitled.txt");
    } else {
      changeDocTitle(newFilename.lastIndexOf(".txt") == -1 ? newFilename + ".txt" : newFilename);
    }
    return true;
  }
}

function saveNote() { // Save
  if (rename()) {
    var blob = new Blob([textarea.value.replace(/\n/g, "\r\n")], {
      type: "text/plain;charset=utf-8"
    });
    saveAs(blob, filename);
    isModified = false;
  }
  textarea.focus();
}

function updatestatusBar() { // Update statusBar
  var text = textarea.value,
    chars = text.length,
    words = text.split(/\S+/g).length - 1,
    lines = text.split("\n").length;
  statusBar.value = lines + " lines, " + words + " words, " + chars + " characters";
}

function showStatusBarFunc() {
  textarea.style.height = "calc(100% - 18px)";
  statusBar.style.display = "";
  showStatusBar = true;
  updatestatusBar();
}

function hideStatusBarFunc() {
  textarea.style.height = "";
  statusBar.style.display = "none";
  showStatusBar = false;
}

function toggleStatusBar() {
  if (showStatusBar) {
    hideStatusBarFunc();
  } else {
    showStatusBarFunc();
  }
}

textarea.addEventListener("input", function() {
  isModified = true;
  if (showStatusBar) {
    updatestatusBar();
  }
});

inputFile.addEventListener("change", function() { // Load file
  var file = inputFile.files[0],
    reader = new FileReader();
  reader.onload = function() {
    newNote(reader.result, file.name);
  };
  reader.readAsText(file);
});

document.addEventListener("keydown", function(e) { // Shortcuts
  if (e.altKey && e.shiftKey) { // Alt+Shift
    newNote();
  }
  if (e.ctrlKey) { // Ctrl+
    switch (e.keyCode) {
      case 79: // O
        e.preventDefault();
        openNote();
        break;
      case 83: // S
        e.preventDefault();
        saveNote();
        break;
      case 66: // B
        e.preventDefault();
        toggleStatusBar();
        break;
      case 191: // /
        e.preventDefault();
        alert("Help note for " + appname + " will be added soon!");
        break;
    }
  }
  if (e.keyCode == 9) { // Tab
    e.preventDefault();
    var sStart = textarea.selectionStart,
      text = textarea.value;
    textarea.value = text.substring(0, sStart) + "\t" + text.substring(textarea.selectionEnd);
    textarea.selectionEnd = sStart + 1;
  }
});

onunload = function() { // Save localStorage
  if (isModified) {
    localStorage.setItem("text", textarea.value);
    localStorage.setItem("name", filename);
  } else {
    // localStorage.clear();
    localStorage.removeItem("text");
  }
  localStorage.setItem("showStatusBar", showStatusBar);
};

onload = function() { // Load localStorage
  if (localStorage.getItem("text")) {
    newNote(localStorage.getItem("text"), localStorage.getItem("name"));
    isModified = true;
  } else {
    newNote();
  }
  showStatusBar = JSON.parse(localStorage.getItem("showStatusBar"));
  if (showStatusBar) {
    showStatusBarFunc();
  } else {
    hideStatusBarFunc();
  }
};


texts: Starting with asynchronous JS and promises

texts:
I've learn to code almost alone, so I really need some ideas/advice, as it started to get really difficult to advance.
Because this is mostly server side, I can't provide a running snippet, but yet it's a short snippet.
Code
When I press a UI button, it fetches a resource, and this should create a set of list items. Simple enough:
const btn = document.getElementById("btn")
const ul = document.getElementById("ul")
const putItems = (items)=>{items.forEach(item=>ul.innerHTML=`
<li>${item.msg}</li>`)}

btn.addEventListener("click", ()=>{
    fetch("https://localhost:3000/todos")
        .then(res=>res.json())
        .then(d=>putItems(d))
        .catch(e=>console.log(e))
})

On the server side, the main function and imports are:
const { MongoClient } = require("mongodb")
const cors = require('cors')
app.use(cors())

async function callDB(){   //get data from mongoDB
    const call = await MongoClient.connect( uri, {useNewUrlParser:true, useUnifiedTopology:true})
    let result
    try{
        result = await call
            .db("todos")
            .collection("items")
            .find({})
            .toArray()
    } catch(e){
        console.log(e)
    }

    return result;
}

app.get("/todos", cors(), (req, res)=>{
    const items = callDB().then(d=>res.json(d)).catch(e=>console.log(e))
});

This code imports dotenv to hide my sensible parts, and uses express I removed those imports just to be concise.
Mainly, I'd like to know if my asynchronous practice makes sense, or not. And I'm also getting a CORS error, that couldn't fix after an hour. That would help too.


texts: Using Curl/Post to execute a HTTP request

texts:
I have a loop in a php file to HTTP_Request Server Via CURL->POST.

But I don't know if I'm missing any security considerations. Also, is there a better way to perform this http request?

<?php
$j = 0;
while ($j <= 1) {
    $url    = 'http://127.0.0.1/index.php';
    $fields = array(
        'input1' => 'variable1',
        'input2'    => 'variable2',
    );
    $postvars         = http_build_query($fields);
    $COOKIE_FILE_PATH = "/tmp/cookiescron.txt";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
    curl_setopt($ch, CURLOPT_TIMEOUT, 2);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
    curl_setopt($ch, CURLOPT_FORBID_REUSE, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
    curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));
    // execute post
    curl_exec($ch);
    // close connection
    curl_close($ch);
    $j++;
    sleep(25);
}
?>

This executes 2 requests in around 25~30 seconds.


texts: Getting the previous sibling of a node using Roslyn

texts:
I am currently creating an analyzer using the roslyn sdk. I ran into a case where it was simpler to check child tokens for Wait()/.Result.

The code i am sharing works perfectly fine - However i was unable to find a better way on google nor through browsing the docs.

This way of getting the previous sibling of a node feels very weird - Is there a better way?

        if (context.Node is IdentifierNameSyntax identifierName)
        {
            if (identifierName.Identifier.Text == TaskIdentifierWait || identifierName.Identifier.Text == TaskIdentifierResult)
            {
                var siblingsAndSelf = identifierName.Parent.ChildNodes().ToImmutableArray();
                var selfIndex = siblingsAndSelf.LastIndexOf(identifierName);
                if (selfIndex <= 0)
                    return;

                var previousSibling = siblingsAndSelf[selfIndex-1];


texts: Casting the left and right numbers as integers or doubles

texts:
How can I remove the code duplication in this code? It is trying to cast the left and right numbers as integers or doubles and then using it.

public Object example(Object left, Object right) {
    if(left instanceof Integer && right instanceof Integer) {
        switch (operator) {
            case ADD:
                return (Integer)left + (Integer)right;
            case SUB:
                return (Integer)left - (Integer)right;
            case MUL:
                return (Integer)left * (Integer)right;
            case DIV:
                return (Integer)left / (Integer)right;
        }
    } else if(left instanceof Double && right instanceof Double) {
        switch (operator) {
            case ADD:
                return (Double)left + (Double)right;
            case SUB:
                return (Double)left - (Double)right;
            case MUL:
                return (Double)left * (Double)right;
            case DIV:
                return (Double)left / (Double)right;
        }
    } else {
        throw new Error("wrong types of arguments");
    }
}