texts: Recursively traverse directory tree and print all files

texts:
I want to build a small console program, that for given directory, will print (for now) all files inside that tree.
Here is an F# script that I came up with:
open System.IO

let getDirObjects (dir :DirectoryInfo) =
    let dirs = dir.GetDirectories()
    let files = dir.GetFiles()
    dirs,files

let rec traverse allFiles dir =
    let dirs,files = getDirObjects dir
    let allFiles' = Seq.append allFiles files
    let allFiles'' = dirs |> Seq.map (traverse allFiles') |> Seq.concat
    Seq.append allFiles' allFiles''

let printFileInfo (fileInfo:FileInfo) =
    printfn "%A" fileInfo.FullName

let printAllFilesFromDir path =
    let dirInfo = DirectoryInfo path
    let allFiles = traverse Seq.empty dirInfo
    allFiles |> Seq.iter printFileInfo

Changelog:

 #1 changed List to Seq to be more generic, no need to convert Arrays returned by GetDirectories and GetFiles to List

I've been reading about F# for past 2 weeks or so. This is actually first toy program that I wrote :)
One thing I don't like is getDirObjects function, that returns a tuple DirectoryInfo * FileInfo. Maybe this could be done in a more fancy way, with pattern matching or sth?
Update
Here is much shorter version, whith same output.
It's get the job done, but my first intention was to do it in an F#, functional way. Please comment on the code above.
open System.IO

let printAllFilesFromDir path =
    Directory.EnumerateFiles(path,"*",SearchOption.AllDirectories)
        |> Seq.iter (printfn "%A")

printAllFilesFromDir "D:\_FTP"


texts: Finding the number of words from a user input string or a text file

texts:
I'm new to Java and is trying to solve the beginners problem of finding out the number of words in an user input string or a text file. I was just wondering if there are any alternatives to any of the steps that can improve efficiency as well as simplicity.

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

public class WordsCount{
    public static void main(String[] args) {

        try(Scanner sc1 = new Scanner(System.in)){
            String userInputOrTextFile = sc1.next();
            if (userInputOrTextFile.equalsIgnoreCase("userInput")){
                WordsCount.countUserInput();
            } else {
                WordsCount.countTextFile();
            }
        }
    }

    private static void countUserInput() {
        try(Scanner sc1 = new Scanner(System.in)){
            String s1 = sc1.nextLine();
            System.out.println(s1.split(" ").length + " words in the user input sentence." );
        }
    }

    private static void countTextFile() {
        int countingWords = 0;
        try(Scanner sc1 = new Scanner(new BufferedReader(new FileReader("xanadu.txt")))){
            while(sc1.hasNext()){
                sc1.next();
                countingWords++;
            }
        } catch (FileNotFoundException e){
            System.out.println("File not found");
        }
        System.out.println(countingWords + " words are in the xanadu.txt file");
    }
}


texts:
Given an array which contains integers (may contain thousands of elements), you have to write a program to find the second largest element of the group.

int secondmax(int array[],int n)
{
 int max;
 int secondmax;
 assert(n>1);
 max=array[0]>array[1] ? array[0] : array[1];
 secondmax=array[0]>array[1] ? array[1] : array[0];
 for(j=2;j<n;j++)
 {
  if(array[j]> max) { secondmax=max;max=array[j];}
  else if (array[j] > secondmax) { secondmax=array[j];}
 }
 return secondmax;
}

Is code correct?
Is usage of assert okay or should it be avoided?


texts:
I am fairly new to Entity Framework and I am not sure I am really using it to it's max potential.  I have this query, that IMHO seems to take a little longer than I feel it should.  I have tried various combinations to retrieve all the data I need making as few connections as possible and so far this query yeilds the best results with an average of about 320 ms.  Is there anything I can do to make this query faster?

Something to note is that the include for Awe_PageContainerBlurb is a many-to-many relationship based on 3 tables.

var roles = from role in db.aspnet_Roles
            join userRole in db.aspnet_UsersInRoles on role.RoleId equals userRole.RoleId
            where userRole.UserId == userID
            select role;

var awePageData = ((ObjectQuery<Awe_Page>)(from page in db.AweBjects.OfType<Awe_Page>()
                                           join app in db.aspnet_Applications on page.ApplicationId equals app.ApplicationId
                                           where app.ApplicationName == user.ApplicationName
                                               && page.Active && page.Name == pageName
                                           from pageRole in page.aspnet_Roles
                                           where roles.Contains(pageRole)
                                           select page))
                                           .Include("Awe_PageContainerBlurb.Awe_Container")
                                           .Include("Awe_PageContainerBlurb.Awe_Blurb");

var menuItems = from menu in db.AweBjects.OfType<Awe_Menu>()
                join app in db.aspnet_Applications on menu.ApplicationId equals app.ApplicationId
                where app.ApplicationName == user.ApplicationName
                    && menu.Active
                from menuRole in menu.aspnet_Roles
                where roles.Contains(menuRole)
                select menu;


texts:
Is there a better way to do this Java 8 String Unique Permutations in Parallel

package com.bos;

import java.util.Date;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.stream.IntStream;

public class StringPermutation {
    private static Set<String> set = new ConcurrentSkipListSet<String>();

    public static void permutation(String str) {
        permutation("", str);
    }

    private static void permutation(String prefix, String str) {
        int n = str.length();
        if (n == 0) {
            set.add(prefix);
        } else {
            IntStream.range(0, n).parallel()
                    .forEach(i -> permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n)));
        }
    }

    public static void main(String[] args) {
        Date startDate = new Date();
        long startTime = System.nanoTime();
        System.out.println("Started at " + startDate);
        permutation("ferrao");
        set.stream().forEach(System.out::println);
        Date endDate = new Date();
        long totalTime = System.nanoTime() - startTime;
        System.out.println("Ended at " + endDate + " total time=" + totalTime + " nanosec");

    }
}


texts: Functions for setting cookies and outputting their IDs

texts:
Below are two functions.

The first is to set a cookie. This function is called on any product page on my website.

function setcookie() {

    $entry_id = $this->EE->TMPL->fetch_param('entry_id');

    if (isset($_COOKIE['recently_viewed'])) {

        $currentSession = unserialize($_COOKIE['recently_viewed']);

        if (!in_array($entry_id, $currentSession)) {

            if (count($currentSession) > 5) {
                unset($currentSession[0]);
            }

            $currentSession[] = $entry_id;

        } else {}

        $currentSession = serialize($currentSession);
        setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', '');

    } else {

        $recently_viewed[] = $entry_id;
        $currentSession = serialize($recently_viewed);
        setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', '');

    }

}

The second function retrieves the IDs in the cookie array and outputs them.

function recently_viewed() {

$tagdata = $this->EE->TMPL->tagdata;

if ( array_key_exists('recently_viewed', $_COOKIE) ) {
    $recent = unserialize($_COOKIE['recently_viewed']);
} else {
    $recent = NULL;
}

if ($recent) {
    $entry_ids = implode('|', $recent);
} else {
    $entry_ids = NULL;
}

$data['entry_ids'] = $entry_ids;

$variables = array();
$variables[] = $data;

return $this->EE->TMPL->parse_variables($tagdata, $variables);

}

The code is built for the content management system Expression Engine. If you don't know 'codeigniter' code, just ignore those bits and take a look at the straight PHP if possible.

Can anyone tell me if there is any way to speed the functions up?

The first function, setcookie, is basically checking to see if a cookie exists.  If it does, it checks if the current entry id is in the array already.  If it's not, then it checks if there are more than 5 items in the array.  If there is, it deletes the first one and adds the new entry id. If no cookie exists, it creates a new cookie and adds the entry id.

The second function (recently viewed) is checks the cookie, converts it to a string with pipelines between entry ids, then outputs this string.


texts:
I have the following code which is responsible for the validation in our app (just an example).

Based on the particular tab where user can add person to the database we need to perform additional validation (more fields in each tab).
Fields that always should be validated are name and surname so we provided an abstract class with subclasses that are specialized for each tab (i.e. Sourcing). Is it somehow possible to simplify this code by using some design patterns or something ?

abstract public class AbstractPersonValidator {

    public boolean isInvalid( Person person ) {
        if ( person.getName() == null || person.getName().length() < 3 )
            return true;

        if ( person.getSurname() == null || person.getSurname().length() < 3 )
            return true;

        return false;
    }
}

Extending:

public class SourcingPersonValidator extends AbstractPersonValidator {
    @Override
    public boolean isInvalid( Person person ) {
        if ( super.isInvalid( person ) )
            return true;

        if ( person.getTechnology() == null )
            return true;

        if ( person.getSource() == null )
            return true;

        return false;
    }
}


texts: Assert LinkedHashMap element in jUnit test

texts:
So I have some test, maybe the given side of that test is not so important to catch the point of my confusion. I wrote

List<LinkedHashMap> failedEvents = ...
//...
assertEquals(failedEvents.size(),1 );
assertTrue(failedEvents.stream().allMatch(x -> x.get("eventId").equals("EVENT3")));

and in the result my code review said I should avoid stream on single element. But I think is clear and readable to show that all elements pass specific matching rule.
Also I though about assertThat, but I ended with much bigger and more complicated piece of code.


texts: Android "ServiceListener" class for listening web services

texts:
I'm new in Android, Java and the whole object-oriented programming, I'm trying to develop an app which needs to listen on many web services (PHP scripts written by me returning a standardized JSON string) and I thought I could design a class which takes this commitment: ServiceListener.

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public abstract class ServiceListener implements runnable {
    public static final String SERVICE_AIRPORTS = "http://example.com/app/a/services/json/airports.php";
    // ...As many constants as web services
    private static final int STATUS_CODE_FORMAT_ERROR = 5;
    private static final int STATUS_CODE_EXECUTION_FAILED = 3;
    private static final int INTERNAL_ERROR = -1;
    private static final int GENERIC_ERROR = 0;

    private JSONObject jsonResult, dataToSend;
    private String serviceUrl;

    protected ServiceListener(String serviceUrl, JSONObject dataToSend) {
        this.serviceUrl = serviceUrl;
        this.dataToSend = dataToSend;

        new Thread(this).start();
    }

    protected JSONObject listenToService() throws JSONException {
        String jsonString;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(serviceUrl + "?data=" + dataToSend.toString(0)).build();
        try (Response response = client.newCall(request).execute()) {
            jsonString = response.body().string();
            jsonResult = new JSONObject(jsonString);

            if(jsonResult.has("Status")) {
                if(jsonResult.getString("Status").equals("Success")) {
                    return jsonResult;
                }
                else if(jsonResult.getString("Status").equals("Failed")) {
                    jsonResult.put("StatusCode", STATUS_CODE_EXECUTION_FAILED);
                    jsonResult.put("StatusMessage", "Service failed execution");
                    return jsonResult;
                }
            }
            else {
                jsonResult.put("StatusCode", STATUS_CODE_FORMAT_ERROR);
                jsonResult.put("StatusMessage", "Service invalid format");
            }
        }
        catch (IOException e) {
            e.printStackTrace();
            jsonResult.put("StatusCode", INTERNAL_ERROR);
            return jsonResult;
        }
        jsonResult.put("Error", GENERIC_ERROR);
        return  jsonResult;
    }
}

