texts: Tokenizing and sorting the strings of a text file with the results of a public competition

texts:
I made this script to carry out a specific real-life task, which was to sort a list of candidates in a public competition by grade. The file with the informations consists of a text file copied from part of a pdf with  the ID, name, grade in the exam and grade in the composition. There are a little more than 1,000 candidates. I needed it sorted by the final grade, which is obtained by the formula:

  Final grade = Exam + (Composition * 2)/3

This file had some singularities:

1) The information about each candidate was separated by '/' and not by new lines. And each information about the candidate (ID, name, exam note, composition note) was separated by ','

2) new line characters were spread randomly throughout the text (I think that  was caused by the Notepad or by the PDF program auto-break line)

3) The page numbers of the original PDF remained in the text file, and could be found beside the ID number, one of the grades or between parts of a name, surrounded by new line characters like "\n26\n". The page numbers ranged from 15 to 26.

This is a fragment of the original text as read by Python:

  \xa0 9.00,\xa0
  8.41\xa0/\xa0\n26\n10069207,\xa0Wilix\xa0Gabriel\xa0Pastor\xa0Silva,\xa08.19,\xa06.35\xa0/\xa010095535,\xa0Willes\xa0Vitorio\xa0do\xa0Carmo,\xa08.25,\xa08.83\xa0/\xa010000327,\xa0\nWilliam\xa0Maia\

(You may note that there's a page number between the last grade of one of the candidates and the ID number of the next one right in the beginning of the fragment)

So I had to find a way of detecting and removing the new line characters and the page numbers, and put each part of the string in the correct place taking into account that the names of the candidates could be of any size (Like "Anderson Soares Freixo" or "Maria Auxiliadora da Silva Santos Xavier".

I came up with this code:

from operator import itemgetter

def remove_page_number(origin_list):
    """Finds if there is a page number with 2
       digits anywhere inside the strings of a given list
       and removes it"""
    new_list = []
    for element in origin_list:
        subelements = element.split()
        no_page = ''
        for el in subelements:
            if el.isdigit():
                if len(el) > 2:
                    no_page+=el
            else:
                no_page+=el+' '
        new_list.append(no_page)
    return new_list

def get_final_grade(exam, composition):
    return round((exam+(composition*2))/3, 2)

def categorize(raw):
    """Gets the raw material and put each piece
       of information in the right category"""
    adjusted = []
    for cand in raw:
        items = remove_page_number(cand.split(','))
        candidate = {'ID': items[0],
                 'Name': items[1],
                 'Exam':float(items[2]),
                 'Composition': float(items[3]),
                 'Final': get_final_grade(float(items[2]), float(items[3]))
                }
        adjusted.append(candidate)
    return adjusted

def print_list(candidates):
    """Prints the list of candidates"""
    rank = 0
    for c in candidates:
        rank+=1
        print("{:4}|{:10}|{:50}|{:4}|{:4}|{:4}|".format(rank, c['ID'],
                                                        c['Name'],
                                                        c['Exam'],
                                                        c['Composition'],
                                                        c['Final']))

if __name__ == '__main__':
    with open('aprovados.txt', 'r') as result:
        text = result.read()

    raw_candidates = [raw_candidate.replace('\n', ' ') for raw_candidate in text.split('/')]
    candidates = categorize(raw_candidates)
    candidates.sort(key = itemgetter('Final') , reverse = True)
    print_list(candidates)

The code works, but I'd like to know if it could be improved (is there a clever and cleaner way of doing it?) and if the style is good.

Thanks.

(Here is a link to the original PDF file: http://www.cespe.unb.br/concursos/TRE_BA_17/arquivos/TRE_BA_2017_ED._6_RES.PDF)


texts:
I'm working on a personal project (Flask CRUD app) and I am currently building the user service. I am trying to use as less as libraries as possible (that's why I do not use WTF-forms for example, just for learning purposes). I am really not sure about a couple of things.
I am aware that form validation should be handled in both front and back-end (or at the very least on the back-end). In order to validate a new user, I am (currently) checking 3 things:
1) email does not already exist on the db (can only be verified on the back-end)
2) password is strong enough (can be done in both front and back end)
3) password and password_confirm matches (can be done in both front and back end)
My goal is to display a small error message on the registration page if either at least one those errors appears. Currently, I am checking option 1, 2 and 3 and the back-end but only return True if the registration is valid otherwise, False.
Since case 1 and 2 can directly be handle also on the front-end, can I display the error message using JavaScript and not from the back-end? I am still confused on what would be the best return for validate_registration (currently a Boolean).
Also, I am not quite sure my code is over-engineered, I made a RegistrationForm class just to validate a registration form. I did that because I am able to pick validations methods from my validators.py which may be used in other Classes as well.
So this is what I did so for for the registration form:
user/blueprints/routes.py
@user.route('/new-user',methods = ['POST'])
def register_user():
    form_email = request.form.get('email')
    form_password = request.form.get('psw')
    form_password_repeat = request.form.get('psw-repeat')
    registration_form = RegistrationForm(form_email, form_password, form_password_repeat).validate_registration()

    if registration_form:
        new_user = UserService().register_user(form_email, form_password)
        user_repository = UserRepository(conn, 'users')
        user_repository.add_user(new_user)
        user_repository.save()
        return "ok" #will probably change return statements later on
    return "not ok" #will probably change return statements later on

user/blueprints/forms.py
from prepsmarter.blueprints.user.validators import email_already_in_use, password_matching

class RegistrationForm():
    def __init__(self, email, pwd_1, pwd_2):
        self.email = email
        self.pwd_1 = pwd_1
        self.pwd_2 = pwd_2

    def validate_registration(self):
        is_valid = email_already_in_use(self.email) and is_strong_password(self.pwd_1) and password_matching(self.pwd_1, self.pwd_2)
        return is_valid

class LoginForm():
 # to do

user/blueprints/validators.py
import re
from email_validator import validate_email, EmailNotValidError
from prepsmarter.extensions import conn

def is_strong_password(password):
    length_error = len(password) < 8
    digit_error = re.search(r"\d", password) is None
    uppercase_error = re.search(r"[A-Z]", password) is None
    return length_error and digit_error and uppercase_error

def is_email_formated_correctly(email):
    is_correct = True
    try:
        validate_email(email)
    except EmailNotValidError:
        is_correct = False
    return is_correct

def password_matching(pwd_1, pwd_2):
    return pwd_1 == pwd_2

def email_already_in_use(email):
    sql = "SELECT CASE WHEN EXISTS ( SELECT * FROM users WHERE email = (%s)) THEN 1 ELSE 0 END;"
    cursor = conn.cursor()
    cursor.execute(sql, (email))
    res = cursor.fetchall()
    return res == 1


texts: Singleton Design Pattern Implementation: Bill Pugh

texts:
I have been trying to implement the Bill Pugh Singleton Design Pattern using a private static class to return the singleton retrofit instance. So far I have been able to come up with the following code. Can someone help me review this code and confirm if this is a proper implementation of the singleton design pattern suggested by Mr. Bill Pugh himself, or suggest a proper way of implementing this?

public class SingletonRetrofit {

    private SingletonRetrofit(){}

    private static class SingletonRetrofitHelper
    {   private static OkHttpClient okHttpClient;
        private static Retrofit retrofit;

        private static Retrofit makeRetrofit()
        {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(interceptor)
                    .readTimeout(20, TimeUnit.SECONDS)
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .build();

            retrofit = new Retrofit.Builder()
                    .baseUrl("http://ci.draftserver.com/hornsbyapp/webservice/")
                    .client(okHttpClient)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            return retrofit;

        }

