texts:
Below is code i used to call Api and display the "Status" results in web page.

my senior told me that code is completely mess and need to improve so that it should be easy to understand for others. but i am not getting how i can refactor below code ? is mixing php and html code is bad ? i really need to mix those html and php to get the results that i needed .please help me for this....

<button type= "button" class="call">Show Status</button>

               ORDERID
               Status

<?php
$tabindex = 1;

if (!empty($orderrecords))
    {
    foreach($orderrecords as $k => $v)
        { ?>

        <?php
        $hide = '';
        $data['username'] = 'admin';
        $data['password'] = 'admin123';

        $url = 'https://plapi.ecomexpress.in/track_me/api/mawbd/?awb=awbnumber&order=' . $orderrecords[$k]["order_id"] . '&username=admin&password=admin123';
        $ch = curl_init();
        // some curl code
        $res = explode("\n", $output);
        if (!isset($res[13]))
            {
            $res[13] = null;
            }

        $status = $res[13];
?>

<tr class="table-row" id="table-row-<?php echo $orderrecords[$k]["id"]; ?>" tabindex="<?php echo $tabindex; ?>">

<input onclick="assignorderids('<?php echo $orderrecords[$k]["order_id"]; ?>')" type="checkbox" name="assigneeid" id="assigneeid-<?php echo $orderrecords[$k]["order_id"]; ?>" value="<?php echo $orderrecords[$k]["order_id"]; ?>">

<?php echo $orderrecords[$k]["order_id"]; ?>
<?php echo $status; ?>

 <?php
 $tabindex++;
 }
    } ?>


texts: Getting the shortest sequence to reach a number

texts:
I want to get the shortest sequence to reach a number.

Rules:

A[0] is always 1
Either A[i] = A[i-1]*2 or A[i] = A[i-1]+1

For example, if my input number is 17, my output should be 6, because

A[0]=1, A[1]=2, A[2]=4, A[3]=8, A[4]=16, A[5]=17

The following code is not working properly for few inputs, such as 15.

public static int GetMinimumSequence(int n)
        {
            if (n == 1)
                return 1;

            int count = 1;
            int temp = 1;
            for (int i = 2; i <= n; i++)
            {
                temp = temp * 2;
                if (temp >= n)
                {
                    temp = temp/2;
                    temp = temp + 1;
                }
                count++;
                if(temp == n)
                    break;
            }
            return count;
        }


texts:
I have two processes. First (main) one is "dealing" with user stuff. Second one is doing some internal stuff and should update its internal state according to user actions. So I've created two pipes. By one I send actions to subprocess, from another I get messages that emits this subprocess.

I wonder about two things:

Is this architecture clean enough?
Is my usage of python's typing is good?

import time
from multiprocessing import Pipe
from multiprocessing import Process
from multiprocessing import Queue
from typing import Any
from typing import Dict
from typing import List

class Counter(object):
    _i: int

    def __init__(self):
        super().__init__()
        self._i = 0

    def drop(self):
        self._i = 0

    def inc(self):
        self._i += 1

    @property
    def i(self) -> int:
        return self._i

class Action(object):
    _data: Dict[str, Any]
    _label: str

    def __init__(self, label: str, data: Dict[str, Any]):
        super().__init__()
        self._data = data
        self._label = label

    @property
    def data(self) -> Dict[str, Any]:
        return self._data

    @property
    def label(self) -> str:
        return self._label

class CounterProcess(Process):
    _counters: Dict[str, Counter]
    _in_queue: Queue
    _out_queue: Queue

    def __init__(self, in_queue: Queue, out_queue: Queue):
        super().__init__()
        self._in_queue = in_queue
        self._out_queue = out_queue
        self._counters = {}
        self._counters["a"] = Counter()
        self._counters["b"] = Counter()

    def run(self):
        for i in range(15):
            time.sleep(0.5)
            self._process_actions()
            self._update()
            self._emit()

    def _dispatch_action(self, action: Action):
        if action.label != "drop":
            return
        if "label" not in action.data:
            return
        self._drop_counter(action.data["label"])

    def _drop_counter(self, label: str):
        if label in self._counters:
            self._counters[label].drop()

    def _emit(self):
        msg = {}
        for c in self._counters:
            msg[c] = self._counters[c].i
        self._out_queue.put(msg)

    def _get_actions(self) -> List[Action]:
        actions = []
        while not self._in_queue.empty():
            actions.append(self._in_queue.get(False))
        return actions

    def _process_actions(self):
        for action in self._get_actions():
            self._dispatch_action(action)

    def _update(self):
        for c in self._counters.values():
            c.inc()

def print_output(queue: Queue, to_receive: int, dt: float):
    while to_receive > 0:
        if not queue.empty():
            print(queue.get(False))
            to_receive -= 1
        time.sleep(dt)

if __name__ == '__main__':
    oq = Queue()
    iq = Queue()

    proc = CounterProcess(iq, oq)
    proc.start()

    print_output(oq, 5, 0.1)

    iq.put(Action(label="drop", data=dict(label="a")))

    # Try to send incorrect actions
    iq.put(Action(label="notdrop", data=dict(lbl="b")))
    iq.put(Action(label="drop", data=dict()))

    print()
    print_output(oq, 5, 0.1)

    iq.put(Action(label="drop", data=dict(label="b")))

    print()
    print_output(oq, 5, 0.1)

    proc.join()


texts:
The following is code on "prime factors of a number". Any suggestions to optimize the code? It runs for a pretty long time for inputs like 35068499. I also want the code to take 10 digit numbers as input.

#include<stdio.h>
void pf(long);
void main()
{
    printf("Enter a number: ");
    scanf("%ld",&n);
    pf(n);
}
void pf(long n)
{
    long i,x;
    while(n%2==0)
    {
        printf("2\n");
        n=n/2;
    }
    x=3;
    while(x<=n)
    {
        for(i=2;i<x;i++)
        {
            if(x%i==0)
            {
                goto abc;
            }
        }
        while(n%x==0)
        {
            printf("%ld\n",x);
            n=n/x;
        }
        abc:
            x=x+2;
    }
}


texts:
I'm building an ASP.NET MVC app and would like some feedback for my way to query/execute statements to the ORM.

I'm using Fluent NHibernate, and have mixed the UoW provided by NHibernate with a Command pattern.

ICommand.cs (Core layer)

using NHibernate;

namespace MyDemon.Core.Commands
{
    public interface ICommand<out TResult>
    {
        TResult Execute(ISession session);
    }
}

ISessionExtensions.cs (Core layer)

using NHibernate;

namespace MyDemon.Core.Commands
{
    public static class ISessionExtensions
    {
        public static TResult Execute<TResult>(this ISession session, ICommand<TResult> unitOfWork)
        {
            return unitOfWork.Execute(session);
        }
    }
}

GetUserById.cs (Core layer)

using NHibernate;

namespace MyDemon.Core.Commands.User
{
    using Entities;

    public class GetUserById : ICommand<User>
    {
        public int UserId { get; set; }

        public GetUserById(int userId)
        {
            UserId = userId;
        }

        #region Implementation of IUnitOfWork<out User>

        public User Execute(ISession session)
        {
            return session.Get<User>(UserId);
        }

        #endregion
    }
}

AccountController.cs (Web layer)

[AjaxOnly]
[Authorize]
public ActionResult Details(int id)
{
    User userToGet = _session.Execute(new GetUserById(id));

    if (userToGet == null)
    {
        return PartialView("Partials/UserNotFound");
    }

    DetailsUserViewModel userToViewModel = Mapper.Map<User, DetailsUserViewModel>(userToGet);

    return PartialView("Partials/Details", userToViewModel);
}

What do you think? A clever design, or just another "too-much code" approach?


texts: React breadcrumbs component implementation

texts:
I've written a breadcrumbs component (RouteBreadcrumbs) that has the following features/behavior:

Takes in an array of labels for each breadcrumb (ex: ['Settings', 'System settings', 'Display']. The component displays these labels in
the order that they're placed in in the array.
Assumes that the last label in the array represents the currently viewed page. For the rest of the labels that come before it, the user
can click on one in order to navigate to that page.
Gets the current path it is rendered in and parses it in order to assign the correct path for each breadcrumb (except the last one)
If the current path does not contain enough "subpaths" to satisfy the number of labels passed in, I've chosen not to render the component. For example, the component would not render if the current path was only /system-settings/display when labels contained three items.

Ultimately, the component would look like this when rendered (I haven't yet implemented the arrows between each breadcrumb):
Settings > System settings > Display

In this scenario, "Display" would be the currently viewed page. And the user would be able to click on "Settings" or "System settings" in order to jump to those respective pages.
I'd love to get feedback on my implementation. I'm also interested in learning more about best coding practices and whether there are any strong code smells in my component (and if there is one, why it is considered a code  smell).
Some areas that I think might be code smells but am not really sure if they are or why they are:

Calling pathNameIdx-- both inside the while loop and then again once the loop is exited
Having a return statement in multiple places in my component (in my case, in just two places)
Using a regular for loop instead of other forms like for..of, for..in, or .forEach.

import React from "react";
import { useHistory, useLocation } from "react-router-dom";

const RouteBreadcrumbs = ({labels = []}) => {
    const location = useLocation();
    const history = useHistory();
    const pathName = location.pathname;

    const numBackslash = (pathName.match(/\//g) || []).length;
    if (numBackslash < labels.length) {
        return null;
    }

    let breadcrumbPaths = [];
    let pathNameIdx = pathName.length - 1;
    for (let i = labels.length - 1; i > 0 ; i--) {
        while ((pathName[pathNameIdx] !== "/")) {
            console.assert(pathNameIdx >= 0, "pathNameIdx is no longer a valid index");
            pathNameIdx--;
        }

        const newPath = pathName.substring(0, pathNameIdx);
        breadcrumbPaths = [newPath, ...breadcrumbPaths];
        pathNameIdx--;
    }

    return (

            {labels.map((label, idx) => <h5 key={idx} onClick={idx < breadcrumbPaths.length ? () => history.push(breadcrumbPaths[idx]) : null} className={"label2"}>{label}
)}

    )
};

```


texts: Is there a 'better' way to find files from a list in a directory tree

texts:
I have created a list of files using find, foundlist.lst.

The find command is simply find . -type f -name "<search_pattern>" > foundlist.lst

I would now like to use this list to find copies of these files in other directories.

The 'twist' in my requirements is that I want to search only for the 'base' of the file name. I don't want to include the extension in the search.

Example:

./sort.cc is a member of the list. I want to look for all files of the pattern sort.*

Here is what I wrote. It works. It seems to me that there is a more efficient way to do this.

./findfiles.sh foundfiles.lst /usr/bin/temp

#!/bin/bash
# findfiles.sh
if [ $# -ne 2 ]; then
    echo "Need two arguments"
    echo "usage: findfiles <filelist> <dir_to_search>"
else
    filename=$1
    echo "$filename"
    while read -r line; do
        name=$line
        # change './file.ext' to 'file.*'
        search_base=$( echo ${name} | sed "s%\.\/%%" | sed "s/\..*/\.\*/" )
        find $2 -type f -name $search_base
    done < $filename
fi


texts: Smoothen page transition for mobile devices

texts:
I have next/previous buttons on my site and all they do is slide sections of the site from left to right and vice versa, it is smooth and looks good on a desktop but on mobile devices it is a bit slow and jumpy.

if (type == "prev") {
    $(this).hide('drop', { direction: 'right' }, 600, function () { $('#dv' + page).show('drop', { direction: 'left' }, 600), $("input:text:visible:not([readonly]):first").focus(); });
} else {
    $(this).hide('drop', { direction: 'left' }, 600, function () { $('#dv' + page).show('drop', { direction: 'right' }, 600), $("input:text:visible:not([readonly]):first").focus(); });
}

Uses the built in jQuery functions to slide the current page out and the next/previous page in based on the current page number, then sets the focus on the first input box.

This was as simple as I could think to do it but maybe there is a better smoother way to do left/right transitions?


texts:
I'm mainly looking at usage of Dapper, but in general, any comments relating SQL -> C# object mapping best practices would be appreciated.

I've got two super simple objects I'm working with:

public class Subcategory
{
    public Guid Id { get; set; }
    public Guid CategoryId { get; set; }
    public string Name { get; set; }
}

public class Category
{
    public Category()
    {
        Subcategories = new List<Subcategory>();
    }

    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<Subcategory> Subcategories { get; set; }
}

Id for both of them is set by the db on insert via T-SQL's newsequentialid().

I'm writing repository classes for each of the objects that conform to the following interface (actually implemented via an abstract class):

public interface IMaintanceRepository<T> where T: class
{
    Guid Create(T toCreate);
    T Read(Guid id);
    T Update(T toUpdate);
    void Delete(Guid id);
}

Right now, I'm trying to write the Update method in the Category repository. I have the following written, but I'm not sure if it's the most performant Dapper code as written.

public override Category Update(Category toUpdate)
{
    var deleteRemovedSubcategories = @"
        DELETE FROM dbo.Subcategories
        WHERE CategoryId = @Id
            AND Id NOT IN @Ids";

    var addNewSubcategories = @"
        INSERT INTO dbo.Subcategories (CategoryId, Name)
        VALUES (@CategoryId, @Name)";

    var updateExistingSubcategories = @"
        CREATE TABLE #subcategories (
            Id uniqueidentifier NOT NULL,
            CategoryId uniqueidentifier NOT NULL,
            Name varchar(50) NOT NULL
        );

        INSERT INTO #subcategories VALUES (@Id, @CategoryId, @Name);

        UPDATE s1
        SET s1.CategoryId = s2.CategoryId, s1.Name = s2.Name
        FROM dbo.Subcategories s1
        INNER JOIN #subcategories s2
        ON s1.Id = s2.Id;

        DROP TABLE #subcategories;";

    var updateCategory = @"
        UPDATE dbo.Categories
        SET Name = @Name
        OUTPUT INSERTED.*
        WHERE Id = @Id;

        SELECT * FROM dbo.Subcategories WHERE CategoryId = @Id";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Execute(deleteRemovedSubcategories, new { Id = toUpdate.Id, Ids = toUpdate.Subcategories.Select(s => s.Id) });
        connection.Execute(addNewSubcategories, toUpdate.Subcategories.Where(s => s.Id == Guid.Empty));
        connection.Execute(updateExistingSubcategories, toUpdate.Subcategories);
        using (var multi = connection.QueryMultiple(updateCategory, toUpdate))
        {
            var category = multi.ReadSingle<Category>();
            category.Subcategories = multi.Read<Subcategory>().ToList();
            return category;
        }
    }
}

Is there any suggested improvements to doing something like this?


texts:
Student http://semisalsaja.com/sekolah/student.asmx?WSDL
- studentList

Mentor http://semisalsaja.com/sekolah/mentor.asmx?WSDL
- mentorList

study http://semisalsaja.com/sekolah/study.asmx?WSDL
- studyList

I'm trying to get data from some SOAP resources (mentioned above):

class SchoolSoap {
    protected $_config = array();
    public $_soap, $_error, $_params, $_result;
    public function __construct($params = array()) {
        $this->_config = $params;
        try {
            $this->_soap = new SoapClient($this->_config['url'], array('trace' => 1, 'exception' => 1));
        } catch (Exception $e) {
            $this->_error = $e->getMessage();
        }
    }
    public function actionSoap($function) {
        try {
            $result = $this->_soap->__soapCall($function, array('parameters' => $this->_params));
            $this->_result = $result;
            return true;
        } catch (Exception $e) {
            $this->_error = $e->getMessage();
            return false;
        }
    }
    public function setParam($params) {
        $this->_params = $params;
        return $this;
    }
}

The 1st class is for calling SOAP and it will be called/ instanced from static classes.

class StudentHelper {
    public static function getStudentList($config, $params, SchoolSoap $soap = null) {
        $function = 'studentList';
        if ($soap == null) {
            $soap = new SchoolSoap($config);
        }
        $result = $soap->setParam($params)->actionSoap($function);
        if ($result == false) {
            return false;
        } else {
            return $soap->_result->$function;
        }
    }
}

class MentorHelper {
    #similar with class StudentHelper
}

class StudyHelper {
    #similar with class StudentHelper
}

The next next classes (I called Helper) are static class. I created resources Student, Mentor, Study, for every SOAP. For example, in class StudentHelper, there is a method named getStudentList that will get the student's data, and it will be called from a function (next code). class Mentor and Study are similar.

Usage

function printStudentList() {
    $config = array(
        'url' => 'http://semisalsaja.com/sekolah/student.asmx?WSDL',
        'username' => 'user123',
        'key' => 'abcdefghij'
        );
    $params = array('start' => 1, 'limit' => 20);
    return StudentHelper::getStudentList($config, $params);
}

Next is function to call Static class (example, call StudentHelper).  I passed configs and params in this function, and it will return bool false if soap failed and data of student if soap succeeded.

$student_list = printStudentList();
print_r($student_list);

Here I call parse function into variable, then print the variable.

Is my design correct with the concept of OOP in PHP? Any suggestion for me to make it better? I'm still new to learning about programming, especially OOP.


texts: Estimate area of cropped circle with Monte Carlo

texts:
I looking around and not finding anything, I developed a simple function for estimating the area of a possibly cropped circle inside a frame. It uses a very basic MC implementation.

It is pretty fast but I think it could be made simpler. Any thoughts are appreciated.

import numpy as np
from scipy.spatial import distance

def circFrac(cx, cy, rad, x0, x1, y0, y1, N_tot=100000):
    """
    Use Monte Carlo to estimate the fraction of the area of a circle centered
    in (cx, cy) with a radius of 'rad', that is located within the frame given
    by the limits 'x0, x1, y0, y1'.
    """
    # Generate a square containing the circle.
    xmin, xmax = cx - rad, cx + rad
    ymin, ymax = cy - rad, cy + rad

    # Generate 'N_tot' uniform random points inside that square.
    xr = np.random.uniform(xmin, xmax, N_tot)
    yr = np.random.uniform(ymin, ymax, N_tot)

    # Obtain the distances of those points to the center of the circle.
    dist = distance.cdist([(cx, cy)], np.array([xr, yr]).T)[0]

    # Find the points within the circle.
    msk_in_circ = dist < rad

    # Find the points that are within the frame, from the points that are
    # within the circle.
    msk_xy = (xr[msk_in_circ] > x0) & (xr[msk_in_circ] < x1) &\
        (yr[msk_in_circ] > y0) & (yr[msk_in_circ] < y1)

    # The area is the points within circle and frame over the points within
    # circle.
    return msk_xy.sum() / msk_in_circ.sum()

# Define the (x, y) limits of the frame
x0, x1 = 0., 1.
y0, y1 = 0., 1.

for _ in range(10):
    # Random center coordinates within the frame
    cx = np.random.uniform(x0, x1)
    cy = np.random.uniform(y0, y1)
    # Random radius
    rad = np.random.uniform(.05, .5)
    print("({:.2f}, {:.2f}), {:.2f}".format(cx, cy, rad))

    frac = circFrac(cx, cy, rad, x0, x1, y0, y1)

    print("Fraction of circle inside frame: {:.2f}".format(frac))


texts: Parse a config-file and add to command-line-arguments using argparse in Python

texts:
I am trying to parse the command line arguments using argparse, and if the user specifies a yaml file for the config-file, add those arguments to the args from argparse

import argparse
import yaml
from pprint import pprint

class CLI(object):

    def execute(self):
        self.create_parser()
        self.options = self.parse_args()
        pprint(self.options)

    def create_parser(self):
        self.parser = argparse.ArgumentParser()

        g = self.parser.add_argument_group('Device Targets')
        g.add_argument(
            '--config-file',
            dest='config_file',
            type=argparse.FileType(mode='r'))
        g.add_argument('--name', default=[], action='append')
        g.add_argument('--age', default=[], action='append')
        g.add_argument('--delay', type=int)
        g.add_argument('--stupid', dest='stupid', default=False, action='store_true')

    def parse_args(self):
        args = self.parser.parse_args()
        if args.config_file:
            data = yaml.load(args.config_file)
            delattr(args, 'config_file')
            for key, value in data.items():
                if isinstance(value, list):
                    for v in value:
                        getattr(args, key, []).append(v)
                else:
                    setattr(args, key, value)
        return args

cli = CLI()
cli.execute()

If my config-file has the following data:

name: [Jill, Bob]
age: [21, 33]
delay: 30

And I run my code like this:

python test.py --conf args.txt --name 'Mark'

I get this for the output:

Namespace(age=[21, 33], delay=30, name=['Mark', 'Jill', 'Bob'], stupid=False)

So, it works, but is it good code?


texts: TamperMonkey script to add a button to Jira

texts:
The below script detects whether we are in Jira, and if it is run in Jira it will add a button. Clicking that button will use the REST API of Jira to create an issue, and navigate to the recently created issue.

// ==UserScript==
// @name         Tell Jira I did a thing
// @namespace    http://demuyt.net/
// @version      0.1
// @description  try to take over the world!
// @author       Tom J Demuyt
// @match        https://jira*
// @match        https://jira.it.aenetworks.com/*
// @grant        none
// ==/UserScript==

//Documentation
//https://docs.atlassian.com/software/jira/docs/api/REST/7.12.0/
//https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/

(function() {
    'use strict';

    let userName = "";
    let projectCode = "CF";
    let fixVersion = "15484";

    //The id of the create button is `create_link`, dont show up if that button is not there
    let createButton = document.getElementById('create_link');
    //Leave quietly if we cannot find that button
    if(!createButton){
        return;
    }

    //Get the parent (
) of the
 that holds the
    let createButtonParent = createButton.parentNode.parentNode;

    //Add a button for the user
    var node = document.createElement("LI");
    node.innerHTML = '

Log activity

';
    createButtonParent.appendChild(node);

    //Get a reference to the button
    let idat = document.getElementById("idat");

    //Make it listen to clicks;
    idat.addEventListener("click", recordTheThing);
    //Try and build a ticket
    function recordTheThing(){
        //Prep a call to Jira
        let xhr = new XMLHttpRequest(),
            url = '/rest/api/2/issue/';
        //Ask what the user did
        var thing = window.prompt("Describe the activity performed?","");
        //Get out if the user got cold feet
        if(!thing){
            return;
        }
        //Start prepping the http request
        xhr.open('POST', url, true);
        //Use JSON since we will not fill in a form
        xhr.setRequestHeader("Content-Type", "application/json");
        //Prep the navigation to the new issue
        xhr.onreadystatechange = function () {
            debugger;
            //readyState:3
            //response: {"id":"125529","key":"CF-10282","self":"https://jira.it.aenetworks.com/rest/api/2/issue/125529"}
            //HTTP/REST return code 201 means created
            if (xhr.readyState === 4 && xhr.status === 201) {
                var json = JSON.parse(xhr.responseText);
                window.location.href = 'https://jira.it.aenetworks.com/browse/' + json.key;
            }
        };
        //The heart of the thing
        var data = JSON.stringify({
            "fields": {
                "project":
                {
                    "key": projectCode
                },
                "summary": thing,
                "description": thing,
                "issuetype": {
                   "name": "Task"
                },
                "assignee": {
                   "name": userName
                },
                //15484 -> Busines As Usual
                "fixVersions": [{ "id": fixVersion}],
            }
        });
        //Finalize the REST call
        xhr.send(data);

    }//Record the thing

    //Find from the load/start the user id
    let xhr = new XMLHttpRequest(),
    url = '/rest/api/2/mypermissions/';
    //Prep to extract the username from the call header
    //200 -> OK
    xhr.onreadystatechange = function () {
      if(xhr.readyState == 4 && xhr.status == 200){
        userName = xhr.getResponseHeader("X-AUSERNAME");
      }
    }
    //Shoot and pray
    xhr.open('GET', url, true);
    xhr.send();
})();

Please review for cleanliness, readability, standards, the usual..


texts: Download file and connect: if one of them fails, go to step one

texts:
My program....

Downloads a file
Connects to a server

If one of these operations were to fail, the program stalls for a minute and goes back to step one.

So, I would avoid recursion and the use of global variables. I think I did the first one right, but I need help to avoid the second one. What would I do if I need to "receive" variables from a function to a while loop?

public class Globals
{
    public static int sockConn = 0;
    public static bool sockRetry = false;
}

static void getInfo()
{
    while (true)
    {
        try
        {
            WebRequest request = WebRequest.Create(INFO_HOST + INFO_PATH);
            WebResponse response = request.GetResponse();

            string content;
            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                content = sr.ReadToEnd();
            }

            string[] contentArray = content.Split(':');

            if (contentArray.Length == 2)
            {
                string serverIp = contentArray[0];
                string serverPortStr = contentArray[1];

                int serverPort = 5000;
                Int32.TryParse(serverPortStr, out serverPort);

                while (Globals.sockConn == 0)
                {
                    if (Globals.sockRetry == false)
                    {
                        connect(serverIp, serverPort);
                    }
                    else
                    {
                        Globals.sockRetry = false;
                        Thread.Sleep(60000);
                        break;
                    }
                }

                continue;
            }
            else
            {
                Thread.Sleep(60000);
                continue;
            }
        }
        catch
        {
            Thread.Sleep(60000);
            continue;
        }
    }
}

static void connect(string serverIp, int serverPort)
{
    Globals.sockConn = 1;

    try
    {
        TcpClient client = new TcpClient(serverIp, serverPort);
        NetworkStream nwStream = client.GetStream();
        StreamReader reader = new StreamReader(nwStream);
        StreamWriter writer = new StreamWriter(nwStream);

        Globals.sockConn = 2;

        string inputLine;

        while ((inputLine = reader.ReadLine()) != null)
        {
            ParseMessage(writer, serverIp, inputLine);
        }
    }
    catch
    {
        Globals.sockRetry = true;
        Globals.sockConn = 0;
        return;
    }
}

public static void ParseMessage(StreamWriter Writer, string serverIp, string msg)
{
    // simple parsing
    // function to upload conf file with using serverIp string
}


texts: Data Class code smell? Java object is modified by multiple methods in a row

texts:
I am sending a series of SOAP messages to a server and capturing the results of the SOAP transaction.  The issue that I am having is that I need to perform five SOAP calls, and each call requires some data from the previous call.  This has led me to create a Data Class that holds Strings accessible with Getters and Setters that gets modified after each call.  This code seems "smelly" to me, there is a lot of state change going on in the class and I'm just wondering if there is a better way to go about this.
Here is what's going on, I have the following method in an abstract class:
protected SoapBodyParameters soapBodyParameters;

public void release(String primaryConfigurationIdentifier) throws ReleaseManagerException {
    this.soapBodyParameters.setPrimaryConfigurationItemIdentifier(primaryConfigurationIdentifier);

    // Implemented by child - Will throw an exception if bad configuration
    verify();

    // Get user full name and append soapBodyParameters
    String userFullName = sendGetUserInfoSoapMessage(this.soapBodyParameters);
    this.soapBodyParameters.setUserFullName(userFullName);

    // Create a release package on the server - no return needed
    sendCreateReleasePackageFromLocalFilesSoapMessage(this.soapBodyParameters);

    // Find the release package ID we just made and append soapBodyParameters
    String releasePackageSystemId = sendGetReleasePackagesSoapMessage(this.soapBodyParameters);
    this.soapBodyParameters.setReleasePackageSystemId(releasePackageSystemId);

    // Open the release package and find the task model information
    TaskModel taskModel = sendOpenReleasePackageSoapMessage(this.soapBodyParameters);
    this.soapBodyParameter.setTaskModelFile(taskModel.getIARTaskModel());
    this.soapBodyParameters.setTaskModelId(taskModel.getTaskModelId());

    // Implemented by child - Update the task model with required info
    updateLocalTaskModel(this.soapBodyParameters);

    // Save the task model to the release package on the server
    sendSaveTaskModelSoapMessage(this.soapBodyParameters);
}

So with each of these calls modifying soapBodyParameters and each following call relying on the previous call to modify soapBodyParameters.... I don't know, it just feels smelly.  Like I am faking a global parameter in the class.
Is there a better way to do this?  I'm trying to get better at recognizing when and where a design pattern would be more appropriate.


texts:
I want implement associative container with next requirements:

It stores key-value pair (associative container)
It should return appropriate value by key (as std::map, std::unordered_map)
Traversing of concrete instance of container should return stable random sequence
Traversing different instances of containers with same elements should return different sequences

Please check this idea:

#include <iostream>
#include <map>
#include <random>

using namespace std;

size_t calcSeed() {
  std::random_device device;
  std::mt19937_64 generator(device());
  std::uniform_int_distribution<size_t> distribution;
  return distribution(generator);
}

template <class T>
struct HashWithUniqueSeed;

template <>
struct HashWithUniqueSeed<int> {
  HashWithUniqueSeed() : seed_(calcSeed()) {
    cout << "build hash with seed: " << seed_ << endl;
  }
  std::size_t operator()(int s) const noexcept {
    // Murmur hash for 64-bit size_t
    return std::_Hash_bytes(&s, sizeof(s), seed_);
  }

 private:
  const size_t seed_;
};

struct randomOrderCmp {
  bool operator()(int a0, int a1) const {
    auto v0 = std::make_pair(h(a0), a0);
    auto v1 = std::make_pair(h(a1), a1);
    return v0 < v1;
  }

 private:
  HashWithUniqueSeed<int> h;
};

int main() {
  std::map<int, string, randomOrderCmp> map_random;
  const size_t MAX_EL = 10;

  for (int i = 0; i < MAX_EL; ++i) {
    map_random[i] = to_string(i);
  }

  cout << "map_rand order:" << endl;
  for (const auto& val : map_random) {
    cout << val.first << ", " << val.second << endl;
  }
  cout << endl;

  cout << "iterate by key" << endl;
  for (int i = 0; i < MAX_EL; ++i) {
    cout << "map_rand[" << i << "] = " << map_random[i] << endl;
  }
  return 0;
}

Questions here:

Is it correct? Doesn't it break any requirements for std::map's comparator?
Does it give good "randomness" when traversing?
Maybe more efficient solution?


texts: Authenticating to Amazon EC2 Container Registry

texts:
New to bash. The script I wrote works, but I don't believe it is written in the best way possible.

The script only assesses how to execute the aws ecr get-login command depending on the parameters and versions of the aws-cli and docker currently installed on the host machine.

#!/usr/bin/env bash

set -e

declare aws_region="${AWS_REGION:?''}"
declare registry_id="${REGISTRY_ID:?''}"
declare docker_version=$(docker version -f {{.Client.Version}} | sed 's/[^0-9.]//g')

if ! [[ -z $aws_region ]]; then
    $aws_region = "--region $aws_region"
else
    echo "Need to set AWS_REGION (eg. us-west-2)"
fi

if ! [[ -z $registry_id ]]; then
    $registry_id = "--registy-id $registry_id"
fi

if [[ $docker_version < '17.06' ]]; then
    options = "--no-include_email"
fi

query="aws ecr get-login $aws_region $registry_id $options"
echo $query
$($query)

if ! [[ $? == 0 ]]; then
    echo "---ERROR! Please login to AWS with myob-auth or ADFS."
    exit 1
fi

Any ideas for improvements? I'm personally getting bad smells in the code from the 3 if statements and the way the $query variable works.


texts:
So I have made this Duplicate image scanner using powershell. It will operate using the SHA256 hashes of the files.
Any tips or suggestions on making this more dynamic/robust/efficient or adding new features would be greatly appreciatied!
$sig=@'
public static void ShowConsoleWindow(int state)
{
  var handle = GetConsoleWindow();
  ShowWindow(handle,state);
}
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
'@
$hc=Add-Type -mem $sig -name Hide -Names HideConsole -Ref System.Runtime.InteropServices -Pas
$hc::ShowConsoleWindow(0)
[console]::title="Duplicate Image Scanner (c) Wasif Hasan | Sep 2020"
$eXt=@('.jpg','.png','.gif','.jpeg','.webp','.tiff','.psd','.raw','.bmp','.heif','indd','.svg')
@('system.windows.forms','system.drawing')|%{add-type -as $_}
$s=[windows.forms.form]::new();$s.size=[drawing.size]::new(400,850);$s.StartPosition="CenterScreen";$s.Text="Select drives to scan"
$drives=gdr -p "FileSystem"|select -eXp name
$top=20;$left=50;$drives|%{
$c=$_.split(" ")-join"_";$top += 20
iex "`$$($c) = New-Object System.Windows.Forms.CheckBox;`$$($c).Top = $($top);`$$($c).Left = $($left);`$$($c).Anchor='Left,Top';`$$($c).Parent='';`$$($c).Text='$($_)';`$$($c).Autosize=`$true;if('$_' -in `$drives){`$$c.Checked=`$true};`$s.Controls.Add(`$$c)"}
$ok=New-Object System.Windows.Forms.Button;$ok.Text='OK';$ok.Top=770;$ok.Left=290
$ok.add_click({$s.Close()});$s.Controls.AddRange($ok)
$sa=New-Object System.Windows.Forms.Button;$sa.Text='Select All';$sa.Top=770;$sa.Left=200
$sa.add_click({$s.Controls|?{($_.Checked) -or !($_.Checked)}|%{try{$_.Checked=$True}catch{}}});$s.Controls.AddRange($sa)
$null=$s.ShowDialog()
$choices=$s.Controls|?{$_.Checked}|select -eXp Text
$i=0;$choices|%{$choices[$i]=$_+':\';$i++}
$f=[windows.forms.form]::new();$f.Size=[drawing.size]::new(600,100);$f.StartPosition="CenterScreen";$f.Text="Please wait"
$l=[windows.forms.label]::new();$l.Text="Please wait until the scan is complete........";$l.Font="Segoe UI,16";$l.AutoSize=$true;$f.Controls.AddRange($l)
$null=$f.ShowDialog()
$files=@();$hCols=@();$choices|%{
dir $_ -r|?{$_.eXtension-in$eXt}|%{
$h=get-filehash $_.fullname -a 'SHA256'|select -eXp hash
if($h-in$hCols){$files+=$_.fullName}else{$hCols+=$h}
}};$f.Close()
$del=$files|ogv -t "Duplicate images (Hold CTRL and select the ones to delete)" -p
$del|%{rm "$_" -fo}
[windows.forms.messagebox]::Show("Thanks for using!","Duplicate image scanner","OK","Information")


texts: How to shorten this terrible HTTP header parser?

texts:
I am trying to read a line ending in \r\n from a Handle. This is an HTTP header.

I’m fairly new to functional programming, so I tend to use a lot of case expressions and stuff. This makes the code very long and ugly.

handleRequest :: HostName -> Handle -> IO ()
handleRequest host handle = do
    requestLine <- readHeaderLine
    putStrLn $ requestLine ++ "\n-------------------"
    -- FIXME: This code is bad, and its author should feel bad.
    where
        readHeaderLine = do
            readHeaderLine' ""
            where
                readHeaderLine' s = do
                    chr <- hGetChar handle
                    case chr of
                        '\r' -> do
                            nextChr <- hGetChar handle
                            case nextChr of
                                '\n' -> return s
                                _    -> readHeaderLine' $ s ++ [chr, nextChr]
                        _    -> readHeaderLine' $ s ++ [chr]

How can I reduce the amount of case expressions in this code? I thought of using Parsec, but that seemed overkill to me for something this trivial, and I don’t know how well it works with Handles.


texts:
I have an HTML login form that is processed by a servlet, which then redirects the user to a result page.

login.jsp:

LOG IN

Please enter your credentials.

<form action="process-login.jsp" method="post">

        Username:
        <input type="text" name="username" size="30" required title="Please enter your username."/>

        Password:
        <input type="password" name="password" size="30" required title="Please enter your password."/>

<input type="submit" value="Login"/>
</form>

Servlet (process-login.jsp):

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String userId = request.getParameter("username");
    String userPassword = request.getParameter("password");

    if(userId != null && userPassword != null) {
        DatabaseManipulator dm = new DatabaseManipulator();
        String[] usernameArray = dm.dbEntriesToArray("user_id");
        String registeredPassword = dm.getRegisteredPassword(userId);

        LoginModule lm = new LoginModule();
        boolean hasExistingAccount = lm.hasExistingAccount(usernameArray, userId);
        boolean isPasswordCorrect = lm.isPasswordCorrect(userPassword, registeredPassword);

        // returns new session if it does not exist
        HttpSession session = request.getSession(true);

        // bind objects to session
        session.setAttribute("hasExistingAccount", hasExistingAccount);
        session.setAttribute("isPasswordCorrect", isPasswordCorrect);

        if(!hasExistingAccount) {
            response.sendRedirect("login-result.jsp");

        } else if(!isPasswordCorrect) {
            response.sendRedirect("login-result.jsp");

        // login success
        } else {
            String currentUserId = dm.getCurrentUserId(userId);
            int currentUserType = dm.getCurrentUserType(userId);

            session.setAttribute("currentUserId", currentUserId);
            session.setAttribute("currentUserType", currentUserType);

            response.sendRedirect("index.jsp");
        }

    } else {
        // redirect on illegal access of servlet
        response.sendRedirect("index.jsp");
    }
}

login-result.jsp:

LOGIN RESULT

<%
// retrieve objects from session
Boolean hasExistingAccount = session.getAttribute("hasExistingAccount") != null ? (Boolean) session.getAttribute("hasExistingAccount") : true;
Boolean isPasswordCorrect = session.getAttribute("isPasswordCorrect") != null ? (Boolean) session.getAttribute("isPasswordCorrect") : true;

if(!hasExistingAccount) {
%>

<form action="login.jsp">

User does not exist!

<input type="submit" value="Try Again"/>
</form>

<% } else if(!isPasswordCorrect) { %>

<form action="login.jsp">

Username or password is incorrect!

<input type="submit" value="Try Again"/>
</form>

<% } else {
    // redirect on illegal access of jsp
    response.sendRedirect("index.jsp");
}
%>

(Kindly forgive the scriptlets for now, as it is what we have reached in our lessons so far, though I am now aware it is deprecated.)
I use plain if-else statements, where the result page gives the appropriate message. Is this an acceptable way to handle user input errors?


texts: Small implementation of a singly-linked list in C89

texts:
I'm very new to C and have extensive experience with C# and very little with C++, but basically none with C.

I wrote a small program that declares a singly-linked list struct, a few methods operating on the list, and then uses it from the main method. Even though I've read about it a lot, this is only my second/third program I've written in C, so please beware.

#include <assert.h>
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct linked_list_node linked_list_node; // forward declare linked_list_node and add it to the struct/global namespaces

struct linked_list_node
{
    linked_list_node* next;
    int32_t item;
};

typedef struct
{
    linked_list_node* head;
    size_t size;
} linked_list;

void init_list(linked_list* list) { /* Nothing to do here */ }

void add_last(linked_list* list, int32_t item)
{
    assert(list != NULL);

    if (list->head == NULL)
    {
        // No elements in the list yet.
        list->head = malloc(sizeof(linked_list_node));
        list->head->next = NULL;
        list->head->item = item;
    }
    else
    {
        // At least 1 element in the list.
        assert(list->size > 0);

        // Walk the list until we find the last node.
        linked_list_node* node = list->head;
        while (node->next != NULL)
        {
            node = node->next;
        }

        // Allocate a new last node
        linked_list_node* next = malloc(sizeof(linked_list_node)); // note: no typecast from void* here
        node->next = next;
        next->next = NULL; // need to explicitly do this since malloc's memory is uninitialized
        next->item = item;
    }

    list->size++;
}

typedef void action(int32_t);

void foreach_list(linked_list* list, action* act)
{
    assert(list != NULL && act != NULL);

    linked_list_node* node;
    for (node = list->head;
        node != NULL;
        node = node->next)
    {
        act(node->item);
    }
}

// Cleans up all of the memory used up by the list's
// nodes. DOES NOT FREE THE LIST ITSELF.
void cleanup_list(linked_list* list)
{
    assert(list != NULL);

    list->size = 0;

    // Walk the list, freeing nodes as we go.
    linked_list_node* node, *next;
    for (node = list->head;
        node != NULL;
        node = next)
    {
        next = node->next;
        free(node);
    }
}

void print_int32(int32_t to_print)
{
    printf("Found %"PRIi32"!\n", to_print); // format specifier for int32_t
}

int main(void)
{
    linked_list list;
    memset(&list, 0, sizeof(list));
    init_list(&list);

    add_last(&list, 3);
    add_last(&list, 4);
    add_last(&list, 5);

    foreach_list(&list, print_int32);
    printf("Size: %"PRIu64"\n", (uint64_t)list.size); // do not use %zu since this is targeting C89

    cleanup_list(&list);
    return 0;
}

I compiled this under MinGW with C89.

Here is the type of feedback I'm looking for:

Did I introduce and potential sources of UB? For example, is there a flaw in my logic where a NULL pointer can be dereferenced and go undetected by asserts?
Is my memory management logic correct? Did I accidentally malloc something that never got cleared, or did I free anything twice in cleanup_list? Is there a way to make all of the logic less error-prone?
Did I rely on any features specific to GCC to get this to work? For example, will this program also work with other compilers under C89?
Any way I could clean up the code and make it more neat/concise? (I am aware that I should probably have put the list definition/methods into separate header/source files than main.)


texts: Doubly linked list with different dependencies

texts:
I need to connect different Task with a double linked list and different Dependencies which affect a calculation for which I need the values of both Task:

public class Task {
    private List<Dependency> parents = new ArrayList<Dependency>();
    private List<Dependency> children = new ArrayList<Dependency>();

    //Uses the parents values and calls `calculateForwards` of the children
    public void calculateForwards() { .. }
    //Uses the children values and calls `calculateBackwards` of the children
    public void calculateBackwards() { .. }
}

public interface Dependency {
    Task getTask();
    void setForwards(Task t);
    void setBackwards(Task t);
    Dependency createCopy(Task t);
}

public class EA implements Dependency {
    private Task task;

    //............

    @Override
    public void setForwards(Task t) {
        if (t.getEarlyStart() < task.getEarlyFinish())
        t.setEarlyStart(task.getEarlyFinish());

        t.setEarlyFinish(t.getEarlyStart() + t.getDuration());
    }

    @Override
    public void setBackwards(Task t) {
        if (t.getLatestFinish() > task.getLatestStart())
        t.setLatestFinish(task.getLatestStart());

        t.setLatestStart(t.getLatestFinish() - t.getDuration());
    }

    //............

 }

For now dependencies are created with the Task it points to and added to the children list. Then a copy of the dependency is created that points to the original task and added to the parent list of the child:

public void addChild(Dependency r) {
    children.add(r);
    r.getTask().addParent(r.createCopy(this));
}

private void addParent(Dependency r) {
    parents.add(r);
}

As you can see this data structure does the job, but very ugly in my eyes. How can I solve this more elegantly?

Task.java,
Dependency.java,
EA.java (implements Dependency)


texts:
I created code for my registration form on my social network. I want to know if it is secured enough to release on the web as a public social network. Also, all of the code works. I just want to make sure it's all secure.

registration.php:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

//check if form is submitted
if ( $_SERVER['REQUEST_METHOD'] != 'POST' || ! isset($_POST['Register']))
{
// looks like a hack, send to index.php
header('Location: index.php');
die();
}

include("connect.php");

            if(isset($_POST['Register'])) {

               if (empty($_POST["username"])) {
                echo"Fill in username to sign up";
                } else {

                if (empty($_POST["pw"])) {
                 echo"Fill in password to sign up";
                } else {

                if (empty($_POST["pw2"])) {
                echo"Confirm password to sign up";
                 } else {

                if (empty($_POST["email"])) {
                     echo"Fill in email to sign up";
                 } else {

                if ($_POST['pw'] == $_POST['pw2']) {
                 $username = mysqli_real_escape_string($conn, $_POST["username"]);
                 $pw= mysqli_real_escape_string($conn, $_POST["pw"]);
                 $pw2= mysqli_real_escape_string($conn, $_POST["pw2"]);
                 $email = mysqli_real_escape_string($conn, $_POST["email"]);

                 $result = mysqli_query($conn ,"SELECT * FROM users WHERE username='" . $username . "'");

                    if(mysqli_num_rows($result) > 0)
                    {
                    echo "Username exists . Try again
 ";
                    } else {

                       $result2 = mysqli_query($conn ,"SELECT * FROM users WHERE email='" . $email. "'");

                       if(mysqli_num_rows($result2) > 0)
                       {
                       echo "Email exist.  Try again
 ";
                       } else {

                       $pw = password_hash($pw, PASSWORD_BCRYPT, array('cost' => 14));

                       $stmt = $conn->prepare("INSERT INTO users (username, pw, email) VALUES(?, ?, ?)");
                       $stmt->bind_param("sss", $username, $pw, $email);

                      $username = $username;
                      $pw = $pw;
                      $email = $email;
                      $stmt->execute();

                      echo"Registration successful Login here
";

                    } } } else{
            echo "The passwords do not match.";  // and send them back to registration page
            }
}
}}}}

login.php:

error_reporting(E_ALL);
ini_set('display_errors', 1);

include("connect.php");

$_SESSION['username'] = $_POST['username'];

//check if form is submitted
if ( $_SERVER['REQUEST_METHOD'] != 'POST' || ! isset($_POST['signin']))
{
// looks like a hack, send to index.php
header('Location: index.php');
die();
}

if (empty($_POST["username"])) {
echo 'Fill in username to sign in. Try again
';
die();
}

if (empty($_POST["pw"])) {
echo 'Fill in password to sign in. Try again
';
die();
}

$sql = "SELECT pw FROM users WHERE username = ?";
$stmt = mysqli_prepare($conn, $sql);
if ( !$stmt ) {
echo mysqli_error($conn);
die();
}

$stmt->bind_param('s', $_POST['username']);
if ( !$stmt->execute() ) {
echo mysqli_error($conn);
die();
}
// we found a row with that username,
// now we need to check the password is correct

// get the password from the row
$stmt->bind_result($hashed_pwd);
$stmt->fetch();

if ( password_verify($_POST['pw'], $hashed_pwd) ) {
// password verified
$_SESSION["username"] = $_POST['username'];
header('Location: profile.php');
} else {
echo 'Incorrect username or Password. Try again
';
}


texts:
I am new to rust and to start learning the language I decided to implement a simple one-time pad encryption program.

The part I am least sure about is the reading and writing from the files. Ideally this would run efficiently on large files.

use clap::{Arg, App};
use std::{
    error::Error,
    fs::File,
    io::{
        self,
        Read,
        Write,
    },
};

const CAPACITY: usize = 1024;

fn main() -> Result<(), Box<dyn Error>> {
    let matches = App::new("onetime")
        .version("0.1")
        .author("Carlo Abelli <carlo@abelli.xyz>")
        .about("Encrypts/decrypts a file using a one-time pad.")
        .arg(Arg::with_name("FILE")
             .required(true)
             .help("The file to encrypt/decrypt"))
        .arg(Arg::with_name("PAD")
             .short("p")
             .long("pad")
             .takes_value(true)
             .value_name("PAD")
             .required(true)
             .help("The pad to use for encryption/decryption"))
        .arg(Arg::with_name("OUTPUT")
             .short("o")
             .long("output")
             .value_name("OUT")
             .help("The output file (default: stdout)"))
        .get_matches();

    let mut file = File::open(matches.value_of("FILE").unwrap())?;
    let mut pad = File::open(matches.value_of("PAD").unwrap())?;

    if file.metadata()?.len() > pad.metadata()?.len() {
        panic!("file is larger than pad!");
    }

    let mut out: Box<dyn Write> = match matches.value_of("OUTPUT") {
        Some(name) => Box::new(File::create(name)?),
        None => Box::new(io::stdout()),
    };

    let mut file_buffer = vec![0u8; CAPACITY];
    let mut pad_buffer = vec![0u8; CAPACITY];
    loop {
        let size = file.read(&mut file_buffer)?;
        if size == 0 {
            break;
        }
        pad.read_exact(&mut pad_buffer[..size])?;
        let out_buffer: Vec<u8> = pad_buffer.iter()
            .zip(file_buffer.iter())
            .map(|(pad_byte, file_byte)| pad_byte ^ file_byte)
            .collect();
        out.write_all(&out_buffer)?;
    }

    Ok(())
}


texts: Optimize Performance of Region Checking in List Comprehension

texts:
I am modeling a linear process at a number of equally spaced time steps. I have a large list (~70k elements) which corresponds to a location at each time step, timerange = np.linspace(0, time, iterations, False) * speed. For each element in this list, I want to compare its value (location) to two other lists and see if that location falls within a valid region. These two other lists, rot.RegionStarts and rot.RegionEnds (~150 elements) contains the start and end locations, respectively, of each region.
I began tackling this problem with list comprehension, using the following code to achieve the desired result.

valid = np.asarray([any((t * dt * speed >= rot.RegionStarts) & (t * dt * speed < rot.RegionEnds) for t in range(iterations)])

Upon using this, I realized that execution was rather slow, about 0.4s each time. As make several hundred calls to this line, this greatly slows down the process. I tried using numpy to achieve a similar effect, which required lots of reshaping and repeating.

valid = np.any(np.logical_and(
      np.greater_equal(np.repeat(np.reshape(timerange, (-1, 1)), rot.RegionStarts.shape[0], axis=1),
            np.repeat(np.reshape(rot.RegionStarts, (1, -1)), timerange.shape[0], axis=0)),
      np.less(np.repeat(np.reshape(timerange, (-1, 1)), rot.RegionEnds.shape[0], axis=1),
            np.repeat(np.reshape(rot.RegionEnds, (1, -1)), timerange.shape[0], axis=0)),
      axis = 1)

Unfortunately, this saw very little performance increase (~0.25s), probably due to the large size of arrays being repeated. Removing lines like np.repeat cause problems aligning shape; element-wise & could not be executed on 2-d arrays.
What optimization techiniques can be used speed up this code?


texts: Geocoding and Reverse in python using Geopy

texts:
I had done this program that takes an input from STDIN and processes it to check if it is a Latitude/longitude combo or a place's name. Then it uses geocoding and returns an address corresponding to the latitude longitude or returns a latitude and longitude if the input is an address. I am using Nomatim, I would like to know how else can we do this?I would also like to know how I can make the code better.

from geopy.geocoders import Nominatim
import re
geolocator=Nominatim()
arg=raw_input()
pattern=re.compile(r'^(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)$')
if pattern.match(arg):
    loc=geolocator.reverse(arg)
    if loc is not None:
        print(loc.address)
        print(loc.latitude, loc.longitude)
    else:
        print "the location doesnt exist"
else:
    loc=geolocator.geocode(arg)
    if loc is not None:
        print(loc.address)
        print(loc.latitude, loc.longitude)
    else:
        print "This address does not exist"


texts: Joining couples, red candidates, and blue candidates

texts:
I have 3 tables:

    Table couples         consist of save_id, id_candidate_red, id_candidate_blue
    Table candidates_red  consist of save_id, id_candidate, enter_match
    Table candidates_blue consist of save_id, id_candidate, enter_match

And I am running the query

 SELECT  *
    FROM  couples as c

    LEFT JOIN candidates_blue as cb
        ON cb.save_id = 3
            AND cb.user_id = c.id_candidate_blue

    LEFT JOIN candidates_red as cr
        ON cr.save_id = 3
            AND cr.user_id = c.id_candidate_red

    WHERE c.save_id = 3
        AND cb.enter_match = 1
        AND cr.enter_match = 1

…which seems pretty simple to me, but as I have a big dataset behind my tables, it takes quite a while to execute.


texts:
I run a coding dojo at work. for one session I'm to showing that you can use a kata to get into a new language.

I'm using the FizzBuzz Kata to show JavaScript (and F#) because it is short.  The problem is my JavaScript knowledge is only slightly above the copy -> paste -> fiddle level.

Thus, I would like to see better ways of doing this (using qunit):

var fizzBuzzer = (function () {
    var For = function (number) {
        var isBuzz = number % 5 === 0;
        var isFizz = number % 3 === 0;

        if ((isFizz) && (isBuzz)) {return "FizzBuzz";}
        if (isBuzz ) {return "Buzz";}
        if (isFizz ) {return "Fizz";}

        return number;
    };

    return { For: For };
})();

test("not a multiple of 5 or 3 returns number", function () {
    equal(fizzBuzzer.For(1), 1);
    equal(fizzBuzzer.For(2), 2);
});

test("multiple of 3 returns Fizz", function () {
    equal(fizzBuzzer.For(3), "Fizz");
    equal(fizzBuzzer.For(6), "Fizz");
});

test("multiple of 5 returns Buzz", function () {
    equal(fizzBuzzer.For(5), "Buzz");
    equal(fizzBuzzer.For(10), "Buzz");
});

test("multiple of 3 and 5 returns FizzBuzz", function () {
    equal(fizzBuzzer.For(15), "FizzBuzz");
    equal(fizzBuzzer.For(30), "FizzBuzz");
});


texts: React higher-order component: withHigherHandlers

texts:
I'm trying to create a helper method just like recompose's withHandlers, but I need to pass my handlers an extra argument.

Here's the code:

import {Component} from 'react'
import {createEagerFactory, wrapDisplayName} from 'recompose';
import {mapValues} from './util';
import {resolveValue} from '../../src/util';
import {MapFn} from '../../src/types/misc';

export interface Handlers {
    [x: string]: (...args: any[]) => void
}

const withHigherHandlers = <TProps extends {}>(handlers: Handlers|MapFn<TProps,Handlers>): React.ComponentClass<TProps> => (BaseComponent: React.ComponentType<TProps>) => {
    const factory = createEagerFactory(BaseComponent);

    class WithHigherHandlers extends Component {
        static displayName = wrapDisplayName(BaseComponent, 'withHigherHandlers');

        handlers = mapValues(
            resolveValue(handlers, this.props),
            (handler, handlerName) => (...args1) => (...args2) => {
                return handler(...args1, this.props, ...args2); // TODO: memoize this somehow?
            }
        );

        render() {
            return factory({
                ...this.props,
                ...this.handlers,
            })
        }
    }

    return WithHigherHandlers
};

export default withHigherHandlers;

You can attach it to your component like this:

withHigherHandlers({
    deleteInstruction(index, {dispatch}, ev) {
        ev.preventDefault();
        dispatch('instructions', inst => arraySplice(inst, index));
    }
})(YourComponent)

And then use it in your render method like this:

instructions.map((inst, i) =>
    <SchedulingInstruction key={i} data={inst} name={`instructions.${i}`} remove={deleteInstruction(i)}/>)

i.e. it's useful when you need to pass some extra context into your event handler. In this case I need the index of the 'instruction' to delete.

I also changed the function signature a bit. withHandlers expects you define your handlers like:

myHandler: props => ev => { ... }

My "higher" handlers go one level deeper. This means they'd look like:

myHandler: context => props => ev => { ... }

But then I figured what's the benefit of that when I can just condense it to this?

myHandler(context, props, ev) { ... }

Anyway, the things I'm not certain about are how to fix this error:

BaseComponent should be a ComponentType from @types/react AFAICT, so I don't know why it's complaining.

And I'm not sure if my handlers need memoizing to avoid re-renders.

The utility methods if you want to see them:

export const mapValues = (obj, func) => {
    // lifted from https://github.com/acdlite/recompose/blob/72eae6758e73ae2c8d094a33a1b3f09c32a36fff/src/packages/recompose/utils/mapValues.js
    const result = {}
    /* eslint-disable no-restricted-syntax */
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            result[key] = func(obj[key], key)
        }
    }
    /* eslint-enable no-restricted-syntax */
    return result
}

export function resolveValue<T>(this: any, functionOrValue: ((...args: any[]) => T)|T, ...args: any[]): T {
    return typeof functionOrValue === 'function' ? functionOrValue.call(this, ...args) : functionOrValue;
}


texts:
In my requestForm submit function I have this logic that checks three checkboxes and then displays the label with an error message. Is there better logic? I would be happy for any kind of feedback since this is quite critical a part of my application.
$("#requestForm").submit(function (e) {
            e.stopPropagation();
            e.preventDefault();

        var checked_sourcecheckboxes = $("#sources input[type=checkbox]:checked");
        if (checked_sourcecheckboxes.length == 0) {
            $("#lblSourcesError").show();
            return false;
        }
        else {
            $("#lblSourcesError").hide();
        }
        var checked_academicformatcheckboxes = $("#academicFormatsRow input[type=checkbox]:checked");
        if (checked_academicformatcheckboxes.length == 0) {
            $("#lblacademicFormatError").show();
            return false;
        }
        else {
            $("#lblacademicFormatError").hide();
        }
        var checked_academicmediaformatcheckboxes = $("#academicMediaFormatRow input[type=checkbox]:checked");
        if (checked_academicmediaformatcheckboxes.length == 0) {
            $("#lblacademicmediaFormatError").show();
            return false;
        }
        else {
            $("#lblacademicmediaFormatError").hide();
        }
})


texts: Calculating months elapsed since a given date

texts:
I am using traceview and DDMS to analyse my operation.  The following is my traceview as displayed in DDMS:

According to the above, the LoaderClass.months() function takes about 51% of the CPU time and 798.80 System time.  I have reproduced this function below:

public int months(String date) {

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = null;
        try {
            d1 = f.parse(date);
        } catch (ParseException e) {

            e.printStackTrace();
        }
        Date d2 = new Date();
        Calendar c1 = Calendar.getInstance();
        c1.setTime(d1);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(d2);
        int diff = 0;
        if (c2.after(c1)) {
            while (c2.after(c1)) {
                c1.add(Calendar.MONTH, 1);
                if (c2.after(c1)) {
                    diff++;
                }
            }
        } else if (c2.before(c1)) {
            while (c2.before(c1)) {
                c1.add(Calendar.MONTH, -1);
                if (c1.before(c2)) {
                    diff--;
                }
            }
        }
        return diff;
    }

Below is a more detailed view of the method as on DDMS:


texts: Express.js routes management for large web application

texts:
I'm currently working on a large web application with numerous routes.  Currently, our routes are in one large list in a single JSON file.  We recently ran into a problem due to the precedence of params being set from top to bottom in the file.  This question details the issue we encountered further: Node.js Express route naming and ordering: how is precedence determined?

My plan is to propose an alternate routing solution based on my work from a personal project.  I feel like it's a valid suggestion but missed out on a chance to really make my case in a meeting the other day.  Here is a routes.js file from my personal project that demonstrates the pattern I would like to use, let me know what you think or of possible better alternatives/edits.  Thanks!

By creating separate routers for each resource, different controllers can access the same URLs without the params being overridden.

const express = require('express');

const usersRouter = express.Router();
const songsRouter = express.Router();
const playlistsRouter = express.Router();

const usersController = require('../controllers/users');
const songsController = require('../controllers/songs');
const playlistController = require('../controllers/playlists');

usersRouter.route('/')
  .post(usersController.create)

songsRouter.route('/')
  .get(songsController.index)
  .post(songsController.create)

playlistsRouter.route('/')
  .get(playlistController.index)
  .post(playlistController.create)

songsRouter.route('/:id')
  .get(songsController.show)
  .put(songsController.update)
  .delete(songsController.destroy)

playlistsRouter.route('/:id')
  .get(playlistController.show)
  .put(playlistController.update)
  .delete(playlistController.destroy)

module.exports = {
  songs: songsRouter,
  playlists: playlistsRouter,
  users: usersRouter,
};

A couple questions that come to my mind are:

How optimal it would be to have all those Express router instances?
Is this approach scalable?


texts: Organizing a long string into a list of lists

texts:
This code loads the data for Project Euler problem 18, but I feel that there must be a better way of writing it.  Maybe with a double list comprehension, but I couldn't figure out how I might do that.  It is a lot more difficult since the rows to split up are not uniform in length.

def organizeVar():
    triangle = "\
75,\
95 64,\
17 47 82,\
18 35 87 10,\
20 04 82 47 65,\
19 01 23 75 03 34,\
88 02 77 73 07 63 67,\
99 65 04 28 06 16 70 92,\
41 41 26 56 83 40 80 70 33,\
41 48 72 33 47 32 37 16 94 29,\
53 71 44 65 25 43 91 52 97 51 14,\
70 11 33 28 77 73 17 78 39 68 17 57,\
91 71 52 38 17 14 91 43 58 50 27 29 48,\
63 66 04 68 89 53 67 30 73 16 69 87 40 31,\
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23"
    triangle = [row for row in list(triangle.split(","))]
    adjTriangle = []
    for row in range(len(triangle)):
        adjTriangle.append([int(pos) for pos in triangle[row].split(" ")])
    return adjTriangle

The code converts this string into a list of lists of ints where the first list contains 75, the second list 95, 64, the third list 17, 47, 82, the fourth list 18, 35, 87, 10 and so on to the bottom row.


texts: Calculate the sum over a list of minima of two vectors

texts:
I have the following metric:

def d(x, y):
    """The metric."""
    return 1 - sum(min(xi, yi) for xi, yi in zip(x, y))

where x and y are numpy arrays of equal length (~3000). I know that the elements of x and the elements of y each sum up to 1 and are non-negative.

Can this be calculated faster?


texts: Improve page-specific CSS for different color schemes

texts:
For a website with four pages (blog, portfolio, profil and impressum) I have four different color schemes (for links, headings, code, etc.).  This results in bloated CSS which I want to reduce.

Here is a demo. You see the navigation items use the color scheme of the page it links to. In the demo we're on the blog page with a green theme. Styling the different pages works by adding a class to the root element (i.e. ).

How can I improve this approach of styling things page-dependant?

Also what kind of naming would be appropriate? I could use the titles of the pages (page--blog, link--blog, …) or the colors (page--green, link--green, …). Other ideas/suggestions?

HTML:

        BlogPortfolioProfilImpressum

Regular paragraph, containing a link. Crazy, huh?

CSS:

.site-nav {
    background-color: #444;

    a {
        color: white;
        display: inline-block;
        padding: 20px;
    }
}

.link--green {
    background-color: forestgreen;

    .page:not(.page--blog) &:hover {
        background-color: yellowgreen;
    }
}

.link--blue { /* ... */ }
.link--orange { /* ... */ }
.link--red { /* ... */ }

.page-content {
    a,
    h1, h2, h3, h4, h5, h6 {
        .page--blog & {
            color: forestgreen;
        }

        .page--profil & { /* ... */ }
        .page--portfolio & { /* ... */ }
        .page--impressum & { /* ... */ }
    }
}

possible solutions/ideas:

additional CSS file only used on these sites (extra HTTP request)
page-specific CSS in style tags inside the actual html document (hard to manage)
Using SASS mixins to generate the CSS for the four pages (won't reduce bloat)


texts:
I am extending the functionalities of a Python list and I would like to include a method to normalize a vector to the [0, 1] range, by using element-wise operations. I came out with this solution, but find that using two classes does not seem clean. The main motivation for using two classes is that the output of data - min(data) from normalize() returns a Python list (due to how __sub__() was implemented), and that native list does not seem to have __truediv__() implemented.

How can I achieve the normalize() method and avoid the creation of the intermediate _BaseList class? The project I am working on has very constrained memory and I cannot use Numpy.

class _BaseList(list):
    def __init__(self, data):
        super().__init__(data)

    def __sub__(self, value):
        if type(value) in (int, float):
            return [elem - value for elem in self]
        elif type(value) is list and len(value) == len(self):
            return [a - b for a, b in zip(value, self)]

    def __truediv__(self, value):
        if type(value) in (int, float):
            return [elem / value for elem in self]
        elif type(value) is list and len(value) == len(self):
            return [a / b for a, b in zip(value, self)]

class Array(_BaseList):

    def __init__(self, data=None):
        super().__init__(data)

    def normalize(self):
        print(type(self))
        return _BaseList((self - min(self))) / float(max(self) - min(self))


texts: Moving character in given direction C++ SFML

texts:
I have written simple input manager which is used for me to detect key press, and fire assigned function. For example I can do something like that:
auto own_pointer = std::make_shared<Player>(*this);
inputControl.addKeyToCheck( sf::Keyboard::H, std::function<void( Player& )>( &Player::sayHello ),own_pointer );

and in my loop manager, I check input managers, and if H is pressed, then function sayHello will be fired.
I have written moving my player with this input manager.
auto own_pointer = std::make_shared<Player>(*this);
inputControl.addKeyToCheck( sf::Keyboard::A, std::function<void( Player& )>( &Player::moveLeft ),own_pointer );
inputControl.addKeyToCheck( sf::Keyboard::D, std::function<void( Player& )>( &Player::moveRight ), own_pointer );
inputControl.addKeyToCheck( sf::Keyboard::S, std::function<void( Player& )>( &Player::moveDown ), own_pointer );
inputControl.addKeyToCheck( sf::Keyboard::W, std::function<void( Player& )>( &Player::moveTop ), own_pointer );

where for example moveTop is just
void Player::moveTop()
{
    this->getComponent<Velocity>()->y -= speed * mv::constants::mob::DEFAULT_SPEED;
}

Generally I am so proud of my InputManager, it works everywhere else but there is really bad to use 4 different function to control moving. Have somebody any advice how to deal with that style problem?
Input manager
    /**
    * @brief Class which manage keys' input
    */
    template <class T>
    class InputManager
    {
        /* ===Objects=== */
    public:
    protected:
    private:
        //when you press KEY you execute FunctionWrapper
        std::map < sf::Keyboard::Key, FunctionPointerWrapper_t<T>> keyData;
        /* ===Methods=== */
    public:
        /**
        * @brief Checks if keys have been clicked
        */
        void update();

        /**
        * @bried adds key to database
        */
        bool addKeyToCheck( sf::Keyboard::Key key, std::function<void( T& )> function, std::shared_ptr<T> object );

        /**
        * @brief remove key from database
        */
        bool eraseKey( sf::Keyboard::Key key );
    protected:
    private:
    };

    template <class T>
    void InputManager<T>::update()
    {
        for ( auto&var : keyData )
            if ( sf::Keyboard::isKeyPressed( var.first ) )
                var.second.function( *var.second.object );
    }

    template <class T>
    bool InputManager<T>::addKeyToCheck( sf::Keyboard::Key key, std::function<void( T& )> function, std::shared_ptr<T> object )
    {
        keyData.emplace( key, FunctionPointerWrapper_t<T>( function, object ) );

        return true;
    }

    template <class T>
    bool InputManager<T>::eraseKey( sf::Keyboard::Key key )
    {
        keyData.erase( key );
        return false;
    }


texts:
I build a Tower of Hanoi solver which print the solution as an image

It works as expected but generating the image is relatively slow compared to the time to calculate the answer.

Here is the code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import argparse
from PIL import Image

def hanoi(disks, source, helper, target, steps):
    if disks > 0:
        hanoi(disks - 1, source, target, helper, steps)
        target.append(source.pop())
        steps.append([SOURCE[:], HELPER[:], TARGET[:]])
        hanoi(disks - 1, helper, source, target, steps)

def save_image(name):
    print('\nSaving image {}.png'.format(name))
    data = []
    peg = args.disks * 2
    cells = peg * 3 + 40  # 40 is to put some spaces between pegs and the border
    for step in steps:
        for _ in range(5):  # White space
            data.append([1 for _ in range(cells)])

        src = step[0]
        hlp = step[1]
        trg = step[2]
        size = max(len(src), len(hlp), len(trg))
        for _ in range(size - len(src)):
            src.append(0)
        for _ in range(size - len(hlp)):
            hlp.append(0)
        for _ in range(size - len(trg)):
            trg.append(0)
        src.reverse()
        hlp.reverse()
        trg.reverse()

        for s, h, t in zip(src, hlp, trg):
            blanksrc = peg - 2 * s
            blankhlp = peg - 2 * h
            blanktrg = peg - 2 * t
            row = [1 for _ in range(10)]
            row += [1 for _ in range(blanksrc // 2)]
            row += [0 for _ in range(s * 2)]
            row += [1 for _ in range(blanksrc // 2)]
            row += [1 for _ in range(10)]
            row += [1 for _ in range(blankhlp // 2)]
            row += [0 for _ in range(h * 2)]
            row += [1 for _ in range(blankhlp // 2)]
            row += [1 for _ in range(10)]
            row += [1 for _ in range(blanktrg // 2)]
            row += [0 for _ in range(t * 2)]
            row += [1 for _ in range(blanktrg // 2)]
            row += [1 for _ in range(10)]
            data.append(row)

        for _ in range(5):  # White space
            data.append([1 for _ in range(cells)])
        data.append([0 for _ in range(cells)])  # Black line to separate steps

    da = [bit for row in data for bit in row]
    image = Image.new('1', (cells, len(data)))
    image.putdata(da)
    image.save('{}.png'.format(name))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--disks', type=int, default=4,
                        help='Number of disks, default 4')
    parser.add_argument('-f', '--filename', help='Filename', required=True)
    args = parser.parse_args()

    if not args.disks > 0:
        raise ValueError('There must be at least one disk')

    SOURCE = list(reversed(range(1, args.disks + 1)))
    TARGET = []
    HELPER = []
    steps = [[SOURCE[:], HELPER[:], TARGET[:]]]

    hanoi(args.disks, SOURCE, HELPER, TARGET, steps)

    save_image(args.filename)

As I add more disks in the problem, compared to the computation of the answer, the time taken to generate the image is longer and longer.

How can I make it faster and why it is so slow?


texts: Function for calculating Archimedean density functions

texts:
I am not sure whether this is the right place to ask this, so please correct me if it's not.

I am following this paper (e.g., Corollary 3.3) for some derived functional representations of the densities and writing code for those. The code for one of the families:

(x will be a vector of 1xd between [0,1], tau - scalar in [1, infty).)

'joe_density' <- function(x, tau){
  require(gmp)
  require(Rmpfr)
  require(magrittr)

  d <- length(x)

  P_d <- function(x, tau, d){
    alpha <- 1/tau
    lapply(1:d, function(k){
      as.numeric(gmp::Stirling2(n = d, k = k)) * gamma(k - alpha) / gamma(1 - alpha) * x^(k-1)
    }) %>% do.call(sum, .)
  }

  h <- prod((1 - (1 - x)^tau))

  mpfr( tau^(d-1), 16) *
    mpfr( prod((1 - x)^(tau - 1)), 16) /
    mpfr( (1 - h)^(1 - 1/tau), 16) *
    mpfr( P_d( h/(1-h), tau, d), 16)
}

Example call:

# Simple case
x <- pnorm(rnorm(100))
joe_density(x, tau = 2)

# Longer performance time when looping, d=2
expand.grid(x = seq(-5,5,by=0.1), y = seq(-5,5,by=0.1)) %>%
  apply(.,1,function(z){
     x <- pnorm(z)
     joe_density(x, tau = 2)
  })

In essence, the typical calculations require tons of looping, gamma/Stirling numbers, and I have noticed that the default precision is usually not enough, hence the Rmpfr usage. One time evaluation of the code is not a problem, however, the calculations become very lengthy when the function is called thousands of time (e.g., passing it to  optim and the likes).

Are there simpler ways to program this? This particular function is just an example, but most of the different functions follow similar approach, with a high usage of Stirling/gamma, lengthy products and etc.

Could, for example, rewriting parts of the code in Rcpp be helpful, or is this not the type of task that we could expect  gains here? I have no experience in writing cpp code, so am not sure what to expect.


texts: Reduce list manipulation for QGIS layer tree

texts:
I am developing a plugin for the GIS software, QGIS. The code below reads the number of layers in various groups (as shown in the image) and adds them to a QTableWidget:

For each group, I want to count the number of layers, divide 1 by this number and then add the result of this to each of the layers in each group in the table.

Taking "Group1" as an example:

Count the number of layers (in this case 3).
Calculate 1 / 3 = 0.33....
Insert 0.33... to the first three layers in the table.
Repeat for the remaining groups.

So the table looks like this:

However, there's a fair bit of list manipulation involved which seems unnecessary so was hoping to see if there's a way to reduce this.

Here is the code:

# Define QTableWidget
qTable = self.dockwidget.tableWidget
# Define group
root = QgsProject.instance().layerTreeRoot()
main_group = root.findGroup('Main group')

def refresh_table():
    # Define parameters for QTableWidget
    qTable.setRowCount(0)
    # Define list to contain all layer names
    layer_data = []
    # Define list to contain the number of layers
    layer_count = []

    # Find all groups in main_group
    for group in main_group.children():
        # Define list to count number of layers in each group
        layer_list = []
        # Find all layers in each group
        for child in group.children():
            node = root.findLayer(child.layer().id())
            try:
                # If layer is visible, add them to lists
                if node.isVisible() == Qt.Checked:
                    layer_data.append(child.layerName())
                    layer_list.append(child.layerName())
            except AttributeError:
                pass
        # Insert the number of layers in each group to layer_count list
        layer_count.append(len(layer_list))

    # Get total number of layers
    layer_data_count = len(layer_data)
    try:
        # Create new list for layer_count but ignore any zeros
        new_layer_count = [x for x in layer_count if x != 0]
    except ValueError:
        pass

    # List manipulation
    # Calculate the number of layers in each group and divide 1 by this number
    value_list = [1 / float(x) for x in new_layer_count]
    # Format the list to one decimal place
    formatted_value_list = ['%.1f' % elem for elem in value_list]
    # Convert the values in list to float
    formatted_value_list_to_float = [float(x) for x in formatted_value_list]
    # Create final list containing each layer and the values of their group
    final_value_list = [x for n,x in zip(new_layer_count,formatted_value_list_to_float) for _ in range(n)]

    # Set number of rows/columns
    nb_row = len(layer_data)
    nb_col = 2
    qTable.setRowCount(nb_row)
    qTable.setColumnCount(nb_col)
    # Hide row index number
    qTable.verticalHeader().setVisible(False)

    # Insert layer names and values
    for row in range(layer_data_count):
        for col in [0]:
            item = QTableWidgetItem(str(layer_data[row]))
            qTable.setItem(row,col,item)
            # Make first column non-editable
            item.setFlags(QtCore.Qt.ItemIsEnabled)
        for col in [1]:
            item = QTableWidgetItem(str(final_value_list[row]))
            qTable.setItem(row,col,item)


texts:
I really hate messy code, but I seem to be rolling in it. I just want to see if anyone has some helpful advice on how to tidy this up.

Zona
Baptismos Mulheres
Conf. Mulheres
Batismos Homems
Conf. Homems

<?php
$currWeek = $CONF->getSetting('current_week');
$zones = $PDO->query("SELECT * FROM zones WHERE active = 1");
foreach($zones as $zone) {
$zoneName = $zone['name'];
$zoneUid = $zone['uid'];
?>

<?php print $zoneName; ?>

<?php

$areas = $PDO->query("SELECT * FROM areas WHERE zone = '".$zoneUid."'");
foreach($areas as $area) {
$areaName = $area['name'];
$areaUid = $area['uid'];
?>

<?php print $areaName; ?>

<?php

$missionaries = $PDO->query("SELECT missionary FROM missionary_areas WHERE semana = '".$currWeek."' AND area_uid = '".$areaUid."'");

$compArr = array();

foreach($missionaries as $missionary) {
$companions = $PDO->query("SELECT CONCAT(title, ' ', mission_name) as name from missionarios WHERE mid = '".$missionary['missionary']."'");

foreach($companions as $comp) {
$compArr[] = $comp['name'];
}

}

$compList = $CONF->commaSeparate($compArr);
?>
<?php print $compList; ?>

<?php
}
}

?>

I am still a bit inexperienced and would like some helpful tips. My MySQL directory stucture is necessaraly crazy so I have to do a bunch of queries to get some simple data. Using PDO is helping quite a bit though.

Edit:

Database structure


texts:
I'm creating a simple generic Map-wrapper with multiple keyed values.

I'm intending to use it with storing edges in a graph, where an edge goes from one vertex to another. Thus, I can fetch any of the two vertices in constant time instead of having to loop to find either to/from.

public class MultiMap<K1 extends Object, K2 extends Object, V extends Object> {

    private Map<K1, V> map1;
    private Map<K2, V> map2;

    /**
     * @param map1
     * @param map2
     */
    public MultiMap() {
        this.map1 = new HashMap<K1, V>();
        this.map2 = new HashMap<K2, V>();
    }

    public void put(K1 key1, K2 key2, V value) {
        this.map1.put(key1, value);
        this.map2.put(key2, value);
    }

    ...

    public V removeByKey1(K1 key) {
        V res = this.map1.remove(key);
        K2 k = null;
        for (Map.Entry<K2, V> entry : this.map2.entrySet()) {
            if (entry.getValue() == res) {
                k = entry.getKey();
                break;
            }
        }
        this.map2.remove(k);
        return res;
    }

    public V removeByKey2(K2 key) {
        V res = this.map2.remove(key);
        K1 k = null;
        for (Map.Entry<K1, V> entry : this.map1.entrySet()) {
            if (entry.getValue() == res) {
                k = entry.getKey();
                break;
            }
        }
        this.map1.remove(k);
        return res;
    }

    ...
}

Is there better way of removing? E.g. using LinkedHashMap and then using the key index to do it in constant time instead of linear?

If there's something else not sitting right with you, tell me. All feedback appreciated.


texts:
What I'm trying to do is very straightforward and easy, but I am wondering whether there is a more elegant solution.

Basically I have a game and I want the difficulty to increase the moment the score gets between 100 - 500, then increase once again when the score is between 500 - 1500, then again when the score is between 1500 - 3000. In total, the difficulty should increase 3 times.

I need to check:

Whether I am in one of those ranges.
Whether I already increased the score when I got in that range.

Here's what I've got.

bool Increased100500 = false;
bool Increased5001500 = false;
bool Increased15003000 = false;

void IncreaseScore()
{
    if (Score >= 100 && Score <= 500 && !Increased100500)
    {
        Increase();
        Increased100500 = true;
    }
    else if (Score >= 500 && Score < 1500 && !Increased5001500)
    {
        Increase();
        Increased5001500 = true;
    }
    else if (Score >= 1500 && !Increased15003000)
    {
        Increase();
        Increased15003000 = true;
    }
}

LE: I should have mentioned that the method above is called multiple times per frame.


texts:
I have the code below, which works successfully, and is used to parse, clean log files (very large in size) and output into smaller sized files. Output filename is the first 2 characters of each line. However, if there is a special character in these 2 characters, then it needs to be replaced with a '_'. This will help ensure there is no illegal character in the filename.
This would take about 12-14 mins to process 1 GB worth of logs (on my laptop). Can this be made faster?
For example, would it help to run this parallel? I am aware I could do }' "$FILE" &. However, I tested and that does not help much. Perhaps AWK itself could run in parallel (the equivalent of  print $0 >> Fpath & )?
Sample log file
email1@foo.com:datahere2
email2@foo.com:datahere2
email3@foo.com datahere2
email5@foo.com;dtat'ah'ere2
wrongemailfoo.com
nonascii@row.com;data.is.junk-Œœ
email3@foo.com:datahere2

Expected Output
# cat em
email1@foo.com:datahere2
email2@foo.com:datahere2
email3@foo.com:datahere2
email5@foo.com:dtat'ah'ere2
email3@foo.com:datahere2

# cat errorfile
wrongemailfoo.com
nonascii@row.com;data.is.junk-Œœ

Code:
#/bin/sh
pushd "_test2" > /dev/null
for FILE in *
do
    awk '
    BEGIN {
        FS=":"
    }
    {
        gsub(/^[ \t"'\'']+|[ \t"'\'']+$/, "")
        $0=gensub("[,|;: \t]+",":",1,$0)
        if (NF>1 && $1 ~ /^[[:alnum:]_.+-]+@[[:alnum:]_.-]+\.[[:alnum:]]+$/ && $0 ~ /^[\x00-\x7F]*$/)
        {
            Fpath=tolower(substr($1,1,2))
            Fpath=gensub("[^[:alnum:]]","_","g",Fpath)
            print $0 >> Fpath
        }
        else
            print $0 >> "errorfile"
    }' "$FILE"
done
popd > /dev/null


texts: Multi class-type Object pool based on Libgdx Pool

texts:
I've done some code so you can obtain Object of any Class from Pool, take a look at it, is it safe? At least it works.

MultiPool class has method obtain with Class param, so can know from which inner-pool obtain Object.

import com.badlogic.gdx.utils.Pool;

import java.lang.reflect.Modifier;
import java.util.HashMap;

public class MultiPool {
    public class MultiPoolException extends Exception {
        public MultiPoolException(String message) {
            super(message);
        }
    }

    public class AnyPool extends Pool<Object> {
        Class<?> type;

        AnyPool(Class<?> type) {
            this.type = type;
        }

        @Override
        protected Object newObject() {
            try {
                return type.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    HashMap<Class<?>, AnyPool> pools = new HashMap<Class<?>, AnyPool>();

    private void initializePool(Class<?> type) {
        pools.put(type, new AnyPool(type));
    }

    @SuppressWarnings("unchecked")
    public <T> T obtain(Class<?> type) {
        if ( Modifier.isAbstract(type.getModifiers()) ) {
            (new MultiPoolException(type.getName() + " is abstract.")).printStackTrace();
            return null;
        }

        if ( pools.get(type) == null ) initializePool(type);

        return (T) pools.get(type).obtain();
    }

    public void free(Object object) {
        Class<?> type = object.getClass();

        if ( pools.get(type) == null ) initializePool(type);

        pools.get(type).free(object);
    }
}

Usage:

MultiPool multiPool = new MultiPool();

String abc = multiPool.obtain(String.class);
SomeOtherClass test = multiPool.obtain(SomeOtherClass.class);

multiPool.free(test);


texts:
I made a simple database class and I wanted to know if there are any improvements I could work on as far as readability, efficiency, methods and making it modular goes.

Any other suggestions are also welcome!

Database.php

class Database
{
    private $config;
    private $pdo;

    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    public function query($sql, $params = null)
    {
        $this->connect();

        $sth    = $this->pdo->prepare($sql);
        $params = is_array($params) ? $params : is_null($params) ? null : [$params];

        if ($params && $sth->execute($params)) {
            return $sth;
        } elseif ($sth->execute()) {
            return $sth;
        }

        return false;
    }

    private function connect()
    {
        if (!$this->pdo) {
            try {
                $dsn       = 'mysql:host=' . $this->config->get('mysql/host') . ';dbname=' . $this->config->get('mysql/database') . ';charset=' . $this->config->get('mysql/charset');
                $this->pdo = new PDO($dsn, $config->get('mysql/username'), $config->get('mysql/password'));

                $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
            } catch (Exception $e) {
                die($e->getMessage());
            }
        }
    }
}


texts:
Based on dropdown value and search text I need to filter a list and return.

Method 1

if (selectedValue == 1 && searchTerm.Length == 0)
return users;

if (selectedValue == 1 && searchTerm.Length > 0)
return users.Where(user=>user.Name == searchTerm).ToList();

if (selectedValue == 2 && searchTerm.Length > 0)
return users.Where(user=>(user.Name == searchTerm && user.Street == "StreetA")).ToList();

if (selectedValue == 2 && searchTerm.Length == 0)
return users.Where(user=>user.Street == "StreetA").ToList();

if (selectedValue == 3 && searchTerm.Length > 0)
return users.Where(user=>(user.Name == searchTerm && user.Street == "StreetB")).ToList();

if (selectedValue == 3 && searchTerm.Length == 0)
return users.Where(user=>user.Street == "StreetB").ToList();

Method 2

if(searchTerm.Length > 0)
{
    if (selectedValue == 1)
    return users.Where(user=>user.Name == searchTerm).ToList();

    if (selectedValue == 2)
    return users.Where(user=>(user.Name == searchTerm && user.Street == "StreetA")).ToList();

    if (selectedValue == 3)
    return users.Where(user=>(user.Name == searchTerm && user.Street == "StreetB")).ToList();
}
else
{
    if (selectedValue == 1)
    return users;

    if (selectedValue == 2)
    return users.Where(user=>user.Street == "StreetA").ToList();

    if (selectedValue == 3)
    return users.Where(user=>user.Street == "StreetB").ToList();
}

I am not convenienced with above logics so please help improve this.


texts: Sherlock is going against the Beast with PowerShell

texts:
I ran into this challenge a couple of times today and thought I could tackle it with PowerShell. I refused to look at other peoples approaches to this hoping to complete it on my own. I'm sure the general idea is the same in either case. I have included more comments than I would normally to help people not familiar with the language/challenge.

  A Decent Number has the following properties:

  Its digits can only be 3's and/or 5's.
  The number of 3's it contains is divisible by 5.
  The number of 5's it contains is divisible by 3.
  If there are more than one such number, we pick the largest one.

  Constraints

  1≤T≤20

  1≤N≤100000

  Input Format

  The first line is an integer, T, denoting the number of test cases.

  The T subsequent lines each contain an integer, N, detailing the number of digits in the number.

  Output Format

  Print the largest Decent Number having N digits; if no such number exists, tell Sherlock by printing -1.

# Split the lines in the string passed as string array. Cast each value as an integer
$inputNumbers = $args[0] -split "`r`n" | ForEach-Object{[int]$_}

# Cycle the numbers. Amount determined by the first line.
for($inputIndex=1;$inputIndex -le $inputNumbers[0];$inputIndex++){
    # Create a loop that runs for the number of passes in the current line of input.
    # Count down from the number until 0
    $highestNumber = $inputNumbers[$inputIndex]..0 | ForEach-Object{
        # Check to see if this digit combination is a decent number.
        # If it is then we pass it thru the pipeline and stop the loop.
        If(($_ % 3) -eq 0 -and (($inputNumbers[$inputIndex] - $_) % 5) -eq 0){
            ("5" * $_).PadRight($inputNumbers[$inputIndex],"3")
            # If we get a result then this is the highest. Exit the loop.
            continue
        }
    }

    # Check the value of $highestNumber. It is possible that for this pass there
    # are no decent numbers. Nulls evaluate to false.
    if($highestNumber){$highestNumber}else{-1}
}

Usage

Save the above code as a ps1 file. Run it passing a multi-line string parameter.

.\Get-DecentNumbers.ps1 "4
1
3
5
11"


texts: API calls organization in Ionic (Angular) application

texts:
I'm doing a prototype of server API calls in my Ionic (Angular) application. I'm considering this use case:

@IonicPage({/* */})
@Component({/* */})
export class SomePage {
  constructor(private api: Api) { }

  ngOnInit() {
    this.api.user.getList();
  }
}

To achieve this I have something like this:

@Injectable()
export class Api {
  constructor(
    public user: UserApi,
    public event: EventApi,
    public search: SearchApi
  ) {

  }
}

@Injectable()
export class UserApi extends BaseApi {
  private static readonly ENDPOINT: string = "user/";

  constructor(public http: HttpClient) {
    super(UserApi.ENDPOINT);
  }

  getList() {
    return this.http.get(this.url);
  }
}

export class BaseApi {
  private host: string = "https://my-site.com/api/";
  protected url: string;

  constructor(endpoint: string) {
    this.url = this.host + endpoint;
  }
}

Next purposes:

Separate API Service from others Servicies
Split one API Service to little parts where each one works with single essence

And I have a few questions about my approach:

Are there any pitfalls in this approach?
Is this a "good" approach to organize API calls? What can I improve or do in another way?


texts: Getting the last date where a given week day occurred

texts:
I'm trying to learn a little bit about functional programming and as my tool I chose F# since I'm a .NET developer and the environment is more natural to me.

In one of my pet projects I'm dealing with dates, so I created a function to get the last date where a given week day occurred. For example, last Tuesday was yesterday (DateTime.Now.AddDays(-1.0)).

#light

module DateTimeExtensions
    open System

    let rec whenWasLastBasedOnDate (weekDay:DayOfWeek, currentDate:DateTime) =
        match currentDate with
        | _ when currentDate.DayOfWeek = weekDay -> currentDate
        | _ -> whenWasLastBasedOnDate(weekDay, currentDate.AddDays(-1.0))

    let whenWasLast (weekDay:DayOfWeek) =
        let currentDate = DateTime.Now
        match currentDate with
        | _ when currentDate.DayOfWeek = weekDay -> currentDate
        | _ -> whenWasLastBasedOnDate(weekDay, currentDate.AddDays(-1.0))

    let now = DateTime.Now
    let lastSunday = whenWasLast DayOfWeek.Sunday
    let lastMonday = whenWasLast DayOfWeek.Monday
    let lastTuesday = whenWasLast DayOfWeek.Tuesday
    let lastWednesday = whenWasLast DayOfWeek.Wednesday
    let lastThursday = whenWasLast DayOfWeek.Thursday
    let lastFriday = whenWasLast DayOfWeek.Friday
    let lastSaturday = whenWasLast DayOfWeek.Saturday