Then you can get the response wherever you want using this:

try {
    JSONObject dataToSend = new JSONObject(/*data to send with GET e.g: UserToken, Query and so on...will be interpreted on the web service*/);
    new ServiceListener(ServiceListener.SERVICE_DATE_SELECTOR, dataToSend) {
        @Override public void run() {
            try {
                JSONObject jo = new JSONObject().put("Content", listenToService());
                // Do whatever you want with the JSONObject (jo)
                Log.d("joContent", jo.getJSONObject("Content").toString(0));
            } catch(JSONException e) {
                e.printStackTrace();
            }
        }
    };
} catch(JSONException e) {
    e.printStackTrace();
}

Is it a good and fast way to request for (my own) web services? Eager to receive criticism


texts: Sorting a file with three-line blocks by the second word of the first line in each block

texts:
I have a text file with the following three line pattern with blank lines in between. My script sorts alphabetically by each person's last name and preserves formatting. I would love to see other options to improve this in Bash. For example, the group command that redirects into final.txt repeats a lot. Also, it would be nice to have the content of output.txt in a variable instead of creating a file.

Sally Smith
UniqueStringSmith_1
UniqueStringSmith_2

Wally Wilson
UniqueStringWilson_1
UniqueStringWilson_2

Tod Taylor
UniqueStringTaylor_1
UniqueStringTaylor_2

Judy Johnson
UniqueStringJohnson_1
UniqueStringJohnson_2

The result looks like the following, sorted alphabetically by last name:

Judy Johnson
UniqueStringJohnson_1
UniqueStringJohnson_2

Sally Smith
UniqueStringSmith_1
UniqueStringSmith_2

Tod Taylor
UniqueStringTaylor_1
UniqueStringTaylor_2

Wally Wilson
UniqueStringWilson_1
UniqueStringWilson_2

Here is my script:

#!/bin/bash

# Get the number of lines in the document.
lines=$(cat my-file.txt | wc -l)

# This is the starting range and end range. Each section is three lines.
x=1
y=3

until [ "$x" -gt "$lines" ]; do
    # Store the three lines to one line.
    block=$(awk 'NR=="'"$x"'",NR=="'"$y"'"' my-file.txt)
    # Echo each instance into my file.
    # The $block variable is not double quotes so new lines are not honored.
    echo $block >> output.txt
    # Increment so it goes on to the next block.
    x=$((x+4))
    y=$((y+4))
done

# Sort the output file in place by the second column.
sort -k2 output.txt -o output.txt

# Put it back into original formatting.
while read i; do
    (echo "$i" | awk '{ print $1 " " $2 }'; echo "$i" | awk '{ print $3 }'; echo "$i" | awk '{ print $4 }'; echo "") >> final.txt
done < output.txt

# Remove the unnecessary file.
rm output.txt


texts:
I'm working on a text based rpg game and a couple of commands make use of a target and container pattern. So I wrote this function to split the string up on a given word and put it back together. I'm not sure how efficient it will be in the real world, but I think that it can be improved.

An example of such input and output would be:

splitOnWord("turkey leg from table", "from") -> {"turkey leg", "table"}

typedef std::vector<std::string> StringVector;

StringVector splitOnWord(std::string line, std::string word){
    std::stringstream sstr(line);
    StringVector tmp;
    std::string str;
    int rescnt = 0;

    sstr >> str;
    tmp.push_back(str);
    while(sstr >> str) {
        if(str == word) {
            ++rescnt;
            tmp.push_back(std::string());
        } else {
            tmp[rescnt] += ' ';
            tmp[rescnt] += str;
        }
    }
    return tmp;
}


texts: Total number of common factors for two numbers LARGE VALUES up to 10^12

texts:
Inputs are two values \$1 \le m , n \le 10^{12}\$. I don't know why my code is taking so long for large values where the time limit is 1 sec. Please suggest some critical modifications.

#include <iostream>
#include<algorithm>
using namespace std;

int main() {
    long long count = 0, m, n;
    cin >> m >> n;

    for (long long int i = 1; i <= ((min(m, n)) / 2) + 1; i++) {
        if ((m%i == 0) && (n%i == 0)) {
            count++;
        }
    }

    if (((n%m == 0) || (m%n == 0)) && (n != m)) {
        count++;
    }

    cout<<count;

    return 0;
}


texts: Run a potentially long running application from within a Python webserver and return different results depending on whether the application finishes

texts:
I want an API on a Flask/Gunicorn webserver to make a call to a separate, potentially long-running java application. If the java application finishes before the Gunicorn timeout, Flask should return the detailed response of the application. If the java application takes too long, I want to prempt any 504's and have Flask return a message saying that it is taking too long, but it will send the detailed response to the user's API when it is done. I have a current solution that appears to satisfy these requirements, and is implemented with multiprocessing and by setting an event in a way that isn't quite easy to understand and probably has issues that I cannot see.

There are three possible cases I can think of:

The Java application finished before the specified timeout, and the detailed response is immediately returned by the main code.
The Java application finished after the specified timeout, and the main code sends a response indicating that the detailed information will come later, which the process eventually does.
The specified timeout was misjudged, and the webserver actually times out before the application finishes. The main code doesn't get a chance to return anything (except a 504). However the process is unaffected and still sends the detailed information.

What follows is basically the same implementation of my code, except I'm faking a few things to make it concise. Unfortunately because the tricks with event and time.sleep(1), it may have to be read twice to understand how it works. Please let me know if I can clarify anything.

import multiprocessing
import subprocess
import time

GUNICORN_TIMEOUT = 45  # 75% of actual timeout, 60 seconds

@app.route('/<uuid>')
def main(uuid):
    event = multiprocessing.Event()
    queue = multiprocessing.Queue()
    detailed_response = {'uuid': uuid}
    queue.put(detailed_response)

    process = multiprocessing.Process(target=_process, args=(queue, event,))
    process.start()
    # The Process will set the Event once the java app finishes
    flag = event.wait(timeout=GUNICORN_TIMEOUT)
    if flag:
        # Case 1: Application finished within time, so tell the process to quit
        event.clear()
    else:
        # Case 2: Application did not finish within time, let the user know
        return jsonify({"testing_complete": False}), 202

    ## Process finished before timeout, get detailed response and return it
    detailed_response = queue.get()
    return jsonify({"detailed_response": detailed_response}), 200

