texts:
I'm using Entity Framework 6 with database first. See the image for the relevant database schema

I have the following method to save a Set to the database:

/// <summary>
/// Saves the list of data sources. This assumes that the ModelTemplateID, SetNumber and TaskNumber
/// are already properly set. Adds a new record to the DataSourceGroups table if necessary.
/// </summary>
/// <param name="dataSources">The list of data sources to save</param>
public void SaveSet(IEnumerable<DataSource> dataSources)
{
    using (var db = _contextFactory.GetContext())
    {
        foreach (var dataSource in dataSources)
        {
            var dataSourceFromDb =
                db.DataSources.FirstOrDefault(x => x.DataSourceID == dataSource.DataSourceID);

            if (dataSourceFromDb == null)
            { // not in database yet, add it
                var dataSourceGroupFromDb =
                    db.DataSourceGroups.SingleOrDefault(
                        x => x.ModelTemplateID == dataSource.ModelTemplateID &&
                             x.SetNumber == dataSource.SetNumber &&
                             x.TaskNumber == dataSource.TaskNumber);
                if (dataSourceGroupFromDb == null)
                { // Add new DataSourceGroup to db
                    db.DataSourceGroups.Add(new DataSourceGroup
                    {
                        ModelTemplateID = dataSource.ModelTemplateID,
                        SetNumber = dataSource.SetNumber,
                        TaskNumber = dataSource.TaskNumber
                    });
                }
                db.DataSources.Add(dataSource);
            }
            else
            { // already in database, if any fields are different then update it
                if (dataSourceFromDb.QueryID      != dataSource.QueryID || // todo make DataSource Comparer
                    dataSourceFromDb.SourceType   != dataSource.SourceType ||
                    dataSourceFromDb.TargetFormat != dataSource.TargetFormat ||
                    dataSourceFromDb.SourcePath   != dataSource.SourcePath ||
                    dataSourceFromDb.TargetPath   != dataSource.TargetPath)
                {
                    db.DataSources.Attach(dataSource);
                    db.Entry(dataSource).State = EntityState.Modified;
                }
            }
        }
        db.SaveChanges();
    }
}

Is this the best way to implement this method? Should I be attaching the DataSources to the Set when they are created and then just pass the Set into the method? Any other critiques welcome.


texts: Huge Fibonacci modulo m optimization in Python 3

texts:
I'm doing some an Algorithm Design online course as a way of learning algorithms and Python as well. One of these challenges requires that I write code for finding a "Huge Fibonacci Number Modulo m". The code works, but for some inputs (such as 99999999999999999 100000), it exceeds the allocated time limit. However, I can't see a way of improving performance.

Here is the problem description:

  Problem Introduction

  The Fibonacci numbers are defined as follows:

  F(0) = 0, F(1) = 1, and F(i) = F(i−1) + F(i−2) for i ≥ 2.

  Problem Description

  Task: Given two integers n and m, output F(n) mod m (that is, the remainder of F(n) when divided by m).

  Input Format: The input consists of two integers n and m given on the same line (separated by a space).

  Constraints: 1 ≤ n ≤ 10^18 , 2 ≤ m ≤ 10^5 .

  Output Format: Output F(n) mod m

  Time Limits:C: 1 sec, C++: 1 sec, Java: 1.5 sec, Python: 5 sec. C#: 1.5 sec, Haskell: 2 sec, JavaScript: 3 sec, Ruby: 3 sec, Scala: 3
  sec. Memory Limit: 512 Mb

  Sample:

Input:

    281621358815590 30524

Output:

    11963

Here is the code:

#!/usr/bin/python3

from sys import stdin

def get_fibonacci_huge(n, m):
    fibonacciNumbers = [0, 1, 1]
    pisanoNumbers = [0, 1, 1]
    pisanoPeriod = 3

    for i in range(2, n):
        if pisanoNumbers[i - 1] == 0 and pisanoNumbers[i] == 1:
            pisanoPeriod = i - 1
            break;

        nextFibonacci = fibonacciNumbers[i - 1] + fibonacciNumbers[i];

        fibonacciNumbers.append(nextFibonacci)
        pisanoNumbers.append(nextFibonacci % m)
    else:
        pisanoPeriod = None # If we exhausted all values up to n, then the pisano period could not be determined.

    if pisanoPeriod is None:
        return pisanoNumbers[n]
    else:
        return pisanoNumbers[n % pisanoPeriod]

if __name__ == '__main__':
    dataEntry = stdin.readline()
    n, m = map(int, dataEntry.split())
    print(get_fibonacci_huge(n, m))

For an input of 99999999999999999 100000, it takes around 5.10 seconds, and the maximum allowed time is 5.00 seconds.

As a complete Python and algorithms newbie, any input is appreciated.


texts: localStorage setExpire code to add time expires

texts:
Storage.prototype.setExpire = function (arrObj) {
    var date,
        now,
        days,
        deletes,
        items,
        fa, ta,
        newItems = [],
        storage = localStorage.getItem('limitStorage');
    items = JSON.parse(storage || "[]");
    date = new Date();
    date = date.toString().split(' ');
    date = Number(date[2]);
    for (var key in arrObj) {
        for (i = 0; i < items.length; i++) {
            if (items[i].value == key) {
                if (typeof (items[i].days) == "number") {
                    if (items[i].date !== date) {
                        days = (date - items[i].date);
                    } else {
                        days = items[i].days;
                    }
                }
            }
        }
        ta = {
            value: key,
            limit: arrObj[key],
            date: date,
            days: days !== undefined ? days : 0
        };
        if (ta.days >= ta.limit) {
            localStorage.removeItem(ta.value);
        }
        if(localStorage.getItem(ta.value) !== null) newItems.push(ta);
    }
    localStorage.setItem('limitStorage', JSON.stringify(newItems));
};

This code runs by simply calling the Storage method and then adding method .setExpire.

Example:

window.localStorage.setExpire({"item1":3,"item2":10,"item3":3});

I have to add more to the code to take into account day 31 to day 1.  But as of now, if the item is added on day 20 and you want it to expire in 7 days on day 27, the localStorage item will be removed.

My question is: does anyone see anything they can review for me? Maybe a cross-browser compatibility issue?  I already have a cross-browser localStorage that falls back to cookies if need be.

Also let me know if you may think of a way for the code to take into account the ending to the start of a months, since the code technically only takes the new date and then subtracts the stored date, which gets our days that have passed.

Any and all suggestions are welcomed.


texts:
I have written the following code for bubble sort. How can it be optimised?

def bubble_sort(details):
    """compares two consecutive integers in a list and shifts the smaller one to left """
    for i in range(len(details)-1):
        try:
            if details[i] > details[i+1]:
                temp = details[i]
                details[i]= details[i+1]
                details[i+1] = temp
                bubble_sort(details)
        except IndexError:
            return
    return details

sort_me = [11,127,56,2,1,5,7,9,11,65,12,24,76,87,123,65,8,32,86,123,67,1,67,92,72,39,49,12, 98,52,45,19,37,22,1,66,943,415,21,785,12,698,26,36,18,97,0,63,25,85,24,94,1501]
print sort_me
print bubble_sort(sort_me)


texts: Finding the indices where a selected player appears in a list of hashes

texts:
I have an array of hashes in a YAML file. When I run the code below it is VERY slow. My YAML pwsarr.count is about 2000.

I am somewhat new to Ruby so I don't know if my code is not efficient or if I am doing something wrong. I know it loops my array before it's in the method and it loops in the method, but I wouldn't think it would make it as slow as it is.

def pwsplayerindex(inplayer)
    #returns array of indicies of selected player
    #if one player is in array twice you will get 2 indicies #s
    #pwsarr my array of hashes

arr = []

    pwsarr.each_with_index do |val,index|
            if val['player'] == inplayer
                arr << index
            end
    end
arr
end

for j in 0..pwsarr.count
    puts pwsplayerindex(pwsarr[j]['player'])
end

my array of hashes is something like this:

pwsarr =[{'player'=>'first1 last1', 'stat'=>0.0},{'player'=>'first2 last2', 'stat'=>0.0}]


texts: Abbreviating and expanding IP v6 addresses with APL