    public static Retrofit getInstance()
    {
        return SingletonRetrofitHelper.makeRetrofit();
    }

}


texts:
I get the coprime numbers less than n with the following algorithm:

int n = 15600000;
int j = n - 1;

while (j > 1)
{
   if (GCD(n, j) == 1)
   Console.WriteLine(j);

   j--;
}

My GCD method, which calculates the greatest common divisor of two numbers, looks like this:

static int GCD(int A, int B)
{
   if (B != 0)
       return GCD(B, A % B);
   else
       return A;
}

This algorithm need approximately 103119 milliseconds on my pc. I am interested in a better (faster and little code) solution to this problem.


texts: Very simple implementation of observer pattern in C++

texts:
I'm reading on design patterns for a software engineering class. I am doing small implementations of some I find the most interesting / applicable to better understand them.

I'd like a code review on my design, more particularly on the degree of coupling between my Observer and Publisher classes. I feel that the add_observer() function may be coupled too strongly with the Observer object and that there may be a way to do this with looser coupling.

Observer.h

#ifndef OBSERVER_H_INCLUDED
#define OBSERVER_H_INCLUDED

#include <string>

class Publisher;

class Observer {
public:
    virtual void eventOnProperty(Publisher* source,
         std::string event_name, std::string value) = 0;
};

#endif

Publisher.h

#ifndef PUBLISHER_H_INCLUDED
#define PUBLISHER_H_INCLUDED

#include "Observer.h"
#include <list>
#include <string>

class Publisher {
public:
    void notify_observers(std::string, std::string);
    void add_observer(Observer*);
protected:
    std::list<Observer*> my_observers;
};

#endif

Publisher.cpp

#include "Publisher.h"
#include "Observer.h"
#include <string>
#include <list>

void Publisher::notify_observers(std::string event_name, std::string value) {
    std::list<Observer*>::iterator it;
    for(it = my_observers.begin(); it != my_observers.end(); it++) {
        (*it)->eventOnProperty(this, event_name, value);
    }
}

void Publisher::add_observer(Observer* obs) {
    my_observers.push_back(obs);
}


texts: How to make this code follow Solid Principle C#

texts:
Currently I have this code:
private async Task<(List<SomeModel> data1, List<string> data2)>
                    ProcessFileAsync(IEnumerable<FileInfo> filesInDirectory)
{
    var data1 = new List<SomeModel>();
    var data2 = new List<string>();

    var inDirectory = filesInDirectory as FileInfo[] ?? filesInDirectory.ToArray();
    for (var lIndex = 0; lIndex < inDirectory.Count(); lIndex++)
    {
        var content = await File.ReadAllTextAsync(inDirectory.ElementAt(lIndex).FullName);

        var name = Path.GetFileNameWithoutExtension(inDirectory.ElementAt(lIndex).Name);

        var data1Task = GetData1Async(content, name);
        var data2Task = GetData2Async(content);

        await Task.WhenAll(data1Task, data2Task);

        data1.AddRange(data1Task.Result);
        data2.AddRange(data2Task.Result);
    }

    return (data1, data2);
}

The calling code:
private async Task<(List<SomeModel> data1, List<string> data2)> BatchProcessFilesAsync()
{
    var batchSize = 4;

    var models
        = await GetDataFromSomewhereAsync().ConfigureAwait(false);
    var listOfRequests = new List<Task<(List<SomeModel> data1, List<string> data2)>>();

    var fileModels = models.ToList();
    for (var skip = 0; skip <= fileModels.Count(); skip += batchSize)
    {
        var files = fileModels.Skip(skip).Take(batchSize);
        listOfRequests.Add(ProcessFileAsync(files));
    }

    // This will run all the calls in parallel to gain some performance
    var allFinishedTasks = await
    Task.WhenAll(listOfRequests).ConfigureAwait(false);

The problem I am facing is if I need to add data3 in future, i have to add code here again. Is there a way to make this code Solid.


texts: Checking if a number is a power of 2 without loops

texts:
I made a short program which checks if a number is a power of 2 without using any loops.
The idea: A number which is a power of 2 must have only one bit "1" ( ex: 8= 1000, 4=100 and so on).
Suppose we have a power of 2:nr = 10...000 (in binary), if we subtract 1 we will get something like this:nr-1= 01...111. Now, if we do nr&(nr-1) we should always get 0 if the nr is a power of 2 and some random number if it isn't. What other solutions are there for this problem?

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

int main()
{
    int nr;
    scanf("%d",&nr);
    if((nr&(nr-1))==0)
    {
        printf("\n%d is a power of 2",nr);
    }
    else
    {
         printf("\n%d is not a power of 2",nr);
    }
    return 0;
}


texts:
I have this custom function to show the combinations:

x<-function(a,b){

  ncol(combn(a,b))

}

combinations<-numeric()

for(i in 0:12){
    combinations<-c(combinations,x(12,i))
}

combinations

It works, but I want to know if it's possible to do something simpler, like this:

x<-function(a,b){

  ncol(combn(a,b))

}

x(12,0:12)


texts: PHP : Custom trim function instead existing ltrim() or rtrim()

texts:
I needed to create a custom trim() function instead of using existing ltrim or rtrim due to below problems.

Here are problem with existing functions.

$string = '

This

';

var_dump(ltrim($string, '
'));

// Output :: string(21) "ul>
This

"

Fiddle.

As you can see ltrim trimming < brace because
 not found I think (Not sure 100%).

Here created function,

function trimString($string, $replaceWith = ' ', $type = 'ltrim')
{
    $type = (!empty($type) && in_array($type, ['ltrim', 'rtrim'])) ? $type : 'ltrim';
    if (!empty($string) && !empty($replaceWith)) {
        // Like ltrim
        if ($type == 'ltrim') {
            if (strpos($string, $replaceWith) === 0) {
                $string = substr_replace($string, '', 0, strlen($replaceWith));
            }
        } elseif ($type == 'rtrim') {
            // Like rtrim
            $reverceString    = strrev($string);
            $replaceWithCount = strlen($replaceWith);
            $count            = 1;
            for ($i = 0; $i < strlen($string); $i++){
                if ($count <= $replaceWithCount) {
                    $newString .= $reverceString[$i];
                }
                $count++;

                if ($count == $replaceWith) {
                    break;
                }
            }
            if (!empty($newString)) {
                if (strrev($newString) == $replaceWith) {
                    $string = strrev(strReplaceFirst($reverceString, strrev($replaceWith), ''));
                }
            }
        }
    }

    return $string;
}

function strReplaceFirst($content, $from, $to)
{
    if (!empty($content) && !empty($from)) {
        $from = '/'.preg_quote($from, '/').'/';

        return preg_replace($from, $to, $content, 1);
    }

    return $content;
}

Fiddle.

So, it is working properly for me! But I still don't know if it's the proper way to do that or not? Or it's side effect and time consumption.


texts:
Looking for optimization, smart tips and verification of complexity:  O (log (base 2) power).

NOTE: System.out.println("Expected 16, Actual: " + Power.pow(2, 7)); is a typo. It correctly returns 128.

/**
 * Find power of a number.
 *
 * Complexity: O (log (base 2) power)
 */
public final class Power {

    private Power() { }

    /**
     * Finds the power of the input number.
     * @param x     the number whose power needs to be found
     * @param pow   the power
     * @return      the value of the number raised to the power.
     */
    public static double pow(double x, int pow) {
        if (x == 0) return 1;
        return pow > 0 ? getPositivePower(x, pow) : 1 / getPositivePower(x,  -pow);
    }

    private static double getPositivePower(double x, int pow) {
            assert x != 0;
        if (pow == 0) return 1;

        int currentPow = 1;
        double value = x;
        while (currentPow <= pow/2) {
            value = value * value;
            currentPow = currentPow * 2;
        }

        return value * getPositivePower(x, pow - currentPow);
    }

    public static void main(String[] args) {
        System.out.println("Expected 6.25, Actual: " + Power.pow(2.5, 2));
        System.out.println("Expected 16, Actual: " + Power.pow(2, 7));
        System.out.println("Expected 0.25, Actual: " + Power.pow(2, -2));
        System.out.println("Expected -27, Actual: " + Power.pow(-3, 3));
    }
}


texts: Simpler state manament alternative to Redux, MobX, Context API, etc

texts:
I got frustrated with the jargon and created an alternative state management solution. Its up at https://github.com/smakazmi/react-soliit. It goes something like this

import React from "react";

export default class StateStore<T>  {
  private listeners: Array<Function>;
  constructor(public state: T) {
    this.listeners = new Array<() => void>();
  }

  private fireOnSetState() {
    this.listeners.forEach(l => {
      try {
        l();
      }
      catch { }
    })
  }

  protected setState(newState: Partial<T>) {
    this.state = { ...this.state, ...newState };
    this.fireOnSetState();
  }
  subscribe(callback: () => void) {
    if (this.listeners.indexOf(callback) < 0)
      this.listeners.push(callback);
  }
  unsubscribe(callback: () => void) {
    this.listeners = this.listeners.filter(l => l !== callback);
  }
}

export const withStores = function (WrappedComponent: any, stores: { [index: string]: StateStore<{}> }) {
  return class extends React.Component {
    updateState = () => {
      this.forceUpdate();
    }
    componentDidMount() {
      Object.keys(stores).forEach(k => {
        stores[k].subscribe(this.updateState);
      });
    }
    componentWillUnmount() {
      Object.keys(stores).forEach(k => {
        stores[k].unsubscribe(this.updateState);
      });
    }
    render() {
      return (<WrappedComponent {...this.props} {...stores} />);
    }
  }
}

Can be used as follows

const counterStore = new StateStore({ count: 0 });

const Counter = function({ counterStore }) {
  const increment = () =>
    counterStore.setState({ count: counterStore.state.count + 1 });
  const decrement = () =>
    counterStore.setState({ count: counterStore.state.count - 1 });
  return (

      <button onClick={decrement}>-</button>
      {counterStore.state.count}
      <button onClick={increment}>+</button>

  );
};
const ConnectedCounter = withStores(Counter, { counterStore });
render(<ConnectedCounter />, document.getElementById("root"));

The sample is available at https://stackblitz.com/edit/soliit-simple-counter

Seems to work fine, at the same time seems too good to be true. So looking for reasons to why to go for Redux, MobX or even Unstated and not something as simple as this.


texts: Passing private variable in JavaScript nested class?

texts:
I am thinking about passing a private variable of one class into another class, for some belonging case like 'company --> department --> employee'. As an employee can tell some information of his company, there's some private variables I'd like to pass.

I think this relationship is not as same as common class and supClass.  As an employee is not a type of department and a department is not a type of company (if I am wrong, please tell me more).

So in a case like this, is it a good idea to use nested constructor functions?

For example: http://jsfiddle.net/JsJJ9/

function TeamClass(name){

    var pass = "privateVariable"
    var slot = 1;
    this.members = []; // I have a list of members
    this.name = name;

    this.add = function(){ //add member into this team
        var m = new MemberClass(slot++);
        this.members.push(m)
    }

    function MemberClass(id){ //here comes the Nested class

        var id = id;
        this.report = function(){
            alert('#'+id+' : Hello, i got some '+pass+'! ')
            //So, this member can tell some private data of his team.
        }

    }

}

class01 = new TeamClass('Team A');
class01.add();
class01.add();

class01.members[0].report();
class01.members[1].report();

Also, I have tried to let the nested class can call the upper level's public variable.  I have a function like this:

//at upper level class
    m.setBelonging(this)

and

//at belonging class
    var team = ''
    this.setBelonging = function(theOdj){
        team = theOdj;
    }

(or see it at http://jsfiddle.net/JsJJ9/1/)

Any comment about this approach?

Added at 2014-01-11 :

Actually,  I am trying to ask how can I pass some variable that can't change outside the class (which in my understand, a private variable) to another class. And i found out may be i can do this by nested class. But I don't know is there any defects or there's some better approach.


texts: Function to build a string based on the recursion depth

texts:
I was doing a JavaScript challenge to test myself and I succeeded in finding a solution but the code is very ugly.  I was hoping to get some opinions on what a better solution would look like.

The problem is this.  We need to write, in Javascript, a function with signature

f(input)

that when called in the following ways give the following outputs

f("a") => "fa"
f()("a") => "foa"
f()()("a") => "fooa"

and so on, with the number of 'o''s being equal to the number of empty parentheses.

Here is my solution

function f(input) {
  function inner(otherInput){
    if(typeof otherInput === 'undefined')
        if(typeof input === 'undefined')
            return f({acc:'foo'});
        else
            return f({acc:input.acc + 'o'});

    if(typeof input !== 'undefined')
        return input.acc + otherInput;
    else
        return 'fo' + otherInput;
  };
  if(typeof input === 'string')
    return "f" + input;
  return inner;
}

How can this be improved?


texts: Code behaviour: Working object orientated with a database

texts:
I'm working on my own PHP framework for a long while now.
Right now I'm in a refactoring process.

I'm came up with the question what a programmer would excpect what happens when he see following code:

// working object orientated with a database.

$UserGroup = new UserGroupModel();
$UserGroup->Title = 'Guest';
$UserGroup->Insert(); // execute sql

$User = new UserModel();
$User->Name = 'Peter';
$User->UserGroupID = $UserGroup->UserGroupID;

// print all users
print_r($UserGroup->Users);

$User->Insert();  // execute sql

// print all users
print_r($UserGroup->Users);

Would you expect that $UserGroup->Users imeditaley contains the reference or after the  statement $User->Insert();.

(Currently it is the second one.)

The same with an update statement:

// lets pretend we got the $UserGroup1 and $UserGroup2 from the database

$User = $UserGroup1->Users[0];
$User->UserGroupID = $UserGroup2->UserGroupID;

print_r($UserGroup1->Users);
print_r($UserGroup2->Users);

$User->Update();

print_r($UserGroup1->Users);
print_r($UserGroup2->Users);

Would you expect that $UserGroup->Users imeditaley contains the changed reference or after the  statement $User->Update().
(Currently it is the first one.)

Because working with new Objects and already existing ones behave differently I thought it might could be confusing.
My suggestion would be that the reference is updated imeditaley.

At the moment references for new Objects aren't updated imeditaley because the reference is based on the primary key that doesn't exists yet. It exists after we run Insert().

Maybe I could solve this problem by working internal ids and not database ids.

But the real question is, what would you expect what happens (for the references) without reading any documentation?

EDIT

@showerhead

If I got you right, you would consider this as an better way:

$UserGroup = new UserGroupModel();
$UserGroup->Name = "...";
$UserGroup->Save(); // runs an insert or update sql statement

$User = new UserModel();
$User->Name = "...";
$User->UserGroupID = $UserGroup->UserGroupID;
$User->Save(); // runs an insert or update sql statement

print_r($UserGroup->Users); // would be still empty here

$UserGroup->LoadChanges(); // load the changes

// now we have the new reference in $UserGroup->Users
print_r($UserGroup->Users);


texts: DateTime internal representation to FILETIME

texts:
Here is a routine I put together to convert SQL Server's internal DateTime representation (BINARY(8)) to a FILETIME. I know that the SQL DateTime (as in GetDate()) is not precise and will vary from the SystemTimeAsFileTime. But it should be different by milliseconds, but by seconds, right?

In any case, here is my routine and I was wondering if anyone saw any flaws in it:

int SQLDateTimeToFileTime(PULARGE_INTEGER t_sql, PULARGE_INTEGER t_ft)
{
    ULONGLONG days = t_sql->LowPart;
    ULONGLONG ticks = t_sql->HighPart;
    days += (ULONGLONG) 109207;         // 01/01/1900 - 01/01/1601
    days *= (ULONGLONG) 864000000000;   // (FT_SECONDS_PER_DAY * FT_SECOND);
    ticks *= (ULONGLONG) 33333333333;   // MS per tick (3.33...) * 10000);
    ticks /= (ULONGLONG) 1000000;       // to avoid floating point operation
    days += ticks;
    t_ft->QuadPart = days;
    return(0);
}


texts: Get process max memory usage while copying large data

texts:
I want to check the memory usage of a process before and after I copy a large file or folder, and also, I want to get the maximum memory usage during file operation. Is this a good method?

def copy_folder(s,d):
    if os.path.isdir(d):
        shutil.rmtree(d)
    shutil.copytree(s, d)
    return get_folder_size(s)

def get_pid(process_exe):
    pid = []
    for proc in psutil.process_iter():
        try:
            if proc.name() == process_exe:
                pid.append(proc.pid)
        except psutil.AccessDenied:
            pass
    return pid[0]

def get_process_memory_usage(process_exe):
    pid = get_pid(process_exe)
    process = psutil.Process(pid)
    process_memory = process.memory_info()[0] / float(2 ** 20)
    return process_memory

def get_process_max_memory_usage(process, funct, source, dest):
    t = threading.Thread(target=funct, args=(source, dest))
    t.start()
    memory_vals = []
    if t.isAlive():
        while t.isAlive():
            memory_vals.append(get_process_memory_usage(process))
            time.sleep(1)
        return max(memory_vals), memory_vals
    else:
        return "Thread not found"

this is how I call the function: get_max_memory_usage("process", copy_folder, source, destination)


texts: Better "find and highlight" implementation in HTML element

texts:
I'm trying to figure out what is best and fastest implementation of a browser-like find and highlight function inside a website using JavaScript.
This function is for one HTML element without any children. Of course it can be expanded to elements with children with some simple loops. That is not part of question.
I wrote this small code to make something working here:

CSS

span.highlight{background:yellow; padding:3px;}

HTML

<input type="search"/>

The Ama...

JavaScript

var s = document.querySelector('input[type="search"]'),
    p = document.querySelector('p'),
    find = function(){
    var words = p.innerText.split(' ');
    for(var i=0; i<words.length; i++){
        if(words[i].toLowerCase() == s.value.toLowerCase()){
            words[i] = '' + words[i] + "";
            p.innerHTML = words.join(' ');
        }
        else{

        }
    }
}
s.addEventListener('keydown', find , false);
s.addEventListener('keyup', find , false);

This code is working fine. Checkout live example here. But this is not fast and sometimes crash the browser. How can I make this functionality with a better approach?

Please note I don't want a full code review here. So don't remind me that querySelector is not supported in IE7 and same things.


texts: Message class, with constructors for data from user and from database

texts:
I'm fairly new to Kotlin, and am looking to slim down a data class.

It has two constructors, one for creation based on user input, and one for creation based on database data.

open class Message : Unique {

    val timestamp: Long
    val contents: String

    constructor(contents: String) : super() {
        validateMessageContents(contents)
        this.contents = contents
        this.timestamp = System.currentTimeMillis()
    }

    constructor(id: String, contents: String, timestamp: Long) : super(id) {
        validateMessageContents(contents)
        this.contents = contents
        this.timestamp = timestamp
    }

    companion object {
        private const val MAX_MESSAGE_LENGTH = 1024

        private fun validateMessageContents(contents: String) {
            if (contents.isEmpty()) {
                throw IllegalArgumentException("Contents cannot be blank/empty")
            }
            if (contents.length > MAX_MESSAGE_LENGTH) {
                throw IllegalArgumentException("Message too long - please limit to $MAX_MESSAGE_LENGTH characters.")
            }
        }
    }
}

The Unique superclass has a single id: String property, but will generate a random UUID if the default constructor is called.

I'm wondering - how can I slim down this class? I've fiddled with trying to add a primary constructor, turn it into a data class, but each route I've hit a hurdle.

The things that stick out:

I'm calling validateMessageContents() in both constructors, but can't move it to init because the contents isn't yet available.
The second constructor, aside from validating the contents, is just two ugly assignment statements.
The two codepaths to either super() or super(id) make it difficult for one of these constructors to be made primary.


texts: Alternative for checking the existence of a value in PHP

texts:
I'm trying to create a wordpress plugin but checking for the existence of a value doesn't really feel right because there's a bunch of values that I have to check:

$flickr_key = '';
if(!empty($ecom['ecom_options_flickr_api'])){
  $flickr_key = $ecom['ecom_options_flickr_api'];
}

$flickr_secret = '';
if(!empty($ecom['ecom_options_flickr_secret'])){
  $flickr_secret = $ecom['ecom_options_flickr_secret'];
}

$freebase_key = '';
if(!empty($ecom['ecom_options_freebase_api'])){
  $freebase_key = $ecom['ecom_options_freebase_api'];
}

$ebay_key = '';
if(!empty($ecom['ecom_options_ebay_api'])){
  $ebay_key = $ecom['ecom_options_ebay_api'];
}

Is there a more elegant alternative for this?


texts: Reading a long file and getting sum of chars by multithreading

texts:
import threading
import os
import sys
import time
l=0
length=[]
def File_Opener(keys,l):
    for lines in keys:
        l = l + len(lines)-1
    length.append(l)
    l=0
if __name__ == "__main__":
    start=time.time()
    f=open(sys.argv[1],"r")
    print "File to be anaysed is %s" %sys.argv[1]
    Threads=[]
    keys=[]
    for i in range(100):
        try:
            for j in range(200000):
                keys.append(f.next())
        except:
            pass
        t = threading.Thread(target=File_Opener,args=(keys,l))
        t.start()
        keys=[]
        print "Created thread %d" %i
        Threads.append(t)
    for thread in Threads:
        thread.join()
print "Total Length of words are", sum(length)
print "Time taken is %f" %(time.time()-start)
print "Done!!"

Issue : Takes 5x more time than non-multi threaded code.

I am trying to get sum of all chars in a file of very big size. The reason why i used the for loop is to divide the file into small list and pass each to a thread and except is used for in case the file does't come complete in 200000 chars I want to know as to how it can be done with multi threading also.
Doing it in python2.7 in Linux


texts: Timus Online Judge Problem 1001 - "Reverse Root"

texts:
The problem statement can be found here.

Description (short):

Input

The input stream contains a set of integer numbers \$A_i\$ (\$0 \le A_i \le 10^{18}\$). The numbers are separated by any number of spaces and line breaks. A size of the input stream does not exceed 256 KB.

Output

For each number \$A_i\$ from the last one until the first one, you should output its square root. Each square root should be printed in a separate line with at least four digits after the decimal point.

#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;

int main()
{
    double t;
    double v [128 * 1024];
    int idx = 0;
    while (cin >> t) {
        v[idx] = sqrt(t);
        ++idx;
    }

    cout << fixed;
    cout << setprecision(4);

    for (int i = idx - 1; i >= 0; --i)
        cout << v[i] << endl;

    return 0;
}

I am encountering a TLE on test case 9, with an execution time of 2.031s and memory usage of 1 474 KB.  (The allowable limits are 2.0s and 64 MB.)  How can I improve (or change) my method to complete the problem successfully?


texts: Retrieve the index of the first element using a predicate

texts:
I want to change the legacy C-style code by using stl:

for (posEmptyItem = startAt; strlen(collection[posEmptyItem]) > 10; posEmptyItem++) {}
std::cout << posEmptyItem << std::endl;

This code seems a bit hard to read. Anyway to do better?

auto it = std::find_if(collection + startAt,
                       collection + COLLECTION_SIZE,
                       [](const char* line) { return strlen(line) <= 10; });
int idx = std::distance(collection, it);

Below a complete example:

#include <cstring>
#include <iostream>
#include <algorithm>

#define COLLECTION_SIZE      250

int main()
{
    const char* collection[COLLECTION_SIZE]{ "time11,time2,time3",
                                       "time12,time2,time3",
                                       "time13,time2,time3",
                                       "time14,time2,time3",
                                       "time15,time2,time3",
                                       "x\n",
                                       "" };
    auto startAt = 2;
    int posEmptyItem;

    // legacy code
    for (posEmptyItem = startAt; strlen(collection[posEmptyItem]) > 10; posEmptyItem++) {}
    std::cout << posEmptyItem << std::endl;

    // replace the loop to search an index by calling to standard library
    auto it = std::find_if(collection + startAt,
                           collection + COLLECTION_SIZE,
                           [](const char* line) { return strlen(line) <= 10; });
    posEmptyItem = std::distance(collection, it);
    std::cout << posEmptyItem << std::endl;

    return 0;
}


texts:
Here is an API for using a warehouse:

public static class WarehouseClient
{
    event Action<IWarehouse> WarehouseCreated;
}

public interface IWarehouse
{
    event Action<IWarehouseSession> NextSession;

    IWarehouseSession Session { get; }

    WarehouseInfo Info { get; }
}

public interface IWarehouseSession
{
    event Action Opened;

    event Action Closed;

    bool IsOpen { get; }

    TariffPolicy TariffPolicy { get; }

    IEnumerable<ITerminal> Terminals { get; }
}

public interface ITerminal
{
    event Action<double> FreeSpaceUpdated;

    string TerminalLetter { get; }

    double FreeSpace { get; }

    IDeposit Deposit(object item);
}

public interface IDeposit
{
    object Item { get; }

    event Action ItemAccepted;

    event Action<int> ItemDeposited;

    event Action ItemWithdrawn;

    void Withdraw();
}

(WarehouseInfo and TariffPolicy are immutable value-like classes)

Also I've got third-party connections to warehouses with interfaces adaptable to mine. But I doubt if I need a mirrored API for connection wrappers, like:

public static class WarehouseProvider
{
    IWarehouseBackend CreateWarehouse(WarehouseInfo info);
}

public interface IWarehouseBackend
{
    IWarehouseSessionBackend Session { get; }

    WarehouseInfo Info { get; }

    IWarehouseSessionBackend NextSession(TariffPolicy tp, params string[] terminalLetters);
}

public interface IWarehouseSessionBackend
{
    bool IsOpen { get; }

    TariffPolicy TariffPolicy { get; }

    IEnumerable<ITerminalBackend> Terminals { get; }

    void Open();

    void Close();
}

public interface ITerminalBackend
{
    // ... and so on

This backend-api can be implemented by library's internal classes.

Removing it means much less code (though it almost written) and harder-to-implement contract for warehouse providers.

So, my question is: do I need backend api?

Also, I would be very grateful for reviewing this API.


texts:
I would appreciate some help with camera movement and zoom. Is there any easier way with cleaner code, or simply how can I improve it?

Window size: 800x600
Image size: 1200x900

This is my code so far (you can move with the camera only around the image and use zoom):

package game.engine.gui;

import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;

public class Camera {

public boolean isEnabled = true;
public int offsetX = 0;
public int offsetY = 0;
public float zoom = 1;
private Point mouseLocation;
private int maxOffsetXZoom = 200;
private int maxOffsetYZoom = 150;
private final int OFFSET_X_MAX = 200;
private final int OFFSET_Y_MAX = 150;
private final float ZOOM_MAX = 1.2F;
private final float ZOOM_MIN = 0.7F;

public Camera() { }

public void draw(Graphics2D g) { }

public void update() { }

public void mousePressed(MouseEvent e) { mouseLocation = e.getPoint(); }

public void mouseReleased(MouseEvent e) { }

public void mouseMoved(MouseEvent e) { }

public void mouseDragged(MouseEvent e)
{
    int newoffsetX = offsetX - (mouseLocation.x - e.getX());
    int newoffsetY = offsetY -  (mouseLocation.y - e.getY());

    if(newoffsetX > maxOffsetXZoom) offsetX = maxOffsetXZoom;
    else if(newoffsetX  < -maxOffsetXZoom + (OFFSET_X_MAX-maxOffsetXZoom) * 4) offsetX = -maxOffsetXZoom + (OFFSET_X_MAX-maxOffsetXZoom) * 4;
    else offsetX = newoffsetX;

    if(newoffsetY  > maxOffsetYZoom) offsetY = maxOffsetYZoom;
    else if(newoffsetY < -maxOffsetYZoom - 25 + (OFFSET_Y_MAX-maxOffsetYZoom) * 4) offsetY = -maxOffsetYZoom - 25 + (OFFSET_Y_MAX-maxOffsetYZoom) * 4;
    else offsetY = newoffsetY;

    mouseLocation = e.getPoint();
}

public void mouseScrolled(MouseWheelEvent e)
{
    if (e.getWheelRotation() < 0) {
        if(zoom<ZOOM_MAX) zoom += 0.05;
    } else {
        if(zoom>ZOOM_MIN) zoom -= 0.05;
    }
    maxOffsetXZoom = (int) (OFFSET_X_MAX * zoom);
    maxOffsetYZoom = (int) (OFFSET_Y_MAX * zoom);
    if(offsetX > maxOffsetXZoom) offsetX = maxOffsetXZoom;
    else if(offsetX  < -maxOffsetXZoom + (OFFSET_X_MAX-maxOffsetXZoom) * 4) offsetX = -maxOffsetXZoom + (OFFSET_X_MAX-maxOffsetXZoom) * 4;

    if(offsetY  > maxOffsetYZoom) offsetY = maxOffsetYZoom;
    else if(offsetY < -maxOffsetYZoom - 25 + (OFFSET_Y_MAX-maxOffsetYZoom) * 4) offsetY = -maxOffsetYZoom - 25 + (OFFSET_Y_MAX-maxOffsetYZoom) * 4;
}
}

It works, but I think it's a huge mess and also if the image size was different it would require a lot of changes. I am using my own engine.


texts:
I was wondering why replace is not in base. I thought, it's because it must be easy to implement with standard combinators. Although I do not like prefix syntax of Applicative I wrote it this way:

replace a b = map (bool <$> id <*> (const b) <*> (== a))

And was slightly surprised after seeing replace in Data.List.Utils:

replace old new l = join new . split old $ l

Are there non-opinion based reasons to prefer one than the other in public projects?


texts: Multi-way Tree organized alphabetically and search in preorder trasversal order

texts:
In attempt to create a k-ary or multiway binary tree sorted alphabetically at every deep, I created this class in Ruby to handle the order and search in a recursive way by the preorderTrasversal method:

Try it here.

class MultiwayTree

def initialize
   @list = Hash.new{|h,k| h[k] = []}
   @sorted_list = Hash.new{|h,k| h[k] = []}
   @child_list = Array.new
   @flattened_categories = Array.new
end

def insert(category, parent)
    return if category == nil # nil categories are not inserted
    puts "Inserting : #{category} " + "- #{if parent == nil; 'nil'; else parent end;}"
    parent.capitalize! unless parent.nil?
    @list[parent] << category.capitalize
end

def flatCategories
    sortAlphabetically

  # Fill a new list of child out of the sorted_list
    @sorted_list.each do |parent, child|
        child.each{|categories| @child_list << categories}
    end

  # Search in the list of childs starting from the root in Preorder Traversal
    @child_list.flatten.each do |child|
        preorderTrasversal(child)
    end

    @flattened_categories

end

# Insert each group of childs into a new hash in alphabetical order
def sortAlphabetically
    @list.each{|parent, child| @sorted_list[parent] << child.sort}
end

# Insert the child into the flattened_categories Array if not already in.
# Search and verify if the inserted childs have a node in the tree and
# insert them in the flattened_categories Array. Keep searching deeper recursively
def preorderTrasversal seed
    @flattened_categories << seed unless @flattened_categories.include? seed
    if @sorted_list.key?(seed)
        @sorted_list[seed].flatten.each do |seeder|
            preorderTrasversal(seeder)
        end
    end
end
end

It receives this list, handled by the insert method:

lista = MultiwayTree.new()
lista.insert("Family", nil)
lista.insert("Parenting", "Family")
lista.insert("Caregiving", "Family")
lista.insert("Finances", "Family")
lista.insert("RRSPs", "Finances")
lista.insert("Savings", "Finances")
lista.insert("Planning", "Finances")
lista.insert("Career", nil)
lista.insert("Managers", "Career")
lista.insert("Employees", "Career")
lista.insert("test", "RRSPs")

Which gives the following output when calling flatCategories method:

["Career", "Employees", "Managers", "Family", "Caregivig", "Finances", "Planning", "Rrsps", "Test", "Savings", "Parenting"]`

This is working how I wanted to right now. However, I'm not too advanced in Ruby, so are there any suggestions on how I can refactor the search method preorderTrasversal?


texts:
I'm writing a C++ high precision library based on GMP, sample code(files which have to be added to project):

//biginteger.cc
#include "biginteger.h"
#include <cstdlib>
#include <iostream>
#include <tuple>
#include <gmp.h>

void biginteger::deleteBiginteger(){
std::cout << "sprzatam bigintegera"; std::cout << std::endl;
mpz_clear(x);
}
void biginteger::printbiginteger(){
gmp_printf("%Zd\n", this->x); //std::cout <<std::endl;
   }
   // overloaded += operators
    biginteger& biginteger::operator += (const unsigned long long int& a){
    mpz_add_ui(this->x, x, a);
    return *this;
    }
biginteger& biginteger::operator += (const signed long int& a){
    if (a < 0) {
    signed long int tmp1 = -a;
    unsigned long long int tmp2 = tmp1;
    mpz_sub_ui(this->x, x, tmp2);
    return *this;
}
else{
    unsigned long long int t1 = (unsigned long long int) a;
    mpz_add_ui(this->x, x, t1);
    return *this;
}
}
biginteger& biginteger::operator += (const biginteger& a){
mpz_add(this->x, this->x, a.x);
return *this;
}

//biginteger.h
#ifndef biginteger_h
#define biginteger_h

#include <cstdlib>
#include <iostream>
#include <tuple>
#include <gmp.h>
 class biginteger{
    public:
    mpz_t x;
    biginteger(mpz_t n){
    mpz_init(x);
    mpz_set(x, n);
    }
    biginteger(unsigned long long int a){
    mpz_init(x);
    mpz_set_ui(x, a);
    }
    biginteger(signed long int a){
        mpz_init(x);
        mpz_set_si(x, a);
    }
biginteger(int a){
    mpz_init(x);
    mpz_set_si(x, a);
}
biginteger(const char *str, int base){
    mpz_init_set_str(x, str, base);
}

void deleteBiginteger();
void printbiginteger();
biginteger& operator += (const unsigned long long int& a);
biginteger& operator += (const signed long int& a);
biginteger& operator += (const biginteger& a);

Those two files are just sample code, is there any way to improve performance of this?


texts:
How can I re-factorise this circular nesting dictionary function?

The challenge:

  I recently received a data extract with a list of folder names and associated subfolders. The challenge was to produce a reusable function that could provide a summary of the unique folder names and all the nested subfolders.

  The data source was an excel spreadsheet containing 2 columns:

  Parent: Folder name

  Child: Subfolder name

  Note: I have recreated spreadsheet data using pandas so the code can be easily tested.

Create table:

import pandas as pd

data = {'Parent': ['A', 'B', 'C', 'D', 'E', 'F', 'C', 'C'],
        'Child': ['B', 'C', 'E', 'E', 'Z', 'Z', 'B', 'A']}

df = pd.DataFrame(data)

print(df):

Parent  Child
0   A   B
1   B   C
2   C   E
3   D   E
4   E   Z
5   F   Z
6   C   B
7   C   A

My solution:

def relationship_dictionary(dataframe, key_column_name, values_column_name):
    """
    The key_column_name is the primary data source that should be considered the
    start of the nested relationship.

    The values_column_name is the subfolder

    Creates a dictionary of unique relationships to each key.
    """

    parent = key_column_name
    child = values_column_name

    d = {}
    for i, row in dataframe.iterrows():
        key = row[parent]
        value = row[child]
        if key in d.keys():
            d[key].append(value)
        else:
            d[key] = [value]

    for k, values in d.items():
        for v in values:
            if v in d.keys():
                for each in d[v]:
                    if (each not in d[k]) and (each != k):
                        d[k].extend([each])
    return d

Result:

relationship_dictionary(df, "Parent", "Child")
{'A': ['B', 'C', 'E', 'Z'],
 'B': ['C', 'E', 'A', 'Z'],
 'C': ['E', 'B', 'A', 'Z'],
 'D': ['E', 'Z'],
 'E': ['Z'],
 'F': ['Z']}

Feedback

  I'm happy to say it works after mitigating the circular nesting issue but I can't help thinking there is a far simpler way of doing this so I thought I'd put it out there for critique so feedback would be welcome... :)


texts:
Summing doubles can cause a loss of precision.
Summing integers, however, doesn't. (Assuming no overflow.)

Here's a high precision sum function I wrote:

#include <iostream>
#include <vector>
#include <cmath>
#define BASE 10

bool is_int(double n) {
  double intpart;
  return std::modf(n, &intpart) == 0.0;
}

double sum(std::vector<double> nums) {
  int n = nums.size();

  int maxepower = 1;
  for (int i = 0; i < n; ++i) {
    while(!is_int(nums[i] * pow(BASE, maxepower))) { maxepower++; }
  }

  int pieces[n];
  for (int i = 0; i < n; ++i) {
    pieces[i] = nums[i] * pow(BASE, maxepower);
  }

  int sum = 0;
  for (int i = 0; i < n; ++i) {
    sum += pieces[i];
  }

  return sum / pow(BASE, maxepower);
}

I'm new to C++ so extra feedback on idioms would be helpful.

EDIT:
Example:

int main() {
  std::cout << 0.1 + 0.2 - 0.3 << std::endl;
  std::cout << sum({0.1, 0.2, -0.3}) << std::endl;
}

gives

5.55112e-17
0


texts:
I've written some code in python in combination with selenium to collect photo shoot spaces in different locations in Paris.

My scraper is harvesting the names successfully at this moment. However, is it possible to do this any better way cause it looks repetitive?

Any input to improve this script will be highly appreciated. Here is what I've written:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://www.peerspace.com/")
wait = WebDriverWait(driver, 10)

wait.until(EC.visibility_of_element_located((By.ID, "activity-input"))).click()
wait.until(EC.visibility_of_element_located((By.XPATH, "//div[contains(@class,'ellipsis')]/a"))).click()
wait.until(EC.visibility_of_element_located((By.XPATH, "//div[contains(@class,'col-xs-12')]/li/a[@data-name='Photo Shoot']"))).click()

wait.until(EC.visibility_of_element_located((By.ID, "searchbar-input"))).send_keys("Paris")
wait.until(EC.visibility_of_element_located((By.ID,"searchbar-submit-button"))).click()

for items in wait.until(EC.presence_of_all_elements_located((By.XPATH, "//div[@class='col-xs-12 ']/h6[contains(@class,'title')]"))):
    print(items.text)
driver.quit()

Inputbox to be filled in before pressing the search button are with:

First one : Photo Shoot
Second one : Paris


texts: Is there anything incorrect about this layout, semantically or otherwise?

texts:
I would like to know if my chosen layout is HTML5 standards compliant, or if I'm using the heading tags incorrectly (or any other tag for that matter)?

Main Header

 for website name

 for webpage name

 for website slogan, or should this be  with styling?

Main Content/Sidebar Content

 for every first heading in each
 element (because a level 1 heading is too large), or should this really be
 with specific styling; e.g. .panel-ws section h1?
.first removes unwanted top margin.
.panel-ws adds whitespace (padding).

Example Code Extracts (OLD; Updated Below!)

Website Name

Page Title

Slogan

Content 1

Lorem ipsum...

Lorem ipsum...

Content 2

Lorem ipsum...

Lorem ipsum...

Content 3

Lorem ipsum...

Lorem ipsum...

Side content 1

Lorem ipsum...

Lorem ipsum...

Side content 2

Lorem ipsum...

Lorem ipsum...

#header-text h1
#header-text h2
#header-text h3
.panel-ws section h2
.first

Example Code Extracts (UPDATED!)

Website Name

Slogan

Page Title

Content 1

Lorem ipsum...

Lorem ipsum...

Content 2

Lorem ipsum...

Lorem ipsum...

Content 3

Lorem ipsum...

Lorem ipsum...

Related Content 1

Lorem ipsum...

Lorem ipsum...

Related Content 2

Lorem ipsum...

Lorem ipsum...

#header-text h1
#header-text p
.panel-ws #page-title-container #page-title
.panel-ws section h1
.panel-ws section h2
.panel-ws section h3


texts: Haskell: rndFile and [Char] vs IO String error

texts:
import System.Environment (getArgs)
import Random

main = do
  args <- getArgs
  let len = length args
  let n = if len < 1 then 10000 else  read (args !! 0) :: Int
  let fileName = if len < 2 then show n ++ "-output.txt"  else args !! 1
  str <- rndStr n
  writeFile fileName (str)
--  writeFile fileName (rndStr n)
-- Couldn't match expected type `[Char]' with actual type `IO String'

rndStr :: Int -> IO String
rndStr n  = sequence . replicate n . randomRIO $ (' ', '~')

This code works. It creates size n file of random chars. That's good.

I have 2 questions:
1. Is my argument sanitizing ok? If not, how to make it better?
2. Swapping writeFile str for writeFile (rndStr n) produces [Char] vs IO String error.
Why? Shouldn't it be the same?
I manage this to work by accident, not because I know what I did.


texts:
I don't get to write multithreaded applications very often, so be gentle with my threads :-)

I have an API input which contains a "score" and then a bunch of child nodes which also have scores, and perhaps child nodes of their own. I need to quickly sum up the total score of the entire tree.

I've elected a newWorkStealingPool as I have read that this is a good implementation for applications where workers may spawn other workers.

My handler is awfully static. I don't always work in Java, but this felt like the appropriate solution. Correct if wrong? :-)

I think I've made thread safe the methods that could be troublesome. I'd obviously like to remove the synchronization from methods that maybe don't need it.

I'm very concerned about how I monitor the running threads to decide when my work is done. I think there is a race condition here that I am having trouble understanding, even if for now, this project works.

Don't worry too much about my throwing an Exception, please :-). It's just for now so as to not clutter up the other code.

Thank you!!

Oh! Java 8 is pretty new to me, too. I only just considered where I could use some new functionality.

Runner

import java.net.URL;

public class Runner {

    public static void main(String[] args) throws Exception {
        try{
            NodeHandler.addNode(new Node(new URL(args[0])));
        }catch(java.net.MalformedURLException e){
            System.out.println("Malformed URL Exception: " + e.getMessage());
        }
        System.out.println(Double.toString(NodeHandler.getTotal()));
    }

}

Node Handler

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class NodeHandler {
    private static int runningThreads = 0;
    private static double rewardsTotal = 0;
    private static ExecutorService es = Executors.newWorkStealingPool();

    public static synchronized void addNode(Node node) {
        es.execute(node);
    }

    public static synchronized void incrementThreadCount() {
        runningThreads++;
    }

    public static synchronized void decrementThreadCount() {
        runningThreads--;
    }

    public static synchronized void updateScore(double score){
        scoreTotal += score;
    }

    public static int getRunningThreads() {
        return runningThreads;
    }

    public static double getTotal(){
        while(getRunningThreads() > 0){
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return scoreTotal;
    }

}

Node

import java.util.*;
import java.net.URL;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class Node implements Runnable{

    private URL url;
    private StringBuilder rawJson = new StringBuilder();

    Node(URL url){
        NodeHandler.incrementThreadCount();
        this.url = url;
    }

    private void processNode() throws Exception{
        Scanner sc = new Scanner(url.openStream());

        while (sc.hasNext()) {
            rawJson.append(sc.nextLine());
        }
        sc.close();

        JSONParser jParser = new JSONParser();
        JSONObject jObj = (JSONObject) jParser.parse(rawJson.toString());
        JSONArray children = (JSONArray) jObj.get("children");
        NodeHandler.updateScore(Double.parseDouble(jObj.get("score").toString()));

        if (children != null && children.size() > 0) {
            for (Object o : children) {
                URL url = new URL(o.toString());
                NodeHandler.addNode(new Node(url));
            }
        }
        NodeHandler.decrementThreadCount();
    }
    @Override
    public void run(){
        try {
            processNode();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}


texts:
The following function finds all local maxima.

A local maxima is an element of a list such that it's greater than either of its neighbor elements. An element with 1 neighbor is not a local maximum.

localMaxima :: [Integer] -> [Integer]
localMaxima (x:y:z:zs) = if (y > x && y > z) then y : localMaxima (y:z:zs)
                         else localMaxima (y:z:zs)
localMaxima _          = []

Please critique it.

Examples:

ghci> localMaxima [1,3,2,55,2]
[3,55]
ghci> localMaxima [1,3,2,55,1000000000]
[3]


texts: How to find the unique values from the JSON file?

texts:
I have JSON files of size data_large(150.1mb). The content inside the file is of type [{"score": 68},{"score": 78}]. I need to find the list of unique scores from each file.

This is what I'm doing:

import ijson  # since JSON file is large, hence making use of ijson

f = open ('data_large')
content = ijson.items(f, 'item') # json loads quickly here as compared to when json.load(f) is used.
print set(i['score'] for i in content) #this line is actually taking a long time to get processed.

Can I make the last line more efficient?  It's currently taking 201 secs to execute.


texts: Convert bitcoin value based on exchange rate from JSON API

texts:
I’m learning F# and trying to find a more ‘functional’ way to code a simple program that retrieves the price of BTC and calculates the EUR value of an amount of Bitcoin.

open System
open System.Net
open Newtonsoft.Json.Linq

let myBTC = 0.1234567
let client = new WebClient()
client.UseDefaultCredentials = true
let priceInfo = client.DownloadString("https://blockchain.info/ticker")
let jPrice = JObject.Parse priceInfo
let eurPrice = float (jPrice.["EUR"].["buy"] :?> JValue)
let calcWorth = myBTC * eurPrice
printfn "%s" calcWorth.ToString("N")


texts:
Following on from my previous question: C pointer based growable stack

I have made some improvements (hopefully!) based on the very helpful comments and suggestions.
I have checked that the stack can push and pop doubles now, so hopefully it will also be OK with structs.

I have a could of questions regarding the changes I have made:

I noticed memcpy() didn't work with void * so I switched to using uin8_t; is that recommended/necessary or could I have cast to uint8_t for memcpy()? Not sure which approach is the best...
How should a failed malloc()/realloc() be handled? Return an error code? Exit? Return NULL?

Again, I would greatly appreciate any suggestions/criticism:

#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>

#define MAX_ITEMS 16

typedef struct {
    uint8_t *data;
    size_t itemSize;
    unsigned count;
    unsigned capacity;
} Stack;

void stack_init(Stack *stack, size_t itemSize, unsigned capacity);
bool stack_is_empty(const Stack *stack);
void stack_push(Stack *stack, void *item);
void* stack_pop(Stack *stack);
void stack_destroy(Stack *stack);

void stack_init(Stack *stack, size_t itemSize, unsigned capacity)
{
    unsigned initialCapacity = capacity == 0 ? 1 : capacity;
    size_t size = initialCapacity * itemSize;

    stack->count = 0;
    stack->capacity = initialCapacity;
    stack->itemSize = itemSize;
    stack->data = (uint8_t *)malloc(size);

    if (stack->data == NULL)
    {
        // TODO
    }

    memset(stack->data, 0, size);
}

bool stack_is_empty(const Stack *stack)
{
    return stack->count == 0;
}

void stack_push(Stack *stack, void *item)
{
    if (stack->count >= stack->capacity)
    {
        stack->capacity *= 2;
        stack->data = (uint8_t *)realloc(stack->data, stack->capacity * stack->itemSize);

        if (stack->data == NULL)
        {
            // TODO
        }
    }

    unsigned offset = stack->count * stack->itemSize;
    memcpy(stack->data + offset, item, stack->itemSize);
    stack->count++;
}

void* stack_pop(Stack *stack)
{
    if (stack_is_empty(stack) == true)
    {
        // TODO
    }

    uint8_t *item = (uint8_t *)malloc(stack->itemSize);

    if (item == NULL)
    {
        // TODO
    }

    stack->count--;
    unsigned offset = stack->count * stack->itemSize;
    memcpy(item, stack->data + offset, stack->itemSize);

    return (void *)item;
}

void stack_destroy(Stack *stack)
{
    free(stack->data);
    stack->count = 0;
}

int main(void)
{
    Stack stack;
    stack_init(&stack, sizeof(int), 0);

    for (int i = 0; i < MAX_ITEMS; i++)
    {
        stack_push(&stack, (void *)&i);
    }

    while (!stack_is_empty(&stack))
    {
        int value;
        value = *((int *)stack_pop(&stack));
        printf("%d\n", value);
    }

    stack_destroy(&stack);
}


texts:
I have some JavaScript code to manage a 2D map in a game. I have a function to create a new room in the map which is at map[x][y]. I need to create that property and also initialize the monsters property. The code I wrote looks like this, which works fine.
'use strict';

let map = {};

function newRoom(x, y) {
    if (map[x] === undefined)
        map[x] = {};
    map[x][y] = {};
    map[x][y].monsters = {};
}

newRoom(0, 0);

Is there a more concise way to write code like this?


texts: JavaScript function for finding perfect numbers

texts:
The following function has been created for finding "Perfect Numbers".

About Perfect Numbers: Wikipedia

function findPerfectNumbers(upperLimit, currentTry = 2) {
  let perfectNumbers = [];
  let divisor;
  let sum;

  if (typeof upperLimit !== 'number' || isNaN(upperLimit) ||
          upperLimit < 2) {
    throw new TypeError(`First parameter is expected to a ` +
                      `number larger then 1 which is not NaN.`);
  }

  while (currentTry <= upperLimit) {  // <------- Start outer loop
    divisor = 2;
    sum = 0;

    while (currentTry >= divisor) {   // <------- Start inner loop
      let fraction = currentTry / divisor;
      let leftOver = currentTry % divisor;

      if (leftOver === 0) {
        sum += fraction;
      }

      divisor++;
    }                                 // <-------- End inner loop

    if (sum === currentTry) {
      perfectNumbers.push(currentTry);
    }

    currentTry++;
  }                                   // <-------- End outer loop

  return perfectNumbers;
}

// ------------ Demo ... --------------------------
console.log(findPerfectNumbers(1000));               // Returns : [6, 28, 496]
console.log(findPerfectNumbers(8140, 8100));         // [8128]
console.log(findPerfectNumbers(33550340, 33550335)); // [33550336]

It finds the first five Perfect Numbers. So I suppose my algorithm is basically correct.

But practically it doesn't work well.

Currently, it has a runtime complexity of \$O(n^2)\$. Therefore it becomes practically unusable from the fourth Perfect Number on upwards.

Therefore my question to the programmers who are more advanced than me:

Is there a way to improve the runtime complexity of the function?
If it isn't possible to change the algorithm, are there performance tricks one could use? like for example using shift operators instead of arithmetic operators?

All hints, comments, and tips concerning the points described above and the function in general appreciated.


texts:
I had to create this program, and I did it fine, all is working and stuff but I was wondering, what is better way of doing such thing? I want more efficient method.

Problem assignment:

  In the file is unknown amount of numbers. Create a program, which
  output is amount of numbers, the lowest number and the highest number.

#include <iostream>
#include <fstream>

/*
INPUT EXAMPLE:
12
15
-1
2
20
-4

OUTPUT EXAMPLE:
numbers: 6
minimum: -4
maximum: 20
*/
int main(){
    std::ifstream fin("input.txt");
    if (fin.is_open()){
        int n;
        int min,max;
        int i = 0;
        while (fin >> n){
            if (!n) break;
            if (i++ == 0){
            min = n; max = n;
            }
            if (n < min)
                min = n;
            else if (n > max)
                max = n;
        }
        if (fin.good())
         std::cout << "numbers: " << i << '\n' << "minimum: " << min << '\n' << "maximum: " << max << '\n';
        else std::cout << "plz you even tryin'\n";
    }
    system("PAUSE");
    return 0xDEADBEEF;
}

Any improvements?


texts:
I come from the R language and I gradually switch to Python (Numpy and Pandas). I coded this python code for fun to solve a Sudoku grid. Could you tell me if my code is pythonic enough? For example, did I use the numpy functions correctly. How to make the code more readable?

import numpy as np
from functools import reduce

def solver_python(grid):
    numbers=np.arange(1,10)
    i,j = np.where(grid==0)
    if (i.size==0):
        return(True,grid)
    else:
        i,j=i[0],j[0]
        row = grid[i,:]
        col = grid[:,j]
        sqr = grid[(i//3)*3:(3+(i//3)*3),(j//3)*3:(3+(j//3)*3)].reshape(9)
        values = np.setdiff1d(numbers,reduce(np.union1d,(row,col,sqr)))

        grid_temp = np.copy(grid)

        for value in values:
            grid_temp[i,j] = value
            test = solver_python(grid_temp)
            if (test[0]):
                return(test)

        return(False,None)

example = np.array([[5,3,0,0,7,0,0,0,0],
                    [6,0,0,1,9,5,0,0,0],
                    [0,9,8,0,0,0,0,6,0],
                    [8,0,0,0,6,0,0,0,3],
                    [4,0,0,8,0,3,0,0,1],
                    [7,0,0,0,2,0,0,0,6],
                    [0,6,0,0,0,0,2,8,0],
                    [0,0,0,4,1,9,0,0,5],
                    [0,0,0,0,8,0,0,7,9]])


texts: A two-method program for running background jobs

texts:
Edit: since originally posting this I have: realized that it won't run from irb/pry, and refactored to remove some sleep calls. I've also separated the sections into different code blocks.

I wanted to make a program for running background jobs (ruby scripts).

The goal was to continuously run a background script on an interval of N seconds until a kill command was issued.

See below for my implementation. Note that this cannot be pasted into irb or pry, it will cause an orphan process. Run it from a script instead. Why is this the case? I don't know. Do you?

The program prints out the process name. In the case of an orphaned process, run ps aux with the process name and kill -9 on each PID shown.

Stdlib depencies and basic OOP setup

require 'securerandom'
require 'tempfile'
class Backgrounder
  attr_accessor :process_name, :interval, :script_content
  def initialize(options={})
    @interval, @script_content = options.values_at(:interval, :script_content)
    raise ArgumentError unless [interval, script_content].all?
  end
end

"begin" command - saves the script to a tempfile, starts a subshell running IRB,
loads the script into IRB, and saves the process identifier.

class Backgrounder
    def begin
        tempfile_name = SecureRandom.urlsafe_base64
        tempfile = Tempfile.new(tempfile_name)
        tempfile_path = tempfile.path
        tempfile_content = <<-RUBY
            $0 = "#{tempfile_name}" # changes the name of the program
            while true
              #{self.script_content}
              sleep #{self.interval.to_f / 1000}
            end
        RUBY
        tempfile.write(tempfile_content)
        tempfile.close # saves the write
        require 'byebug'
        cmd = <<-SH
            echo "load '#{tempfile_path}'" | irb
        SH
        cmd_pid = spawn(cmd, pgroup: true) # runs the tempfile in IRB
        self.process_name = tempfile_name # used later to kill the process
        Process.detach(cmd_pid) # prevents the process from blocking the current script
      end
    end

"kill" command - loops twice for good measure
because orphan processes are really annoying. it actully makes a difference though.
My test program (shown later) didnt work otherwise. kill -9 is called twice per
iteration because there are actually two processes for each process_name.
The first is the headless irb console, and the second is the loaded file.

class Backgrounder
    def kill
        2.times {
            puts "--------\Trying to kill process named: #{self.process_name}\n----------"
            pid1 = `ps aux | grep #{self.process_name} | awk 'NR==1{print $2}'`.chomp
            `kill -9 #{pid1}`
            pid2 = `ps aux | grep #{self.process_name} | awk 'NR==2{print $2}'`.chomp
            `kill -9 #{pid2}`
        }
    end
end

Usage example / test code - start and stop 2 background processes.

# Initialize Backgrounder object with script and interval
process1 = Backgrounder.new(
  interval: 2000, script_content: "system('chromium-browser http://google.com')"
)
process2 = Backgrounder.new(
  interval: 2000, script_content: "system('chromium-browser http://yahoo.com')"
)

# start processes, opens chrome tabs once every two seconds
[process1, process2].each(&:begin)

 # some sleep time is required between starting & stopping a process
sleep 2

# stop the processes
[process1, process2].each(&:kill)


texts: Update the idx values if vals element match between consecutive rows

texts:
I want to update the numbers in idx field if there is any matching letter between the vals from two consecutive row.

Input data = '''pos\tidx\tvals
    23\t4\tabc
    25\t7\tatg
    29\t8\tctb
    35\t1\txyz
    37\t2\tmno
    39\t3\tpqr
    41\t6\trtu
    45\t5\tlfg'''

Explantion: Since there is letteramatching between idx 4 and 7 the idx at pos 25 will be updated to 4, but again there istmatching between vals at pos 25 and 29 we update the idx at 29 also to 4 instead of just 7.

#Expected output to a file (tab separated):
pos    idx    vals
23    4    abc
25    4    atg
29    4    ctb
35    1    xyz
37    2    mno
39    3    pqr
41    3    rtu
45    5    lfg

I have written the given workable code (below) so far, and would also like to

write the expected output to a file
optimize the code for the work I am doing.
the answer has to follow my method of reading two consecutive rows (as keys, values) pairs at a time in ordered way. The reason is this question is just a trial of other problem I am trying to solve. Other parts of the code can be optimized in any pythonic way.

Code:

import csv
import itertools
import collections
import io
from itertools import islice

data = '''pos\tidx\tvals
23\t4\tabc
25\t7\tatg
29\t8\tctb
35\t1\txyz
37\t2\tmno
39\t3\tpqr
41\t6\trtu
45\t5\tlfg'''

data_As_Dict = csv.DictReader(io.StringIO(data), delimiter='\t')
grouped = itertools.groupby(data_As_Dict, key=lambda x: x['idx'])

''' Function to read the data as key, val pairs in Ordered way.'''
def accumulate(data):
    acc = collections.OrderedDict()
    for d in data:
        for k, v in d.items():
            acc.setdefault(k, []).append(v)
    return acc

''' Store data as keys,values '''
grouped_data = collections.OrderedDict()
for k, g in grouped:
    grouped_data[k] = accumulate(g)

''' Print the very first k1. After this we only need to print k2 and update the idx '''
header_with_1stK1 = io.StringIO(data).read().split('\n')[0:2]
print('\n'.join(header_with_1stK1))

''' make an empty new_k2 value. This k2 value is updated and carried on base on match between vals from two different rows. '''
k2_new = ''

for n in range(2):
    if n > 0:
        break. # just to run the loop one time and to prevent resetting of k2_new values to ‘’

    ''' Now, read as keys, values pairs for two consecutive keys '''
    for (k1, v1), (k2, v2) in zip(grouped_data.items(), islice(grouped_data.items(), 1, None)):

        v1_vals = ''.join(v1['vals'])
        v2_vals = ''.join(v2['vals'])

        v1_list = list(v1_vals)
        v2_list = list(v2_vals)

        ''' to check if there is any matching element '''
        commons = [x for x in v1_list if x in v2_list]

        v2_pos = ''.join(v2['pos'])

        ''' start updating the idx values '''
        if k2_new == '':
            if len(commons) > 0:
                k2_new = k1
                print('\t'.join([v2_pos, k2_new, v2_vals]))

            else:
                k2_new = ''
                print('\t'.join([v2_pos, k2, v2_vals]))

        elif k2_new != '':
            if len(commons) > 0:
                k2_new = k2_new
                print('\t'.join([v2_pos, k2_new, v2_vals]))

            else:
                k2_new = ''
                print('\t'.join([v2_pos, k2, v2_vals]))

print('\nUpdated the idx values')


texts:
According to the Doctrine docs, you should use Array hydration rather than record hydration when retrieving data for read-only purposes.

Unfortunately, this means I have to use array syntax (as opposed to object syntax) to reference the data.

$q = Doctrine_Query::create()
    ->from('Post p')
    ->leftJoin('p.PostComment pc')
    ->leftJoin('pc.User u')
    ->where('p.post_id = ?', $id);

$p = $q->fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY);

...

foreach ($p['PostComment'] as $comment) {
    $this->Controls->Add(new CommentPanel($comment['text'],
                         $comment['User']['nickname'],
                         $comment['last_updated_ts']));
}

Maybe it's just me, but all of those string literals as array indexes are kinda scary.  Does anyone have some ideas for cleaning this up?


texts: AppTaskWorker - Running class methods at sporadic intervals

texts:
I decided to write a class to do this for me. I had a lot of methods that needed to be invoked at sporadic intervals, across multiple projects.

The dictionary will eventually be class methods, I just put new Task()... as an example. I'm fairly new to asynchronous programming, so constructive criticism is 100% welcome.

I set a low interval (10s) on  the main timer because I want to stay as close to the interval in the dictionary as possible. I'm not sure the lowest I can put it without ruining performance.

At some point, I plan to implement non async methods. If anyone has any ideas on how I should implement that, please let me know. I feel like running a non async method inside a task would be a bad idea, maybe a seperate dictionary and process method would work?

Thanks.

public class AppTaskWorker : IAppTaskWorker
{
    private readonly ILogger _logger;
    private readonly ConcurrentDictionary<Task, DateTime> _tasksLog;
    private readonly ConcurrentDictionary<int, Task> _tasks;

    public AppTaskWorker()
    {
        _logger = new ConsoleLogger(typeof(AppTaskWorker));
        _tasksLog = new ConcurrentDictionary<Task, DateTime>();
        _tasks = new ConcurrentDictionary<int, Task>();

        TryRegisterTask(30, new Task(() => // every 30 seconds
        {
            Console.WriteLine("Task 1 has been processed.");
        }));

        TryRegisterTask(120, new Task(() => // every 2 minutes
        {
            Console.WriteLine("Task 2 has been processed.");
        }));

        TryRegisterTask(25, new SomeController().Process()); // every 25 seconds

        Start();
    }

    public void Start()
    {
        while (true)
        {
            Task.Run(async () =>
            {
                await ProcessActionsAsync();
                await Task.Delay(10000);
            });
        }
    }

    public bool TryRegisterTask(int interval, Task task)
    {
        return _tasks.TryAdd(interval, task);
    }

    private async Task ProcessActionsAsync()
    {
        foreach (var keyValuePair in _tasks)
        {
            var task = keyValuePair.Value;

            if (!_tasksLog.TryGetValue(task, out var lastProcessed))
            {
                continue;
            }

            if (!((DateTime.Now - lastProcessed).TotalSeconds >= keyValuePair.Key))
            {
                continue;
            }

            _tasksLog[task] = DateTime.Now;

            try
            {
                await task;
            }
            catch (Exception e)
            {
                _logger.Error(e.ToString());
            }
        }
    }
}


texts: DP algorithm to find minimum average wait for customer-serving system

texts:
Below is the code to find the minimum average waiting time for customers at a store. I want improve the time complexity of the code. As an overview of the logic, I start from currentTime = 0 and increment it by preparation time of the current order (as only one order can be prepared at any given time). When that order is complete, look for customers whose order/arrival time is before or equal to the current time. It goes on till all the customers are served.

    InputStreamReader inputStreamReader = new InputStreamReader(System.in);
    Scanner scanner = new Scanner(fileReader);
    int noOfCustomers = scanner.nextInt();
    int[] arrivalTime = new int[noOfCustomers];
    int[] orderPreparationTime = new int[noOfCustomers];
    int i = 0;
    while (scanner.hasNext()) {
        arrivalTime[i] = scanner.nextInt();
        orderPreparationTime[i] = scanner.nextInt();
        i++;
    }

    int[] weightTimes = new int[noOfCustomers];
    int customersServed = 0;
    int currentTime = 0;
    while (customersServed < noOfCustomers) {
        int minWeightTime = Integer.MAX_VALUE;
        int customerIndex = Integer.MIN_VALUE;
        int preparationTime = 0;
        for (int j = 0; j < noOfCustomers; j++) {
            if (arrivalTime[j] <= currentTime) {
                int weightTime = (currentTime - arrivalTime[j] + orderPreparationTime[j]);
                if (weightTime < minWeightTime) {
                    minWeightTime = weightTime;
                    customerIndex = j;
                    preparationTime = orderPreparationTime[j];
                }
            }
        }
        if (customerIndex != Integer.MIN_VALUE) {
            weightTimes[customerIndex] = minWeightTime;
            arrivalTime[customerIndex] = Integer.MAX_VALUE;
            customersServed++;
            currentTime += preparationTime;
        }
    }

    int totalWeightTime = 0;
    for (int weightTime : weightTimes) {
        totalWeightTime += weightTime;
    }
    System.out.println((int) totalWeightTime / noOfCustomers);

Input (Arrival Time, Order time) for 6 customers:

6
0 3
1 9
2 5
4 4
4 7
5 3


texts:
I've extended FragmentPagerAdapter but reading the example implementation automatically generated by Android Studio's "tabbed application" preset, getItem, getCount, and getPageTitle seem to have a lot of duplicated code. It uses a switch statement and hardcodes what tabs you can have and their names for the UI. This doesn't seem to be a very good solution. So I modified the solution to use a list internally to store the Fragments.

When I came to modifying the getPageTitle method, I had two choices:

I could either extend Fragment, add a way to method that returns the desired name, and then make all tabs extend from this extended class,
or I could simply use .getClass().getSimpleName() and some string processing to get it.

Of course, I would

(String) getResources().getText(getResources().getIdentifier(key, "string", "com.example.app"));

after that to get localized strings from strings.xml.

From what I've seen, it's popular to name classes in upper camelCase, followed by the class name it has extended.

For example: if I had three tabs that were settings, history, and test results, they would be named SettingsFragment, HistoryFragment, and TestResultsFragment. As long as I consistently name it in this manner, the string processing that I did before will always work.

I remember in school that it was a bad idea to use .getClass() unless you're debugging. I felt a little dirty implementing option 2 but it's significantly less code and seemingly less complex.

public class SectionsPagerAdapter extends FragmentPagerAdapter {
    private List<Fragment> mFragmentList;

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
        mFragmentList = new ArrayList<Fragment>();
    }

    public void addFragment(Fragment fragment) {
        mFragmentList.add(fragment);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        //regex handles case where class name can more than one word like "TestResultsFragment" => "test_results"
        String className = mFragmentList.get(position).getClass().getSimpleName();
        return (String) getResources().getText(getResources().getIdentifier(className.substring(0, className.length() - 8).replaceAll("([a-z])([A-Z]+)", "$1_$2").toLowerCase(), "string", "com.example.app"));
        //"fragment".length() == 8
    }
}

Or is there another method that I haven't thought about?


texts: Create array of date pairs for next 10 days

texts:
I wrote the below function which successfully creates pairs of dates in the format I need. However, I'm fairly new to Python and feel there must be a way to make this easier to read. Can this code be improved?

def getNextTenDays():
    dates = []
    arrive = datetime.datetime.now()
    for n in range(1, 11):
        arrive += datetime.timedelta(days=1)
        next_day = arrive + datetime.timedelta(days=1)
        arrive_s = datetime.datetime.strftime(arrive, '%m/%d/%Y')
        next_day_s = datetime.datetime.strftime(next_day, '%m/%d/%Y')
        dates.append({'arrive': arrive_s, 'depart': next_day_s})
    return dates


texts: Algorithm to compute the n-th derivative of a polynomial in Python

texts:
As a personal exercise, I'm trying to write an algorithm to compute the n-th derivative of an ordered, simplified polynomial (i.e., all like terms have been combined). The polynomial is passed as an ordered list where the i-th index corresponds (though is not equivalent) to the coefficient of x to the n-th power.

Example:
Take the derivative of: \$3x^3 + 5x^2 + 2x + 2\$ -> [3,5,2,2]

1st derivative: \$9x^2 + 10x + 2\$
2nd derivative: \$18x + 10\$
3rd derivative: \$18\$
4th...n-th derivative: \$0\$

Implementation in Python:

def poly_dev(poly, dev):
    """
    :param poly: a polynomial
    :param dev: derivative desired, e.g., 2nd
    """

    c = 0                                # correction
    r = dev                              # to remove
    while dev > 0:
        for i in range(1, len(poly)-c):
            poly[i-1] = (len(poly)-(i+c))*poly[i-1]
        dev -= 1                                    # I suspect this
        c += 1                                      # this can be simplified
    return poly[:-r]

E.g., print(poly_dev(poly = [3,5,2,2], dev = 2))

I have a math background, but I'm only starting to learn about computer science concepts like Complexity Theory.

I've intentionally tried to avoid reversing a list, as I know that can be expensive. What other steps can I change to decrease this procedure's run time?


texts: MailboxProcessor and prioritized messages

texts:
I'm trying to create an agent that holds on to Data and does further work with it upon receiving the Work message. Update is sent to the agent several times a minute, may potentially run longer than 10 seconds and signals the need to update Data.

Because update takes a lot of time, I've decided to do it on the background so as not to block the processing of Work messages. One option is to do the updating elsewhere and receive the new version as, say, NewData of Data message. However, I'd like to use new data as soon as possible, skipping the backlog of Work messages (MailboxProcessor.Scan would surely work, but I want to avoid it), so I keep the computation (actually, I had to resort to using a Task, because I could not find a way to check the status of an Async) as part of State and check it on every cycle.

Is there a better way to achieve the same behavior? I appreciate any comments and suggestions.

type Data = unit

type Message =
    | Work
    | Update

type State = { Data: Data; Updating: System.Threading.Tasks.Task<Data> option }

let update data = async {
    do! Async.Sleep 5000
    return data }

let work data = async {
    do! Async.Sleep 10 }

let mb = MailboxProcessor.Start (fun inbox ->
    let rec loop state = async {
        let state =
            match state.Updating with
            | Some t when t.IsFaulted ->
                { state with Updating = update state.Data |> Async.StartAsTask |> Some } // retry
            | Some t when t.IsCompleted ->
                { Data = t.Result; Updating = None }
            | _ -> state

        let! msg = inbox.Receive ()

        match msg with
        | Work ->
            work state.Data |> Async.Start
            return! loop state
        | Update ->
            match state.Updating with
            | Some _ -> return! loop state // old update still in progress, ignore
            | None -> return! loop { state with Updating = update state.Data |> Async.StartAsTask |> Some }
    }

    loop { Data = (); Updating = None }
)


texts: Load JSON from server using jQuery and display it in html5

texts:
I am just starting with JavaScript and jQuery, so I appreciate your help!

I want to read items from a JSON file like this:

{
  "items": [
    "this",
    "that"
  ]
}

My code (inspired by a number of stackoverflow and jQuery reference example code) looks like this:

    <!DOCTYPE html>

<meta charset="utf-8">
<title></title>

And it works. Yay.

My questions:

Is that more or less ok what I nitted? What can be enhanced?
Why does the commented-out section not work? I took this from https://api.jquery.com/jQuery.getJSON/


texts: Detecting capturing moves that pawns can make, in both directions

texts:
I have this function that contains two similar if statements that is kind of hard to re-factor.

I am saying this because these two share a significant portion of duplicated code, but because of the part where it differs slightly, like board[startX + 1][startY - 1] and board[startX - 1][startY - 1], I find it difficult to re-factor it efficiently.

In other words, I can surely re-factor this by creating another function that contains the common parts, but I am afraid of creating a few more if blocks inside that function and making the code dirtier.

Any advice for refactoring this kind of code?

public boolean hasCapturableEnemy(Piece[][] board, int startX, int startY, int endX, int endY) {

    //If the Pawn belong to the Upper Team (Faces downward)
    if(board[startX][startY] != null && board[startX][startY].getTeam() == Player.UP) {
        //If a Piece exists on a diagonally adjacent tile, return true
        if(startX - endX == -1 && Math.abs(startY - endY) == 1) {
            if( (board[startX + 1][startY - 1] != null && board[startX + 1][startY - 1].getTeam() != Player.UP) ||
                    (board[startX + 1][startY + 1] != null && board[startX + 1][startY + 1].getTeam() != Player.UP)) {
                return true;
            }
        }
    }

    if(board[startX][startY] != null && board[startX][startY].getTeam() == Player.DOWN) {
        //If the Pawn belongs to the Down Team (Faces upward)

        if(startX - endX == 1 && Math.abs(startY - endY) == 1) {
            //If a Piece exists on a diagonally adjacent tile, return true
            if( (board[startX - 1][startY - 1] != null && board[startX - 1][startY - 1].getTeam() != Player.DOWN) ||
                    (board[startX - 1][startY + 1] != null && board[startX - 1][startY + 1].getTeam() != Player.DOWN)) {
                return true;
            }
        }
    }

    return false;

}


texts:
I have this brute force code, where you input a password and runs through combinations of numbers, lowercase and uppercase letters, and special characters until it match the password given.

The problem with it, is that it took about 2 days just to crack the password "password".

What is a way that I can speed up this process and get the passwords faster? Is there a way I can implement multi-threading to speed up the process?

All I'm really asking is, is there a better way for the program to run through all of the characters and match the password faster?

//This program is used for a school project, where I have to create a list of commonly used passwords and run them through the program and see how long it take for the program to crack them. *I would like to get the best result possible and speed up the process*

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Text;

  namespace Bruteforce
 {
   class Program
 {
   //define likely password characters
    static char[] Match =            {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j' ,'k','l','m','n','o','p',
                        'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','C','L','M','N','O','P',
                        'Q','R','S','T','U','V','X','Y','Z','!','?',' ','*','-','+'};
//your password
static string FindPassword;
static int Combi;
static string space;
static int Characters;

static void Main(string[] args)
{
    Console.Title = "Brute Force";

    Console.ForegroundColor = ConsoleColor.Green;
    Console.WriteLine("ALL FILES LOADED...");
    Console.ForegroundColor = ConsoleColor.White;

    space = " ";
    int Count;

    //user types in a password

    Console.WriteLine("Welcome to BRUTE FORCE");
    Console.WriteLine("This program was crated by Nick");
    Console.WriteLine(space);
    Console.WriteLine("Enter your Password:");

    //initialize your password
    FindPassword = (Console.ReadLine());
    Characters = FindPassword.Length;
    Console.Clear();

    DateTime today = DateTime.Now;
    today.ToString("yyyy-MM-dd_HH:mm:ss");
    Console.WriteLine(space);
    Console.WriteLine("START:\t{0}", today);

    for (Count = 0; Count <= 15; Count++)
    {
        Recurse(Count, 0, "");
    }
}

static void Recurse(int Lenght, int Position, string BaseString)
{
    int Count = 0;

    for (Count = 0; Count < Match.Length ; Count++)
    {
        Combi++;
        if (Position < Lenght - 1)
        {
            Recurse(Lenght, Position + 1, BaseString + Match[Count]);
        }
        if (BaseString + Match[Count] == FindPassword)
        {
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine("Your password is: " + FindPassword);
            Console.WriteLine("Your password is: " + Characters + " character(s) long");
            Console.ForegroundColor = ConsoleColor.White;
            DateTime today = DateTime.Now;
            today.ToString("yyyy-MM-dd_HH:mm:ss");
            Console.WriteLine(space);
            Console.WriteLine("END:\t{0}\nCombi:\t{1}", today, Combi);
            Console.ReadLine();
            Environment.Exit(0);
        }
    }
  }
 }
 }


texts: Animation Template Method for Snake Game

texts:
I have recently finished my first iteration of a template method implementation for a JavaScript canvas animation of the snake game. However, I would love for the community to critique this code and inform me where I am going wrong?

In my opinion, a bad smell for me is the number of times this is used throughout. Furthermore, the number of properties in the SnakeAnimator implementation (Note: These properties are passed upon extension).

const VectorFactory = require("./model/vector");
const _ = require("lodash");
const Animator = require('./animators/animator');

let SnakeAnimator = {
    vectors: [],
    canvas: null,
    xAdd: null,
    canvas_context: null,
    canvas_height: 0,
    canvas_width: 0,

    initialise: function (options) {
        this.canvas_context = this.canvas.getContext("2d");
        this.canvas_width = this.canvas.width = window.innerWidth;
        this.canvas_height = this.canvas.height = window.innerHeight;
        this.canvas_context.strokeStyle = options.colour;
    },

    draw: function () {
        this.canvas_context.beginPath();

        for( let i = 0; i < this.vectors.length; i++) {
            this.canvas_context.moveTo(this.vectors[i][0].x, this.vectors[i][0].y);
            this.canvas_context.lineTo(this.vectors[i][1].x, this.vectors[i][1].y);
        }

        this.canvas_context.stroke();
        this.canvas_context.closePath();
    },

    update: function() {
        for (let i = 0; i < this.vectors.length; i++) {
            this.vectors[i][0].x = this.vectors[i][0].x + this.xAdd;
            this.vectors[i][1].x = this.vectors[i][1].x + this.xAdd;
        }
    },

    clear: function() {
        this.canvas_context.clearRect(0, 0, this.canvas_width, this.canvas_height);
    },

    addSnake: function() {
        this.vectors.push([VectorFactory(0, this.canvas_height / 2), VectorFactory(this.xAdd, this.canvas_height / 2)]);
    }
};
_.extend(SnakeAnimator, Animator);

module.exports = SnakeAnimator;

The template method implementation is as follows:

let Animator = {
    animate: function() {
        this.update();
        this.clear();
        this.draw();
    }
};

module.exports = Animator;

I would greatly appreciate any feedback on how I can improve this / my overall knowledge of JavaScript applications should be structured as I have struggled with this for a while.


texts: Leetcode #91 - Number of ways to decode a string

texts:
I'm working on problem 91 on Leetcode.com called Decode Ways and I've successfully managed to get a working recursive solution but it results in Time Limited Exceeded (TLE). I'm new to utilizing memoization and I've been unable to discover how to properly memoize my results at each recursive step and check if I've already solve the sub-problem.

Prompt:

  A message containing letters from A-Z is being encoded to numbers using the following mapping:

  'A' -> 1   'B' -> 2   ...   'Z' -> 26

  Given a non-empty string containing only digits, determine the total
  number of ways to decode it.

Working Code (TLE):

public int NumDecodings(string s)
{
    if (s == null || s.Length == 0) return 0;
    // int[] dp = new int[s.Length + 1];
    // for (int i = 0; i < dp.Length; ++i) dp[i] = -1;
    // dp[0] = 1;
    // dp[1] = Decode(s, 0, 1, dp) + Decode(s, 0, 2, dp);
    int jump1 = Decode(s, 0, 1);
    int jump2 = Decode(s, 0, 2);
    return jump1 + jump2;
    // return dp[1];
}

public int Decode(string s, int i, int len)
{
    if (i + len - 1 >= s.Length)
        return 0;

    // if (dp[i] > -1)
    //     return dp[i];

    int sub = Convert.ToInt32(s.Substring(i, len));
    if (sub > 26 || sub < 1 || s.Substring(i, len)[0] == '0')
        return 0;
    else if (i + len - 1 == s.Length - 1 && sub < 27 && sub > 0)
        return 1;

    int jump1 = i + len - 1 + 1 < s.Length ? Decode(s, i + len, 1) : 0;
    int jump2 = i + len - 1 + 2 < s.Length ? Decode(s, i + len, 2) : 0;
    // dp[i] = jump1 + jump2;

    return jump1 + jump2;
    // return dp[i];
}


texts: Purchase tickets calculation with JavaScript

texts:
I'm creating a page where users can purchase an adult, child or senior ticket, each with it's own pricing.

Here's the code for review. Please let me know if there are ways to improve upon this code.

// declare all variables
   var adultQty = document.getElementById('quantityAdult');
   var childQty = document.getElementById('quantityChild');
   var seniorQty = document.getElementById('quantitySenior');
   var submitBtn = document.getElementById('submitButton');
   var outputPara = document.getElementById('totalPrice');

   // generic function that takes in quantity and multiplies with appropriate price
   function calcPrice(qty, price){
     return qty * price;
   }

   // generic function that outputs final price and amout it tickets purchased
   function getMessage(qty, total){
     return outputPara.innerHTML = 'You purchased ' + qty + ' ticket(s) and your total price is $' + total + '

' + '<button>Proceed To Checkout</button>';
   }

   submitBtn.addEventListener('click', function() {

    if(adultQty.value === '0' && childQty.value === '0'  && seniorQty.value === '0'){
      alert('Please purchase at least 1 ticket');
    } else {
      var totalAdult = calcPrice(adultQty.value, 49);
      var totalChild = calcPrice(childQty.value, 20);
      var totalSenior = calcPrice(seniorQty.value, 30);

      var totalPrice = totalAdult + totalChild + totalSenior;
      var totalTix = parseInt(adultQty.value) + parseInt(childQty.value) + parseInt(seniorQty.value);

      getMessage(totalTix, totalPrice);
    }

   });

Purchase your tickets online!

$49 - Adult

$20 - Child

$30 - Senior

Quantity: <input type="text" id="quantityAdult" value="0"> Adult

Quantity: <input type="text" id="quantityChild" value="0"> Child

Quantity: <input type="text" id="quantitySenior" value="0"> Senior

<button type="submit" id="submitButton">Submit</button>


texts: Dotty 0.19 (Scala 3) features: contextual abstractions

texts:
tl;dr

I tried to write some as general and as feasible as possible code where entities are able to communicate with other entities of the same type or of different types, allowing for the recipient to reply to the sender.

Details :

Trying to work with some of the new contextual abstractions e.g. given and extension methods
Have a general Entity type to enable sending and receiving messages
To be able to send message types different from what I can receive.
To have the ability to reply to a received message
To be able to send messages between 2 instances of the same type T given the presence of Entity[T, TMsg]
To be able to send messages between different types T and U given the presence of both Entity[T, TMsg] and Entity[U, UMsg]
Have a Person example capable of receiving Strings that can do all this

Concerns I have regarding the code :

Feels more complex, more difficult to understand than it needs to be
Type parameters are often just single character ones, but I felt like it would render the code totally unreadable, now however I have very long type signatures

The code

trait Entity[Me, InMsg]
  def (me: Me) send[Receiver, OutMsg] (receiver: Receiver, msg: OutMsg) (given Entity[Receiver, OutMsg], Entity[Me, InMsg]): Unit
  def (me: Me) receive[Sender, ReplyMsg] (sender: Sender, msg: InMsg) (given Entity[Sender, ReplyMsg]): Unit
  def (me: Me) name(): String

class Person(private val name: String)

object Person

  given Entity[Person, String]

    def (me: Person) send[Receiver, OutMsg] (receiver: Receiver, msg: OutMsg) (given Entity[Receiver, OutMsg], Entity[Person, String]): Unit =
      receiver.receive[Person, String](me, msg)

    def (me: Person) receive[Sender, ReplyMsg] (sender: Sender, msg: String) (given Entity[Sender, ReplyMsg]): Unit =
      println(f"I'm ${me.name} and I just RECEIVED a msg saying $msg from ${sender.name()}")

    def (me: Person) name () =
      me.name

@main def m = Person("AAA").send(Person("BBB"), "Hi")