def _process(queue, event):
    detailed_response = queue.get()

    # Make call to Java aapp
    args = ['/path/to/app.sh', detailed_response['uuid']]
    p = subprocess.Popen([args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    detailed_response['stdout'], detailed_response['stderr'] = p.communicate()
    detailed_response['exit_code'] = p.returncode

    # Put detailed response on Queue so calling code can access it
    queue.put(detailed_response)

    # App has finished, let main code know by setting the event
    event.set()
    # Sleep to let main code react to the event getting set
    time.sleep(1)
    if not event.is_set():
        # Main code is still alive, so die
        return

    # Main code has timed out either by case 2 or case 3
    # Hit API with detailed response
    hit_api(detailed_response)


texts:
I'm working on building understanding of data structures in general, and specifically linked lists in this example. I'm also trying to increase my ability with templates.

In cross-referencing dozens of examples, I've blended what I've seen into the following node template "Node.h" file:

/*
11 May 2015
VS 2015 Community
Author: Diche Bach
Node template header file.
*/
#ifndef NODE_H
#define NODE_H

#include<iostream>

template<class tNode>
class Node
{
    friend std::istream& operator>>(std::istream& str, tNode& data)
    {
        return str >> data_;
    }
    friend std::ostream& operator<<(std::ostream& str, tNode const& data)
    {
        return str << data_ << " ";
    }
    public:
      Node(tNode data, tNode *link);

    private:
      tNode data;
      tNode *next;
};

#endif /* NODE_H */

The goal is that this Node template be as modular and 'resusable' as possible. Thus, the same node template could be used with a LinkedList template, a DoubleLinked List template, a Stack template, etc.

With only two semesters of C++ under my belt, I'm pushing my envelope, and I appreciate suggestions and comments.

The use of the friend mechanism is something I've never done before, but it seems salient to the goals, so I particularly appreciate comments on that portion.


texts:
This is my first reactJS project and I am trying to build a page out of my components. I thought it would be best to create a section component and then put appropriate components inside of it.

I'm not sure if this is the correct way... it works but looks a bit weird when there is more than one component. Also VS Code yells at me if I put an apostrophe in a heading.

MySection.js

            {this.props.content}

Homepage.js

      <MySection
        bgColor={'bg-gray'}
        content={
          [
            <MediaObject heading={'today's rates!'} />,
            <MediaObject heading={'some other heading'} />,
            <MediaObject heading={'other other heading'} />
           ] />

      <MySection
        bgColor={'bg-gray'}
        content={
            <MediaObject heading={'today's rates!'} />,
        } />


texts:
I have my PDO Wrapper class and would love to get some more tips/opinions about what you think. This is my first class and I basically put my time into making it as logical and standardized as possible. I know I need to add comments.

<?php
/*
    COPYRIGHT © SIMPLEBB.NET
    CREATED BY: MikeM.
    CREATED IN: 2014
    COPYRIGHT © SIMPLEBB.NET
*/
class Database{
    private $db;

    public function __construct($config){
        $driver = strtolower($config['database']['driver']);
        $host = $config['database']['host'];
        $database = $config['database']['name'];
        $username = $config['database']['username'];
        $password = $config['database']['password'];

        $this->connect($driver, $host, $database, $username, $password);
    }

    private function connect($driver, $host, $database, $username, $password){
        try{
            $this->db = new PDO($driver.":host=".$host.";dbname=".$database, $username, $password);
            $this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }catch(PDOException $ex){
            $errorCode = $ex->getCode();
            $errorMessage = $ex->getMessage();
            $errorFile = $ex->getFile();
            $errorLine = $ex->getLine();
            include(dirname(dirname(__FILE__))."/error.php");
        }
    }

    public function close(){
        $this->db = null;
    }

    public function nonQuery($query){
        try{
            $run = $this->db->prepare($query);
            if(func_get_args() > 0){
                $args = func_get_args();
                array_shift($args);
                return $run->execute($args);
            }else{
                return $run->execute();
            }
        }catch(PDOException $ex){
            $errorCode = $ex->getCode();
            $errorMessage = $ex->getMessage();
            $errorFile = $ex->getFile();
            $errorLine = $ex->getLine();
            include(dirname(dirname(__FILE__))."/error.php");

        }
    }

    function query($query){
        try{
            $run = $this->db->prepare($query);
            if(func_get_args() > 0){
                $args = func_get_args();
                array_shift($args);
                $run->execute($args);
            }else{
                $run->execute();
            }
            return $run; // using: ->fetchall(PDO::FETCH_ASSOC); needs: print_r($db->query("SELECT * FROM `test2`"));
        }catch(PDOException $ex){
            $errorCode = $ex->getCode();
            $errorMessage = $ex->getMessage();
            $errorFile = $ex->getFile();
            $errorLine = $ex->getLine();
            include(dirname(dirname(__FILE__))."/error.php");
        }
    }
}
$db = new Database($config);
/*
    COPYRIGHT © SIMPLEBB.NET
    CREATED BY: MikeM.
    CREATED IN: 2014
    COPYRIGHT © SIMPLEBB.NET
*/
?>

I'd recommend to do:

$db = new Database($config);

only when you really need the database class, you don't want un-closed connections to be open. You can let this the same but make sure you manually do the connection when you need it!

Therefore this is globalized error logging. In some cases you do not want that so I'd recommend for such cases to destroy these try catches and actually do that when you call the function.


texts:
I have two numbers: a and b. I want to put the smaller of them in one variable, and the larger in another variable (if they are equal, then any of them can be in any of the variables). Currently my code (in Javascript / Java) takes 7 lines:

if (a<=b) {
    small = a;
    large = b;
} else {
    small = b;
    large = a;
}

I could also use the Math.max and Math.min functions:

small = Math.min(a,b);
large = Math.max(a,b);

This takes only 2 lines but it is wasteful because the test of which one is larger will be done twice - once in Math.min and once in Math.max.

Is there a shorter / more elegant way to do this?


texts: Does this tkinter-based web browser widget use a well implemented class?

texts:
I have fully functional code in class format, and as far as I am aware from my previous question, it conforms to PEP 8 and the code logic and implementation is suitably pythonic. My main concerns here is whether or not I have put self. in front of the correct variables, and some ambiguity surrounding my @staticmethod.

Should I leave it as it is?
Should I change the logic so it is not static?
Should it be in the class at all?

# This imports some necessary libraries.
import webbrowser
import tempfile
import urllib.request
from tkinter import *

class Browser:
    """This creates a relay that allows a user to directly view data sent from a web server."""
    def __init__(self, master):
        """Sets up a browsing session."""
        # Explicit global declarations are used to allow certain variable to be used in all methods.
        global e1

        # Here we create some temporary settings that allow us to create a client that ignores proxy settings.
        self.proxy_handler = urllib.request.ProxyHandler(proxies=None)
        self.opener = urllib.request.build_opener(self.proxy_handler)

        # This sets up components for the GUI.
        Label(master, text='Full Path').grid(row=0)
        e1 = Entry(master)
        e1.grid(row=0, column=1)
        Button(master, text='Go', command=self.browse).grid(row=0, column=2)

        # This binds the return key to self.browse as an alternative to clicking the button.
        root.bind('<Return>', self.browse)

    @staticmethod
    def parsed(data):
        """Cleans up the data so the file can be easily processed by the browser."""
        # This removes removes all python-added special characters such as b'' and '\\n' to create understandable HTML.
        initial = str(data)[2:-1]
        lines = initial.split('\\n')
        return lines

    def navigate(self, query):
        """Gets raw data from the queried server, ready to be processed."""
        # This gets the opener to query our request, and submit the response to be parsed.
        response = self.opener.open(query)
        html = response.read()
        return html

    def browse(self):
        """Wraps all functionality together for data reading and writing."""
        # This inputs and outputs the necessary website data from user-specified parameters.
        raw_data = self.navigate(e1.get())
        clean_data = self.parsed(raw_data)

        # This creates a temporary file in which we store our HTML data, and open it in the default browser.
        with tempfile.NamedTemporaryFile(suffix='.html', delete=False) as cache:
            cache.writelines(line.encode('UTF-8') for line in clean_data)
            webbrowser.open_new_tab(cache.name)

# Creates a Tk() window that is always in front of all other windows.
root = Tk()
root.wm_attributes('-topmost', 1)

# Starts the program by initializing the Browser object and main-looping the Tk() window.
anon = Browser(root)
root.mainloop()


texts: Generic object pooler implementation for Unity prefabs

texts:
2 scripts:
    - ObjectPooler
    - PoolableObject

The ObjectPooler acts as a singleton manager of poolable objects. Any prefab can be instantiated using the pooler via:

    GameObject go = GetPooledObject(prefabReference)

You would use this rather than instantiate the object manually. If an object of that prefab type already exists and is inactive, it is returned instead of instantiating a new one. Currently I am unsure if I should SetActive(true) the gameobject when it is returned from the pool, as that would invoke Start() on that GameObject before its values can be updated.

ObjectPooler.cs:

using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

/* This class is used for pooling objects and reusing objects for performance
 * This works best when lots of the same object are spawned multiple times
 * such as projectiles from a gun */
public class ObjectPooler : MonoBehaviour
{
    public static ObjectPooler instance;
    public List<PrePooledObjects> prePooledObjects;
    private Dictionary<string, Queue<GameObject>> dict = null;

    [Serializable]
    public struct PrePooledObjects
    {
        public GameObject gameObject;
        public int count;
    }

    void Awake()
    {
        if (instance == null)
        {
            instance = this;
            dict = new Dictionary<string, Queue<GameObject>>();
        }
        else
        {
            Destroy(this);
        }
    }

    private void Start()
    {
        List<GameObject> pooledObjects = new List<GameObject>();
        foreach (PrePooledObjects prePoolObj in prePooledObjects)
        {
            for (int i = 0; i < prePoolObj.count; i++)
            {
                pooledObjects.Add(GetPooledObject(prePoolObj.gameObject));
            }
        }

        foreach (GameObject go in pooledObjects)
        {
            go.SetActive(false);
        }
    }

    public GameObject GetPooledObject(GameObject go)
    {
        if (!dict.ContainsKey(go.name))
        {
            dict.Add(go.name, new Queue<GameObject>());
        }

        if (dict[go.name].Count > 0)
        {
            return dict[go.name].Dequeue();
        }
        else
        {
            GameObject newGo = Instantiate(go);
            PoolableObject po = newGo.GetComponent<PoolableObject>();
            if (po == null)
            {
                po = newGo.AddComponent<PoolableObject>();
            }
            po.prefab = go;
            return newGo;
        }

    }

    public void ReleasePooledObject(PoolableObject po)
    {
        if (!dict.ContainsKey(po.prefab.name))
        {
            dict.Add(po.prefab.name, new Queue<GameObject>());
        }
        dict[po.prefab.name].Enqueue(po.gameObject);
    }
}

PoolableObject.cs:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PoolableObject : MonoBehaviour
{
    [SerializeField]
    public GameObject prefab = null;

    private void OnDisable()
    {
        if (prefab != null)
            ObjectPooler.instance.ReleasePooledObject(this);
    }
}
```


texts: Newbie Map/Reduce word frequency counter

texts:
I present you my first ever module to learn some Erlang awaiting your scrutiny . It does a word frequency count using map/reduce . I'm an Erlang noob, so I would very much like feedback about:

Unneeded verbosity / code

Erlang 'style' mistakes

Things that can be done more elegantly

-module(main).

-export([map/1]).
-export([main/0]).
-export([reducer_wrapper/1]).
-export([reducer/2]).

-define(NUMBER_OF_PARTITIONS, 100).

main() ->
    Lines = readlines('pg20417.txt') ,
    lists:foreach( fun main:map/1, Lines ),
    start_reduce().

%% signals all reducer_wrappers that all emits are received, and the actual reduce can be started
start_reduce() ->
    lists:foreach( fun(PartitionNr) -> get_reducer(PartitionNr) ! start_reduce end, lists:seq(1, ?NUMBER_OF_PARTITIONS) ).

%% emits every word with cnt = 1
map(Line) ->
    Words = string:tokens( string:to_lower(Line), " .,;:\n()?"),
    lists:foreach ( fun(Word) -> get_reducer( Word, ?NUMBER_OF_PARTITIONS ) ! {emit, {Word, [1]}} end, Words ).

%% returns the reducer Pid
get_reducer( PartitionNr ) ->
    ProcessName = list_to_atom( lists:concat( [PartitionNr, '_reducer'] ) ),
    case whereis( ProcessName ) of
    undefined ->
        Pid = spawn(?MODULE, reducer_wrapper, [[]]),
        register( ProcessName, Pid ),
        Pid;
    Pid ->
        Pid
    end.

get_reducer( Key, NumberOfPartitions ) ->
    get_reducer(  erlang:phash2(Key) rem NumberOfPartitions + 1 ).

%% the reducer wrapper proces
reducer_wrapper(KeyValueTuples) ->
    receive
    { emit, KeyValueTuple } ->
        reducer_wrapper( [KeyValueTuple] ++ KeyValueTuples );
        start_reduce ->
        Dictionary = lists:foldl( fun main:reducer/2, dict:new(), KeyValueTuples ),
        show_all( dict:to_list(Dictionary) )
    end.

reducer( { Key, [Cnt] }, Dictionary ) ->
    case dict:is_key( Key, Dictionary ) of
    true ->
        dict:store( Key, dict:fetch( Key, Dictionary ) + Cnt, Dictionary );
    false ->
        dict:store( Key, Cnt, Dictionary )
    end.

readlines(FileName) ->
    {ok, Device} = file:open(FileName, [read]),
    get_all_lines(Device, []).

get_all_lines(Device, Accum) ->
    case io:get_line(Device, "") of
        eof  -> file:close(Device), Accum;
        Line -> get_all_lines(Device, Accum ++ [Line])
    end.

show_all([Head|Tail]) ->
        io:format("~p~n", [Head]),
        show_all(Tail);

show_all([]) ->
        void.


texts: Conversion of datetime strings in PHP pages to user's timezone

texts:
I am working on a PHP/MySQL application that uses a different time zone from the server it runs on, and neither of the timezones are UTC.  I'm converting displayed times to be in the user's timezone, and am wondering whether my approach is sensible.  I would love any feedback you might have.

Firstly, the application's current time is written to the output HTML page as a meta value:

<meta name="date" content="<?php echo date('Y-m-d H:i:s') ?>" />

And, every instance of a datetime string is wrapped thus:

<?php echo $data->datetime_column ?>

Then, after the page is loaded, the following JQuery gets the application time, the user time, figures out the difference between these, and adds that difference to the datetime data:

$("span.datetime-convert").each(function(){
    var serverTime = parseDatetime($("meta[name='date']").attr("content"));
    var userTime = new Date();
    var userOffset = new Date(userTime.getTime() - serverTime.getTime());
    var timeToConvert = parseDatetime($(this).text());
    var convertedTime = new Date(timeToConvert.getTime() + userOffset.getTime());
    $(this).text(convertedTime.toLocaleString());
});
function parseDatetime(value) {
    var a = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/.exec(value);
    if (a) {
        return new Date(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]);
    }
    return null;
}

What am I doing wrong?


texts:
I am making a small project in Spring MVC. My login controller looks like this:

@Controller
public class LoginController
{
   @Autowired
   private Environment env;

   private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

   private AuthenticationService authenticationService = AuthenticationService.getAuthenticationInstance();

   @RequestMapping(value = "/login.jsp" , method = RequestMethod.GET)
   public ModelAndView userLoginPage(){
    return new ModelAndView("Login");
   }

   @RequestMapping(value = "/login", method = RequestMethod.POST)
   public ModelAndView userLogin(@ModelAttribute LoginModel loginModel) {
    LOGGER.info("Employee trying to login [{}] ", loginModel.toString());
    ModelAndView loginView = new ModelAndView();
    loginView.addObject("loginModel", loginModel);
    String login = authenticationService.authenticateUser(loginModel,env);
    switch (login) {
    case "Authenticated":
        loginView.setViewName("dashboard");
        break;
    case "Authenticated First time Login":
        loginView.setViewName("changepassword");
        break;
    case "Not Authenticated":
        loginView.setViewName("Login");
        loginView.addObject("invalid", "invalid user/password");
        break;
    }

    return loginView;
 }

     @RequestMapping(value = "/changePassword" , method = RequestMethod.POST)
     public ModelAndView userPasswordChange(@ModelAttribute
       PasswordChangeModel passwordChangeModel){
     LOGGER.info("Employee trying to change password [{}]
       ",passwordChangeModel.getUserid());
     authenticationService.changePassword(passwordChangeModel, env);
     return new ModelAndView("passwordchangesuccess");
   }

 }

I am using switch case to delegate to different views. Is this the right approach or should I do something else to delegate response to views?


texts:
Can you please tell me whether this is a good way to get the user's IP (IPv4 or IPv6)? Does someone have a better way to do this? Please take a look at the entire code, the server_params order and the comments.

/* We are looking for ip in server params */
$server_params = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR');

foreach($server_params as $server_param)
{
    /* If server param exists and his value is a real ip */
    if(isset($_SERVER[$server_param]) && filter_var($_SERVER[$server_param], FILTER_VALIDATE_IP))
    {
        /* If we are here, then means that the ip is whether IPV4 or IPV6 */
        /* This means that we can set user_ip as binary - We will insert this ip into an mysql column - VARBINARY (16) */
        define('user_ip',inet_pton($_SERVER[$server_param]));
        break;
    }
}

/* If the user_ip is not defined or the inet_pton failed (can inet_pton fail if is defined ?) */
if(!defined('user_ip') || user_ip === false) { echo 'Error. Your ip is not valid'; exit(); }


texts:
How would I go about checking to make sure only valid results are entered/How do I create a loop that will continue to ask one of the questions until answered correctly?

def hotel():
    rooms = [0, 150, 180, 400]
    breakfast = [0, 20, 0]
    type_of_room = input('what type of room would you like?\n1: Queen ($150)\n2: King ($180)\n3: Suite ($400)\n')
    room = rooms[int(type_of_room)]
    number_of_nights = input('how many nights will you be staying?')
    optional_breakfast = input('would you like to include the optional breakfast?\n1: Yes\n2: No')
    breakfast_answer = breakfast[int(optional_breakfast)]
    total = 'your total bill will come to: $'
    result = str((int(room) * int(number_of_nights)) + int(breakfast_answer))

    print(total + result)

hotel()


texts: Sendgrid + Mako email templates quick code review

texts:
I created small module to help me create rich sendgrid html emails using the mako templating engine.  Any feedback on the design would be appreciated:

makosg.py

from sendgrid.message import Message
from mako.template import Template
from mako.lookup import TemplateLookup

class MakoMessage(Message):

    def __init__(self, addr_from, subject, vars={}, text="",
                 temp_path=None, temp_filename=None):
        html = self.render_template_output(vars, temp_path, temp_filename)
        subject = self._render(subject, vars)
        text = self._render(text, vars)
        super(MakoMessage, self).__init__(addr_from, subject, text, html)

    def render_template_output(self, vars, temp_path, temp_filename):
        if temp_path and temp_filename:
            lookup = TemplateLookup([temp_path])
            template = lookup.get_template(temp_filename)
            return template.render(**vars)
        return ""

    def _render(self, temp_data, vars):
        template = Template(temp_data)
        return template.render(**vars)

tests.py

import unittest

class MakoMessageTests(unittest.TestCase):

    def _callUT(self, addr_from, subject, vars={}, text="", temp_path=None,
                temp_filename=None):
        from makosg import MakoMessage
        return MakoMessage(addr_from, subject, vars, text, temp_path,
                           temp_filename)

    def test_should_render_basic_txt_template(self):
        message = self._callUT('test@example.com', 'Hello ${name}',
                               vars={'name': 'bob'},
                               text="How's it going ${name}?",
                               )
        self.assertTrue('bob' in message.subject, message.subject)
        self.assertTrue('bob' in message.text, message.text)
        self.assertTrue(not message.html, message.html)

    def test_should_render_html_file(self):
        message = self._callUT('test@example.com', 'Hello ${name}',
                               vars={'name': 'jim'},
                               text="",
                               temp_path='./makosg/test_templates/',
                               temp_filename='example.mako')
        self.assertTrue('
jim
' in message.html, message.html)
        self.assertTrue(not message.text, message.text)

    def test_should_render_rich_html_message(self):
        message = self._callUT('test@example.com', 'Hello ${name}',
                               vars={'name': 'Brian', 'fruits':
                                     ['apple', 'pear', 'berry']},
                               text="My favorite fruit is an ${fruits[0]}",
                               temp_path='./makosg/test_templates/',
                               temp_filename='example2.mako')
        self.assertTrue('
apple
' in message.html and \
                        '
pear
' in message.html and \
                        '
berry
' in message.html and \
                        '
Hello Brian
' in message.html, message.html)
        self.assertTrue('apple' in message.text, message.text)
        self.assertTrue('Brian' in message.subject, message.subject)

https://github.com/bcajes/makosg


texts: React.js with Ramda functions - hiding rather than removing from DOM

texts:
I would like to make this function more efficient. Currently, its performance is lacking.

From my understanding, for large list that is being kept locally - I may might be better doing display:none on the hidden ones rather than removing them from the DOM. This could dramatically cut down on interactions.

I also need to add new "entries" to the list of "movies", but need to refrain from storing the results of the filtering operation to state as this will slow it down again.

For a working codesandbox, see here.

const andFilter = (x, filters) => {
    // if we have no filters, we just return everything
    if (filters.length == 0) {
      return x.movies;
    }

    const wheres = filters.map(g => where({
      genres: pipe(pluck('name'), contains(g))
    }));

    return pipe(
      prop('movies'),
      filter(
        allPass(wheres)
      )
    )(x);
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedFilters: {},
      movies:x.movies
    };
  }

  handleChange = genre => {
    const { selectedFilters } = this.state;
    selectedFilters[genre] = !selectedFilters[genre];
    this.setState({
      selectedFilters: {
        ...reject(v => !v, selectedFilters),
      },
    });
  };
  addNew = () =>{
      this.setState({movies:this.state.movies.concat([newObject])});
    }

  uniqueGenres(movies) {
    return pipe(pluck('genres'), flatten, pluck('name'), uniq)(movies);
  }

  render() {
    const { selectedFilters } = this.state;
    console.log(selectedFilters);

    const filteredResults = andFilter(x, Object.keys(selectedFilters));

    return (

        Add

        <CreateNew
          onChange={this.addNew}
        />
        Filters:

        {this.uniqueGenres(filteredResults).map(e => (
          <Filter1
            key={e}
            genre={e}
            isActive={!!selectedFilters[e]}
            onChange={this.handleChange}
          />
        ))}

          {filteredResults.map(movies => (
            <Results key={movies.id} result={movies} />
          ))}

    );
  }
}
class CreateNew extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
      value:'',
      genres:''
    };
  }
  render() {
const { value, genres } = this.props;
    return (

        Add a new movie
        <input type="text" value={value} />

        Add genres
        <input type="text" value={genres} />

    );
  }
}
class Results extends React.Component {
  render() {
    const { result } = this.props;

    return (

          {result.name}

        <il>
          {result.genres.map(e =>  {e.name} )}
        </il>

    );
  }
}

class Filter1 extends React.Component {
  handleClick = () => {
    this.props.onChange(this.props.genre);
  };

  render() {
    const { genre, isActive } = this.props;

    return (
      <button onClick={this.handleClick}>
        {genre}
        {' '}
        {isActive ? 'Active' : 'Inactive'}
      </button>
    );
  }
}


texts: How can I shorten the runtime of my simulation?

texts:
Before you read the code below, note the following explanation:
I have three classes: Driver, Vehicle, and Itinerary.
They have attributes Driver.behavior, Vehicle.pRange, Vehicle.pBattery, Itinerary.destinations, and Itinerary.startTime.
The function findCand takes all these class attributes as input and returns as an output a dataframe with three columns.
So here is the code that I use to run my simulation:
n = 1000
m = 1000

agentA = []
iterationA = []
itineraryA = [None]*n
behaviorA = [None]*n
rangeA = [None]*n
batteryA = [None]*n
startTimeA = [None]*n
df = pd.DataFrame(columns = ['Loc', 'Amount', 'Time'])

for j in range(m):
    for i in range(n):
        x = Itinerary()
        y = Vehicle()
        z = Driver()
        itineraryA[i] = x.destinations
        behaviorA[i] = z.behavior
        rangeA[i] = y.pRange
        batteryA[i] = y.pBattery
        startTimeA[i] = x.startTime
        dfi = findCand(itineraryA[i], behaviorA[i], rangeA[i], batteryA[i], startTimeA[i])
        df = df.append(dfi)
        agentA = agentA + [i]*len(dfi)
        iterationA = iterationA + [j]*len(dfi)

df['Ag'] = agentA
df['It'] = iterationA

I run it n times, m iterations. For each dataframe I get from findCand, I append it to the dataframe df.
The code works, but it's taking a crazy amount of time to run.
If n=10 and m=10, it takes about a second.
If n=100 and m=100, it takes around 97 seconds.
I put n=1000 and m=1000 and it was running for more than 3 hours before I stopped it.
I need to do this for a way higher value of both n and m. I realize that it takes a lot of time to append a dataframe so often but I've tried a few other methods

I used a dictionary and appended larger dataframes fewer times.
I used lists instead of dataframes and then made one large dataframe in the end.

But these methods took just as long or even longer than the one above. So my question is, can anyone suggest areas that I can improve that might shorten the runtime?


texts:
I have around 350 People loading into a CollectionView and am already noticing some lag when filtering on their Name. This concerns me as we could easily reach > 1000 People quickly and I need filtering to be as quick as possible.

I'm trying to avoid calling Refresh() as I know this is expensive but I am not quite sure how to do this here. Here is my code:

C#

public PeopleViewModel()
{
    using (var context = new DashboardContext())
    {
        People = new ObservableCollection<Person>(context.People.ToList());
        SearchPeople = new ObservableCollection<SearchPerson>(
            People.Select(c => new SearchPerson
            {
                Id = c.Id,
                FullName = c.FullName.ToLower(),
                DisplayName = c.FullName
            }).ToList().OrderByDescending(x => x.Id));
    }

    SearchPeopleView = CollectionViewSource.GetDefaultView(SearchPeople) as CollectionView;
    if (SearchPeopleView != null) SearchPeopleView.Filter = ViewFilter;
}

C# Filter

private void FilterPeople()
{
    SearchPeopleView.Refresh();
}

private bool ViewFilter(object obj)
{
    var user = obj as SearchPerson;
    return user != null && user.FullName.Contains(_searchString);
}

XAML

<DataGrid Grid.Row="1" Margin="5"
            SelectedItem="{Binding SelectedSearchPerson}"
            ItemsSource="{Binding SearchPeopleView}"
            Style="{StaticResource HomeDataGrid}">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding DisplayName}" Width="*"/>
    </DataGrid.Columns>
</DataGrid>

I use a DataGrid here as I couldn't get the styling I was looking for in a ListBox. I also created a minimal version of a Person, SearchPerson so I can search on fewer properties.

Reading around there are solutions but many are < 5 years old. I'm also aware that Contains() can be slow so I suppose I should be looking at a different approach to the Filter itself.

I'd appreciate any help and advice, thanks!


texts:
I have large dataframe containing many replicates.
The replicates are in groups of 3. So the first 3 replicates are in column 1, 2 and 3. The second set 4, 5 and 6... and so on.

Now I create a new dataframe containing for each set of replicates the mean.

The code below works, but it is really clumpy and especially the cbind and the collumname setting is really ugly.

# first i create the new dataframe
data.mean<- data.frame(matrix(nrows=30))

# iterate over every third collumn
for(col in seq(1,length(colnames(data)), by=3)){

    # create a subset from the dataframe and compute the mean of the rows and finally cbind it to the result dataframe
    data.mean <-cbind(data.mean,apply(subset(data, select=seq(col,length.out =   3)),1,mean, na.rm = TRUE))

    # setting the new collumn name to the colname from the old dataset (name of the first replicate)
    colnames(data.mean)[ncol(data.mean)] <- colnames(data)[col]
}

I really want to improve my R coding style so i am happy about every tip!


texts:
About a week ago, I put up this code and got some really good help.  I've modified it a bit and was seeking if someone would review my second iteration. Original can be found here.

Here's the new stuff.  Basically, I stuck it all in a module, added support for the option of a dash or no dash.  And gave it the ability to work with sentences.

module PigLatin
class Translator
#how all the words end
ENDING = "ay"

def initialize (options = {:dash => true})
  @dash = options[:dash]
end

def translate (phrase)
  sentences = phrase.split(".")
  translated_sentences = sentences.map do |sentence|
    translation(sentence) + "."
  end
  translated_sentences.join(" ")
end

private

def translation (phrase)
  words = phrase.split
  translated_words = words.map do |word|
    if vowel_is_first(word)
      translate_with_vowel(word)
    else
      translate_with_consonant(word)
    end
  end
  translated_phrase = translated_words.join(" ")
  if @dash == false
    translated_phrase = translated_phrase.delete("-")
  end
  translated_phrase.capitalize
end

def vowel_is_first(word)
  return true if word[0] =~ /a|e|i|o|u|A|E|I|O|U/
  return false
end

def translate_with_vowel(word)
  "#{word}-#{"w"+ENDING}"
end

def translate_with_consonant(word)
  return "#{word[1]}-#{word[0]+ENDING}" if word.size == 2
  second_segment, first_segment = split(word)
  return "#{first_segment}-#{second_segment+ENDING}"
end

def split(word)
  split_location = word =~ /a|e|i|o|u/
  second_segment = word[0,split_location]
  first_segment = word[split_location,word.size]
  return second_segment, first_segment
end
end

class InputAcceptor

def initialize input, options
  @options = options
  @input = input
end

def do_it
  pig_latin = Translator.new(@options)
  pig_latin.translate(@input)
end

end

end
  j = PigLatin::InputAcceptor.new("Hello. You. Guy.",{:dash => false})
  p j.do_it


texts: Listing the representations of integer M as a sum of three squares M = x^2 + y^2 + z^2

texts:
I am trying a number as the sum of 3 squares.  For my particular project I will require a complete list since the next step is to compute nearest neighbors (here).

In any case we'd like to find \$ M = x^2 + y^2 + z^2 \$ in all possible ways.  Here's what I wrote in Python:

M = 1062437
m = int(np.sqrt(M))

x = np.arange(int(np.sqrt(m)))
y = M - x**2

sq = [(i,j, int(np.sqrt(M - i**2 - j**2))) for i in range(m) for j in range(m) if i**2 + j**2 in y]

This is easy to explain in pseudocode.

build a list of remainders \$\{ M - k^2 : 0 \leq k \leq \sqrt{M} \}\$
loop over all possible \$0 < i,j < \sqrt{M} \$ check that \$i^2 + j^2 \$ is in the list

This is one of several possible strategies.  In my case, I don't even need a fixed M it could be a range, such as 10**6 < M < 10**6 + 10*4.

I do not  mind looping over values of M at this point. Can we recycle our computations somehow?


texts:
Problem

There was an interesting problem on the dailyprogrammer subreddit:

  A number of sailors (let's call it N) are stranded on an island with a
  huge pile of coconuts and a monkey. During the night, each sailor (in
  turn) does the following without the others knowing:

  He takes one N'th (e.g. if N=5, one fifth) of the coconuts in the pile and hides them
  The division leaves one coconut left over, which is given to the monkey.

  In the morning, they split the remaining coconuts between them. This
  time the split is even. There's nothing left over for the monkey.

  Your task: Given the number of sailors (N), how many coconuts were in
  the pile to begin with (lowest possible number)?

I was hoping to get feedback on my solution, and possibly suggestions as to better implementation.

I am not terribly satisfied with my use of a potential infinite while loop (replace with a for and an upper bound - if so, what's the upper bound)?
Should I type cast to double when I calculate the multiplier value?

Example

The solution for 2 sailors is 11 coconuts.
11 => 11 / 2 (since first sailor takes 1/2 of coconuts) => 5 remainder 1 (which goes to the monkey)
5 => 5 / 2 (since seconds sailor takes 1/2 of remaining coconuts) => 2 remainder 1 (which again goes to the monkey)
2 can be split evenly between the 2 sailors

Implementation

public class CoconutCalculatorImpl implements CoconutCalculator {
    @Override
    public double calculateCoconuts(final long sailors) {
        long factor = 1;
        final double multiplier = (double) sailors / (double) (sailors - 1);
        while (true) {
            double baseValue = (factor * sailors);
            long counter = 0;
            while ((0 == baseValue % (sailors - 1)) & (counter < sailors)) {
                baseValue = (baseValue * multiplier) + 1;
                counter++;
            }

            if (counter == sailors) {
                return baseValue;
            }

            factor++;
        }

    }
}


texts:
This is my first program written outside of using books and tutorials. Any help on style and functionality would be helpful.

import sys
from textwrap import dedent
import os
import random

os.system('CLS')

# board number setup
board = [0,1,2,
         3,4,5,
         6,7,8]

# Defines the board layout printed to the console
def board_layout():
    print(dedent(f'''
    *************
    * {board[0]} | {board[1]} | {board[2]} *
    *-----------*
    * {board[3]} | {board[4]} | {board[5]} *
    *-----------*
    * {board[6]} | {board[7]} | {board[8]} *
    *************
    '''))

move_count= 0
def main():
    while  True:

        #Prints board layout to console.
        board_layout()
        #checks for a winner when called at end of each turn
        def check_winner():
            global move_count
            #list of lists with all the winning combinations for from the tic tac toe board
            winning_list = [[board[0],board[1],board[2]],[board[3],board[4],board[5],],
            [board[6],board[7],board[8]],[board[0],board[4],board[8]],[board[2],board[4],board[6]],
            [board[0],board[3],board[6]],[board[1],board[4],board[7]],[board[2],board[5],board[8]]]
            #Keeps a reference to winning_list so it is updated at the end of every turn
            new_list = winning_list

            #iterates over the lists in winning_list
            for i,j,k in winning_list:
                #looks at the lists in winning_list to determine if a list has all x's for a win
                if i ==  'x' and j ==  'x' and k ==  'x' :
                    print('X wins')
                    end()
                #looks at the lists in winning_list to determine if a list has all o's for a win
                elif i ==  'o' and j ==  'o' and k ==  'o' :
                    print('O wins')
                    end()
            #possible moves is 9 in tic tac toe. If all moves are taken and there is no winner no winner forces a draw.
            if move_count == 9:
                print('You Tied')
                end()

        #Takes user input for the move
        move =int(input('Please select a spot: '))
        print(move)

        #Player move, makes sure the spot is not taken and adds 1 to move_count
        if board[move] !='x' and board[move] != 'o':
            board[move] = 'x'
            move_count += 1
            check_winner()
            #npc move, chooses a random spot that is not taken and adds 1 to move_count
            while True:
                npc = random.randint(0,8)
                if board[npc] != 'o' and board[npc] != 'x':
                    board[npc] = 'o'
                    print('Computer chooses spot ', npc)
                    move_count += 1
                    check_winner()
                    break
        #If spot is taken prints that the spot is already taken
        else:
            print('This spot is taken')

        #Game ending
        def end():
            print('Thank you for playing')
            sys.exit()

if __name__ == "__main__":
    main()


texts:
I use this to automate the lights in my home while I am away at night (simulating presence).  The scheduling of when this runs is handled by my home automation software (Indigo Domotics).

I'm open to any/all critique, but am especially interested in whether doing the randomization within the Light object is the right approach (and if the method of randomizing is good/pythonic/efficient).  I'm a self taught programmer as a hobby only and am always trying to refine my thinking around code structure.

#!/usr/bin/python

from datetime import datetime
import random

# (min/max) seconds to delay before light turns on (randomized every time)
start_delay_range = (15, 70)
# (min/max) brightness (0-100, randomized every time)
brightness_range = (50, 85)
# (min/max) duration for light to stay on (randomized every time)
duration_range = (300, 900)

class Light():
    '''
    Define a light object.

    Attributes:
        name (str): Name of the light.
        device_id (int): The Indigo ID of the device.
        dimmable (bool): Set the light as dimmable or not.
    '''
    def __init__(self, name, device_id, dimmable):
        self.name = name
        self.device_id = device_id
        self.dimmable = dimmable

    def brightness(self):
        '''Return random brightness within <brightness_range>.'''
        return random.randint(brightness_range[0], brightness_range[1])

    def duration(self):
        '''Return random duration within <duration_range>.'''
        return random.randint(duration_range[0], duration_range[1])

    def start_delay(self):
        '''Return random delay within <start_delay_range>.'''
        return random.randint(start_delay_range[0], start_delay_range[1])

    def run(self):
        '''Turn on the light to <brightness> after <start_delay> for <duration>.'''
        if self.dimmable:
            # Turn on light
            indigo.dimmer.setBrightness(self.device_id,
                                        value = self.brightness(),
                                        delay = self.start_delay())
        else:
            # Turn on light
            indigo.device.turnOn(self.device_id,
                                 self.start_delay())

        # Turn off light after <delay>
        indigo.device.turnOff(self.device_id,
                              delay = self.duration())

# List of Light() objects to randomize
lights = [
    Light(name='Breakfast Room', device_id=1222428814, dimmable=True),
    Light(name='Kitchen Cabinet', device_id=18462733, dimmable=False),
    Light(name='Hallway', device_id=93680547, dimmable=True),
    Light(name='Living Room Recessed', device_id=7507220, dimmable=True),
    Light(name='Stairs', device_id=1842915774, dimmable=True),
    Light(name='TV Room', device_id=1569858222, dimmable=True)
]

def main():
    for light in lights:
        light.run()

if __name__ == '__main__':
    main()


texts: Project Euler 62: cubic permutations, logic

texts:
Problem 62 of Project Euler goes

  The cube, 41063625 (3453), can be permuted to produce two other cubes: 56623104 (3843) and 66430125 (4053). In fact, 41063625 is the
  smallest cube which has exactly three permutations of its digits which
  are also cube.

  Find the smallest cube for which exactly five permutations of its digits are cube.

Now I have written the following code to handle the problem. In essence I iterate over the cubes, and sort the numbers from highest to lowest. These values I use as keys in a dictionary. When the count reaches the desired amount (5) i break the loop.

Well that is almost correct, or it was my first code. It gave me the correct answer, however someone made the following remark:

  Even if the chain of permutations is 5, it is possible that you will
  find permutations later on that increases the count.

To overcome this silly issue i do the following: if the count is right i add them to a list of possible candidates. Once the number of digits in the current cube is larger than the number of digits in the candidates, i iterate over the candidates. Here i again check the number of cube permutations (it is still stored in the dictionary) and find the smallest one. If none of the candidates are valid, we clear the candidate list and start over.

It seems like quite a convoluted way of doing things.. and I do not like the logic of my try's and exceptions. I also think there is a logic break if the best permutation is the one where we go from $n$ to $n+1$ digits, since then it will be added to the list of permutations, and then removed.

Question: Is there a clearer way to code my reasoning in this problem? Does my code cover the corner / limit cases?

When I look at the code of others solving the same excercise their code looks so tiny and compact in comparison to mine =(

# Sorts a number from highest to lowest
def num2highest(num):
    string = sorted(str(num))
    rev_string = string[::-1]
    return int(''.join(map(str, rev_string )))

def cube_perms(perms, limit):
    checked = dict()
    cube_lst = []
    candidates = []
    len_cand = len(str(limit**3)) + 1

    for i in range(min(10**6, limit)):
        cube = i**3
        low_perm = num2highest(cube) #Sort the cube

        # Add sorted cube as a key in dict
        if checked.has_key(low_perm):
            count, cube_lst = checked[low_perm]
            cube_lst.append(i)
        else:
            count = 0
            low_cube = cube
            cube_lst = [i]
        checked[low_perm] = count+1, cube_lst #Increases the count of one

        # If the count is -1 of the wanted number of perms
        # add it to a list of possible candidates (since the count might increase)
        if count == perms - 1:
            if low_perm not in candidates:
                candidates.append(low_perm)
            len_cand = len(str(cube))

        # If the number of digits of the current cube is greater than the candidates
        # iterate over the possible candidates
        if len(str(cube)) > len_cand and len_cand < (len(str(limit**3)) + 1):
            the_one = choosen(candidates, perms, checked)
            if the_one > 0:
                count, cube_lst = checked[the_one]
                return sorted(cube_lst)
            else:
                candidates = set()
                len_cand = len(str(limit**3)) + 1

# Iterates over the possible candidates, finding the smallest one
def choosen(candidates, perms, checked):
    choosen = 0
    minimal = candidates[0]
    for cand in candidates:
        count, cubes = checked[cand]
        if count == perms:
            temp_minimal = min(cubes)
            if temp_minimal < minimal:
                    minimal = temp_minimal
                    choosen = cand
    return choosen

if __name__ == '__main__':

    print cube_perms(5, 10**6)


texts:
I have the below code that takes the sql data and exports it to xml or csv. The xml is processing at good speed but my csv sometimes takes 1 hour depending on how many data rows it exports. My question is my code effective writing the csv or it can be improved for speed? Has around 40 columns and x rows which can be over 10k.

public static void SqlExtract(this string queryStatement, string xFilePath, string fileName)
        {
            string connectionString = @"Data Source=ipaddress; Initial Catalog=name; User ID=username; Password=password";
            using (SqlConnection _con = new SqlConnection(connectionString))
            {
                using (SqlCommand _cmd = new SqlCommand(queryStatement, _con))
                {
                    using (SqlDataAdapter _dap = new SqlDataAdapter(_cmd))
                    {
                        if (fileName == "item1" || fileName == "item2" || fileName == "item3")
                        {
                            DataSet ds = new DataSet("FItem");
                            _con.Open();
                            _dap.Fill(ds);
                            _con.Close();
                            FileStream fs = new FileStream(xFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
                            StreamWriter writer = new StreamWriter(fs, Encoding.UTF8);
                            ds.WriteXml(writer, XmlWriteMode.IgnoreSchema);
                            fs.Close();
                            StringWriter sw = new StringWriter();
                            ds.WriteXml(sw, XmlWriteMode.IgnoreSchema);
                            string OutputXML = sw.ToString();
                            OutputXML = OutputXML.Replace("Table", "Item");
                            System.IO.File.WriteAllText(xFilePath, OutputXML);
                        }
                        else
                        {
                            DataTable table1 = new DataTable("Table1");
                            _con.Open();
                            _dap.Fill(table1);
                            _con.Close();
                            string exportCSV = string.Empty;
                            foreach (DataRow row in table1.Rows)
                            {
                                int i = 1;
                                foreach (DataColumn column in table1.Columns)
                                {
                                    if (row[1].ToString() == "002" && i > 41 || row[1].ToString() == "END" && i > 4)
                                    {
                                        //do nothing
                                    }
                                    else
                                    {
                                        if (i > 1)
                                        {
                                            exportCSV += ";";
                                        }
                                        exportCSV += row[column.ColumnName].ToString();
                                    }
                                    i++;
                                }
                                exportCSV += "\r\n";
                            }
                            //Write CSV
                            File.WriteAllText(xFilePath, exportCSV.ToString());
                        }
                    }
                }
            }
        }


texts: Generating the sequence of the digits that appear in the sequence of natural numbers

texts:
This is a revisit to a question already asked here about a year and a half ago.

Project Euler's Problem 40 involves generating the sequence of digits that appear in the natural numbers, all concatenated together (123456789101112131415161718192021…).  As part of the solution, I wrote this:

def counting_digits():
    for number in count(1):
        for digit in str(number):
            yield digit

After finishing the solution, I tried this:

def counting_digits():
    return (digit for number in count(1) for digit in str(number))

My questions:

In the face of Python 3, Which solution is more pythonic?
As someone who just wants to understand the code. Which is easier/clearer to read?
If you haven't read the statement for Project Euler's Problem 40, Which version lets you better know what the function does?

Performance is not part of the question: pythonism and understandability is the issue.


texts:
The code below takes an input and based on the input gives out a time, date or both. Please will you review me for this and tell me how I can improve this? By the way, I only started learning python.

import datetime

x = datetime.datetime.now()
s = '/'
c = ':'
print("Welcome to Date and Time!")
input = int(input("Please choose one of these options below and type it in the prompt: \n 1 - To know the date (DD : MM : YY) \n 2 - To know the time (Hours : Minutes : Seconds ) \n 3 - To know both date and time.\n"))

if input == 1 :
    print(str(x.day) + s + str(x.month) + s + str(x.year) )
elif input == 2 :
    print(x.strftime('%H') + c + x.strftime('%M') + c + x.strftime('%S'))
elif input == 3 :
    print(str(x.day) + s + str(x.month) + s + str(x.year) + ' ' + x.strftime('%H') + c + x.strftime('%M') + c + x.strftime('%S'))
else:
    print("You didn't type in 1, 2 or 3!")


texts: Checking whether a word satisfies a template with wildcards

texts:
I'm working one of the recommended tutorials -- actually, the UPenn online course CS194 -- for learning Haskell, and I have a working solution to the final "challenge exercise" for HW 2. But it seems to be a very brute-force way of doing things, so I'm wondering if this is really the idiomatic Haskell way, or if I'm bringing my imperative programming habits in by accident.

The function is supposed to take a template representing a portion of a Scrabble board, and a set of tiles making up the Scrabble "hand", and see if you can legally play a given word within those constraints. The input would be:

A Template - a string containing letters or '?' characters, representing empty spaces
A Hand - a list of characters representing the available letters that can fill in the spaces.
A Word - the string being checked to see if it fits the template.

A word "fits" the template if:

Every letter in the template matches the letter at that position in the word
Every '?' in the template can be replaced by the letter at that position in the word by removing it from the hand
'?' letters at the end of the template can also be "blank", if the template is longer than the word.

e.g.:

wordFitsTemplate "??r?" [’c’,’x’,’e’,’a’,’b’,’c’,’l’] "care" == True
wordFitsTemplate "??r?" [’c’,’x’,’e’,’w’,’b’,’c’,’l’] "care" == False
wordFitsTemplate "??r?" [’c’,’x’,’e’,’a’,’b’,’c’,’l’] "car" == True
wordFitsTemplate "let" [’x’,’x’] "let" == True

This is what I came up with; I feel like there are too many different patterns and guards that I should be able to condense somehow:

type Hand = [Char]
type Template = String

wordFitsTemplate :: Template -> Hand -> String -> Bool
wordFitsTemplate [] _ []            = True
wordFitsTemplate [] _ _             = False
wordFitsTemplate _ [] _             = False
wordFitsTemplate (t:ts) h []
    | t == '?'                      = wordFitsTemplate ts h []
    | otherwise                     = False
wordFitsTemplate ('?':ts) hs (s:ss)
    | s `elem` hs                   = wordFitsTemplate ts (delete s hs) ss
    | otherwise                     = False
wordFitsTemplate (t:ts) hs (s:ss)
    | t == s                        = wordFitsTemplate ts hs ss
    | otherwise                     = False


texts: Pruning unwanted columns from a selected row

texts:
I've got this little module that returns basic user data required for a web app that's extracted from a large number of columns per row. I was asked to replace the small, column specific select statement I'd prepared with a stored procedure that returns the entire row. This moves column pruning into the server.

I've modified my original function to work as expected with the code below, but it feels like I could be doing better with Array.find((e) => {})

sqlRequest.on('row', function(columns) {
  response = {};
  const keys = ['id', 'fn', 'ln', 'ctr'];

  columns.forEach(function (c) {
    let key = String(c.metadata.colName).toLowerCase();
    if (keys.find((e) => { return key === e})) {
      let value = String(c.value).charAt(0).toUpperCase() + String(c.value).slice(1).toLowerCase();
      response[key] = value;
    }
  });
});


texts: Todo List Application Code in Pure JavaScript

texts:
I'd highly appreciate it if you can:

Spot flaws, especially bad practices and suggest a possible alternative method.
Spot inefficiencies and suggest how to perform that task efficiently.
You may review my HTML/CSS as well.

var addRecordFormVisibility = false;
var addRecordForm = document.getElementById('addRecord');
var addRecordFormButton = document.getElementById('submit');
var errors = document.getElementById('errors');
var addRecordFormTrigger = document.getElementById('addRecordFormTrigger');

function prepare() {
    addRecordForm.style.display="none";
}

function triggerAddRecordForm() {
    if(addRecordFormVisibility === false) {
        addRecordForm.style.display="block";
        addRecordFormVisibility = true;
    } else {
        addRecordForm.style.display="none";
        addRecordFormVisibility = false;
    }
}

function submit(event) {
    var userInput = document.getElementById('description').value;

    errors.innerHTML = '';

    if(userInput.length === 0) {
        errors.innerHTML = "Please fill in the form!";
    } else {
        var listItem = document.createElement('li');
        listItem.innerHTML = userInput;

        document.getElementById('todoList').appendChild(listItem);
    }

    event.preventDefault();
}

document.addEventListener("DOMContentLoaded", prepare, false);
addRecordFormButton.addEventListener("click", submit, false);
addRecordFormTrigger.addEventListener("click", triggerAddRecordForm, false);
#todoApplication {
    width: 800px;
    height: 100%;
    margin: 0 auto;
    background: #EEEEEE;
    border: 1px solid #DDDDDD;
    border-radius: 5px;
    padding: 10px;
}
#errors {
    color: red;
}
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>JavaScript</title>
        <link rel="stylesheet" href="src/style.css">

            <button id="addRecordFormTrigger">Trigger Add Record Form</button>

            <form id="addRecord" method="POST">
                <input id="description" type="text" name="description" placeholder="Enter the task here">

                <button id="submit">Submit</button>
            </form>


texts: My own method for sorting numbers in array

texts:
I've written some method for sorting asc and desc numbers in array. All I want to know is this good logic, and is there a space for improving this code?

-(NSArray *)sortHanded:(NSArray *)inputArray ascending:(BOOL)ascending {
    NSMutableArray *inputMutableArray = [inputArray mutableCopy];
    NSMutableArray *sortedArray = [NSMutableArray new];
    NSNumber *min;
    NSNumber *max;
    if (ascending == YES) {

        //starting while
        while (inputMutableArray.count > 0) {

            //starting switch
            switch (inputMutableArray.count) {

                    //case 0
                case 0:

                    break;

                    //case 1
                case 1:
                    [sortedArray addObject:[inputMutableArray objectAtIndex:0]];
                    [inputMutableArray removeObject:[inputMutableArray objectAtIndex:0]];
                    break;

                    //starting default switch
                default:
                    for (NSNumber *temp in inputMutableArray) {
                        if (min == nil) {
                            min = temp;
                        }

                        if (min > temp) {
                            min = temp;
                        }

                    }

                    [sortedArray addObject:min];
                    [inputMutableArray removeObject:min];
                    min = nil;
                    break;
                    //end default
                    //end start switch
            }

            //ending while
        }

    }
    else {
        //starting while
        while (inputMutableArray.count > 0) {

            //starting switch
            switch (inputMutableArray.count) {

                    //case 0
                case 0:

                    break;

                    //case 1
                case 1:
                    [sortedArray addObject:[inputMutableArray objectAtIndex:0]];
                    [inputMutableArray removeObject:[inputMutableArray objectAtIndex:0]];
                    break;

                    //starting default switch
                default:
                    for (NSNumber *temp in inputMutableArray) {
                        if (max == nil) {
                            max = temp;
                        }

                        if (max < temp) {
                            max = temp;
                        }

                    }

                    [sortedArray addObject:max];
                    [inputMutableArray removeObject:max];
                    max = nil;
                    break;
                    //end default
                    //end start switch
            }

            //ending while
        }

    }
        //returning sorted array
    return sortedArray;
}


texts:
I just want to make sure that my Rolling (Moving) Average class is understandable and reasonably thread safe.
My main questions are:

Is having totalCounts as a long just for a potential edge case overkill?

Is checking to see if the number of observed counts is 1 (and thus, just return the observed total), also edge case overkill?

Is there any way to minimize the locking in Add Method? (It's not a bottle neck or anything, but I'm just wondering if I might be locking that part more than needed)

--
public sealed class RollingAverage
{
    public RollingAverage()
        : this(defaultMaxRememberedNumbers)
    {
        //
    }

    public RollingAverage(int maxRememberedNumbers)
    {
        if (maxRememberedNumbers <= 0)
        {
            throw new ArgumentException("maxRememberedNumbersmust be greater than 0.", "maxRememberedNumbers");
        }

        this.counts = new Queue<int>(maxRememberedNumbers);
        this.maxSize = maxRememberedNumbers;
        this.currentTotal = 0L;
        this.padLock = new Object();
    }

    private const int defaultMaxRememberedNumbers = 10;

    private readonly Queue<int> counts;
    private readonly int maxSize;

    private long currentTotal;

    private object padLock;

    public void Add(int value)
    {
        lock (this.padLock)
        {
            if (this.counts.Count == this.maxSize)
            {
                this.currentTotal -= (long)this.counts.Dequeue();
            }

            this.counts.Enqueue(value);

            this.currentTotal += (long)this.value;
        }
    }

    public int CurrentAverage
    {
        get
        {
            long lenCounts;
            long observedTotal;

            lock (this.padLock)
            {
                lenCounts = (long)this.counts.Count;
                observedTotal = this.currentTotal;
            }

            if (lenCounts == 0)
            {
                throw new InvalidOperationException("No counts to average.");
            }
            else if (lenCounts == 1)
            {
                return (int)observedTotal;
            }
            else
            {
                return (int)(observedTotal / lenCounts);
            }
        }
    }

    public void Clear()
    {
        lock (this.padLock)
        {
            this.currentTotal = 0L;
            this.counts.Clear();
        }
    }
}

-Edit-
Fixed inconsistent use of "this.".


texts: Two classes to avoid confusion when handling degrees and radians

texts:
Experimenting with operator overloading for the first time. Based on my reading, it appears to be a bit of a minefield.

Have I fallen into any traps?

namespace Units
{
    class Degree; // Forward declare Degree so it can be passed by reference into Radian.

    /// \class Radian
    /// Encapsulates a double, and used to represent a radian.
    class Radian
    {

    public:
        /// Constructor.
        /// \param radian The  angle (radians).
        Radian(double radian) : angle_(radian) {}

        /// Constructor.
        /// \param degree The  angle (degrees).
        Radian(const Degree& degree);

        /// Function Call Operator.
        /// \return <double> The angle value (radians).
        operator double() const { return angle_; }

    private:
        double angle_;

    };

    /// \class Degree
    /// Encapsulates a degree, and used to represent a degree.
    class Degree
    {
    public:
        /// Constructor.
        /// \param degree The angle value (degrees).
        Degree(double degree) : angle_(degree) {}

        /// Constructor.
        /// \param radian The  angle (radians).
        Degree(const Radian& radian);

        /// Function Call Operator.
        /// \return <double> The angle (degrees).
        operator double() const { return angle_; }

    private:
        double angle_;
    };

    /// Constructor.
    /// Constructor defined outside of class declaration, to allow Degree class to be defined before it.
    /// \param degree The  angle (degrees).
    Radian::Radian(const Degree& degree)
    : angle_(degree * SoC::Maths::Trigonometry::DegToRad)
    {}

    /// Constructor.
    /// Constructor defined outside of class declaration, to allow Radian class to be defined before it.
    /// \param radian The  angle (radians).
    Degree::Degree(const Radian& radian)
    : angle_(radian * SoC::Maths::Trigonometry::RadToDeg)
    {}

} // namespace Units

#endif // UNITS_H

EDIT

and initialised in the way:

const Units::Degree latitude = 48.8566;


texts:
I have the following code where I need to return an array of objects as a response that has values from the server. The objects are filled with the right values, but when they are pushed into the array they are pushed before. What's the best way of rewriting this asynchronously?

  router.post('/teacher-schedule',function(req,res){
var teacher_id= req.body.teacher_id,
    school_id= req.body.schoolId,
    array = [], tempo = {};

Schedule.find({school_id:school_id}).then(function(schedules){
    schedules.forEach(function(element){
        ClassSection.findOne({_id:element.class_section_id},function(err,cla){
            if(err){
                console.log(err);
                return res.json({status:"error", message:"error occurred"})
            }else{
                element.entry.forEach(function(entries){
                    if( entries.teacher_id==teacher_id){
                        tempo = {};
                        console.log("tempo fade"+ tempo)
                        tempo.class_section = cla.class_title;
                        tempo.class_section_code = cla.code;
                        tempo.schedule_id =schedules._id ;
                        tempo.class_section_id = element._id;
                        tempo.subject_id = entries.subject_id;
                        console.log("tempo gabel el subject"+ tempo)
                        Subject.findOne({_id:entries.subject_id},function(err,subject){
                            if(err){
                                console.log(err);
                                return res.json({status:"error", message:"error occurred"})
                            }else{
                                tempo.subject_title = subject.title;
                            }
                        })

                        array.push(tempo);// its always an empty value
                    }

                })
            }
        })

    });
    res.json({status:"success",message:"successfully returned", records: array})
}).catch(function(err){
    console.log(err);
    res.json({status:"error", message:"error occurred"});
})
});


texts: Current user as a class-level property in Objective-C and Swift

texts:
I was recently tasked with architecting a user/profile object in Objective-C and wanted the ability to access a static instance from the class level, similar in style to the way Parse manages their current user (a static variable on a class, not a singleton).  With Parse, I can call a class method to return the current user object if a user is logged in, or nil if there is no current user session with [PFUser currentUser].

I architected my class like so:

User.h

@interface User : NSObject

/// Returns the current user if logged in, or nil if logged out
+ (User *)currentUser;

/// Sets the current user, call this on login
+ (void)setCurrentUser:(NSDictionary *)userInfo;

/// Removes the current user, call this on logout
+ (void)removeCurrentUser;

// Getters

/// Returns the user's name if logged in, nil if logged out
@property (nonatomic, readonly, strong) NSString *name;

@end

User.m

@interface User ()

@property (nonatomic, readwrite, strong) NSString *name;
@property (nonatomic, strong) NSString *address;

@end

@implementation User

#pragma mark - Static Variables

static User *currentUser;

#pragma mark - Static Object Setters and Getters

+ (User *)currentUser
{
    return currentUser;
}

+ (void)setCurrentUser:(NSDictionary *)userInfo
{
    currentUser = [[User alloc] initWithDictionary:userInfo];
}

+ (void)removeCurrentUser
{
    currentUser = nil;
}

#pragma init

- (instancetype)initWithDictionary:(NSDictionary *)userInfo
{
    self = [super init];

    if (self) {
        NSString *name = userInfo[@"name"];
        NSString *address = userInfo[@"address"];

        if (!name || !address ) { return nil; }

        _name = name;
        _address = address;
    }

    return self;
}

@end

This works well.  I have a single static User instance which can be non-nil if a user is logged in, and nil if the user is logged out.  I can access this object from anywhere with [User currentUser] without a singleton.

Now as an additional challenge I'm trying to translate this type of pattern into Swift.  Here is my fist pass:

public class User {

    // Private Properties
    private var name: String?
    private var address: String?

    // Private instance of User
    private static var user: User?

    // Class Functions

    public class func currentUser() -> User? {
        return self.user
    }

    public class func setCurrentUser(userInfo: [String : AnyObject]) {
        self.user = User(dictionary: userInfo)
    }

    public class func removeCurrentUser() {
        self.user = nil
    }

    // Instance methods

    public func getName() -> String? {
        return self.name
    }

    // Private

    private convenience init?(dictionary: [String : AnyObject]) {
        self.init()

        guard let name = dictionary["name"] as? String else { return nil }
        guard let address = dictionary["address"] as? String else { return nil }

        self.name = name
        self.address = address
    }
}

This works but doesn't feel "Swifty" enough.

Questions:

Is there a way to expose a public getter on a private property (sort of like a property redeclaration through a class extension in Objective-C)?  Or do I need to write an additional accessor.

Does declaring my private User object as private static ensure that it can only be accessed on the class level and not on the instance level?  Is this variable really static like it would be in C or Objective-C?

Can a User setter and getter be added/modified to remove the need for setCurrentUser and removeCurrentUser?

I am open to optimizations in both my Swift and Objective-C code.


texts: Displaying sorted results of a web crawl

texts:
The issue I have with this class is that most of the methods are almost the same. I would like for this code to be more pythonic.

Note: I plan on replacing all the for loop constructs with list comprehensions.

class Sorter(BaseCrawler):

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

    def by_size(self, *options):
        '''
        Sort files by size
        '''
        file_list = []
        for fn in self.files(*options):
            file_list.append((fn, float(os.path.getsize(fn))))
        file_list.sort(key=lambda fn: fn[1])
        return file_list

    def by_mtime(self, *options):
        '''
        Sort files by modified time.
        '''
        file_list = []
        for fn in self.files(*options):
            file_list.append((fn, os.path.getmtime(fn)))
        file_list.sort(key=lambda fn: fn[1])
        return file_list

    def by_ctime(self, *options):
        '''
        Sort files by creation time.
        '''
        file_list = []
        for fn in self.files(*options):
            file_list.append((fn, os.path.getctime(fn)))
        file_list.sort(key=lambda fn: fn[1])
        return file_list

    def by_atime(self, *options):
        '''
        Sort files by access time.
        '''
        file_list = []
        for fn in self.files(*options):
            file_list.append((fn, os.path.getatime(fn)))
        file_list.sort(key=lambda fn: fn[1])
        return file_list

    def last_modified(self):
        '''
        Return the last modified file.
        '''
        return self.by_mtime()[0]

    def last_accessed(self):
        '''
        Return the last accessed file.
        '''
        return self.by_atime()[0]

    def last_created(self):
        '''
        Return the last created file.
        '''
        return self.by_ctime()[0]

    def average_fsize(self):
        '''
        Return the average file size.
        '''
        sizes = []
        for name, size in c.by_size():
            sizes.append(size)
        return sum(sizes) / len(sizes)

    def above_avg_size(self, times):
        '''
        Yield files that have an above average file size.
        '''
        avg = self.average_fsize()
        for f, s in c.by_size():
            if s > avg * times:
                yield f, s


texts:
I have created a BeautifulSoup vacancies parser, which works, but I do not like how it looks. Therefore, I'd be very happy if somebody could give me any improvements.

from urllib.request import urlopen
from bs4 import BeautifulSoup

page = urlopen('http://rabota.ua/zapros/python/%D0%BA%D0%B8%D0%B5%D0%B2')
soup = BeautifulSoup(page, "lxml")
vacancies = {}

a = soup.find_all("a", class_="t")
inx = 0
for x in a:
    inx += 1
    vacancies[inx] = {'position': x.contents[0].strip(),
                      'link': 'http://rabota.ua{}'.format(x.get('href'))}

a = soup.find_all("a", class_="rua-p-c-default")[2:]
inx = 0
for x in a:
    inx += 1
    vacancies[inx].update({'company': x.get_text()})

for x in vacancies:
    print('{}\n{}\n{}\n'.format(vacancies[x]['company'], vacancies[x]['position'], vacancies[x]['link']))

Here is the HTML code:


texts:
I'm trying to make a reusable data layer that is mostly generated from a database via T4 templates. On top of this data layer, I'd like to have WebAPI endpoints for each repository, with most of the basic CRUD operations generated/from a base class. The generics are somewhat getting out of hand, and I don't know if I'm trying to build too much of a swiss army knife here.

Starting at the bottom, I have an entity class (some bits truncated):

public class Entity<T>
{
    public T Id { get; set; }
}

A T4 template runs a SQL statement to pull out database schema, and spits out a file with a bunch of classes along the lines of:

public partial class Visit : Entity<int>
{
   //Fields on the table
}

Generated along side these entity classes are corresponding repositories, all implementing this interface:

public interface IRepository<TEntity, in TKey> where TEntity: Entity<TKey>
{
    Task<IList<TEntity>> GetAll();
    // Other Methods
}

These get filled out with proper SQL statements for the action. Specific repositories can have additional methods as needed.

This bit I'm happy with, it's easy to understand, and the code generators for it aren't complicated. Where it starts getting complicated is when I move up into the WebAPI Controllers.

All data access is handled from a Unit of Work, which handles connection and transaction lifetimes. Currently, there are individual properties for each repository, and this is done via a T4 template:

public partial class RulesWorkUnit : ITransactionWorkUnit
{
    private readonly Lazy<VisitRepository> _Visit;
    public RulesWorkUnit(DbConnectionFactory connectionFactory)
    {
        _Visit = new Lazy<VisitRepository>(() => new VisitRepository(_conn, _tran));
    }

    public VisitRepository Visit { get { return _Visit.Value; } }
}

This part I also like, and is what I've been doing for a bit for data access, and works well for the cases where I'm coding by hand.

Now, here's where it starts going off of the rails a bit. I have a base API Controller class. This needs to know which repository to create, so that goes in as a generic parameter. This parameter needs to go down to the Work Unit so it knows which repository to return, that results in this code added to the work unit:

//Member variable
private Dictionary<Type, Func<dynamic>> _repositoryTypes;

//Added to constructor
_repositoryTypes[typeof(VisitRepository)] = () => new VisitRepository(_conn, _tran);

//New Method
public TRepository GetRepository<TRepository, TEntity, TKey>()
        where TRepository : class, IRepository<TEntity, TKey>
        where TEntity : Entity<TKey>
    {
        return _repositoryTypes[typeof (TRepository)] as TRepository;
    }

This is where the generic definitions start exploding. The base API controller is one worse, since it also needs to know the model to map to:

public abstract class RepositoryApiController<TRepository, TModel, TEntity, TKey> : ApiController
    where TRepository : class, IRepository<TEntity, TKey>
    where TEntity : Entity<TKey>

Which starts setting off my code smell alarms. I would like somehow to manage the boilerplate code for most of the basic API methods (they'll all have a Get All, Get By Id, Post, Put, Delete that have the same code, with the exception of the entity type and the return model type).

Is there a better way of designing this?