texts:
Recently I solved a challenge (problem 1 of the 3rd easy problem set of phase 2 of the '19 APL Competition) on abbreviating and expanding IP v6 addresses. For that matter, I had to write two functions, AbbreviateIPv6 and ExpandIPv6. The first function ought to take a character vector of a v6 IP address and abbreviate it like this online tool. The second function ought to undo exactly what the first one did.

I need a community review because these two were among a series of problems rated as easy and while most of them were fairly easy to solve and could be decently solved in a couple of lines, I found really hard to write the AbbreviateIPv6 function so I think I overlooked something. What is more, I failed to find a solution that didn't use regular expressions, which bothered me even more.

First, a helper function:

:Namespace ReplaceFirst
    _ReplaceFirst_ ← {
        ⍝ Operator that replaces the first occurrence of the left operand with the right operand.
        ⍝ e.g. ('ui' ReplaceFirst 'fafa') 'this ui is ui' gives 'this fafa is ui'

        startAt ← ⊃⍸⍺⍺⍷⍵
        stopAt ← startAt + (¯1+≢⍺⍺)×startAt>0
        pruned ← ⍵/⍨ ~(startAt∘<∧≤∘stopAt)⍳≢⍵
        replaceAt ← (>∘0⍴⊢) startAt
        ∊ ((⊂,⍵⍵)@replaceAt) pruned
    }
:EndNamespace

that I used in the AbbreviateIPv6 function:

AbbreviateIPv6 ← {
  ⍝ Monadic function taking character vector as input and returning character vector.
  ⍝ Abbreviates an IP v6 address.
  ⍝ e.g. '2001:0DB8:0000:0042:0000:8A2E:0370:7334' becomes '2001:DB8:0:42:0:8A2E:370:7334'
  ReplFirst←⎕fix 'file://path/to/ReplaceFirst.dyalog'

  reduced ← ('0000' ':0{1,3}' ⎕R (,¨'0' ':'))⍵
  runs ← ⌽ ⍴∘'0:'¨ 1+2×⍳7
  shortened ← {(⍵ ReplFirst._ReplaceFirst_ '') reduced}¨ runs
  ((⊃∘⍋≢¨)⊃⊢) shortened
}

I know I could've defined the _ReplaceFirst_ as a function inside AbbreviateIPv6 specialized for the case I wanted, but I figured the function was getting so long I might as well write a general operator that I might reuse later.

Finally, just for comparison, I was able to write the ExpandIPv6 in a much more compact way:

ExpandIPv6 ← {
    ⍝ Monadic function expecting and returning character vector.
    ⍝ Expands an abbreviated IP v6 address.
    ⍝ e.g. '2041:0:140F::875B:131B' gives '2041:0000:140F:0000:0000:0000:875B:131B'.

    colons ← +/':'=⍵
    intermediate ← ('::' ⎕R(':0'⍴⍨ 3+2×7-colons))⍵
    splits ← (':'∘≠⊆⊢) intermediate
    LeftZeroPadder ← (⍴∘'0')∘(4∘-)∘≢,⊢
    ⊃ {∊⍺':'⍵}/ LeftZeroPadder¨ splits
}


texts: Resolve (domainless) machine name from DNS alias

texts:
So I have a URI with a DNS alias, and I need to dynamically replace the alias with the actual machine. I started out with this:

var builder = new UriBuilder("http://server-alias/path/to/resource");
builder.Host = Dns.GetHostEntry(builder.Host).HostName;
return builder.Uri; // http://server1.mydomain.net/path/to/resource

However, what I need is the URI with just the machine name, http://server1/path/to/resource. Of course I can use this, but string manipulation seems seems a bit kludgey:

builder.Host = Dns.GetHostEntry(builder.Host).HostName.Split(new[] { '.' }, 2)[0];

Is there a better way to get just the machine name from a DNS alias, without the domain?


texts: Linked list implemented as classes, not imperative code

texts:
As an update to previous code I've submitted:

Improvements this time are mainly having everything moved to a class, before I plough on and add more functionality (I've come back to C++ after a few years away and this is a revision exercise).

#include <iostream>
#include "LinkedList.h"

class LinkedList
{
public:
    LinkedList(void);
    ~LinkedList(void);
    void traverseList();
    int length();
    void push(int data);

private:
    struct node{
    int data;
    node *pointee;
    };

    node *head;
    node *last;
    int count;
};

LinkedList::LinkedList(void)
{
        head = new node();
    last = new node();
    head->data = 0;
    head->pointee = last;
    last->data = 0;
    last->data = NULL;
    count = 2;
}

LinkedList::~LinkedList(void)
{
}

/*
    To be replaced with an iterator and an overloaded print operator for output
*/
void LinkedList::traverseList(){
    for(node *iterator = LinkedList::head ; iterator ; iterator = iterator->pointee)
    {
        std::cout << iterator->data << std::endl;
    }
}

int LinkedList::length(){
    return LinkedList::count;
}

void LinkedList::push(int data){

    node *newNode = new node();
    newNode->data = data;
    newNode->pointee = NULL;
    last = newNode;
    ++count;
}

int main(){

    LinkedList list;

    for(int i=1 ; i<4 ; i++)
    {
        list.push(i);
    }

    int length = list.length();
    std::cout << length << std::endl;
    list.traverseList();
    return 0;
}


texts:
The intent of the function is to simply tell me whether or not two vectors contain the same values that have the same column names. At this point of my algorithm I'm just checking the whether or not I should add the concatenated Row and RowRT by checking those locations where the column names are the same to assure that the corresponding values in the rows in fact all the same.  To be clear, I'm passing in the map Duplicates which is simply all of the Columns that had a duplicate and the corresponding indices.

This function is the bottleneck of my program and I'm not sure how to optimize it further. Is there a better way to do this?  Am I overcomplicating this?

What I think could be optimized: It seems to me that I should be able to check those Rows without needing to merge the two together, but I'm not sure what other optimizations I need to make could be.

bool  Database::NaturalJoinAddRowQuery(std::vector<Token> Row, std::vector<Token>& RowRT,
std::map<Token, std::vector<int>>& Duplicates)
{

typedef std::map<Token, std::vector<int>>::iterator it_type;
Row.insert(Row.end(), RowRT.begin(), RowRT.end());

for (it_type it = Duplicates.begin(); it != Duplicates.end(); it++) {

        if (it->second.size() != 1)
            for (int k = 0; k < it->second.size(); k++)
            {
              for (int i = 0; i < Row.size(); i++)
              {
                    if (std::find(it->second.begin(), it->second.end(), i) != it->second.end())
                    {
                       if (Row[i].Content() != Row[it->second[k]].Content())
                                return false;

                    }
              }

            }
}


texts:
Here's a simple gulpfile.js I'm using on a very simple project which basically consists of an animation built with Sass, SVG and very little JS.

var gulp = require('gulp'),
    usemin = require('gulp-usemin'),
    rimraf = require('gulp-rimraf'),
    sass = require('gulp-sass'),
    prefix = require('gulp-autoprefixer'),
    minifyCSS = require('gulp-minify-css'),
    // minifyHTML = require('gulp-minify-html'), // messes up the SVG
    uglify = require('gulp-uglify'),
    watch = require('gulp-watch'),
    livereload = require('gulp-livereload');

gulp.task('rimraf', function() {
  return gulp.src('./dist', { read: false })
    .pipe(rimraf());
});

gulp.task('sass', function() {
    return gulp.src('app/sass/**/*.scss')
        .pipe(sass())
        .pipe(prefix('> 1%')) // this could be on usemin (to also prefix css files from index.html), but doesn't seem to work
        .pipe(gulp.dest('./app/css'));
});

gulp.task('usemin', function() {
  gulp.src('./app/index.html')
    .pipe(usemin({
        css: [
            // prefix('> 1%') // doesnt work
            minifyCSS()
        ],
        html: [
            // minifyHTML()
        ],
        js: [
            uglify()
        ]
    }))
    .pipe(gulp.dest('./dist'));
});

// For production
gulp.task('default', ['rimraf', 'sass'], function(){
    gulp.start('usemin');
});

// Watch SASS and keep CSS updated and auto-prefixed (for development)
gulp.task('watch-sass', function () {
    gulp.src('app/sass/**/*.scss')
        .pipe(watch(function(files) {
            return files.pipe(sass())
                .pipe(prefix('> 1%'))
                .pipe(gulp.dest('./app/css'))
                .pipe(livereload())
        }));
});

I'm not a back-end person and gulp is brand new to me, so I'd like to have some feedback on it. In addition, I had some problems regarding the autoprefixer, which you can see in the comments.


texts: java integration test wait for websocket message and verify content

texts:
I am following some java training where I am asked to write a websocket server which accepts orders to be placed and matched with previous orders.
The matching engine is unit tested separately.
There should be integration tests which check the server accepts messages and send replies.
Below is an example of such test. I was wondering if it is acceptable and what could be improved. Specifically, I want to make sure using the FutureTask and mapping the response string to HashMap are the best alternatives.
The test should send a PLACE_ORDER message (contents do not matter) and expects a PLACE_ORDER_RESPONSE to be received.
package com.stackoverflow.codereview.question260771;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketMessage;
import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;

@SpringBootTest(
        classes = Application.class,
        webEnvironment = RANDOM_PORT
)
class OrdersWebSocketIntegrationTests {
    @LocalServerPort
    Integer port;

    @Test
    @DisplayName("should accept place order message and send response")
    void placeOrder() throws ExecutionException, InterruptedException, JsonProcessingException {
        var response = new Object() { String value; };
        var respond = new FutureTask<Object>(() -> response);

        var uri = URI.create(MessageFormat.format("ws://localhost:{0}/orders", port.toString()));
        var handler = ((WebSocketHandler) session -> {
            var message = "{ \"@type\": \"PLACE_ORDER\", \"body\": { \"action\": \"BUY\", \"accountId\": \"a\", \"quantity\": 1, \"price\": 50 }}";
            var input = Mono.just(session.textMessage(message));
            var output = session.receive().map(WebSocketMessage::getPayloadAsText).doOnNext(value -> {
                response.value = value;
                respond.run();
            });
            return session.send(input).thenMany(output).then();
        });
        var client = new ReactorNettyWebSocketClient();
        client.execute(uri, handler).subscribe();

        respond.get();

        var objectMapper = new ObjectMapper();
        var map = objectMapper.readValue(response.value, HashMap.class);
        assertEquals("PLACE_ORDER_RESPONSE", map.get("@type"));
    }
}


texts:
I wrote this code in Java using the Jaunt library. The program scrapes all words from Wiktionary from category "English_uncountable_nouns". And after save
each world to text file.
I am not sure that exceptions are handled in best way, so I'm looking for tips on how to make this code easier to understand and more stable. I removed some of the redundancies but it is still strange.

package wiksurfer;
import com.jaunt.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Wiksurfer {

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

    public static void surfPages() {
        int i = 0;//counter for number of processed pages
        UserAgent userAgent = new UserAgent();
        userAgent.settings.autoSaveAsHTML = true;  //change settings to autosave last visited page.
        Elements elements;
        String wikiword;

        try {
            PrintWriter pw = new PrintWriter(new FileWriter("wkwords.txt"));
            try {
                String href = "http://en.wiktionary.org/wiki/Category:English_uncountable_nouns";

                for (i = 0;; i++) {
                    userAgent.visit(href);
                    href = userAgent.doc.getHyperlink("next page").getHref().replaceAll("amp;", "");
                    //Jaunt has now a strange bug on processing strings, so the fragment replaceAll("amp;", "")
                    //is devoted to fix this issue
                    System.out.println("next page:" + href);

                    elements = userAgent.doc.findEvery("<div class=mw-category-group>").findEach("<li>").findEach("<a>");
                    //select all links which contan words we need
                    for (Element el : elements) {           //iterate through Results
                        wikiword = el.getText().replaceAll("amp;", "");
                        if (isGoodWord(wikiword)) {
                            pw.println(wikiword);
                        }
                    }
                }

            } catch (JauntException e) {
                System.err.println(e);
            } finally {
                pw.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(Wiksurfer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static boolean isGoodWord(String s) {
        char c;
        if (s.split(" +").length > 1) {
            return false;
        }
        c = s.charAt(0);
        return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
    }
}


texts: Convert a list of dictionaries to a dictionary of dictionaries

texts:
I need to convert a list of dictionaries to a dictionary of dictionaries, with a particular item as the new key.

This is the way I'm currently doing it:

>>> a
[{'bar': 'baz', 'id': 'foo'}, {'bar': 'baz', 'id': 'qux'}]
>>> {
    item['id']:{
        sub_item:item[sub_item] for sub_item in item if sub_item != 'id'
    } for item in a}

{'qux': {'bar': 'baz'}, 'foo': {'bar': 'baz'}}

However, this looks really ugly to me.  Is there a more elegant way to do this?


texts:
This program calculates the sum of all integers in the range \$[1, 1000)\$ which are multiples of either 3 or 5 or both.
Inspired by x86-64 Assembly - Sum of multiples of 3 or 5 the other day, and also drawing from some of what I learned through Calculate the centroid of a collection of complex numbers I decided to try to tackle this using C++20 ranges.  By heavy use of constexpr, I had hoped to find a solution that would calculate everything at compile time, and indeed this does as you can see if you try it online.
This version is inspired by this talk C++20 Ranges in Practice - Tristan Brindle - CppCon 2020.
I'm interested in general improvements.
euler1.cpp
#include <iostream>
#include <concepts>
#include <ranges>
#include <iterator>
#include <functional>
#include <numeric>

template <std::ranges::input_range R,
    typename Init = std::ranges::range_value_t<R>>
constexpr Init accumulate(R&& rng, Init init = Init{})
{
    return std::reduce(std::ranges::begin(rng), std::ranges::end(rng),
        std::move(init));
}

int main() {
    constexpr auto div3_or_5 = [](int i){ return i % 3 == 0 || i % 5 == 0; };
    std::cout << accumulate(std::ranges::iota_view{1, 1000}
        | std::views::filter(div3_or_5)
        | std::views::common)
    << '\n';
}


texts:
I try to avoid using classes in Python as much as possible; if I don't plan on building on it, I don't build it in the first place. It helps me avoid Java-like classes like FileDownloader(), when I could build download_file() instead.

That being said, I wanted to discuss getter and setter methods -- particularly getter methods. Instead of using class methods, I typically make them module methods (and use the module as others might use a class).

For example:

package/
|
| __init__.py
| constants.py
| main.py
| helpers.py

How this might be used:

#constants.py
import os
def get_default_directory():
    return os.path.join(os.expanduser('~'), 'Desktop', 'files')
def get_server_name():
    return '127.0.0.1'
def get_url_template(site, timezone):
    ...

And so on. This is the go here and change stuff if something changes area of the code.

For helpers.py, you might have some convenience functions that work well as one liners here and there, but duplicating them in each script might be a stretch while you're still formulating a final draft.

For instance, I had something like this, but ended up copying it into a second file later on:

def filename_from_path(path):
    return os.path.split(path)[-1]

def trimext(filename):
    return os.path.splitext(filename)[0]

def raw_filename(path):
    return trimext(filename_from_path(path))

This replaced return os.path.splitext(os.path.split(path)[-1])[0], which ended up in a couple of places (and looked ugly).

main() simply holds all of my high level convenience functions, my "dumb functions", as they were. They just carry out a task, and make it take the least amount of keystrokes possible. Like a main method, but you have many different arrangements available to you.

#main.py
import constants
import helpers

def admin_dry_run(safe_mode=True):
    do_main_a(safe_mode)
    do_main_b(safe_mode)
    do_main_c(safe_mode)

def dry_run(safe_mode=False):
    if safe_mode:
        #even this code could be defined in `helpers` to use
        #the login credentials in `constants`, saving space here
        if helpers.login(constants.get_credentials()):
            do_main_a()
        else:
            do_main_b()
    else:
        do_main_c()

def do_main_a():
    pass #...

Is this typical? Is there anyone who does this, or might be able to suggest a different approach to structuring programs that stretch across multiple files in a similar manner?


texts:
Some archives contain folders with spaces in their name.
Sometimes while I'm browsing these folders, I want to open a terminal in current position, so I copy the path to paste it after a cd command.
Of course when there are spaces in the path, cd won't work unless all spaces are escaped.

Since I find it annoying not to be able to paste paths after cd, I just added this function to my .bash_aliases:

function cd {
  if [ -z "$*" ]; then
    command cd
  else
    command cd "$*"
  fi
}

So mkdir "an awful dir name" && cd an awful dir name now works as expected (what else should cd an awful dir name do?).

Since .bash_aliases shouldn't affect non-interactive shells, other scripts should still work with builtin cd.

Now the question is: can this trick cause problems on my shell? Or am I freaking out for no reason?


texts:
Today I had an interview, where I was asked to solve this question:

Find all the permutations of a given string
Example:
str = 'abc'
Answer: 'abc', 'acb', 'bac', 'bca', 'cab', 'cba'

I have written this code, but can it be improved or is there any other way to do it in better manner?
   public class Permutation{
     public static void main(String []args){
        Permutation p = new Permutation();
        String str = "1234";
        int n = str.length();
        p.permute(str, 0 ,n-1);

     }

     public static void permute(String str, int l, int r){
         if(l==r){
             System.out.println(str);
         }

         for(int i=l;i<=r;i++){
             str = swap(str,i,l);
             permute(str, l+1, r);
             str = swap(str,i,l);
         }
     }

     public static String swap(String str, int i, int l){
             char[] charArr = str.toCharArray();
             char t = charArr[i];
             charArr[i] = charArr[l];
             charArr[l] = t;
             return (String.valueOf(charArr));
         }

}


texts:
I don't feel that my code is secure, and would like some help in using prepare statements for the following;

$track = "INSERT INTO resources_record (name,email,stage,format,topic,max_cost,mentor,total_cost,duration)
          VALUES ('".$fullName."', '".$email."', '".$stage."', '".$format."', '".$topic."', '".$cost."', '".$mentor."', '".$price."', '".$duration."')";

// Execute track query
 mysqli_query($con, $track);


texts: Filter an array of objects, checking only specified properties and child objects

texts:
The function filterList recieves an array of objects and filters the list, checking only the properties of the object specified in a 'filterFields' array.
It compares the values of those specified properties to a string 'filterTerm' using a comparison function.
If the property specified by 'filterFields' is an array or object, it also checks through those and returns the entire top-level object if the specified fields of any child objects are matched with the comparison function.
I would like to check to see if this is normal/sensible javascript and whether there is a better way of writing this functionality, performance-wise.
    //if filterTerm or filterFields are empty, return original list
    function filterList(list, filterTerm, filterFields) {
        if(filterTerm && filterFields.length > 0) {
            return list.filter(filterCallback(filterFields, filterTerm));
        }else{
            return list;
        }
    }
    //use closure to pass filterFields and filterTerm to callback
    function filterCallback(filterFields, filterTerm) {
        return function(element) {
            return filterFields.some((filterField)=>{
                if(Array.isArray(element[filterField])){
                    return element[filterField].some(function(childElement){
                        return filterCallback(childElement);
                    })
                }else if(typeof element[filterField] === 'object'){
                    return filterCallback(element[filterField]);
                }
                return comparisonFunction(element[filterField], filterTerm);
            })
        }
    }
    //comparisonFunction - field value is populated, and either filterterm contains the fieldValue or visa-versa
    function comparisonFunction(fieldValue, filterTerm) {
        return fieldValue &&
        (String(fieldValue).toLowerCase().indexOf(filterTerm.toLowerCase()) >= 0
        || String(filterTerm).toLowerCase().indexOf(fieldValue.toLowerCase()) >= 0);
    }

//EXAMPLE USE:
    arr = [{name: "a", job: "b"}, {name:"c", job:"d"}];
    filterList(arr, "a", ["name"]); // => [{name: "a", job:"d"}]
    arr2 = [{name: "a", job: "b", employees: [{name: "d", job:"e" }]}, {name: "f", job: "g"}];
    filterList(arr2, "d", ["name", "employees"]); //=> [{name: "a", job:"b", employees: [{name: "d", job: "e"}]}]

```


texts: Extracting relevant form data to an array

texts:
I have the following function, it works exactly how I need it to; however I think there is room for improvement.

The script is supposed to loop through all input and text area html elements. It should only work with elements that have a name, and a value, and it should ignore "hidden". However some of the elments do not have a type attribute, so I can't do something like input.attr('type').toLowerCase() != 'hidden'.

After that, it ignores any field with the class element_reference_input, and looks for fields with form-control or question_textarea_input.

Last it writes the values to an array.

jQuery('input, textarea').each(function(index){
    var input = jQuery(this);
    if (input.val() && input.attr('name') && input.attr('type') != 'hidden' && input.attr('type') != 'HIDDEN') {
        if (input.attr('class')) {
            elmClass = input.attr('class');
        }

        if (elmClass.indexOf('element_reference_input') <= -1 && (elmClass.indexOf('form-control') > -1 || elmClass.indexOf('question_textarea_input') > -1 )) {
            objOutgoingData.push(
                {
                    name:'' + input.attr('name').split('.').pop(),
                    value:'' + input.val(),
                    table:'' + tableName,
                }
            );
        }
    }
});

I feel that I have to many if statements, I'd like to streamline it. But I am trying to avoid undefined errors if class or type is not present on the html tag.


texts:
I made an implementation of atoi (ascii to integer) in Python a while ago for fun, and I'd like to know what I could do to improve it.

class CannotConvertToInteger(Exception):
  """A non-numeric character was present in the string passed to atoi"""
  pass

def atoi(string : str) -> int:
  sign = multiplier = 1
  val = 0
  if string[0] == '-':
    string = string[1:]
    sign = -1
  elif string[0] == '+':
    string = string[1:]
  for i in string[::-1]:
    code = ord(i)
    try:
      if ((code > 57) or (code < 48)):
        raise CannotConvertToInteger
      else:
        val += (code - 48) * multiplier
        multiplier *= 10
    except CannotConvertToInteger:
      return print('Cannot convert string to an integer!')
  return (val * sign)

test_string = input('Enter an optionally signed integer: ')
result = atoi(test_string)
if result:
  print('It was a valid int! atoi() returned:', result)
else:
  print('It was an invalid int! atoi() returned:', result)

input()

One specific question I have is if it's bad practice to return a print call, as a way to print an error and simultaneously return from the function? I did that so that I could print the error and return None on the same line.


texts:
I just started with deep learning of x86 architecture and assembly so i decided to go from bare metal and write my own bootloader. To add some "functionality" i decided to make quine (from binary perspective) and i have some questions:

Could this be considered as valid quine ?
Is mechanic and design of my code acceptable?
Is there some asm patterns that generally should be followed (i come from
Java background where patterns are everywhere)
How to properly format asm code ?

  My code :

start:
mov si, 7F00h   ;; set stack pointer after our bootloader
mov ax, 0h
mov ds, ax      ;; set DS to 0;
mov di, 7C00h   ;; set Data pointer to memory location where is our bootloader loaded

.printMemoryValue:
mov al, 0          ;;  Using int15 to simulate pause for real time output, ax,ah,cx,dx dictate pause length
mov ah, 86h
mov cx, 0006H
mov dx, 8480H
int 15h
mov ah, 0Eh     ;; Ah to 0eh setting for teletype output ( int 10h)
mov dx, [ds:di]     ;; moving content of first memory location in dx (7c00h)
push dx             ;; save dx in our stack
xor  cx, cx        ;; for (int i = 0; ;; for loop used to output 16 bit string (0 & 1)

.loopstart:
cmp  cx, 00010h     ;; i < 16;
je  .loopend    ;; break if i >= 16
pop dx
rol dx, 1           ;; rotating left 1 bit so we can extract MSF bit with our mask. because we write on screen from right to left
push dx             ;; save our curent dx to stack
and dx, 0000000000000001   ;; mask
add dx, 30h         ;; adding (30h) for ASCII ( 0 or 1)
push cx             ;; saving our counter in stack because cx is volotile register
mov al, dl          ;; moving low 8 bits from dx (dl) to our teletype output register Al for calling int 10h
int 10h         ;; int 10h ( al = character to output if ah = 0eH, teletype )
pop cx
add cx, 1       ;; i++
jmp .loopstart

.loopend:
mov al, 000Ah   ;; new Row
int 10h
mov al, 000Dh       ;; carriage return
int 10h
add di, 2h          ;; adding 2 to our di pointer ( because we are in 16bit mode)
cmp di, 7E00h       ;; are we at the end of our bootloader (7c00h + 200h )?
je .hlt             ;; if yes halt
jmp .printMemoryValue   ;; print next memory location ( di is increased by 2 )
.hlt:
hlt             ;; ende

times 510-($-$$) db 0
dw 0xAA55           ; => 0x55 0xAA (little endian byte order)

U can try code with mountable image available here

Any suggestions are welcome.


texts: Data structure to count occurrences of words

texts:
I have some code for a assignment where the main marks are awarded based on efficiency. The program uses a given wordgenerator which generates random words and adds them to a user-made data structure. You also have to provide 3 methods, one to add a item, one to remove a item and one to count how many times a word is present in the structure. Here is my code:

public class WordStoreImp implements WordStore{

public class Node{
   public String data;
   public Node next;
   public Node(String addingWord, Node theNext){
        data = addingWord;
        next = theNext;
   }
}

private Node[] array;
int usedAmount=0;

public WordStoreImp(int n){
    array = new Node[n];
}

public void add(String word){
    int position = hashFunction(word);
    array[position]=new Node(word,array[position]);
}

public int count(String word){
    int number = 0;
    int position = hashFunction(word);
    Node temp = array[position];
    while(temp!=null){
        if(temp.data.equals(word)){
            number++;
        }
        temp=temp.next;
    }
    return number;
}

    public int hashFunction(String a){
    int sum = 1;
        for(int i = 0; i<a.length(); i++){
            char b = a.charAt(i);
            int value = (int) b;
            sum *= value;
     }
     sum = sum % array.length;
     if(sum<0){
         return -sum;
     }
     return sum;
 }

public void addthings(String word, int n){
    for(int i = 0; i<n; i++){
        add(word);
    }
}

public int printSize(){
    int count = 0;
    for(int i = 0; i<array.length; i++){
        if(array[i] != null){
            count++;
        }
    }
    System.out.println(count);
    return count;
}

public static void main(String[] args) {
    WordStoreImp a = new WordStoreImp(100);
    a.addthings("abc", 100);
    System.out.println(a.count("abc"));
    System.out.println(a.count("abc"));
}
}

So far I have written two of the methods, add and count. Whilst my add function is very quick, the count method is rather slower and takes a lot more time to compute. Is there a more efficient way to write this method or change things here to make it quicker?

Also - we arent allowed to use any methods or data structures that are inbuilt Java methods, such as HashMaps.


texts:
I just added a new feature to my portfolio: Night Mode. I created it with CSS and session storage in JavaScript. I want you to review my CSS of night files, I feel it's filled with !important and I'm sure this is a bad practice. Can anyone help me make them better?

My second question, the default mode (white mode) runs in the first milliseconds when moving from page to another. I think it's not a good practice. Can anyone help me make it better?

Live: just set the session to night using this JavaScript line sessionStorage.setItem("mode", "night"); and refresh.

Alll files.

CSS files:

body{
    background-color: black;
    color: white;
}
.indx-contnt p {
    color: white !important;
}
.signature span, a {
    color: white;
}
h1{
    color:#f90 !important;
}
.latest li span{
    color: black !important;
}
.latest li a{
    color:white !important;
}

.contentlist li:nth-child(2) a{
    color:#2CAAE1 !important;
}

.contentlist li:nth-child(3) a{
    color:#0177B5 !important;
}

.contentlist li:nth-child(1) a{
    color:#717171 !important;
}

#rss{
    background-color: black;
}

.signature span, a{
    color: white !important;
}
.latest li a:hover {
    color: #f90 !important;
}

p, h1, h2,h4,span{
    color: white;
}

body{
    background-color: black;
    color: white;
}
.signature span, a{
    color: white !important;
}
p, h1, h2, h4, span {
    color: white !important;
}
.project span {
    color: black !important;
}
.card{
    background-color: #ffffff0f !important;
}
.card:hover {
    box-shadow: 10px 7px 10px 0px rgb(255, 153, 0) !important;
}
.card a{
    background-color: black !important;
}

#rss{
    background-color: black !important;
}

.card-title{
    color: #f90 !important;
}

.posts a {
    color: white !important;
}


texts: Haskell functions to extract and reverse integers hiding in strings

texts:
There may not be a "right" way to do it, but I'm inexperienced in functional programming. I'd like some feedback on how the code can be written in a more idiomatic way.

Here it is:

import Data.Maybe (fromJust, isJust)

sepInt n = if n >= 10
            then  ( sepInt ( n `div` 10 ) ) ++ ((n `mod` 10):[])
            else n `mod` 10 : []

getStuff (x:xs) = if isJust x || null xs
                    then fromJust x
                    else getStuff xs

base10IntTOstring num =
                 let chars = [ (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (0, '0') ]
                     numbahs = sepInt num in
                     map getStuff ( map (\a -> (map (\(x,y) -> if a == x then Just y else Nothing ) chars ) ) numbahs )

charTOBase10Int char =
                 let chars = [ ('1', 1), ('2', 2), ('3', 3), ('4', 4), ('5', 5), ('6', 6), ('7', 7), ('8', 8), ('9', 9), ('0', 0) ] in
                     let charslist = ( map (\(a,x) -> if char == a then Just x else Nothing) chars ) in
                         getStuff charslist

stringTOBase10Int string =
    let integers = ( map charTOBase10Int string ) in
        let multByBase i (x:xs) = if null xs
                                   then (10^i)*x
                                   else (10^i)*x + multByBase ( i-1 ) xs
        in multByBase ( (length integers)-1 ) integers

It also reverses integers.

sepInt n = if n >= 10
            then  ( sepInt ( n `div` 10 ) ) ++ ((n `mod` 10):[])
            else n `mod` 10 : []

reverseInteger string =
    let integers = sepInt string in
        let multByBase i (x:xs) = if null xs
                                   then (10^i)*x
                                   else (10^i)*x + multByBase ( i-1 ) xs
        in multByBase ( (length integers) - 1 ) integers


texts: Bash script to clear files not matching a given extension

texts:
Using LaTeX creates a bunch of auxiliary files like foo.aux, foo.log, etc. Sometimes, I want to create a clean run of my document. I usually manually execute this in the terminal as

$ ls foo*
foo.tex
foo.aux
foo.log
foo.bbl
foo-blx.bib
$ rm foo{.aux,.log,.bbl,-blx.bib}

This works fine. However, it is error-prone and I don't want to accidentally erase my .tex file. So I added this function to my ~/.bashrc:

# Delete all non-TeX files
# invoke as: cleantex foo
# where: foo.tex, foo.aux, foo.log, etc. are files in directory
cleantex () {
    if [ -n "$1"]; then
        name = $(basename -s ".tex" "$1")
        rm -f $name{.!(*tex),-blx.bib}
    fi
}

My question is about the key line

rm -f $name{.!(*tex),-blx.bib}

that actually executes the script.

Is this line well-written? What might I improve here?


texts:
I've recently started using PHP OOP, and I'm now working on an application where different company representatives can create job offers that candidates can look at.

I have a variety of objects for most entities such as Company, Candidate, Offer.

The problem that I have is that these objects all need to be stored in a database, and I need methods to retrieve the information, create the objects and return them. Since it does not make sense - at least to me with my limited experience in OOP - for an object to have access to the database and be able to fetch itself, I'm using a Database class for each of my main objects that are stored in the database : CompanyDatabase, CandidateDatabase, OfferDatabase.

Each of the aforementionned classes have static methods that retrieve one or multiple "objects" from the database - this is a three-step process, they fetch the data, create the objects and return them.

Here's an example of such a xDatabase class (where x  is the name of the class)

class CompanyDatabase{

    public static function getFromID($id)
    {
         $company = Database::query("SELECT * FROM companies WHERE id = ?", [$id]);
         return new Company($company->id, $company->name);
    }

    public static function save($company)
    {
        Database::update("UPDATE compagnies SET name = ? WHERE id = ?", [$company->name, $company-id]);
    }
}

And the Company class in this case :

class Company{

   public $id;
   public $name;

   public function __construct($id, $name)
   {
       $this->id = $id;
       $this->name = $name;
   }
}

I've excluded some code, like the validation to check wether or not data was fetched from the database, because I felt it wasn't relevant to my concerns here.

Is this the proper way of doing it? I end up with two seperate classes for just about every object type that I have, and I'm wondering if I'm doing something wrong and should rather keep everything in one class.


texts: Sort and source configuration files from one of two directories

texts:
In a zsh I want to loop over all files in a configuration files' directory (/etc/myapp/) to source them. The files should be sourced in order and are named with two leading digits 10-early 40-middle 99-last. A user without write permission to /etc should be allowed to extend the list of files and override the global ones. This is done by creating a $HOME/.myapp directory. The user files should be sourced in order with the global files, i.e. /etc/myapp/10-early $HOME/.myapp/20-rightafter /etc/myapp/40-middle $HOME/.myapp/90-late /etc/myapp/99-last. A user should also be allowed to override global files, i.e. when $HOME/.myapp/99-last exists, then /etc/myapp/99-last should be skipped.

As answerded here and here, I create an array with all the config files and then use basename on the array (like here) to restrict it to the NN-lllll part and sort them. Eventually each file gets sourced from $HOME/.myapp if it exists there, and from /etc/myapp otherwise.

# https://stackoverflow.com/a/10981499
# https://unix.stackexchange.com/a/26825
thefiles=(/etc/myapp/* $HOME/.myapp/*(N))
# https://stackoverflow.com/a/9516801
uniquified=( $( for f in "${thefiles[@]}" ; do basename $f ; done | sort -V | uniq) )
for f in $uniquified
do
# -r checks if file exists and is readable
  if [[ -r $HOME/.myapp/$f ]]
  then
    source $HOME/.myapp/$f
  else
    source /etc/myapp/$f
  fi
done

Is there a more elegant solution and should I be aware of errors I need to catch?


texts:
The function should get some text on input and return a map in a following format:

("word1" -> 1, "word2" -> 2 ...)

The keys are words from text and the values are representing the number of times the word appeared in the text. We take into a count only words which at least 4 characters long. Special chars are ignored, words are case insensitive.

import scala.collection.mutable.Map

def wordCounter(text: String) = {
  var map:Map[String, Int] = Map()

  text.toLowerCase.replaceAll("[^a-z ]", "").split(" ").filter(_.length > 3).foreach(x => addWord(map, x))
  map
}

def addWord(map: Map[String, Int], word: String) = {
  map(word) = map.getOrElse(word, 0) + 1
}

Is that fine to use mutable in this case?
Should I always be suspicious about the solutions that require to use mutable and use it only when its problematic to implement it with immutable types?
I'm doing an extra loop to filter words longer than 3 chars. In my mind this way it looks a bit cleaner than to have a condition in foreach. Should I care more about the performance or readability in my code?


texts:
I'm working on a project where a spinlock is more appropriate than a mutex, and after few tries I came up with:

type SpinLock uint32

func (sl *SpinLock) Lock() {
    for !atomic.CompareAndSwapUint32((*uint32)(sl), 0, 1) {
        runtime.Gosched() //without this it locks up on GOMAXPROCS > 1
    }
}

func (sl *SpinLock) Unlock() {
    atomic.StoreUint32((*uint32)(sl), 0)
}

It works fine, and it's even a little bit faster than sync.Mutex, and 2x the speed of sync.RWMutex.

➜ go test -bench=. -benchmem -v -cpu 4
BenchmarkSpinL-4            2000           1078798 ns/op           33923 B/op       2006 allocs/op
BenchmarkMutex-4            2000           1195814 ns/op           32781 B/op       2002 allocs/o
BenchmarkRWMutex-4          1000           2352117 ns/op           78253 B/op       2147 allocs/op

The test uses multi readers / writers to a map[int]*struct{int, int}. Running it with -race doesn't detect any data races, either.

But I have that nagging feeling that I forgot something, so I'm wondering if my implementation is correct?


texts: Unstructured quantum search algorithm for unknown solutions

texts:
This code was tested on IBM's 5-Qubit processor as an implementation of Grover's search algorithm, but for an unknown number of solutions.  This code is based on Arthur Pittenger's book, "An Introduction to Quantum Computing Algorithms" and the mathematical structure was posted as a proof-verification question here.

h q[0];
h q[1];
x q[2];
s q[0];
cx q[1], q[2];
t q[3];
cx q[0], q[2];
s q[3];
x q[0];
z q[1];
s q[2];
tdg q[3];
cx q[0], q[2];
id q[3];
cx q[1], q[2];
h q[0];
h q[1];
h q[2];
x q[0];
x q[1];
x q[2];
cx q[0], q[2];
h q[0];
cx q[1], q[2];
s q[2];
h q[2];
tdg q[2];
h q[2];
measure q[0];
measure q[1];
measure q[2];
measure q[3];
measure q[4];

For successful implementations of Grover's algorithm, there has to be a bias towards $$\vert 0 \rangle$$ while $$\vert 1 \rangle$$ only occurs upon a successful query of the qubit oracle.

In line with this, the output produces a probabilistic distribution across all possible output permutations of the 5-qubit system, with a |0> bias.  Since I am using the "amplitude amplification" method, or "reflection about the mean" the output value will generate a fluctuation in probabilities based on the solution to the problem presented.  The fifth qubit Q4 is unused, and is reserved for problem encoding.

While IBM allows anyone to publicly access their 5 qubit processor, you will need to be upgraded to Expert User status to copy/paste the QASM code provided.  Otherwise, as a Standard User you can build this same algorithm by following the drag and drop operations provided.  I've already run this experiment on their live system using 4096 shots, as I do with all tests I run live.

I'd like feedback on suggestions of whether I need to keep the Q4 qubit reserved strictly for problem encoding, or if a problem would be more optimally encoded distributed across all qubits.


texts:
https://leetcode.com/problems/valid-parentheses/

Given a string containing just the characters (, ), {, }, [
and ], determine if the input string is valid.
For an input string to be valid:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.

Note that an empty string is considered valid.
Example 1:
Input: ()
Output: true
Example 2:
Input: ()[]{}
Output: true
Example 3:
Input: (]
Output: false
Example 4:
Input: ([)]
Output: false
Example 5:
Input: {[]}
Output: true

using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace StackQuestions
{
    [TestClass]
    public class ValidParentheses
    {
        [TestMethod]
        public void OpenOpenClosedClosedMixTest()
        {
            string input = "([)]";
            bool result = IsValid(input);
            Assert.IsFalse(result);
        }
        [TestMethod]
        public void OnePairTest()
        {
            string input = "()";
            bool result = IsValid(input);
            Assert.IsTrue(result);
        }

        public bool IsValid(string s)
        {
            Stack<char> myStack = new Stack<char>();
            foreach (var curr in s)
            {
                if (curr == '(')
                {
                    myStack.Push(curr);
                }
                else if (curr == '[')
                {
                    myStack.Push(curr);
                }
                else if (curr == '{')
                {
                    myStack.Push(curr);
                }
                else if (curr == ')')
                {
                    if (myStack.Count > 0)
                    {
                        var top = myStack.Pop();
                        if (top != '(')
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else if (curr == ']')
                {
                    if (myStack.Count > 0)
                    {
                        var top = myStack.Pop();
                        if (top != '[')
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else if (curr == '}')
                {
                    if (myStack.Count > 0)
                    {
                        var top = myStack.Pop();
                        if (top != '{')
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }

            }
            return myStack.Count == 0;
        }

    }
}

Please review coding style as it was a job interview with 30 minutes to code.


texts:
In my Tkinter projects I almost always end up with __init__() methods that look like this:

import tkinter as tk
from .common import ConfigPageFrame

class SystemInformationPageFrame(ConfigPageFrame):
    def __init__(self, parent, callback_dict):
        super().__init__(parent)

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        self.button_text = "Refresh"
        self.button_callback = callback_dict['btn_refresh']

        self.lbl_sys_desc_text = "System description:"
        self.lbl_model_text = "Model:"
        self.lbl_serial_text = "Serial number:"
        self.lbl_mac_text = "Burned in MAC:"
        self.lbl_soft_ver_text = "Software version:"
        self.lbl_os_text = "Operating system:"
        self.lbl_net_chip_text = "Network processing device:"

        self.btn_refresh = tk.Button(self, text=button_text,
                                command=button_callback)
        self.btn_refresh.grid(column=0, row=10, columnspan=2)

        self.lbl_sys_desc = tk.Label(self, text=lbl_sys_desc_text, anchor=tk.E)
        self.lbl_model = tk.Label(self, text=lbl_model_text, anchor=tk.E)
        self.lbl_serial = tk.Label(self, text=lbl_serial_text, anchor=tk.E)
        self.lbl_mac = tk.Label(self, text=lbl_mac_text, anchor=tk.E)
        self.lbl_soft_ver = tk.Label(self, text=lbl_soft_ver_text, anchor=tk.E)
        self.lbl_os = tk.Label(self, text=lbl_os_text, anchor=tk.E)
        self.lbl_net_chip = tk.Label(self, text=lbl_net_chip_text, anchor=tk.E)

        self.lbl_sys_desc.grid(column=0, row=0, sticky=tk.E)
        self.lbl_model.grid(column=0, row=1, sticky=tk.E)
        self.lbl_serial.grid(column=0, row=2, sticky=tk.E)
        self.lbl_mac.grid(column=0, row=3, sticky=tk.E)
        self.lbl_soft_ver.grid(column=0, row=4, sticky=tk.E)
        self.lbl_os.grid(column=0, row=5, sticky=tk.E)
        self.lbl_net_chip.grid(column=0, row=6, sticky=tk.E)

This sample is a GUI class from quite a large project, so I can't really show you the whole code (1700+ lines right now, tending towards much more).

As you can see, the overall structure of the widgets instantiation is very repetitive.

Is there a better way to widget instantiation? Maybe some less repetitive approach that doesn't seem to violate DRY?


texts: Photoshop Script to Rename Layers to be Unique

texts:
I recently tried to dip back into my old JavaScript 'skills' to make a script for Photoshop. It's simply a recursive function that will loop over all the layers in a file and renames any duplicate names to add numbers so every layer name is unique.

In Photoshop, an ArtLayer is just a regular layer, and a LayerSet is a folder that contains layers, so I need to address them both separately. I wasn't sure if I could just make a function to do the main body of renameLayerNames because I wasn't sure if I could pass the ArtLayer and LayerSet objects by reference or if they'd become copies.

The format is copied from a pre-existing Photoshop script, so it might be funny looking and I'm not averse to changing it to fit how JavaScript normally works. I'm looking for all feedback, particularly about any notes about not writing 'proper' JavaScript style.

// Written by Gary Chadwick

///////////////////////////////////////////////////////////////////////////////
// Dispatch
///////////////////////////////////////////////////////////////////////////////

main();

///////////////////////////////////////////////////////////////////////////////
// Functions
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// Function: main
// Usage: the core routine for this script
// Input: <none>
// Return: <none>
///////////////////////////////////////////////////////////////////////////////
function main()
{
    if (app.documents.length <= 0)
    {
        return;
    }

    var doc = app.activeDocument;
    layerNames = [];
    renameLayerNames(doc, layerNames);
    alert("Script complete.")
}

///////////////////////////////////////////////////////////////////////////////
// Function: uniqueName
// Usage: Conform name to be a unique name
// Input: Layer name and list of layer names
// Return: Unique name as a string
///////////////////////////////////////////////////////////////////////////////
function uniqueName(name, layerNames)
{
    dupe = 0;
    original = name;
    while (contains(layerNames, name)){
        dupe++;
        name = original + ' ' + dupe.toString();
    }
    layerNames.push(name);
    return name;
}

///////////////////////////////////////////////////////////////////////////////
// Function: renameLayerNames
// Usage: Iterate over a list of layers to disambiguate duplicate names.
// Input: List of Layers and previously found layer names.
// Return: <none>
///////////////////////////////////////////////////////////////////////////////
function renameLayerNames(layerSet, layerNames)
{
    var name = '';
    for (var i = 0; i < layerSet.artLayers.length; i++)
    {
        visible = layerSet.artLayers[i].visible;
        name = layerSet.artLayers[i].name;
        name = uniqueName(name, layerNames);
        layerSet.artLayers[i].name = name;
        if (!visible)
        {
            layerSet.artLayers[i].visible = false;
        }
    }
    for (var i = 0; i < layerSet.layerSets.length; i++)
    {
        visible = layerSet.layerSets[i].visible;
        name = layerSet.layerSets[i].name;
        name = uniqueName(name, layerNames);
        layerSet.layerSets[i].name = name;

        if (!visible)
        {
            layerSet.layerSets[i].visible = false;
        }
        // Recurse
        renameLayerNames(layerSet.layerSets[i], layerNames);
    }
}

///////////////////////////////////////////////////////////////////////////////
// Function: contains
// Usage: Check if an array contains an object.
// Input: An array, object to check for.
// Return: Boolean result of check
///////////////////////////////////////////////////////////////////////////////
function contains(array, object)
{
    for (var i = 0; i < array.length; i++){
        if (array[i] == object){
            return true
        }
    }
    return false
}


texts: Finding the greatest number from three numbers

texts:
The user is prompted to enter three numbers. The function finds the largest number and outputs it to the user.

What do you think of my overall program flow and style?

#include <iostream>

using namespace std;

int maxNumber(int num1, int num2, int num3); //function  prototype/declaration

int main() {

int a, b, c, final;

cout << "Enter first number";
cin >> a;
cout << "Enter sec number";
cin >> b;
cout << "Enter third number";
cin >> c;

final = maxNumber(a, b, c);

cout << "Largest: " << final;

cin.get();
return 0;
}

//function def
int maxNumber(int num1, int num2, int num3)
{
    int result;

if (num1 > num2  && num1 > num3) {
    result = num1;
}
else if (num2 > num1  && num2 > num3) {
    result = num2;
}
else if (num3 > num1  && num3 > num2) {
    result = num3;
}
return result;

}


texts: Concisely handling both arrays and Backbone.Collection as parameter

texts:
I've got a Backbone.Collection which looks like this:

define([
    'background/mixin/collectionMultiSelect',
    'background/model/searchResult'
], function (CollectionMultiSelect, SearchResult) {
    'use strict';

    var SearchResults = Backbone.Collection.extend({
        model: SearchResult,

        mixins: [CollectionMultiSelect],

        //  Reset the collection's values by mapping a single or list of Song objects into
        //  JSON objects which will be instantiated by Backbone.
        setFromSongs: function (songs) {
            var searchResults = [];

            if (songs instanceof Backbone.Collection) {
                searchResults = songs.map(function (song) {
                    return {
                        song: song,
                        title: song.get('title')
                    };
                });
            } else if (_.isArray(songs)) {
                searchResults = _.map(songs, function (song) {
                    return {
                        song: song,
                        title: song.get('title')
                    };
                });
            } else {
                searchResults.push({
                    song: songs,
                    title: songs.get('title')
                });
            }

            this.reset(searchResults);
        },

        //  Returns the underlying Songs of the selected SearchResults.
        getSelectedSongs: function() {
            return _.map(this.selected(), function (searchResult) {
                return searchResult.get('song');
            });
        }
    });

    return SearchResults;
});

I feel like I'm being overly verbose with my setFromSongs method. The intent of the method is to allow outside objects to dumbly give a single Song object, an array of Song objects, or a Backbone.Collection of Songs to the method and have it handle them appropriately.

I thought that this made sense for a few reasons:

Backbone already anticipates singular versus multiple objects with its add and reset methods. I would like my methods to do so, as well.
When working with a Collection it often becomes an array through use of underscore utility methods such as map, pluck, etc.

Is this as concise as this method can be while still making its intent clear? How would you approach this?


texts: Bash function to produce variants of images at 2X and 3X resolutions

texts:
I use ImageMagick to crop image, encapsulate the related code to functions.
Here is the code:
convertc2(){
  convert $1 -crop $2 "two.png"
}

converto3(){

  Delimeter="placeHolder"

  if [[ $2 == *"x"* ]]; then
    Delimeter="x"
  else
    Delimeter="X"
  fi

  First="${2%$Delimeter*}"
  Fourth="${2##*+}"
  Lhs="${2%%+*}"
  Rhs="${2#"$Lhs+"}"

  Second="${Lhs##*$Delimeter}"
  Third="${Rhs%+*}"

  One=$(echo "scale=0 ; $First * 1.5" | bc)
  One=${One%.*}
  Two=$(echo "$Second * 1.5" | bc)
  Two=${Two%.*}
  Three=$(echo "$Third * 1.5" | bc)
  Three=${Three%.*}
  Four=$(echo "$Fourth * 1.5" | bc)
  Four=${Four%.*}

  Final=$One"X"$Two"+"$Three"+"$Four

  echo $Final

  convert $1 -crop $Final "three.png"
}

Usage like this:

convertc2 /Users/dengjiangzhou/Desktop/Simulator\ Screen\ Shot\ -\ iPhone\ 8\ -\ 2019-02-20\ at\ 14.39.02.png   300X300+0+0

converto3 /Users/dengjiangzhou/Desktop/Simulator\ Screen\ Shot\ -\ iPhone\ 8\ -\ 2019-02-20\ at\ 14.39.02.png    300X300+0+0

I need the image size of @2X and @3X. So the function converto3  use convertc2 's size and transform to its size.
Delimeter="placeHolder"

if [[ $2 == *"x"* ]]; then
    Delimeter="x"
else
    Delimeter="X"
fi

I really care about how to improve the above code. The "x" , I may type "X" or "x".
how to use this "${2%$Delimeter*}" insensitive?
And the calculation code in  converto3() is very ugly.


texts:
I have a tree view with a list of cars and a webservice to get the details for each car.

On page load, there are no cars selected so the details footer is loaded with all cars.

$.ajax({
        type: 'POST',
        url: '@Url.Content("/GTracker/Cars/CarTreeDetails")',
        data: { "id": [] }, // not cars filter
        traditional: true,
        success: function (data) {
            $('#footer-details').html(data);
        }
    });

When the user select cars from the treeview, the details are then updated with only those cars.

This is the changed.jstree event:

    var ajaxDetails;

    $('#carTree').on('changed.jstree', function (e, data) {
        var i, j, p = [];

        // create the id[] array
        for (i = 0, j = data.selected.length; i < j; i++) {
            node = data.instance.get_node(data.selected[i]);
            if (node.data.type != 'root') {
                p.push(parseInt(data.instance.get_node(data.selected[i]).id));
            }
        }

        // cancel previous request
        if ((ajaxDetails && ajaxDetails.readyState != 4)) {
            ajaxDetails.abort()
        }

        // get only selected cars info.
        ajaxDetails = $.ajax({
            type: 'POST',
            url: '@Url.Content("/GTracker/Cars/CarTreeDetails")',
            data: { "id": p },  //cars list
            traditional: true,
            success: function (data) {
                $('#footer-details').html(data);
            }
        });
    });

But I feel I'm repeating myself. How may I merge those two functions together?

one for the on_load.
the other for the js_tree change event.


texts: Classifying connectivity status based on online and connected status of multiple nodes

texts:
I need to determine the status of a parent object based on 2 variables of each of its children. I came up with a working solution, but this includes a nested "if-else if-else". Needless to say, it doesn't look very elegant.

I was wondering if there is a way to simplify this. I have muddled around with some map/reduce code, but did not get to anything that is more elegant than the code below.

const parent = {
  children: [{
      connected: true,
      online: true

    },
    {
      connected: true,
      online: true
    }
  ]
}

// all online & all connected  => connected
// all online & some connected => partially disconnected
// all online & none connected => disconnected
// some online => partially offline
// none online => offline

const onlineArr = parent.children.map(c => c.online);
const connectedArr = parent.children.map(c => c.connected);
let status;

if (!onlineArr.includes(true)) {
  status = 'Offline';
} else if (!onlineArr.includes(false)) {
  if (!connectedArr.includes(true)) {
    status = 'Disconnected';
  } else if (!connectedArr.includes(false)) {
    status = 'Connected';
  } else {
    status = 'Partially disconnected';
  }
} else {
  status = 'Partially offline';
}

console.log(status);


texts: Hackerrank All Women's Codesprint 2019: Name the Product

texts:
Link: https://www.hackerrank.com/contests/hackerrank-all-womens-codesprint-2019/challenges/name-the-product/

Problem

  You are contesting to name a new product in your company given the following conditions:

  You are given an array of \$n\$ different names, \$names\$, where \$names_i\$ denotes the \$i^{th}\$ name and all the names are of length \$5\$. The distance between any two names is the number of positions in which the characters in these names differ. For example, "bubby" and "bunny" differ in two positions.

  You have to choose a name such that the sum of differences of all names in \$names\$ with the chosen name is maximal. In order to win the contest, give the new product this chosen name.

  Note: If there are many such names chose the lexicographically largest one.

  Take for example, names = ["bubby", "bunny", "berry"], with length \$n = 3\$. Then, the name that you should choose is "zzzzz" as this name has no common character with any name in the names list and is also lexicographically the largest.

  Function Description

  Complete the productName function in the editor below. It should return the lexigraphically largest string of length  whose sum of differences with all the names is maximal.

  productName has the following parameter(s):

  names: array of \$n\$ names

  Input Format

  The first line contains an integer, \$n\$, denoting the number of elements in \$names\$.
  Each line \$i\$ of the \$n\$ subsequent lines (where \$0 \le i \le n\$) contains a string describing \$names_i\$.

  Constraints

  \$1 \le n \le 10^5\$
  All characters in the names are lowercase English alphabets.
  Each name is of length \$5\$.

  Output Format

  The output should contain the lexigraphically largest string of length  whose sum of differences with all the names is maximal.

  Sample Input 0

3
bubby
bunny
berry

  Sample Output 0

zzzzz

  Explanation 0

  Difference between \$names_0\$, bubby, and zzzzz is \$5\$.
  Difference between \$names_1\$, bunny, and zzzzz is \$5\$.
  Difference between \$names_2\$, berry, and zzzzz is \$5\$.
  So, total difference is 15, which is maximal.

  Sample Input 1

3
ready
stedy
zebra

  Sample Output 1

yzzzz

  Explanation 1

  Difference between \$names_0\$, ready, and yzzzz is \$5\$.
  Difference between \$names_1\$, stedy, and yzzzz is \$5\$.
  Difference between \$names_2\$, zebra, and yzzzz is \$5\$.
  So, total differce is 15, which is maximal.

I would strip the extraneous parts from my solution:

import math, os, random, re, sys
from collections import defaultdict as dd, Counter as count

alphabet = "abcdefghijklmnopqrstuvwxyz"
def productName(names):
    charmap = [dd(lambda: 0, count(name[i] for name in names)) for i in range(5)]
    return "".join(max(alphabet, key=lambda x: (-charmap[i][x], x)) for i in range(5))

I'm concerned with adhering to best practices and maximising performance.


texts:
I've written a simple lock-free multi-consumer/-producer FIFO queue.
It's supposed to work like this:

At any time many consumers may read from it
At any time multiple producers can write to it, added elements will
be made available later
After write modification is finished, we call makePushedElementsAvailable(), so that consumers can read the newly added elements

It's meant to be used for several worker threads to communicate with the GUI simultaneously. I wouldn't necessarily need multi-consumers, single would suffice, but I figured it would be relatively easy to have multi-consumers.

#pragma once
#include <list>
#include <atomic>

template<typename T, int Size>
class MCMP
{
public:
    MCMP();
    bool tryPushLater(const T &element);
    bool tryPop(T &element);
    void makePushedElementsAvailable();
    bool wasEmpty();
    int size();
protected:
private:
    T elements[Size];
    std::atomic<int> iHead, iTail, iWrite;
};

template<typename T, int Size>
int MCMP<T, Size>::size()
{
    return (iTail.load() - iHead.load());
}

template<typename T, int Size>
bool MCMP<T, Size>::wasEmpty()
{
    return (iHead.load() == iTail.load());
}

template<typename T, int Size>
MCMP<T, Size>::MCMP() : iHead(0), iTail(0), iWrite(0)
{
}

template<typename T, int Size>
void MCMP<T, Size>::makePushedElementsAvailable()
{
    iTail.store(iWrite.load());
}

template<typename T, int Size>
bool MCMP<T, Size>::tryPop(T &element)
{
    int newIndex;
    int index;
    do {
        index = iHead.load();
        if (index == iTail.load())
            return false;
        newIndex = index + 1;
    } while (!iHead.compare_exchange_weak(index, newIndex));

    index = index % Size;
    element = elements[index];
    return true;
}

template<typename T, int Size>
bool MCMP<T, Size>::tryPushLater(const T &element)
{
    int newIndex;
    int index;
    do {
        index = iWrite.load();
        if (index - iHead.load() >= Size)
            return false;
        newIndex = index + 1;
    } while (!iWrite.compare_exchange_weak(index, newIndex));

    index = index % Size;
    elements[index] = element;
    return true;
}

So far this seems to work fine. I'd like to have it checked and validated by some others though, please. Is there a simpler way than making the elements available after all updating has finished?


texts: Clojure: Find specific element in HTML tree

texts:
I am trying to find all "link" elements that link to RSS feeds in a data structure created by clj-tagsoup. I wrote the following code, which seems to work fine. But: I come from a Java background and I am new to functional programming and clojure, so I am not sure if this is the right way to do it. Could you please give me some hints about what I could improve in the following code:

(defn- matches-attributes [current-attributes required-attributes]
    (reduce #(and %1 (= (second %2) ((first %2) current-attributes)))
            true
            required-attributes))

(defn- find-tag [tag-name current-tag attributes]
    (if (= tag-name (tagsoup/tag current-tag))
        current-tag
        (filter #(and (= tag-name (tagsoup/tag %1))
                (matches-attributes (tagsoup/attributes %1) attributes))
                (tagsoup/children current-tag))))

(defn- find-rss-feed [page-result]
    (let [document (tagsoup/parse-string (:body page-result))
          head (first (find-tag :head document nil))
          rss-links (if (nil? head)
                        nil
                        (find-tag :link head {:type "application/rss+xml"}))]
    ... do something with rss-links...))

Edit To clarify a bit, what I am particularily interested in is if traversing the HTML tree the way I do it is the "right" was in a functional language. What I'm also interested in is if "filter" and "reduce" are a good choice as I use them, or if there is a better way. And, of course, I'd also appreciate general hints about what I could do better in this little program...


texts:
I wrote this class to one-line all my JSON serialization, and I'm curious of any input on it.

It's only responsible for serializing/deserializing any type to/from JSON.

The comments and code are pretty self explanatory, but if you want any extra explanation of it please feel free to comment.

Not a lot here, so comment on what you can.

/// <summary>
/// Provides methods for Serialization and Deserialization of JSON/JavaScript Object Notation documents.
/// </summary>
public class JsonSerialization
{
    /// <summary>
    /// Serializes an object to a JSON/JavaScript Object Notation string.
    /// </summary>
    /// <typeparam name="T">The type of the object to serialize.</typeparam>
    /// <param name="value">The object to serialize.</param>
    /// <param name="serializedJson">Filled with a string that is the JsonSerialized object.</param>
    /// <param name="throwErrors">If true, will throw errors. Otherwise, returns false on failures.</param>
    /// <returns>A boolean value indicating success.</returns>
    public static bool Serialize<T>(T value, ref string serializedJson, bool throwErrors = false)
    {
        if (value == null)
        {
            return false;
        }

#if DEBUG
#warning When in DEBUG Mode JavaScript Serialization Errors will be thrown regardless of throwErrors parameter.
            throwErrors = true;
#endif

        try
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            serializedJson = jss.Serialize(value);
            return true;
        }
        catch
        {
            if (throwErrors)
                throw;

            return false;
        }
    }

    /// <summary>
    /// Deserializes a JSON/JavaScript Object Notation string to an object.
    /// </summary>
    /// <typeparam name="T">The type of the object to serialize.</typeparam>
    /// <param name="value">The JSON string representing the serialized object.</param>
    /// <param name="deserializedObject">Filled with the object that is the JsonSerialized string.</param>
    /// <param name="throwErrors">If true, will throw errors. Otherwise, returns false on failures.</param>
    /// <returns>A boolean value indicating success.</returns>
    public static bool Deserialize<T>(string value, ref T deserializedObject, bool throwErrors = false)
    {
        if (value == null)
        {
            return false;
        }

#if DEBUG
#warning When in DEBUG Mode JavaScript Deserialization Errors will be thrown regardless of throwErrors parameter.
            throwErrors = true;
#endif

        try
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            deserializedObject = jss.Deserialize<T>(value);
            return true;
        }
        catch
        {
            if (throwErrors)
                throw;

            return false;
        }
    }
}


texts: Find the total volume traded for each stock and also find the high and low for each of those stocks

texts:
I would like to know whether the following code can be changed in any way as to improve its functionality. Could there be any potential bugs that may arise as a result of how the code is written?

The program is designed to find the total volume traded for each stock
and to also find the high and low for each of those stocks.

Are there any lines of code that are poorly written?  Either syntactical or just a better way to express the logic.

#include <cstdio>
#include <cstring>
#include <map>
#include <iostream>
#include <string>

using namespace std;

typedef basic_string<char> string;

class   CHighLow
{
public:
    CHighLow() : nCurLow(0), nCurHigh(0) {};

    void    add(int nHigh, int nLow)
    {
        if (nHigh > nCurHigh)
            nCurHigh = nHigh;

        if (nLow < nCurLow)
            nCurLow = nLow;
    }

    int& getSum()
    {
        int sum = nCurLow + nCurHigh;
        return sum;
    }

    int     nCurLow;
    int     nCurHigh;
};

int main(int argc, char* argv[])
{
    if (!strcmp("version", argv[1]))
    {
        cerr << "Using version 1.0 VWAPer" << endl;
        return 0;
    }

FILE*   file = fopen(argv[2], "r");

    cerr << "Reading file" << argv[2] << endl;

    char    line[256];
    char    Stocks[1000][10];
    int     Intervals[1000];
    int     Volumes[1000];
    float   Highs[1000];
    float   Lows[1000];

    int     i = 0;
    int     sum = 0;

    while (fgets(line, 256, file))
    {
        sscanf(line, "%s %d %d %f %f",
Stocks[i], &Intervals[i],
&Volumes[i], &Highs[i], &Lows[i++]);
    }

    cerr << "Calculating total volumes" << endl;

    Map<std::string, int>       TotalVolumes;

    for (int s = 0; s <= I; ++s)
    {
        std::string stockname = Stocks[s];

        for (int j =0; j <= i; ++j)
        {
            if (!strcmp(Stocks[j], stockname.c_str()))
            {
                TotalVolumes[stockname] += Volumes[j];
            }
        }
    }

    cerr << "Calculating high lows" << endl;

    map<std::string, CHighLow>  HighLows;

    for (int s = 0; s <= i; ++s)
    {
        HighLows[Stocks[s]].add(Highs[s], Lows[s]);
        cout << HighLows[Stocks[s]].getSum();
    }

    cerr << "Writing files" << endl;

    for (int s = 0; s <= i; ++s)
    {
        cout << Stocks[s] << "," << Intervals[s] << "," <<
TotalVolumes[Stocks[s]] / Volumes[s] * 100 << endl;
    }

    map<std::string, CHighLow>::iterator itr = HighLows.begin();
    while (itr != HighLows.end())
    {
        cout << (*itr).first << "," << (*itr).second.nCurLow << "," <<
(*itr).second.nCurHigh << endl;

        ++itr;
    }

    return 1;
}


texts: PANDAS code for calculating distance between waypoints

texts:
I've written some python code designed to take a csv of waypoints for a series of trips, and calculate the distance of each trip by the sum of the distance between the waypoints.

An example csv might be:

9e77d54918dd25c3f9d2e5354ec86666,0,2015-10-01T14:14:15.000Z,45.0988,7.5811,,
9e77d54918dd25c3f9d2e5354ec86666,1,2015-10-01T14:17:15.000Z,45.0967,7.5793,,
9e77d54918dd25c3f9d2e5354ec86666,2,2015-10-01T14:20:15.000Z,45.1012,7.6144,,
9e77d54918dd25c3f9d2e5354ec86666,3,2015-10-01T14:23:15.000Z,45.0883,7.6479,,
9e77d54918dd25c3f9d2e5354ec86666,4,2015-10-01T14:26:15.000Z,45.0774,7.6444,,
ect...

I've got code working, using pandas and numpy, however I'm entirely self-taught and I want to know if there's any serious or obvious mistakes I'm using that might make my code inefficient. It currently takes quite a while to run, I'm guessing because of my for loop. The code I'm using is:

import pandas as pd
import numpy as np
from math import radians, cos, sqrt

def dist(lat1, lon1, lat2, lon2): #short distances using Equirectangular approximation
    lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
    x = (lon2 - lon1) * cos( 0.5*(lat2+lat1) )
    y = lat2 - lat1
    D = 6371 * sqrt(x**2 + y**2)
    return D

waypoint = pd.read_csv('TripRecordsReportWaypoints.csv',sep=',',header=None, usecols=[0,3,4], names=['TripID','Lat','Lon'])
output = pd.DataFrame(columns = ['TripID','Distance','No. of Waypoints'])

tripList = waypoint['TripID'].tolist() #creates list of tripids
tripList = list(set(tripList)) #makes list unique

for ID in tripList:
    temp = waypoint.loc[waypoint['TripID'] == ID] #creates a temporary dataframe with all waypoint for each trip

    temp['endLat'] = temp['Lat'].shift(periods=-1) #adds two columns with next waypoints lat and lon
    temp['endLon'] = temp['Lon'].shift(periods=-1)

    temp['Distance']=np.vectorize(dist)(temp['Lat'],temp['Lon'],temp['endLat'],temp['endLon']) #calculates distance, can change function 'dist' for more accuracy
    SumDist = temp['Distance'].sum() #calculates the total distance
    trpId = temp['TripID'].iloc[0] #takes the tripid
    wpcount = temp.shape[0] #length of dataframe
    temp2 = pd.DataFrame([[trpId,SumDist,wpcount]],columns=['TripID','Distance','No. of Waypoints']) #creates a single row dataframe with the total distance
    output = pd.concat([output,temp2]) #adds the row to the output
output.to_csv('TripDistances.csv',sep=',')


texts: Android - handle navigation to multi activities from list view

texts:
Here is my case I made list of items when I click at any item it should navigate to certain activity.

Here is my I am done First I set number of constants to distinguish between each activity

// constants to show activities onclick event
private static final int LOC = 0, SERVICES = 1, PRE_APPROVE = 2, CLAIMS = 3, BENEFITS = 4, QUE = 5;

Secondly I create method navigate according to this constant

private void ShowActivity(int position) {
        switch (position) {
            case LOC:
                NavigateTo(LocLacatorActivity.class);
                break;
            case SERVICES:
                NavigateTo(ServicesActivity.class);
                break;
            case PRE_APPROVE:
                NavigateTo(PreApproveActivity.class);
                break;
            case CLAIMS:
                NavigateTo(ClaimsActivity.class);
                break;
            case BENEFITS:
                NavigateTo(BenefitsActivity.class);
                break;
            case QUE:
                NavigateTo(QuestionsActivity.class);
                break;
        }
    }

 private void NavigateTo(Class mActivity) {
        Intent intent = new Intent(MainActivity.this, mActivity);
        startActivity(intent);
    }

Finally , here is how I call the method

servicesButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                     ShowActivity(SERVICES);
                }
            });

Is this good way to handle multi activity navigation, or can I decrease the size of my methods?


texts:
Reads from a flat file of three columns, delimited by at least one tab character.  Filters the three columns based on input; returns list of corresponding emails.  Arguments passed like key=value or key= for blank.

#!/bin/perl
use warnings;
use strict;

sub get_list {
   my $cols   = {'list'=>0, 'email'=>1, 'sub'=>2};
   my $list   = '[a-z0-9_\- ]+';
   my $email  = '[a-z0-9@\._\-]+';
   my $subls  = '[a-z0-9\. ]+';
   my $return = $cols->{'email'};
   foreach (@ARGV) {
      my ($key, $value) = split '=';
      $value = q{} if not defined $value;
      if    ($key eq 'list')   { $list  = $value; }
      elsif ($key eq 'email')  { $email = $value; }
      elsif ($key eq 'sub')    { $subls = $value; }
      elsif ($key eq 'return') {
         $return = $cols->{$value}
                   if defined $cols->{$value};
      }
      else  { die "invalid key: $key\n"; }
   }
   my $file = 'input.txt';
   open FH, '<', $file
         or die "Could not open '$file' $!\n";
   my %emails = map { (split /\s*\t\s*/)[$return] => 'tacos' }
                grep m/^${list}\s*\t\s*${email}(\s*\t\s*${subls})?\s*$/gi,
                <FH>;
   close FH;
   return (join ', ', keys %emails);
}

print get_list(@ARGV);
print "\n";

# test input... three columns delimited by at least one tab
# third column may be blank.  nothing should contain spaces
# in real life, but i'm allowing it...

# archive   email@email.com success
# archive       email2@email.com    fail
# archive   email2@email.com    success
# archive   email3@email.com
# archive   email@email.com fail
# taco  email@email.com success
# taco  email2@email.com    fail
# taco  email2@email.com    success
# taco meat     email3@email.com
# tacor email@email.com fail

I realize some people may not be down with the $thing = $value if defined $value; arrangement but I went ahead and used it since the logic wasn't complex.  I prefer it over using space for brackets on one line conditionals.  Also, please note, I'm not trying to validate email addresses with regex and I these are truly the only characters the strings will contain.

for the future person... this is what I ended up with:

#!/bin/perl
use warnings;
use strict;

sub get_list {
   my $file = 'input.txt';
   my %emails;

   my $cols  = {'list'=>0, 'email'=>1, 'sub'=>2, 'subls'=>2};
   my $index = $cols->{'email'};

   my $dlmtr = qr{\s*\t\s*};
   my $list  = qr{[a-z0-9_\- ]+};
   my $email = qr{[a-z0-9@\._\-]+};
   my $subls = qr{[a-z0-9\. ]+};

   foreach (@ARGV) {
      my ($key, $value) = split qr{=};
      $value //= qr{};
      if    ($key eq 'list')   { $list  = $value; }
      elsif ($key eq 'email')  { $email = $value; }
      elsif ($key eq 'sub')    { $subls = $value; }
      elsif ($key eq 'return' && defined $cols->{$value}) {
         $index = $cols->{$value};
      }
      else  { die "invalid key: $key\n"; }
   }

   open FH, '<', $file or die "Could not open '$file' $!\n";
   while (<FH>) {
      chomp;

      # i couldn't get the syntax in the accept answer to parse for me
      # so i changed it to this... also, %emails is better as a hash
      # b/c it prevents emails added multiple times... and for my thing,
      # the first two columns are required but the third may be blank.

      if (m/^${list}${dlmtr}${email}(${dlmtr}(${subls}))?\s*$/gi) {
         my $value   = (split $dlmtr)[$index];
            $value //= q{};
         $emails{ $value } = 'tacos';
      }
   }
   close FH;

   return join ' ', keys %emails;
}


texts: Review Python script for getting the stats of codereview.SE into a file for analysis

texts:
I wrote a script for getting the stats of codereview.SE from the front page into a file. Github link if someone prefers reading there. Here is  data_file.txt's current contents

23-08-2013
dd-mm-yyyy, questions, answers, %answered, users, visitors/day

22-08-2013,9079,15335,88,26119,7407,
23-08-2013,9094,15354,88,26167,7585,

The first sentence contains the last date at which the data is written into the file. It is a check to make sure that I don't write the data for the same date twice in the file. Also note that there is a newline at the end which isn't being shown above.

What I plan to do is to collect the data for many data and then use matplotlib to get graphs for finding out about the growth of this website. The part about plotting is currently under progress so I am not putting that here.

The python script that I am using is below. I would like a general review of this script and any suggestions about its design in particular.

#! python3
import urllib.request
import datetime

FILE_NAME = 'data_file.txt'
CURRENT_URL = 'http://codereview.stackexchange.com/'

def today_date():
    return datetime.date.today().strftime('%d-%m-%Y')

def already_written():
    with open(FILE_NAME, 'a+') as f:
        f.seek(0)
        first_line = f.readline()
        if today_date() == first_line[:-1]:
            return True
        return False

def parse(line):
    """This separates the stat-name and associated number"""
    temp = [0, '']
    braces = False
    for c in line:
        if c == '<':
            braces = True
        elif c == '>':
            braces = False
        elif braces is True or c in [' ', ',', '%']:
            continue
        elif c.isdigit():
            temp[0] *= 10
            temp[0] += int(c)
        else:
            temp[1] += c

    return temp

def write_stats():
    '''This writes the stats into the file'''
    with open(FILE_NAME, 'r') as f:
        data = f.readlines()

    with open(FILE_NAME, 'w') as f:
        f.write(today_date() + '\n')
        f.writelines(data[1:])

        url_handle = urllib.request.urlopen(CURRENT_URL)
        write_this = today_date() + ','
        for line in url_handle:
            temp_line = str(line)[2:-5]
            if 'stats-value' in temp_line and 'label' in temp_line:
                temp = parse(temp_line)
                write_this += str(temp[0]) + ','
        else:
            write_this += '\n'
            f.write(write_this)

def main():
    if not already_written():
        write_stats()

if __name__ == "__main__":
    main()

EDIT:

I think this line might need some explanation.

if 'stats-value' in temp_line and 'label' in temp_line:

I choose this for finding out the lines in the source code of the html of codereview.SE's front page. Only the 5 lines containing the stats have these 2 in it. So in front they tell me which line to parse.


texts: Logging module for use in other projects

texts:
I'm trying to make a simple module I can paste into my various projects to provide basic logging capabilities. I'm hoping to become less dependent on print because:

Using logging will allow me to quickly enable and disable what's being logged
logging has built-in file and formatting utilities
The built-in levels of logging are helpful

Here's the log.py module:

import argparse
import logging
import sys

def parse_log_args(parser: argparse.ArgumentParser):
    default_level = 'INFO'
    parser.add_argument("-l", "--log", dest="loglevel",
                        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
                        default=default_level,
                        help=f"Set the logging level (default: {default_level})",
                        type=str)

    parser.add_argument(
        '-lf', '--logfile',
        help="File for logging",
        dest="logfile",
        type=str
    )

    return parser

def conf_logging(logger: logging.Logger, loglevel: str, path=None):

    if loglevel.upper() not in ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'):
        raise ValueError("Invalid logging level")

    if path is None:
        console_formatter = logging.Formatter('[%(levelname)s] %(message)s')
        handler = logging.StreamHandler(sys.stdout)
        handler.setFormatter(console_formatter)
    else:
        file_formatter = logging.Formatter(
            ('%(asctime)s [%(levelname)s] %(name)s.%(funcName)s'
             '@ L%(lineno)d\n  %(message)s'))
        handler = logging.FileHandler(path, encoding='utf-8')
        handler.setFormatter(file_formatter)

    l_name = logging.getLevelName(loglevel)
    handler.setLevel(l_name)
    logger.setLevel(l_name)

    logger.addHandler(handler)

    return logger

Here's an example of its usage:

import logging
import argparse
from log import parse_log_args, conf_logging

logger = logging.getLogger(__name__)

parser = argparse.ArgumentParser()

parser = parse_log_args(parser)
args = parser.parse_args()
logger = conf_logging(logger, args.loglevel, args.logfile)

logger.debug("What")
logger.info("okay")

Which can be called as follows:

> python basic.py --log INFO
[INFO] okay
> python basic.py --log DEBUG
[DEBUG] What
[INFO] okay

I'm not super familiar with the logging module, so I was a little surprised I had to have to set the logging lever for both the logger and the handler. Is there a better, more explicit way of writing this?


texts:
I have this question in my exam and I want to know if my answer is correct.

Consider the following program written in C language to implement a reader:

// to simplify the exercise, are not checked the return values of calls to the operating system

 int main(int argc, char* argv[]) {
     sem_t *sem_wrt;
     int fd, readcount;
     fd=shm_open("/readcount",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
     ftruncate(fd, sizeof(int));
     readcount=mmap(0,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
     sem_wrt=sem_open("/write",O_CREAT ,0xFFFFFFFF,1);
     while(1) {
        readcount++;
        if (readcount==1) sem_wait (wrt);
        my_read();
        (readcount)--;
        if (readcount==0) sem_post (wrt);
     }
 }

After some time of using this program, it was found that the program only works properly when it is executed only by a process simultaneously.

Change the code of the program in order to provide a solution to this problem.

int main(int argc, char* argv[]) {
     sem_t *sem_wrt;
     int fd, readcount;
     fd=shm_open("/readcount",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
     ftruncate(fd, sizeof(int));
     readcount=mmap(0,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
     sem_wrt=sem_open("/write",O_CREAT ,0xFFFFFFFF,1);
     //sem_mutex=sem_open("/mutex",O_CREAT ,0xFFFFFFFF,1);
     while(1) {
        //sem_wait(mutex);
        readcount++;
        if (readcount==1) sem_wait (wrt);
        //sem_post(mutex);
        my_read();
        //sem_wait(mutex);
        (readcount)--;
        if (readcount==0) sem_post (wrt);
        sem_post(mutex);
     }
 }


texts:
I'm trying to write a policy based auto-registering class using the Curiously Recurring Template Pattern. I decided as design choice to not using registering macro.

Factory Class

template<typename Base>
class Factory{
   template<typename, typename>
   friend class Registrable;

public:
   static Base* create(std::string name){
      auto callable = map().at(std::move(name));
      return callable();
   }

   static std::unique_ptr<Base> createUnique(std::string name){
      auto callable = map().at(std::move(name));
      return std::unique_ptr<Base>(callable());
   }

   static std::shared_ptr<Base> createShared(std::string name){
      auto callable = map().at(std::move(name));
      return std::shared_ptr<Base>(callable());

   }

private:
   static std::unordered_map< std::string, std::function<Base*()> >& map(){
      static std::unordered_map< std::string, std::function<Base*()> > map;
      return map;
   }

   template<typename Derived>
   static void subscribe(std::string name){
      // insert already-exist-check here
      std::cout<< "registered: " << name << std::endl;
      map().emplace(std::move(name), [](){ return static_cast<Base*>(new Derived{}); });
   }
};

Registrable Class

template<typename Base, typename Derived>
class Registrable{
protected:
   virtual std::string registerName() const = 0;

   Registrable(){
      isRegistered = true;
   }
   ~Registrable() = default;

   static bool init(){
      Derived t;
      Factory<Base>::template subscribe<Derived>(t.registerName());
      return true;
   }

private:
   static bool isRegistered;
};

template<typename Base, typename Derived>
bool Registrable<Base, Derived>::isRegistered = Registrable<Base, Derived>::init();

Client Code Example

struct MyFactoryBase{
   virtual ~MyFactoryBase() = default;
   virtual void method() const = 0;
};

struct MyFactory1 : public MyFactoryBase, public Registrable<MyFactoryBase, MyFactory1>{
   std::string registerName() const override{
      return "Class1";
   }
   void method() const override{ std::cout << "yay Class1" << std::endl; }

   MyFactory1() : MyFactoryBase(), Registrable<MyFactoryBase, MyFactory1>(){}
};

struct MyFactory2 : public MyFactoryBase, public Registrable<MyFactoryBase, MyFactory2>{
   std::string registerName() const override{
      return "Class2";
   }
   void method() const override{ std::cout << "yay Class2" << std::endl; }

   MyFactory2() : MyFactoryBase(), Registrable<MyFactoryBase, MyFactory2>(){}
};

LIVE EXAMPLE

This code was meant to be in Qt, so originally was with QMap instead of std::unordered_map and QString instead of std::string, I could have missed something due to the conversion of the code.

There are improvements I could do or issues I'm not considering?

Please review.