texts:
I built a very basic image slider, but I'm still having trouble refactoring.

I caught myself reusing same code for clicking the previous/next buttons, selecting a slider dot, and the automated sliding.  The difference between these actions is how the index of images changes.  I'm not sure how to break out that piece of code "efficiently".

Here's the sample code: JSFiddle

As an example of duplicate code that I'm not sure how to refactor efficiently:

If I want to select a slider dot:

$("#dots li").click(function() {
    var select = $("#dots li").index(this);
    dotItems.removeClass('active');
    listItems.eq(i).fadeOut(transition_speed);
    i = select;
    dotItems.eq(i).addClass('active');
    listItems.eq(i).fadeIn(transition_speed);
  });

And if I want to select the previous button:

$("#prev").click(function() {
    dotItems.removeClass('active');
    listItems.eq(i).fadeOut(transition_speed);
    i = i >= 0 ? i - 1 : listLen - 1;
    dotItems.eq(i).addClass('active');
    listItems.eq(i).fadeIn(transition_speed);
  });

Hope somebody can take a look at it and at least point me in the right direction.

My background: Worked in Finance a few years, currently self-studying web development ( < 1 year).  Still new to programming, and it may be that I'm still learning to think like a programmer.


texts: Code in Python that parses fund holdings pulled from EDGAR, given a ticker or CIK

texts:
Challenge:
Write code in Python that parses fund holdings pulled from EDGAR, given a ticker or CIK.
Example:

For this example, we will use this CIK: 0001166559
Start on this page.
Enter in the CIK (or ticker), and it will take you here.
Find the "13F" report documents from the ones listed. Here is a "13F-HR".
Parse and generate tab-delimited text from the XML.

Goals:
The code should be able to use any mutual fund ticker. Try morningstar.com or lipperweb.com to find valid tickers.
Be sure to check multiple tickers, since the format of the 13F reports can differ.
My solution
from bs4 import BeautifulSoup
import requests
import re

def getHoldings(cik):
    """
    Main function that first finds the most recent 13F form
    and then passes it to scrapeForm to get the holdings
    for a particular institutional investor.
    """
    urlSec = "https://www.sec.gov"
    urlForms =  "{}/cgi-bin/browse-edgar?action=getcompany&CIK={}&type=13F".format(urlSec, cik)
    urlRecentForm = urlSec + BeautifulSoup(requests.get(urlForms).content,
                                  'lxml').find('a', {"id":"documentsbutton"})['href']
    contents = BeautifulSoup(requests.get(urlRecentForm).content, 'lxml')
    urlTable = "{}{}".format(urlSec,contents.find_all('tr', \
                            {"class" : 'blueRow'})[-1].find('a')['href'])
    return scrapeForm(urlTable)

def scrapeForm(url):
    """
    This function scrapes holdings from particular URL
    """
    soup = BeautifulSoup(requests.get(url).content, 'lxml')

    holdings = set([h.text for h in soup.find_all((lambda tag : 'issuer' in tag.name.lower()))])
    if(not holdings):
        print("No Holdings at: {}".format(url))
        return
    return holdings

Could you provide me some feedback on my code? I completed this challenge recently and just received a general rejection email, so I want to know how could I improve my solution.


texts: Simple retrieving sessionId rows from indexed SQL column is slow

texts:
I have to select all the rows from a database table containing a defined (long)sessionId where the sessionId row is indexed.
But it is slow, and since the code to access it is really simple, I'm wondering where the problem is. Here is the code of the three layers:

var localPath = BusinessClient.Instance.Tracker.GetSpecifiedMilestonesInSessionObjects(milestonesInSession.SessionId).ToList();

public IQueryable<MilestonesInSession> GetSpecifiedMilestonesInSessionObjects(long sessionId)
    {
        var query = from m in _milestonesInSessionRepository.GetAll()
                    where m.SessionId == sessionId
                    select m;

        return query;
    }

    public IQueryable<Model.Tracker.MilestonesInSession> GetAll()
    {
        var query = from milestoneSession in _dataContext.Repository<Linq.TrackerMilestonesInSession>()
                    select new Model.Tracker.MilestonesInSession
                               {
                                   MilestoneId = milestoneSession.MilestoneId,
                                   CreatedDate = milestoneSession.CreatedDate,
                                   SessionId = milestoneSession.SessionId,
                                   ProductId = milestoneSession.ProductId,
                                   TrackerId = milestoneSession.TrackerId,
                                   StatusId = milestoneSession.StatusId,
                                   BankId = milestoneSession.BankId
                               };
        return query;
    }

Here attached the screenshot of the performance using ANTS:

Presentation Layer

Business Layer

Data Access Layer

The sessionId in the database is not unique, but I created an index on them, why accessing it is not an instant operation?


texts:
This is an update of Test thousands of combinations quickly.

I have a physical robot which has a function, turn(degrees). For different robots, there will be small differences in the accuracy of the turn. I have fine turning variables, multiplier and adder. The degrees are multiplied by the multiplier, and then adder is added on.

The data set will be manually created by someone requesting a turn, and recording what the actual turn was. This means the data set will usually be around 4 to 8 results long.

The PRECISION is how accurate we want the result to be. Ideally it would be as precise as possible, but since the robot has a fair amount of unpredictability, 2 d.p is fine.

The Code:

from numpy import arange

# list of actual test results in the form
# (requested turn degrees, actual turn degrees)
REAL_RESULTS = (
    (90, 101),
    (100, 112),
    (110, 123),
    (120, 134),
    (130, 145),
)
# how accurate a multiplier you want
PRECISION = 0.001
# multiplier will be less than this
# and more than negative this
MULTIPLIER_BOUNDS = 10
# number of results to print
PRINT_TOP_RESULTS = 3

def calculateLine(multiplier, test_cases):
    """Calculates the absolute error and adder."""
    # calculate the error with no adder
    error_no_adder = 0
    for test in test_cases:
        error_no_adder -= test[0] * multiplier - test[1]
    # the adder is the average error
    adder = error_no_adder / len(REAL_RESULTS)

    # calculate error with the adder
    error = 0
    for test in test_cases:
        error += abs((test[1] - adder) / multiplier - test[0])

    return error, adder, multiplier

if __name__ == "__main__":
    # calculate results for every multiplier
    results = [calculateLine(multiplier, REAL_RESULTS) for multiplier in
               arange(-MULTIPLIER_BOUNDS, MULTIPLIER_BOUNDS, PRECISION)]
    # sort from lowest error to highest error
    results.sort()

    printed_num = 0
    i = -1
    last_multiplier = 999
    # print the top (least error) x results
    while printed_num < PRINT_TOP_RESULTS:
        i += 1
        # don't print results with very similar precision
        if abs(results[i][2] - last_multiplier) < PRECISION * 20:
            continue
        printed_num += 1
        last_multiplier = results[i][2]
        # print average error, the adder and multiplier
        print("Average error: {:.3f}\nAdder: {:.3f}\nMultiplier: {:.3f}\n"
              .format(*results[i]))

Have I followed standard coding conventions? pep8online says that it is fine.

Is it "better" - performance or conventions - to map the results or use list comprehension? I had previously used map and the calculate function used the global variable REAL_RESULTS, but I changed this because it defeats the purpose of reusable modules if a function relies on predefined global variables.

Are there any areas where performance could be improved? Performance isn't really an issue anymore because it has been hugely improved from my original code, but it's still nice to know if it could be better. Also this code could theoretically be used with a much larger data set where performance could matter.


texts:
I'm not doing too well in school, so to pass my final year, and get my degree I need to do an off-school project. The teacher chose to give me the assignment of an A grade CMS, since I've always had a thing with PHP.

Now I've made a new template class for in this particular CMS, but I'm not completely sure about it, so I came here for your help. Please review my code.

Have I used things in a correct way?
Have I used things in a efficient way?
Is there a better way to achieve the same result?

class template
{

    function __construct( $db, $functions )
    {
        $this->db = $db;
        $this->functions = $functions;
    }

    public function pageExist( $id )
    {
        $query = $this->db->connection->prepare( 'SELECT id FROM ' . $this->functions->prefix( 'pages' ) . ' where id = ?' );
        $query->bind_param( 'i', $id );
        $query->execute();
        $query->store_result();
        if ( $query->num_rows > 0 )
        {
            return true;
        }
            else
        {
            return false;
        }
        $query->close();
    }

    public function fetchPage( $id )
    {
        $query = $this->db->connection->prepare( 'SELECT * FROM ' . $this->functions->prefix( 'pages' ) . ' WHERE id = ?' );
        $query->bind_param( 'i', $id );
        $query->execute();
        $result = $query->get_result();
        while ( $row = $result->fetch_assoc() )
        {
            $this->setTemplateData( 'title', $num_rows[ 'title' ] );

        }
        $query->close();
    }

    public function getTheme()
    {
        $theme = 'theme';
        $query = $this->db->connection->prepare( 'SELECT value FROM ' . $this->functions->prefix( 'settings' ) . ' WHERE name = ?' );
        $query->bind_param( 's', $theme );
        $query->execute();
        if ( ! $query )
        {
            throw new Exception( $query->error(), 1 );
        }
        $query->bind_result( $result );
        while ( $query->fetch() )
        {
            return $result;
        }

    }

    public function loadPage()
    {
        $path = './_templates/' . $this->getTheme() . '/';
            $this->content = file_get_contents( $path . 'header.tpl');
            $this->content .= file_get_contents( $path . 'middle.tpl');
            $this->content .= file_get_contents( $path . 'footer.tpl');
    }

    public function createParameter( $key, $value )
    {
        $this->parameter[ $key ] = $value;
    }

    public function langParameters( $key, $value )
    {
        $this->langParameters[ $key ] = $value;
    }

    public function setTemplateData( $key, $value )
    {
        $this->templateData[ $key ] = $value;
    }

    public function parseParameters()
    {
            foreach ($this->parameter as $key => $value)
            {
                $this->content = str_replace( '{' . $key . '}', $value, $this->content);
            }

            foreach ($this->langParameters as $key => $value)
            {
                $this->content = str_replace( '{' . $key . '}', $value, $this->content);
            }

            foreach ($this->templateData as $key => $value)
            {
                $this->content = str_replace( '{' . $key . '}', $value, $this->content);
            }

        echo $this->content;
    }

    public function handlePageLoad( $id )
    {
        if ( $this->pageExist( $id ) )
        {
            $this->fetchPage( $id );
            $this->loadPage();
            $this->parseParameters();
            return true;
        }
        else
        {
            $this->fetchPage( 404 );
            $this->loadPage();
            $this->parseParameters();
            //header('Location: index.php?page=404');
            echo '! <br /> He\'s a true genius.';
        }
    }

}


texts:
I wrote a script that places documents to the folders they should be (based on my preferences of course).
It even creates the folder if it doesn't exists.
Here's how it works:

You run de script by clicking on it. (idk if I should let this run in the background constantly, I don't use it that much)
Checks the selected directory for files with a "-" in their name.
(Physics- Homework.docx)
It checks the targeted directory (where my folder hierarchy is meant to be) if there's a folder named after the file's name before the "-" part. ("Physics- Homework.docx" goes to a folder named "Physics")
If there isn't a folder, it creates one. If there is a folder, it just moves the file inside

So Like I said in the first step, you have to click to run this, I would love to make it automatic, but I don't want it to run in the background just to move a file twice in a week or so. I would love to know if there's another cool way to achieve this automatic way of working.
My idea (to achieve what I said above) was to create a ".bat" file that runs Word and the script at the same time (this time script keeps running in the background once started), next to script's based functionality, it would also check for the apps running in the background and when Word is closed, it performs the file movement and closes itself. But I don't know if this is a great idea or if it can be done in much simpler way.
I want to know what I could've done better. Since the code is relatively short, I feel like I have done a great job, but I believe that there's always room for improvement.
Here's the code:
import shutil
import os

Dir = "D:/OneDrive/Documents/"  # Where are the files? Add "/" at the end of your directory.
TragetDir = "D:/OneDrive/Documents/school/6a9/"  # Where are the target folders? Add "/" at the end of your directory.

FileNames = glob.glob(Dir + "*-*")  # scans the dir with the selected character (*[selected character]*), searches directly for the name now.

StartIndex = len(Dir)  # The chars of the Dir are useless
for x in range(len(FileNames)):  # Each file gets moved one by one
    Index = FileNames[x].find("-")  # I always create my files using: "class + "-" + topic" way
    SFolder = FileNames[x][StartIndex:Index]  # My folders are always named after the subject, so "Math- exam 1.docx" should be placed in a folder named "Math"

    try: #tries to make a target dir
        os.makedirs(TragetDir + SFolder)
    except: #if the directory already exists just skips this process
        pass

    shutil.move(FileNames[x], TragetDir + SFolder)  # moves to the target folder


texts: Checking if a student ID is present in the database

texts:
What I need to do is fetch the XML link using curl then get a student ID and check if the ID is present in the database. If yes, then I need to get other details from another database table.

My code works fine but it's kinda slow. I later need to add more functions in this which will make the loading speed slower. Is there any way I can improve this code?

It currently takes around 5-6 second to display result when XML has 10-12 ID elements.

<?php

$parseXml = "example.com/xml.xml";
$result = curl_json($parseXml);
if ($result['httpcode'] === 200) {
    $output = simplexml_load_string($result['result']) or die('err');
    if ($output->result) {
        echo 'Results: ';
        foreach ($output->result as $resultItem) {
            echo checkID($resultItem->title, $resultItem->dataID);
        }
        echo '';
    } else {
        echo 'no result';
    }
}

function checkID($title, $id) {
    $con = mysql_connect(HOST, DBUSER, DBPASS);
    if ($con) {
        mysql_select_db(DBNAME);
        $sql = "SELECT * FROM idlist WHERE id='$id'";
        $retval = mysql_query($sql);
        if (!$retval) {
            die();
        }
        $num_rows = mysql_num_rows($retval);
        if ($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
            $out['val'] = 'yes';
            $out['data'] = getInfo($id);
            return $out;
        }
    }
}

function getInfo($id) {
    $con = mysql_connect(HOST, DBUSER, DBPASS);
    if ($con) {
        mysql_select_db(DBNAME);
        $sql = "SELECT * FROM infolist WHERE id='$id'";
        $retval = mysql_query($sql);
        if (!$retval) {
            die();
        }
        if ($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
            $arr = array();
            $arr['name'] = $row['name'];
            $arr['class'] = $row['class'];
            return $arr;
        }
    }
}

function curl_json($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    $result = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $out['result'] = $result;
    $out['httpcode'] = $httpcode;

    return($out);
}


texts: Dynamic programming solution for cross river algorithm

texts:
Working on below cross river problem, and post my code in Python 2.7 using dynamic programming. Any advice on performance improvement in terms of algorithm time complexity, code bugs or code style advice is appreciated.

More specifically, my idea is,

build a DP array to represent if we can reach a location by a certain speed;
when checking whether we are reach a certain location by a certain speed, we check if we can reach (1) location - speed with speed, (2) location - speed with speed + 1, (3) location - speed with speed - 1, if any (1), (2) or (3) is true, it means we can reach a certain location with such specific speed;
For the last location, if could be reached by any speed, return True

Problem,

Given a string representation of the rocks in the river e.g. "*****  *   * * *  *  *", determine whether the river is crossable. Where,

* = landable
  = cannot land there

Suppose Initial location: 0 and Initial speed: 0

in each step:
    1. choose a new speed from {speed, speed + 1, speed - 1} (but not negative)
    2. move speed spaces: loc += speed
    3. if I land on water, I fail
    4. if I land past end of river, I win
    5. otherwise, keep going

For example, below river could be crossed by the first method. So, it should return True.

X~~~~~~~~~~~~~~~~~~~~~_______($)
*****  *   * * *  *  *
011 2  3   4   4  3  3   4 (crossed)
01 2 2 (failed)
01111 2 (failed)

Source code in Python 2.7,

from collections import defaultdict
def can_cross_river(river):
    # key: (location, speed) tuple,
    # value: True or False for whether reachable at a specific location
    # with a specific speed
    dp = defaultdict(lambda : False)
    dp[(0,0)] = True
    for i in range(1, len(river)):
        if river[i] != '*':
            continue
        for speed in range(0,i+1):
            if dp[(i-speed, speed)] or dp[(i-speed, speed-1)] or dp[(i-speed, speed+1)]:
                dp[(i, speed)]= True
                if i == len(river) - 1: # reach end of river at any speed is fine
                    return True
    return False

if __name__ == "__main__":
    river = "*****  *   * * *  *  *" # should return True
    #river = "* *" # should return False
    print can_cross_river(river)


texts:
I have a dropdownbox, ActiviteitAardItems, where ActiviteitAard items can be checked (checkbox). If one (or more) are checked the property Opacity will be changed, and the code beneath will be executed. The Tijdblok mentioned below also has a property Activiteit and ActiviteitAard.

public double Opacity
{
    get
    {
        if (Planning.ActiviteitAardItems.Where(aa => aa.IsChecked == true).Count() > 0)
        {
            if (this.Tijdblokken.Where(t => t.Activiteit != null && t.Activiteit.ActiviteitAard != null).Count() > 0)
            {
                Tijdblok tijdblok;
                var tijdblokken = new List<Tijdblok>();

                foreach (var item in Planning.ActiviteitAardItems.Where(aa => aa.IsChecked == true))
                {
                    tijdblok = this.Tijdblokken.Where(t => t.Activiteit != null && t.Activiteit.ActiviteitAard != null && t.Activiteit.ActiviteitAard.Code == item.Code).FirstOrDefault();
                    if (tijdblok != null)
                        tijdblokken.Add(tijdblok);
                }

                tijdblok = tijdblokken.OrderByDescending(tb => tb.Activiteit.RoosterKleurPrioriteit).FirstOrDefault();

                if (tijdblok != null && tijdblok.Activiteit != null && tijdblok.Activiteit.ActiviteitAard != null)
                {
                    if (Planning.ActiviteitAardItems.Where(aa => aa.IsChecked).Select(x => x.Code).Contains(tijdblok.Activiteit.ActiviteitAard.Code))
                    {
                        return 1.0;
                    }
                    else
                    {
                        return 0.1;
                    }
                }
                else
                {
                    return 0.1;
                }

            }
            else
            {
                return 0.1;
            }
        }

        return 1.0;
    }
}


texts: Raku / Perl6: A module to enable escape codes in the win32 console, naming suggestions

texts:
I have this little project i am about to release.

https://github.com/holli-holzer/perl6-Win-VT

I would be happy about a code review and suggestions for a better name.

Discussion in IRC yielded Terminal::Win::VT or Terminal::Win32::VT::Enable as better alternatives. Or even Win32::Console::VT.

This is the gist of it. There are additional files, but those provide just sugar.

unit module Win::VT;

use NativeCall;

constant STD_INPUT_HANDLE                   = -0xA;
constant STD_OUTPUT_HANDLE                  = -0xB;
constant ENABLE_VIRTUAL_TERMINAL_INPUT      = 0x0200;
constant ENABLE_PROCESSED_INPUT             = 0x0001;
constant ENABLE_PROCESSED_OUTPUT            = 0x0001;
constant ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
constant DWORD  := uint32;
constant BOOL   := int32;
constant HANDLE := Pointer[void];

sub GetConsoleMode(HANDLE, DWORD is rw) is native('Kernel32') returns BOOL { * };
sub SetConsoleMode(HANDLE, DWORD) is native('Kernel32') returns BOOL { * };
sub GetStdHandle(DWORD) is native('Kernel32') returns HANDLE { * };

my HANDLE $input-handle;
my HANDLE $output-handle;
my DWORD $output-mode;
my DWORD $input-mode;

INIT {
    if $*VM.osname eq "mswin32"
    {
        $input-handle  = GetStdHandle( STD_INPUT_HANDLE );
        $output-handle = GetStdHandle( STD_OUTPUT_HANDLE );
    }
}

sub vt-on(Bool :$vt-input=True, Bool :$vt-output=True ) returns Bool is export(:MANDATORY)
{
    return False
        unless $input-handle.defined && $output-handle.defined;

    return False
        unless GetConsoleMode($input-handle,  $input-mode) && GetConsoleMode($output-handle, $output-mode);

    my $new-input-mode  = $input-mode  +| ENABLE_PROCESSED_INPUT  +| ENABLE_VIRTUAL_TERMINAL_INPUT;
    my $new-output-mode = $output-mode +| ENABLE_PROCESSED_OUTPUT +| ENABLE_VIRTUAL_TERMINAL_PROCESSING;

    return (
        ( $vt-input  ?? SetConsoleMode($input-handle, $new-input-mode)  !! 1 ) &&
        ( $vt-output ?? SetConsoleMode($output-handle, $new-output-mode) !! 1 )
    ).Bool;
}

sub vt-off() returns Bool is export(:MANDATORY) {
    return (
        $input-handle.defined && $output-handle.defined &&
        SetConsoleMode($output-handle, $output-mode) &&
        SetConsoleMode($input-handle, $input-mode)
    ).Bool;
}

sub cls() is export(:cls) {
    vt-on;
    print chr(27) ~ '[2J' ~ chr(27) ~ '[;H';
    vt-off;
}


texts:
The follow code should correctly run the test cases at the bottom.

It works correctly.
I just don't feel like this is clearest way I could write it.

A lot of the complexity comes from having to return the middle two characters if the length of the string is even.

Here is a link to the Programing Challenge.

(defn convert-to-zero-based-list [index]
  (- index 1))

(defn convert-to-one-based-list [index]
  (+ index 1))

(defn get-middle-with-offset [s]
    (/ (convert-to-one-based-list (count s)) 2))

(defn get-start-of-middle [s]
    (convert-to-zero-based-list (Math/floor (get-middle-with-offset s))))

(defn get-end-of-middle [s]
    (Math/ceil (get-middle-with-offset s)))

(defn get-middle [s]
    (subs s (get-start-of-middle s) (get-end-of-middle s)))

(= (get-middle "a") "a")
(= (get-middle "aa") "aa")
(= (get-middle "aba") "b")
(= (get-middle "abba") "bb")
(= (get-middle "abcba") "c")

An alternative would be to recursively/iteratively trim off the first and last elements of the string until you reached the middle one or two characters.

(defn trim-first-and-last [s]
  (subs s 1 (dec (count s)))
)

(defn get-middle-recur [s]
  (if (<= (count s) 2)
      s
      (get-middle-recur (trim-first-and-last s))
  )
)

(= (get-middle-recur "a") "a")
(= (get-middle-recur "aa") "aa")
(= (get-middle-recur "aba") "b")
(= (get-middle-recur "abba") "bb")
(= (get-middle-recur "abcba") "c")
(= (get-middle-recur "abccba") "cc")


texts:
Today I'll demonstrate a simple function that searches for a item in all sublists of a list. For this it uses iteration, and keep in mind that it can be slow because of this. How can I improve it? Linked lists?

I doubt __contain__ can do the same.

def ListContainWSublist(searchfor, *args):

    Result = False

    for x in args:
        if type(x) == list:
            Result = ListContainWSublist(searchfor, *x)

        if x == searchfor:
            Result = True

    return Result


texts:
I've created a very plain version of page flip onscroll. I made it to look like turning the pages of a book.
It looks OK on browsers I have (Firefox 52.9, Chrome 49, IE8). Though the effect doesn't work on IE8 and similar old browsers, it still doesn't look messy. I want to use this presentation method on a website.

Are there any parts of the code that I need to create a fallback for?
Could this page be faster?
Are there any accessibility concerns?
Are there any 'Best Coding Practices' that I need to include here?
Any other improvements?

New Question:

Will this effect make viewing a page uncomfortable on touch devices?

CodePen: https://codepen.io/ZechariahRaman/pen/NOYbXL/

var h = 0,
  r = 1,
  y = 0,
  yh = 1,
  section = document.getElementsByTagName("section"),
  d = section[0];

function load() {
  h = window.innerHeight;
  r = 180 / h;
  for (var i = section.length - 1; i >= 0; i--) {
    section[i].style.position = "fixed";
  }
}

function turn() {
  y = window.pageYOffset;
  if (y == 0) {
    section[0].style.transform = "initial";
  }
  if (y >= 0 && y < h) {
    yh = y;
    d = section[0];
    section[1].style.transform = "initial";
  }
  if (y >= h && y < h * 2) {
    yh = y - h;
    d = section[1];
  }
  d.style.transform =
    "perspective(" + h * 5 + "px) rotate3d(1,0,0," + r * yh + "deg)";
}
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  background-color: #274171;
  height: 300vh;
}

section {
  transform-origin: top;
  transition: all 0.3s ease;
}

#p1 {
  z-index: 3;
  background-color: #d9bd75;
}

#p2 {
  z-index: 2;
  background-color: #67a893;
}

#p3 {
  z-index: 1;
  background-color: #353cc9;
}

.page {
  margin: 1vh 9vw;
  height: 98vh;
  width: 80vw;
  display: flex;
}

p {
  margin: auto;
  font-size: 5em;
  padding: 0.5em;
  color: #fff;
  background-color: rgba(19, 41, 79, 0.7);
}

Hi

Short Story

The End


texts: Filtering cards into appropriate list elements

texts:
Background:

I have two lists: one with a list of workcentres and the other with a list of the stations in the centres.

This code matches the stations to the centres by comparing the stations' workcentre number property with the name property of the centres.

    private void WsSorter(WorkcentreList wcl, List<WorkstationCard> wscl)
    {
        // Find index of workcentres
        foreach (Workcentre wc in wcl.WcList)
        {
            foreach (WorkstationCard wsc in wscl)
            {
                if (!(wsc.WorkcentreNo == MAIN_WORKCENTRE_1 ||
                 wsc.WorkcentreNo == MAIN_WORKCENTRE_2 ||
                 wsc.WorkcentreNo == MAIN_WORKCENTRE_3 ))
                {
                    wc.CardList.Add(wsc); // Must be adding to "Other WC"
                }
                // Add to matching workcentre
                else if (wsc.WorkcentreNo == wc.WcName)
                {
                    wc.CardList.Add(wsc);
                }
            }
        }
    }

Question

The lint tool I am using, SonarLint is telling me off for violating the DRY principle in the else if condition.

It works, albeit with poor error checking but I would like to know, is there a better way I could write the code / approach the situation, especially regarding not repeating the line wc.CardList.Add(wsc);?

Additional context: There are 3 main workcentres. All other workcentres (of which there is an arbitrary amount) should be classified under 'other'. I set the code up such that if the stations don't belong to a main workcentre, it must belong in the 'other' workcentre.


texts:
I created a library class in CodeIgniter that handles building the HTML body view.

This class builds the body, adds content and adds javascript element tags at the end. The body is built by using a layout, inserting the content to the appropriate hooks within the layout and finally the javascript. Layout, content and javascript elements have their own objects and instantiated by the objFactory. objFactory was necessary because CI follows a singleton approach and library classes can only be loaded within the super class and not instantiated as a new object. The class also has a default content that can be set and default javascript (i'm using bootstrap).

Most of the variables used by the class I made into class properties. I'm not sure if I did this correctly

Did I implement the correct OOP standards?
Is my code coherent? understandable and well-formed?

private $_CI, $_layout, $_header;
private $_defaultContent    = array();
private $_defaultJS         = array();
private $_JS                = array();
private $_content           = array();

public function __construct($layout = 'Base'){
    $this->_CI      =& get_instance();
    $this->_layout   = $layout;

    $this->_JS['inline'] = "";
    $this->_JS['external'] = array();

    $this->_setDefaultJS();
}

public function addContent($contentOpt){
    $this->_CI->load->library('ObjFactory');
    $this->_content[] = $this->_CI->objfactory->createContentObj($contentOpt);
}

public function addJS($location, $script){
    if($location == "external")
        $_JS[$location][] = $this->_CI->objfactory->createJSTagObj($location, $script);
    else
        $_JS[$location] .= $script;
}

public function build(){
    $layoutObj = $this->_CI->objfactory->createLayoutObj($this->_layout);
    $layoutObj->setContentData($this->_content);

    // build layout with content
    $data['content'] = $layoutObj->build();

    // build script elements
    $data['scripts'] = $this->_buildJS();

    // build actual body and close </body>
    $this->_CI->load->view('body.php',$data);
}

private function _buildContentHtml(){
    $htmlString = "";

    foreach($this->_content as $content)
    {
        $htmlString .= $content->build();
    }

    return $htmlString;
}

private function _buildJS(){
    return $this->_generateJSHtmlString("default").
           $this->_generateJSHtmlString("external").
           $this->_generateJSHtmlString("inline");
}

private function _generateJSHtmlString($type){
    $jsString = "";

    switch($type)
    {
        case "default":
            $jsCollection = $this->_defaultJS;
            break;

        case "external":
            $jsCollection = $this->_JS["external"];
            break;

        default:
            if(strlen($this->_JS["inline"]) > 0)
            {
                $newJSObj = $this->_CI->objfactory->createJSTagObj($this->_JS["inline"]);
                $jsString = $newJSObj->build();
            }
            return $jsString;
            break;
    }

    foreach($jsCollection as $jsTagObj)
        $jsString .= $jsTagObj->build();

    return $jsString;
}

private function _setDefaultJS(){
    $script1 = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js";
    $script2 = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js";

    $this->_defaultJS[] = $this->_CI->objfactory->createJSTagObj('external', $script1);
    $this->_defaultJS[] = $this->_CI->objfactory->createJSTagObj('external', $script2);
}


texts: Transforming data from an API using Typescript and Lodash

texts:
As a front-end developer, I am given the following result from an API, an array of objects that looks like:
[{
    Color: "#065b79",
    GroupName: "VXYZ",
    QuoteCount: 4,
    SortOrder: 0,
    TabCategoryID: "CHSI1",
    TabCategoryName: "Workers' Compensation",
    TabCategoryOrder: 0,
    TabID: 1,
    TabName: "new"
}]

I need to display the data in a more hierarchical/nested format:
[{
    GroupName: 'VXYZ',
    TabCategories: [
        {
            TabCategoryID: 'CHSI1',
            TabCategoryName: "Workers' Compensation",
            TabCategoryOrder: 0,
            Tabs: [
                {
                    Color: '#065b79',
                    SortOrder: 0,
                    TabID: 1,
                    TabName: 'new',
                    QuoteCount: 4
                }
            ]
        }
    ]
}]

Any data in an array can have any number of array items. In the models above, I just use a single instance of each array item.
This is the code I used to format the data
I'm using Typescript and lodash. The API is experimental, and our policy is to just use the any type for any data coming from experimental APIs. This explains the (Quotes: any) — it is the data from the API.
public FormatQuoteSummaries(Quotes: any): any {

    return _(Quotes)
    .map(Quote => Quote.GroupName)
    .uniq()
    .map(UniqueGroupName => {
        const GroupName = UniqueGroupName
        const AllTabCategories = _.filter(Quotes, (Quote: any) => {
            return Quote.GroupName === UniqueGroupName
        })
        const TabCategories = _(AllTabCategories).map(TabCategory => {
            return {
                TabCategoryID: TabCategory.TabCategoryID,
                TabCategoryName: TabCategory.TabCategoryName,
                Tabs: _.filter(Quotes, (Quote: any) => {
                    return Quote.TabCategoryName === TabCategory.TabCategoryName &&
                        Quote.GroupName === TabCategory.GroupName
                })
            }
        })
            .uniqBy('TabCategoryID')
            .value();

        return {
            GroupName,
            TabCategories
        }
    })
    .value();
}


texts:
I just started learning Ruby and thought that this relatively simple HackerRank challenge would be a good opportunity to try to write clean, tested and documented code without getting bogged down in very complex problems.

  In this challenge, your task is to write a method which takes an array of strings (containing secret enemy message bits!) and decodes its elements using ROT13 cipher system; returning an array containing the final messages.

I'd like to know if this follows the "Ruby Way" (I'm willing to bet it doesn't!) and I am open to improvements on all aspects of the code, including the documentation, which is meant to follow RDoc format.

I use Ruby v 2.4. Note that, coming from a mostly Python background, there may be some patterns that are very Python-like, if so please point out if there's a more Ruby way of doing it!

I am also planning to learn about TDD libraries with Ruby soon, for now using that short solution from Stack Overflow seemed sufficient for this exercise.

# AssertionError class & assert method copied from Stack Overflow
# https://stackoverflow.com/a/3264330/3626537
class AssertionError < RuntimeError
  # Extends RunTimeError
end

def assert &block
  # Evaluates whether the input block is true and raises AssertionError if not
  # +block+:: the block to evaluate
  raise AssertionError unless yield
end

def is_uppercase_letter? str
  # Evaluates whether a single is a single uppercase letter, i.e.: A-Z
  # +str+:: string to evaluate
  str.length == 1 && /[[:upper:]]/.match(str)
end

assert { is_uppercase_letter? "A" }
assert { !is_uppercase_letter? "a" }
assert { !is_uppercase_letter? "Hello" }

def is_lowercase_letter? str
  # Evaluates whether a string is a single lowercase letter, i.e.: a-z
  # +str+:: string to evaluate
  str.length == 1 && /[[:lower:]]/.match(str)
end

assert { is_lowercase_letter? "a" }
assert { !is_lowercase_letter? "A" }
assert { !is_lowercase_letter? "hello" }

def rot13_char ch
  # Apply ROT13 cipher to a single character
  # - Each letter is rotated by half of the alphabet, or 13 places
  # - Original case is preserved
  # - Non-letter characters remain unchanged
  # - https://en.wikipedia.org/wiki/ROT13
  # +ch+:: the character to apply ROT13 to
  rot_byt = ch.ord + 13
  if is_uppercase_letter? ch
    rot_byt <= "Z".ord ? rot_byt.chr : (rot_byt - 26).chr
  elsif is_lowercase_letter? ch
    rot_byt <= "z".ord ? rot_byt.chr : (rot_byt - 26).chr
  else
    ch
  end
end

assert { rot13_char("W") == "J" }
assert { rot13_char("J") == "W" }
assert { rot13_char("j") == "w" }
assert { rot13_char("w") == "j" }
assert { rot13_char("?") == "?" }

def rot13_string str
  # Apply ROT13 cipher to all characters in a string
  # +str+:: the string to apply ROT13 to
  chars = str.split('')
  results = []
  chars.each do |ch|
    results.push(rot13_char ch)
  end
  results.join("")
end

assert { rot13_string("Why did the chicken cross the road?") == "Jul qvq gur puvpxra pebff gur ebnq?" }
assert { rot13_string("Gb trg gb gur bgure fvqr!") == "To get to the other side!" }

# puts rot13_string "Why did the chicken cross the road?"
# puts rot13_string "To get to the other side!"
# puts rot13_string "Jul qvq gur puvpxra pebff gur ebnq?"
# puts rot13_string "Gb trg gb gur bgure fvqr!"

def rot13 messages
  # Apply ROT13 to an array of "messages" i.e. strings
  # +messages+:: the array of strings to apply ROT13 to
  rotated = []
  messages.each do |msg|
    rotated.push(rot13_string msg)
  end
  rotated
end

assert do
  input = ["Why did the chicken cross the road?", "To get to the other side!"]
  expected = ["Jul qvq gur puvpxra pebff gur ebnq?", "Gb trg gb gur bgure fvqr!"]
  actual = rot13 input
  expected == actual
end

assert do
  input = ["Jul qvq gur puvpxra pebff gur ebnq?", "Gb trg gb gur bgure fvqr!"]
  expected = ["Why did the chicken cross the road?", "To get to the other side!"]
  actual = rot13 input
  expected == actual
end


texts: Detecting the presence of multiple URL segments

texts:
I have two versions of a function that performs the same task, however I'm not sure which one to use. Speed is something to take into consideration, but I also want to know what the best practice is. Below is the same function, except one uses an If statement to throw an exception where as the other uses the try catch.

private string getCampaignUrl(IEnumerable<BaseFilterDto> baseFilters)
{
    try
    {
        var campaignSegments = baseFilters.Where(x => x.SegmentType == UrlSegmentType.Campaign);
        if (campaignSegments.Any())
        {
            return campaignSegments.Single().Url;
        }
        return string.Empty;
    }
    catch (InvalidOperationException ex)
    {
        throw new InvalidDuplicateUrlSegmentException("Multiple Campaign Url Segments Found", ex);
    }
}

private string getCampaignUrl(IEnumerable<BaseFilterDto> baseFilters)
{
    var campaignSegments = baseFilters.Where(x => x.SegmentType == UrlSegmentType.Campaign);
    if (campaignSegments.Any())
    {
        if (campaignSegments.Count() != 1)
        {
            throw new InvalidDuplicateUrlSegmentException("Multiple Campaign Url Segments Found");
        }
        return baseFilters.Single(x => x.SegmentType == UrlSegmentType.Campaign).Url;
    }
    return string.Empty;
}


texts:
Q: Given a list, reverse the order of its elements (don't use
  collections).

Here is my solution:

public static <T> void reverse(List<T> list) {
    if (list.size() > 0) {
        T t;
        t = list.get(0);
        list.remove(0);
        reverse(list);
        list.add(t);
    }
}

I want to know if this is an efficient way of reversing a list
Is this working for every list as input?


texts: Combining CSVs using ruby to match headers

texts:
I am trying to write a ruby script that will take all of the CSVs in a given directory and map their headers out so that duplicate columns will match up and columns unique to a file will have their own column in the final data file. The following code produces the output I desire, however something about it seems overly complicated and clumsy. Are there better practices or patterns I should follow to accomplish this? For example it seems to me like the master_hash variable should lose scope when I transfer it to the key_arr, but when I try to make the code reflect that I end up overwriting it each time I open a new file. Am I trying to hard to avoid "slurping" the files? Can this be done using less memory/faster? Forgive me if this question is too general in nature and if I can improve it to be more useful please let me know.

require 'CSV'
key_arr = [] # create Key array to store the headers
master_hash = {} # create master hash to consolidate headers
# get each csv in file
Dir.glob('datasample*.csv').each do |file|
  # open each csv
  File.open(file) do |csv|
    # Create a temporary hash of the headers
    temp_hash = Hash[csv.readline.split(',').map.with_index.to_a]
    # merge temporary hash to master hash
    master_hash = master_hash.merge(temp_hash)
  end
  key_arr = master_hash.keys # Put keys from hash into array
end

CSV.open('dest.csv', 'w') do |dest_csv| # open destination file
  dest_csv << key_arr # write header row
end

Dir.glob('datasample*.csv').each do |file| # get all the csv's to be merged
  # Open destination file in append mode
  CSV.open('dest.csv', 'a', headers: true) do |dest_csv|
    # open each source file for reading
    CSV.open(file, headers: true) do |source_csv|
      source_csv.each do |row| # iterate over each row of the source file
        row_arr = Array.new(key_arr.length) # create array to hold Row
        row.each do |cell| # get each header/field combination
          # iterate over the key arr
          # (key arr is the total number of fields on the final csv)
          key_arr.length.times do |master_key_index|
            # check if the header for the selected cell matches the header
            # at the index on the key array to determine position in row array
            if cell[0] == key_arr[master_key_index]
              # set row array element to cell value if a match
              row_arr[master_key_index] = cell [1]
            end
          end
        end
        dest_csv << row_arr # Write row to dest_csv
      end
    end
  end
end

While the scale of this individual script is relatively small and performance isn't a huge concern per se, I would rather get into the habit of using the "right" tools for the job than just guessing. Also, sorry about any formatting issues here. I can put this on gist if need be.


texts: JavaScript solution for diagonal difference

texts:
hackerrank.com - diagonal difference:

  Problem Statement

  You are given a square matrix of size N×N. Calculate the absolute
  difference of the sums across the two main diagonals.

  Input Format

  The first line contains a single integer N. The next N lines contain N
  integers (each) describing the matrix.

  Constraints

  \$1 \le N \le 100\$
  \$−100 \le A[i] \le 100\$

  Output Format

  Output a single integer equal to the absolute difference in the sums
  across the diagonals.

  Sample Input

3
11 2 4
4 5 6
10 8 -12

  Sample Output

15

  Explanation

  The first diagonal of the matrix is:

11
    5
        -12

  Sum across the first diagonal = 11+5-12= 4

  The second diagonal of the matrix is:

        4
    5
10

  Sum across the second diagonal = 4+5+10 = 19

  Difference: |4-19| =15

How can this solution be improved?

function processData(input) {
    inputAll = input.split("\n");
    var currentLine = 0;
    var numberOfInputs = parseInt(inputAll[currentLine].trim(), 10);

    currentLine = 1;
    var sumFirstDiagonal = 0;
    var sumSecondDiagonal = 0;
    var difference = 0;
    for(currentLine = 1 ; currentLine <= numberOfInputs ; currentLine++)
        {
            var inputs = inputAll[currentLine];
            var inputArray = inputs.split(" ");

            for(var i=0 ; i<=(numberOfInputs-1);i++)
                {
                    if(i == (currentLine - 1))
                        {

                            sumFirstDiagonal = sumFirstDiagonal + parseInt(inputArray[i]);
                        }
                }

            for(var j=(numberOfInputs-1) ; j>=0;j--)
                {
                    if(j ==  ( (numberOfInputs - 1) - (currentLine - 1)))
                        {

                            sumSecondDiagonal = sumSecondDiagonal + parseInt(inputArray[j]);
                        }
                }

        }
    difference = sumFirstDiagonal - sumSecondDiagonal;
    difference = Math.abs(difference);
    process.stdout.write(""+difference+"\n");
}


texts: Refactor jquery (coffescript) code with checkboxes

texts:
I have two different set of checkboxes. With the coffescript code below I set the maximum amount of checkable items at 3. I would like to refactor this code, to be cleaner and compact, but I can't get it.

$("div.feature_list :checkbox").click ->
  if $("div.feature_list :checked").length >= 3
    $("div.feature_list :checkbox:not(:checked)").attr "disabled", "disabled"
    $("div.feature_list :checkbox:not(:checked)").button disabled: true
  else
    $("div.feature_list :checkbox:not(:checked)").button disabled: false

$("div.style_list :checkbox").click ->
   if $("div.style_list :checked").length >= 3
     $("div.style_list :checkbox:not(:checked)").attr "disabled", "disabled"
     $("div.style_list :checkbox:not(:checked)").button disabled: true
   else
     $("div.style_list :checkbox:not(:checked)").button disabled: false


texts:
def toPairs[A](xs : Seq[A]) : Seq[Tuple2[A,A]] = {
      @tailrec
      def accumulator(as : Seq[A], accum: Seq[Tuple2[A,A]]) : Seq[Tuple2[A,A]] = as match {
        case Nil => accum
        case x :: tail => tail match {
          case Nil => accum
          case _ =>  accumulator(as.tail, accum :+ (x,tail.head))
        }
      }

      accumulator(xs, Seq.empty[Tuple2[A,A]])
    }

I use this code for the following use case: for a Seq[A] i.e. List(1,2,3) I want a Seq of Tuples of A i.e. List((1,2)(2,3)). Is this the most optimal, idiomatic way in Scala, what could be improved?

For the record: the order of the elements is important and is expected to be congruent with the example in the preceding paragraph.


texts: Show/hide text field depending on select option

texts:
I'm new with JavaScript and need your advice. The idea is to show/hide text field depending on select option. I have a working code, but I believe it could be more readable and better. What have I missed?

   <script type="text/javascript">
<!--
    function showHide(){
        var selectedValue =document.getElementById("choice_criteria_id").value;
        var src_addr = document.getElementById("id_src_addr");
        var dst_addr = document.getElementById("id_dst_addr");
        var port = document.getElementById("id_port");
        var port_range = document.getElementById("id_port_range");

        if (selectedValue == "source_ip"){
            src_addr.style.display = "inline";
            dst_addr.style.display = "none";
            port.style.display = "none";
            port_range.style.display = "none";

        } else if (selectedValue == "dest_ip"){
            dst_addr.style.display = "inline";
            src_addr.style.display = "none";
            port.style.display = "none";
            port_range.style.display = "none";

        } else if (selectedValue == "port"){
            port.style.display = "inline";
            src_addr.style.display = "none";
            dst_addr.style.display = "none";
            port_range.style.display = "none";

        } else if (selectedValue == "port_range"){
            port_range.style.display = "inline";
            src_addr.style.display = "none";
            dst_addr.style.display = "none";
            port.style.display = "none";
        }
}

-->
</script>


texts:
I have been developing this plugin architecture, mostly for fun and education, its a simple WinForm with some plugin logic and two plugins, i want to know if there is a better way of doing it.

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Plugin_architecture
{
    public partial class Form1 : Form
    {
    // -----------------------Plugin logic ----------------------------------

    private static IEnumerable<Type> getDerivedTypesFor(Type baseType)
    {
        var assembly = Assembly.GetExecutingAssembly();
        return assembly.GetTypes().Where(baseType.IsAssignableFrom).Where(t => baseType != t);
    }

    public void invokePlugin(object sender, EventArgs e, string pluginIdentifier) {
        Type type = Type.GetType(pluginIdentifier);
        object instance = Activator.CreateInstance(type);
        MethodInfo method = type.GetMethod("start");
        method.Invoke(instance, null);
    }

    public void registerPlugins() {
        // Register plugins at application startup
        IEnumerable<Type> plugins = getDerivedTypesFor(typeof(Plugin));

        foreach(Type plugin in plugins) {

            LinkLabel pluginLabel = new LinkLabel();
            pluginLabel.Text = plugin.ToString();
            pluginLabel.Click += delegate(object sender, EventArgs e) { invokePlugin(sender, e, plugin.ToString()); };
            pluginContainer.Controls.Add(pluginLabel);

        }
    }
    // --------------------------------------------------------------------------

    public Form1()
    {
        InitializeComponent();
        registerPlugins();
        }
    }
}

Plugin.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

abstract class Plugin
{
/*
 * Base class for plugins
 * Implement the start method and add any functionality you want. The start method will be
 * called each time the plugin is started. Use the stop method to do any nessesary cleanup.
 */

//public void init() {
//    // Initialize plugin
//}

//public void register() {
//    // Register plugin in application
//}

abstract public void start();
abstract public void stop();
}

ServicePlugin.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

class ServicePlugin : Plugin
{
override public void start() {

    const string message = "Yeahh! Plugins!!";
    const string caption = "Plugins!";
    var result = MessageBox.Show(message, caption,
                                 MessageBoxButtons.OK,
                                 MessageBoxIcon.Information);
}
override public void stop() {

}
}

ClientPlugin.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Plugin_architecture.Plugins.ClientPlugin;

class ClientPlugin : Plugin
{
override public void start() {

    Client frm = new Client();
    frm.Show();
}
override public void stop() {

    }
}

Client.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Plugin_architecture.Plugins.ClientPlugin
{
    public partial class Client : Form
    {
        public Client()
        {
            InitializeComponent();
        }
    }
}

The code works great, and should compile without problems.


texts:
I wrote a BMI Calculator. I tested the code and everything seems to be working fine. I would like to check if there is any room for improvement.

class bmi:
    def __init__(self):
        to_start = input("Y to start N to exit: ")
        if to_start in ("Y","y"):
            found = False
            while not found:
                weight_input = float(input("Please enter your weight(kg): "))
                if weight_input < 0:
                    print("Invalid Value")
                else:
                    weight_confirm = input("Y to confirm. N to exit: ")
                    if weight_confirm in ("Y","y"):
                        while not found:
                            height_input = float(input("Please enter your height(m): "))
                            if height_input < 0:
                                print("Invalid Value")
                            else:
                                BMI = round(weight_input/(height_input*height_input),2)
                                print ("Your BMI is: ",BMI)
                                if BMI < 18.5:
                                    print("Under-Weight")
                                    found = True
                                elif 18.5 <= BMI <= 24.99:
                                    print("Healthy Weight")
                                    found = True
                                elif 25.0 <= BMI <= 29.99:
                                    print("Over-weight")
                                    found = True
                                elif BMI > 30:
                                    print("Obese")
                                    found = True
                    else:
                        print("Re-enter")
                        found = False
        else:
            exit()

if __name__ == '__main__':
    a = bmi()


texts: Probability suite for an array of elements

texts:
I wrote a function that can be used to generate a probability distribution for an array of elements (probGen()), and another that can be used to select an element from an array with a specified probability (probSelect()). I want to optimise my code.

probGen.php

<?
    require_once("randX.php");  #"randX()" generates a random floating point number in a specified range.
    error_reporting(E_ERROR | E_WARNING | E_PARSE);

    function probGen(array $arr, float $control = 0.01)
/*
*   Generates a valid, random probability distribution for a given array of elements, that can be used in conjunction with "probSelect()".
*   Input:
        $arr: An array of elements.
        $control: A value that decides how much mass is allowed to be unilaterally dumped onto one element. A high value would permit distributions where most of the mass is concentrated on one element.
        If an invalid value is provided, the default is used.
*   Output: An associative array where the keys are the elements in the original array, and the values are their probabilities.
*/
    {
        $control = ($control <= 1 && $control >= 0)?($control):(0.00001);   #Use the default value if an invalid number is supplied.
        static $result = [];    #Initialises $result with an empty array on first function call.
        static $max = 1;    #Initialises $max with 1 on first function call.
        foreach ($arr as $value)
        {
            $x = randX(0, $max);    #Random probability value.
            $result[$value] = ($result[$value] + $x)??0;    #Initialise the array with 0 on first call, and on subsequent calls increment by $x to assign probability mass.
            $max -= $x;     #Ensures that the probability never sums to more than one.
        }
/*
*   After the execution of the above code, there would be some leftover probability mass.
*   The code below adds it to a random element.
*/
        $var = array_values($arr);
        if($max <= $control)    #To limit concentration of most of the probability mass in one variable.
        {
            $result[$var[rand(0,(count($var)-1))]] += $max; #Selects a random key and adds $max to it.
            return $result;
        }
        else
            return probGen($arr, $control);
    }
?>

probSelect.php

<?
    require_once("confirm.php");

    function probSelect(array $arr)
/*
*   A function to select an element from an array with indicated probabilites.
*   Input: An associative array whose keys are the elements to be selected from, and whose values are the associated probabilities.
*   Output: The selected element, or "NULL" if an invalid probability distribution was supplied.
*/
    {
        if(confirm($arr))
        {
            $var = lcg_value(); #The random float that would be used to select the element.
            $sum = 0;
            foreach ($arr as $key => $value)
            {
                $sum += $value;
                if($var <= $sum)
                    return $key;
            }
        }
        else
        {
            print("ERROR!!! The supplied probability distribution must sum to 1. <br>");
            return null;
        }
    }
?>

Dependencies

The required functions in case they are necessary for evaluating performance:

randX.php

<?
    function randX(float $a, float $b): float
/*
*   Generates a random number between between two real numbers (both inclusive).
*   Input: Two floating point numbers.
*   Output: A random floating point number.
*/
    {
        $max = max($a, $b);
        $min = min($a, $b);
        $x = $max - $min;
        $y = lcg_value()*$x;
        return ($min+$y);
    }
?>

confirm.php

<?
    function confirm(array $arr)    #Confirms that the supplied array has a valid probability distribution
    {
        return (array_sum($arr) == 1)?true:false;
    }
?>


texts:
We have this long .htaccess mainly rewriting our URLs. Everything works fine (except blog titles containing a ' , but we're working on that) but I'm sure it can be shorter. Feel free to review our code and propose some generic or simpler ways to rewrite the URLs instead of rewriting each and every concerned page like the example below.

Options +FollowSymlinks
RewriteEngine on

RewriteCond %{HTTP_HOST} ^oursite\.site$ [OR]
RewriteCond %{HTTP_HOST} ^www\.oursite\.site$
RewriteRule ^admin\/?$ "http\:\/\/oursite\.site\/admin\/connexion" [R=301,L]

# Rewrite spaces as long as there are more than 1 spaces in URI
RewriteRule "^(\S*)\s+(\S*\s.*)$" /$1-$2 [L,NE]

# Rewrite spaces when there is exactly 1 space in URI
RewriteRule "^(\S*)\s(\S*)$" /$1-$2 [L,R=302,NE]

#Redirect non-www to www
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

#Rewrite urls blog
RewriteRule blog/(.*)/([0-9]+)-(.*)$ blogpost.php?brand=$1&blog_id=$2&titre=$3

#Rewrite urls brands
RewriteRule brand/([0-9]+)-(.*) brand.php?id=$1&brand=$2

#Rewrite urls shop brands
RewriteRule shop/brands/([0-9]+)-(.*) shopbrand.php?id=$1&brand=$2

#Rewrite urls shop category
RewriteRule shop/category/([0-9]+)-(.*) shopcategory.php?id=$1&cat_nom=$2

#Rewrite ADMIN profile
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/profil$ admin/profil.php?user_id=$1&brand=$2

#Rewrite ADMIN panel
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/panel$ admin/panel.php?id=$1&brand=$2

#Rewrite ADMIN panel-blog
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/blog$ admin/panel-blog.php?id=$1&brand=$2

#Rewrite ADMIN panel-blog-add
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/blog-add$ admin/panel-blog-add.php?user_id=$1&user_brand=$2

#Rewrite ADMIN panel-blog-modif
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/blog-modif$ admin/panel-blog-modif.php?id=$1&brand=$2

#Rewrite ADMIN post-modif
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/post-modif/([0-9]+)$ admin/post-modif.php?user_id=$1&user_brand=$2&blog_id=$3

#Rewrite ADMIN add
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/add$ admin/add.php?user_id=$1&user_brand=$2

#Rewrite ADMIN update
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/update/([0-9]+)$ admin/update.php?user_id=$1&user_brand=$2&blog_id=$3

#Rewrite ADMIN delete
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/delete/([0-9]+)$ admin/delete.php?id=$1&brand=$2&blog_id=$3

#Rewrite ADMIN panel-prod
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/boutique$ admin/panel-prod.php?id=$1&brand=$2

#Rewrite ADMIN panel-prod-add
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/boutique-add$ admin/panel-prod-add.php?id=$1&brand=$2

#Rewrite ADMIN panel-prod-modif
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/boutique-modif$ admin/panel-prod-modif.php?id=$1&brand=$2

#Rewrite ADMIN prod-modif
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/produit-modif/([0-9]+)$ admin/prod-modif.php?id=$1&brand=$2&prod_id=$3

#Rewrite ADMIN prod-add
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/produit-add$ admin/prod-add.php?user_id=$1&user_brand=$2

#Rewrite ADMIN prod-update
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/produit-update/([0-9]+)$ admin/prod-update.php?id=$1&brand=$2&prod_id=$3

#Rewrite ADMIN prod-delete
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/produit-delete/([0-9]+)$ admin/prod-delete.php?id=$1&brand=$2&prod_id=$3

#Rewrite ADMIN faq
RewriteRule admin/([0-9]+)-([a-zA-Z0-9\-]+)/faq$ admin/faq.php?id=$1&brand=$2

#Remove php extensions
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L]

ErrorDocument 404 http://oursite.site/404

#CACHESYSTEM
<FilesMatch "(?i)^.*\.(ico|flv|jpg|jpeg|png|gif|js|css)$">
ExpiresActive On
ExpiresDefault A2592000
</FilesMatch>

#MAINTENANCE SYSTEM (if required)
#RewriteCond %{REQUEST_URI} !/maintenance.php$
#RewriteCond %{REMOTE_ADDR} !^555\.555\.555\.555
#RewriteRule $ /maintenance [R=302,L]


texts:
I tried to implement a definitive, reliable URL query string parser that handles every corner case:

it tries to be efficient by avoiding regex
it takes full URLs or just query strings (as long as the query string begins with a question mark)
it ignores the hash value
it handles multiple equal parameter names
it handles parameter names that equal built-in JavaScript methods and keywords

What do you think - did I miss something?

function parseURLParams(url) {
  if (url === null) return;

  var queryStart = url.indexOf("?") + 1,
      queryEnd   = url.indexOf("#") + 1 || url.length + 1,
      query      = url.slice(queryStart, queryEnd - 1);

  if (query === url || query === "") return;

  var params = {},
      nvPairs = query.replace(/\+/g, " ").split("&");

  for (var i=0; i<nvPairs.length; i++) {
    var nv = nvPairs[i],
        eq = nv.indexOf("=") + 1 || nv.length + 1,
        n  = decodeURIComponent( nv.slice(0, eq - 1) ),
        v  = decodeURIComponent( nv.slice(eq) );
    if ( n !== "" ) {
      if ( !Object.prototype.hasOwnProperty.call(params, n) ) {
        params[n] = [];
      }
      params[n].push(v);
    }
  }
  return params;
}

It returns an object of arrays for parsed URLs with query strings and undefined if a query string could not be identified.

I used this in an answer over at SO.


texts: Is this a decent way of writing a start-stop-daemon script?

texts:
This is the first time I've written a start-stop-daemon script, so I would love some feedback. :) The goal is to have it start late, when the network and everything is ready. I also have 2 other start-stop-daemons that depend on this once being started before they launch and are nearly identical.

#! /bin/sh
# chkconfig 345 85 60
# description: startup script for foo
# processname: foo

NAME=foo
DIR=/etc/foo/services
EXEC=foo.py
PID_FILE=/var/run/foo.pid
IEXE=/etc/init.d/foo
RUN_AS=root

### BEGIN INIT INFO
# Provides:          foo
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     5
# Default-Stop:      0 1 2 3 6
# Description:       Starts the foo service
### END INIT INFO

if [ ! -f $DIR/$EXEC ]
then
        echo "$DIR/$EXEC not found."
        exit
fi

case "$1" in
  start)
        echo -n "Starting $NAME"
    cd $DIR
    start-stop-daemon -d $DIR --start --background --pidfile $PID_FILE --make-pidfile --exec $EXEC --quiet
        echo "$NAME are now running."
        ;;
  stop)
    echo -n "Stopping $NAME"
        kill -TERM `cat $PID_FILE`
    rm $PID_FILE
        echo "$NAME."
        ;;
  force-reload|restart)
        $0 stop
        $0 start
        ;;
  *)
        echo "Use: /etc/init.d/$NAME {start|stop|restart|force-reload}"
        exit 1
    ;;
esac
exit 0


texts: Project Euler # 20 factorial digit sum in Python

texts:
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100!

def fact(n):
    """returns factorial of n."""
    if n <= 1:
        return 1
    return n * fact(n - 1)

def count_digits(n):
    """Assumes n > 1.
    returns sum of digits of n's factorial."""
    factorial = fact(n)
    total = 0
    for digit in str(factorial):
        total += int(digit)
    return total

if __name__ == '__main__':
    print(count_digits(100))


texts: Reading a file chunk by chunk in QT 4.3.3

texts:
I have following  code in QT in

// myEditor.h
class myEditor : QScintilla {
    public:
        readFile();
};

#include "myEditor.h"
// myEditor.cc
myEditor::readFile() {
   FILE* fp = fopen("mynew.v","r"):
   QTextStream ts(fp, QIODevice::ReadOnly);
   /* reading the  text stream  buffer by buffer
   bufferSize is calculated using following formula
   2 to power(k) *  n  =  2 to power 31*
   where n is  size of each block in linux filesystem*/

   int bufferSize =(1024* 1024)/2;
   do {
      QString s = ts.read(bufferSize);
      append(s);
    } while(!ts.atEnd());
}

I calculated the bufferSize as per comments .It will be helpful if someone can review the code and let me know if there are issues.


texts: Builder pattern for Codeigniter ActiveRecord queries

texts:
I am using Codeigniter and it's ActiveRecord.

I had this idea for a base class that provided a generic getter/setter for doing simple queries on a database. I have a lot of database objects that could benefit from not having to duplicate the basic query patterns.

Instead of writing functions whose sole purpose were to chain a few active record queries and return the result, I could instead do it with a generic $parameters array and providing the table name via the function call.

<?php

class ORMModel extends CI_Model {

    public function __call($name, $args) {
        $method = strtolower(substr($name, 0, 3));
        $object = substr($name, 3);

        // Parsing arguments
        $params = (isset($args[0])) ? $args[0] : array();
        $single = (isset($args[1])) ? $args[1] : false;
        $count = (isset($args[2])) ? $args[2] : false;
        $page = (isset($args[3])) ? $args[3] : '';
        $per_page = (isset($args[4])) ? $args[4] : '';

        if ($method === 'get') {
            $this->db->from($object);
        } elseif ($method !== 'set') {
            throw new Exception('Unsupported method ' . $name);
        }

        if (method_exists($this, $name)) {
            $this->{$name}($params);
        } elseif ($method === 'get') {
            $this->__getter($params);
        } else {
            $this->__setter($params);
        };

        if ($method === 'set') {
            // Insert on duplicate method, for both insert/updates, this way the SET can act as the WHERE as well
            return $this->db->on_duplicate($object);
        }

        $this->db->limit($per_page, $page);
        $result = $this->db->get();
        if (!$result) {
            throw new Exception('No result from ' . $name);
        }

        if ($count) {
            return $result->num_rows;
        }

        if ($single) {
            return $result->row_array();
        } else {
            return $result->result_array();
        }
    }

    private function __getter($params) {
        foreach ($params as $field => $value) {
            if (method_exists($this, $field)) {
                $this->where{$field}($value);
            }
            $this->db->where_in($field, $value);
        }
    }

    private function __setter($params) {
        foreach ($params as $field => $value) {
            $this->db->set($field, $value);
        }
    }

}

Example usage:

// Returns all orders
$this->ORMModel->getOrder()

// Returns order ID 3
$this->ORMModel->getOrder(array('id' => 3))

// Returns orders before a certain date
function orderWhereDateBefore() {
    $this->db->where('date <=', $value);
}

$this->ORMModel->getOrder(array('dateBefore' => '2012-01-01'))

// Huge search query (from a form)
$params = array(
    'status' => 'Paid',
    'dateBefore' => '2012-01-01',
    'name' => 'Some Guy',
    ...
);
$this->ORMModel->getOrder($params);

// Set an order
$params = array(
    'status' => 'Paid',
    'dateBefore' => '2012-01-01',
    'name' => 'Some Guy',
    ...
);
$this->ORMModel->setOrder($params);

The additional arguments also provide more flexibility for standard display of results, such as pagination and full count of the result set.

However, I am concerned whether its reusability can trump the concerns of readability, usability and debuggability (for lack of a better word)Maintainability, and if so, can it be improved on?


texts: Haskell function to format a floating-point number with some precision

texts:
I have not yet developed a satisfying coding style in Haskell. In the code snippet below, there is a lot wrong to my taste:

Helper functions which should be local to showEngFloat are defined outside.
let ... in indentation madness
More than 80 columns

Can you show me how this same code can be written in a less indentation and pollution prone way?

I am aware that the name I chose for my function is not well chosen. (show... functions should return a ShowS type, right?)

import Numeric

normalize :: Int -> (Int,Int)
normalize dp =
    loop dp 0
    where
        loop dp e
            | dp > 3 = loop (dp - 3) (e+3)
            | dp < 1 = loop (dp + 3) (e-3)
            | otherwise = (dp,e)

toString :: [Int] -> [Char]
toString ia = concat (fmap show ia)

padZeroes nz v  = v ++ take nz (repeat '0')

showEngFloat :: RealFloat a => Int -> a -> [Char]
showEngFloat precision x
    | x >= 0.0 = calc x
    | otherwise = "-" ++ calc (-x)
    where
        calc n =
            let (digits,dotPos0) = floatToDigits 10 n in
                let (ndigits,(dotPos1,e)) = (length digits,normalize dotPos0) in
                    let a
                            | ndigits >= dotPos1 = toString (take dotPos1 digits)
                            | otherwise = padZeroes (dotPos1 - ndigits) (toString (take ndigits digits))
                            in
                            let b = padZeroes (precision - max dotPos1 ndigits) (toString (drop dotPos1 digits))
                                in
                                    let c = toString [e] in
                                        a ++ "." ++ b ++ "E" ++ c


texts: Faster way to create linked list of length n in Python

texts:
I'm attempting to create a linked list of length n using Python. I have the simple list implemented, a working concatenation function, and a working create_list function; however, I just want to know if there is a more efficient method at making the linked list than using my concatenate function (made for testing).

Simple List Class:

class Cell:

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

Concatenate Function:

def list_concat(A, B):
    current = A
    while current.next != None:
        current = current.next
    current.next = B
    return A

List create (that takes forever!):

def create_list(n):
    a = cell.Cell(0)
    for i in (range(1,n)):
        b = cell.Cell(i)
        new_list = cell.list_concat(a, b)
    return new_list

This is an assignment, but efficiency is not part of it. I am just wondering if there is a more efficient way to create a large list using this implementation of the structure.


texts: Generating a C++ header containing OpenGL function definitions

texts:
I'm currently working with Win32 and OpenGL a little bit and I needed a way to get the pointers of the OpenGL functions that aren't included in the Windows gl/GL.h header file. Rather than spending hours going through the OpenGL specification and manually typing out each OpenGL function definition in a header file, I created the following Python script which will automatically generate that header file for me.

INITIAL_HEADER_STRING_ONE = """
#ifndef OPENGL_FUNCTIONS_H_
#define OPENGL_FUNCTIONS_H_

#include <Windows.h>
#include <gl/GL.h>
#include <gl/GLU.h>
#include <gl/glext.h>
#include <gl/wglext.h>

"""

INITIAL_HEADER_STRING_TWO = """

void* GetGLProcPointer(const char* name)
{
    void* procPointer = (void*)wglGetProcAddress(name);
    if(
        procPointer == 0 ||
        procPointer == (void*)0x1 ||
        procPointer == (void*)0x2 ||
        procPointer == (void*)0x3 ||
        procPointer == (void*)-1
    )
    {
        HMODULE module = LoadLibraryA("opengl32.dll");
        procPointer = (void*)GetProcAddress(module, name);
    }
    return procPointer;
}

void GenerateGLProcPointers()
{
"""

def generate_header_string(function_names_file_name):
    header_string = INITIAL_HEADER_STRING_ONE

    with open(function_names_file_name, "r") as function_names:
        for line in function_names.readlines():
            stripped_line = line.rstrip("\n");
            stripped_line_upper = stripped_line.upper();
            header_string += "PFN{0}PROC {1};\n".format(stripped_line_upper, stripped_line)
        header_string += INITIAL_HEADER_STRING_TWO

    with open(function_names_file_name, "r") as function_names:
        for line in function_names.readlines():
            stripped_line = line.rstrip("\n");
            stripped_line_upper = stripped_line.upper();
            header_string += "\t{1} = (PFN{0}PROC)GetGLProcPointer(\"{1}\");\n".format(stripped_line_upper, stripped_line)
        header_string += "}\n"
        header_string += "\n#endif"

    return header_string

def generate_header_file(generated_header_string):
    with open("opengl_functions.h", "w+") as opengl_functions_header:
        opengl_functions_header.write(generated_header_string)

def main():
    generated_header_string = generate_header_string("OpenGL_Functions.txt");
    generate_header_file(generated_header_string)

if __name__ == "__main__":
    main()

The text file linked here contains a list of all OpenGL 4.5 function names.


texts: Testing code that changes the DOM on page load

texts:
I am in the process of writing tests for my JS code with CasperJS and Mocha. I have a function that changes the DOM and gets run on page load (through jQuery's document.ready event). I'm wondering what the best practice is for testing this kind of code. For example, I have a function removeElements that gets run before my tests start:

removeElements: function() {
    // Remove the original onsubmit attribute.
    $("#LoginForm").attr("onsubmit", "");
    $("#btnEnter").attr("onclick", "");

    // Modify form inputs.
    $("label[for=fieldPassword]").remove();

    $("#fieldPassword").remove();

    $("input[name=username][type=hidden]").remove();
}

Do you think I should only test that those elements have already been removed from the page from the execution of the code above? I am thinking that I should first test that those elements were there initially, call the function, then test that those elements and attributes were removed.

I suppose my real question is: what do I need to test, and what can I safely assume works without testing when it comes to DOM-altering code?


texts: Refactoring jQuery slider code suggestions

texts:
I needed to build a slider, and this is my first attempt. I'm trying to make it as dynamic as possible. My code works, but I'm wondering if there is a better way and if anyone has any suggestions. I'll be making the width calculated as well. I just have it hardcoded for testing.

Also, I need to make pagination for this. I'm not sure where to start with the way I have things set up. Any hints as to where to start would be much appreciated.

Here is the link to the working slider: http://wss.manage-website.com/stg/4406

Javascript:

jQuery.noConflict();
  jQuery(document).ready(function ($) {
    function doAnimation() {
      count = $('.slider img').length;
      $('.slider img').each(function(index) {
        // calculate and asign z-index to the images. First image in the stack recieves highest.
        var zindex = count - index;
        $(this).css('z-index', zindex);
        $(this).delay(3000*index).animate({
          left: '495px'
        }, 500, function() {
          $('.slider img').each(function(index) {
            // convert z-index to an integer
            var zindex = parseInt($(this).css('z-index'));
            // calculate z-index of images to retain order in the stack. Send this one to the back, push the rest up one.
            if (zindex < count) {
              $(this).css('z-index', zindex + 1);
            } else {
              $(this).css('z-index', zindex - (count-1));
            }
          });
          $(this).animate({
            left: '0'
          }, 500, function() {
            // if we're at the end, repeat.
            if (index == count - 1) {
              setTimeout(doAnimation,1500);
            }
          });
        });
      });
    }
    doAnimation();
  });


texts:
My code is meant to update the positions and velocities of planets. There are a few methods in this class, but updatePosition and updateVelocity are the most important, as they implement the velocity verlet algorithm. Could it be shorter/more efficient?

public class Particle{

private double mass;
private PhysicsVector initialPosition = new PhysicsVector();
private PhysicsVector initialVelocity = new PhysicsVector();

public PhysicsVector updatePosition(PhysicsVector initialPosition, PhysicsVector initialVelocity, double timeStep, PhysicsVector aDueToGravity){
    PhysicsVector x = new PhysicsVector(initialVelocity);
    x.scale(timeStep);
    PhysicsVector z = new PhysicsVector(aDueToGravity);
    z.scale(0.5*timeStep*timeStep);

    initialPosition.increaseBy(x);
    initialPosition.increaseBy(z);
    return initialPosition;
}

public PhysicsVector updateVelocity(PhysicsVector initialVelocity, double timeStep, PhysicsVector a, PhysicsVector newA){
    PhysicsVector z = new PhysicsVector(newA);
    z.increaseBy(a);
    z.scale(0.5*timeStep);
    initialVelocity.increaseBy(z);
    return initialVelocity;
}

public PhysicsVector[] centreOfMass(double[] mass, PhysicsVector[] positions){
    PhysicsVector centreOfMass = new PhysicsVector();
    centreOfMass.setVector(0,0);
    double sum = ArrayLogic.sumArray(mass);
    for(int i=0;i<positions.length;i++){
        centreOfMass.increaseBy(positions[i].scale(mass[i],positions[i]));
    }
    centreOfMass.scale(1/sum);
    positions = ArrayLogic.subtract(positions, centreOfMass);
    return positions;
}

public PhysicsVector[] cOMVel(double[] mass, PhysicsVector[] velocity){
    PhysicsVector cOMV = new PhysicsVector();
    double total = ArrayLogic.sumArray(mass);
    for(int ae=0;ae<velocity.length;ae++){
        cOMV.increaseBy(velocity[ae].scale(mass[ae],velocity[ae]));
    }
    cOMV.scale(1/total);
    velocity = ArrayLogic.subtract(velocity, cOMV);
    return velocity;
}

public static PhysicsVector[] momentum(double[] planetMass, PhysicsVector[] velocity, PhysicsVector[] positions){
    PhysicsVector[] momentum = new PhysicsVector[planetMass.length];
    PhysicsVector[] angularMomentum = new PhysicsVector[planetMass.length];
    PhysicsVector a = new PhysicsVector(0,0);
    for(int i=0; i<velocity.length; i++){
        a = a.scale(planetMass[i], velocity[i]);
        momentum[i] = a;
    }

    for(int i=0; i<velocity.length; i++){
        angularMomentum[i] = angularMomentum[i].vectorProduct(positions[i], momentum[i]);
    }

    return angularMomentum;
   }

}

At the moment, increasing the timestep seems to improve my results. This seems odd, which is partly why I suspect my implementation is incorrect.


texts:
I am building an encryption program for a messenger app I am developing.

I was wondering if the code looks clean and succinct, and at the same times is safe and secure:

import random
import os
import time

key = os.urandom(64)

def encrypt(_key, message):
    letter_map_message = []
    ascii_msg_value = ''.join(str(ord(c)) for c in message)
    for c in message:
        ''.join(str(ord(c)))
        letter_map_message.append(ord(c))
    ascii_key_value = ''.join(str(ord(x)) for x in str(_key))
    new_msg_encrypted = int(ascii_msg_value) * int(ascii_key_value)
    returned = (new_msg_encrypted, letter_map_message)
    return returned;

def decrypt(_key, message, letter_map):
    ascii_key_value = ''.join(str(ord(x)) for x in str(_key))
    msg_ascii_divided = int(message)/int(ascii_key_value)
    letters = []
    for c in range(len(letter_map)):
        li = letter_map[c]
        c = int(li)
        letter = chr(c)
        letters.append(letter)
    new_msg_decrypted = ''.join(letters)
    return new_msg_decrypted;

encrypted = encrypt(key, "HEHHEHEHHE")
print(encrypted[0])
decrypted = decrypt(key, encrypted[0], encrypted[1])
print(decrypted)


texts:
You can place the script where you want the content to be checked and loaded in your design.

urlCheck is the name given to the function.  You can change it, and if you do, change all urlCheck references within the code.
window.location.href returns the current address as http://....  Use this to identify certain pages on which you want the content to be loaded.  Make as many if/else combinations as necessary.
document.write builds the content to be loaded first.  Type with later in one unique line or create multiple document.writes for each line of your content.


texts: Array that stores values from two ranges and compares if one cell is blank

texts:
This is my first Array in VBA for Excel, but I need some help to optimize the code and try to reduce the number of If statements.

The long and short of the code is that it checks to see if there is a Customer name in Column B and checks that against Column A; if there is no value in Column A then  an input box opens to prompt the user to add the CIF number to the specific named range.

Cells B2 through B9 will always have a value, but not every cell B2 through B9 will be used.  Cells A2 through A9 will not always have a value.

Below is the Code:

Sub CheckCIF()
    Dim fileArray
    Dim finalRow As Long
    Dim targetCol As Long

    With Sheets("Loan Data")
        finalRow = .Range("B" & Rows.Count).End(xlUp).Row
        targetCol = .Range("A1").EntireRow.Find("CIF #").Column
        fileArray = Array(.Range("B2:B" & finalRow), _
                    .Range(.Cells(2, targetCol), .Cells(finalRow, targetCol)))
    End With

    'fileArray(1)(1) Number in first parenthesis is the column and the number in the second parenthesis is the row

    If fileArray(1)(1) = vbNullString And fileArray(0)(1) <> vbNullString Then
        With Sheets("Loan Data")
            .Range("CIF_1") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(1))
        End With
    End If

    If fileArray(1)(2) = vbNullString And fileArray(0)(2) <> vbNullString Then
        With Sheets("Loan Data")
            .Range("CIF_2") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(2))
        End With
    End If

    If fileArray(1)(3) = vbNullString And fileArray(0)(3) <> vbNullString Then
        With Sheets("Loan Data")
            .Range("CIF_3") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(3))
        End With
    End If

    If fileArray(1)(4) = vbNullString And fileArray(0)(4) <> vbNullString Then
        With Sheets("Loan Data")
            .Range("CIF_4") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(4))
        End With
    End If

    If fileArray(1)(5) = vbNullString And fileArray(0)(5) <> vbNullString Then
        With Sheets("Loan Data")
            .Range("CIF_5") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(5))
        End With
    End If

    If fileArray(1)(6) = vbNullString And fileArray(0)(6) <> vbNullString Then
        With Sheets("Loan Data")
            .Range("CIF_6") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(6))
        End With
    End If

    If fileArray(1)(7) = vbNullString And fileArray(0)(7) <> vbNullString Then
        With Sheets("Loan Data")
            .Range("CIF_7") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(7))
        End With
    End If

    If fileArray(1)(8) = vbNullString And fileArray(0)(8) <> vbNullString Then
        With Sheets("Loan Data")
            .Range("CIF_8") = InputBox("Please enter the CIF Number for " & vbCrLf & fileArray(0)(8))
        End With
    End If

End Sub


texts: Test all properties with single test function

texts:
In writing unit tests for c# functions, there is a good case made for testing properties. In testing those properties, I felt there should be a few goals.

Provide a wide range of inputs
Test additional features like PropertyChanged
Don't write a ton of very repetitive test code

So I came up with this function for a specific class (although it could even be generalized with a templated method for all classes) that essentially gives a property name, a value to set the property to, the expected value to receive out, and a list of PropertyChanged names that should be fired as a result. This is accomplished by taking advantage of MSTestv2's DataTestMethod and DataRow attributes.

Looking for feedback on the quality/durability/usefulness of this code.

[TestMethod()]
[DataTestMethod]
[DataRow("Name", "A normal name", "A normal name", new string[] { "Name" })]
[DataRow("Name", null, null, new string[] { "Name" })]
[DataRow("Name", "", "", new string[] { "Name" })]
[DataRow("Name", "A normal name", "A normal name", new string[] { "Name" })]
[DataRow("Name", "A really very super duper long string to test the overall allowed length", "A really very super duper long string to test the overall allowed length", new string[] { "Name" })]
[DataRow("Address", 0, 0, new string[] { "Address", "AbsAddress"})]
[DataRow("Address", -1, null, new string[] { "Address", "AbsAddress" })]
[DataRow("Address", 300, 300, new string[] { "Address", "AbsAddress" })]
[DataRow("Address", int.MaxValue, int.MaxValue, new string[] { "Address", "AbsAddress" })]
public void ConfigItem_AllProperties_Test(string propName, object set, object expected, string[] propChangedNames)
{
    var item = new ConfigItem();
    var propsChanged = new Dictionary<string, bool>();
    foreach (var s in propChangedNames)
    {
        propsChanged.Add(s, false);
    }
    item.PropertyChanged += (sender, args) =>
    {
        if (propsChanged.ContainsKey(args.PropertyName))
        {
            propsChanged[args.PropertyName] = true;
        }
    };
    typeof(ConfigItem).GetProperty(propName).SetValue(item, set);
    object actual = typeof(ConfigItem).GetProperty(propName).GetValue(item);
    Assert.AreEqual(expected, actual);
    foreach (var pair in propsChanged)
    {
        Assert.IsTrue(pair.Value, pair.Key);
    }
}


texts: Static class for constants with reference to java resources

texts:
I want to store the colors I use in the colors.xml file. In addition to using them in an xml-layout, I also want to use these colors in my Java code, when drawing things to the Canvas.

The thing is, I am not always using the colors in a class that extends Application. For example, I have classes for objects that get drawn to the Canvas.

The thing is, I don't want to store the context in each class that needs access to my resources file.

My current solution is the following:

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorOne">#123456</color>
</resources>

A static class called Attributes for constants, including colors:

public class Attributes {
    private static final Resources RESOURCES = MainActivity.getContext().getResources();

    public static final int ONE_COLOR = RESOURCES.getColor(R.color.colorOne);
    public static final int SOME_OTHER_CONSTANT = 1;
}

MainActivity:

public class MainActivity extends Activity {

    private static Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.context = getApplicationContext();

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public static Context getContext() {
        return context;
    }
}

And, finally in my object class:

public class ScreenArea {
    private Rect area;
    private Paint paint;

    public ScreenArea(Rect area) {
        this.area = area;
        paint = new Paint();
        paint.setColor(Attributes.COLOR_ONE);
    }

    public void draw(Canvas canvas) {
        canvas.drawRect(area, paint);
    }
}

Okay, so first of all, this works. But, I am wondering if this is the right way to go. I have been reading about the Singleton class, but most examples are very basic an not focusing on storing constants, like I am doing right now.

So my questions:

Is this the right way to go or should I implement a Singleton?
If so, who can point me in the right direction?


texts: Java 2d array Hourglass Sums challenge from Hackerrank

texts:
This is a java solution to a Hackerrank problem.

I know it's not optimized, can anyone help me to refactor and optimize?

  Task:

  Calculate the hourglass sum for every hourglass in the 6×6 array, then print the maximum hourglass sum.

  An "hourglass sum" is defined as the sum of any 7 entries of the array that are selected by this pattern mask:

✓ ✓ ✓
  ✓
✓ ✓ ✓

  Input Format:

  There are 6 lines of input, where each line contains 6 space-separated
  integers describing 2D Array; every entry is in the inclusive range -9 to 9.

  Output Format

  Print the largest (maximum) hourglass sum found in the array.

  Sample Input

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0

  Sample Output

19

Solution:

public class TestHourGlass {

        public static void main(String[] args) {
                Scanner in = new Scanner(System.in);
                int arr[][] = new int[6][6];
                int hourGlassSum[] = new int[16];
                int pos = 0;

                //Reads data from user input and store in 6*6 Array
                for (int arr_i = 0; arr_i < 6; arr_i++) {
                    for (int arr_j = 0; arr_j < 6; arr_j++) {
                        arr[arr_i][arr_j] = in.nextInt();
                    }
                }
                //Find each possible hourGlass and calculate sum of each hourGlass
                for (int i = 0; i < 4; i++) {
                    for (int j = 0; j < 4; j++) {
                        hourGlassSum[pos] = calculateHourGlassSum(arr, i, i + 2, j, j + 2);
                        pos++;
                    }
                }
                System.out.println(findmax(hourGlassSum));

            }
            /**
             * @param arr
             * @param pos1 - Row startPoint
             * @param pos2 - Row endPoint
             * @param pos3 - column startPoint
             * @param pos4 - column endPoint
             * @return
             */
            public static int calculateHourGlassSum(int arr[][], int pos1, int pos2, int pos3, int pos4) {

                int sum = 0;
                int exclRowNum = pos1 + 1;
                int exclColNum1 = pos3;
                int exclColNum2 = pos4;
                for (int arr_i = pos1; arr_i <= pos2; arr_i++) {
                    for (int arr_j = pos3; arr_j <= pos4; arr_j++) {
                        sum = sum + arr[arr_i][arr_j];
                    }
                }
                sum = sum - (arr[exclRowNum][exclColNum1] + arr[exclRowNum][exclColNum2]);
                return sum;
            }

            /**
             * @param arr
             * @return max elem of Array
             */
            public static int findmax(int arr[]) {
                int max = arr[0];
                for (int i = 0; i < arr.length; i++) {
                    if (arr[i] >= max)
                        max = arr[i];
                }
                return max;
            }
}


texts:
The code, written in Rust, solves the Days in Month problem in CodeChef. It is also one of my first few programs written in Rust.

The code is accepted so that there are no logical mistakes. I am more interested in getting review feedback on style. I am not particularly happy with the code as is; it is rather bulky.

use std::io;

fn read_line(stdin: &io::Stdin) -> io::Result<String>
{
    let mut input = String::new();
    match stdin.read_line(&mut input)
    {
        Ok(_) => Ok(input.trim().to_string()),
        Err(e) => Err(e)
    }
}

fn to_day_of_week(input: &str) -> Option<usize>
{
    if input == "mon"
    {
        Some(0)
    }
    else if input == "tues"
    {
        Some(1)
    }
    else if input == "wed"
    {
        Some(2)
    }
    else if input == "thurs"
    {
        Some(3)
    }
    else if input == "fri"
    {
        Some(4)
    }
    else if input == "sat"
    {
        Some(5)
    }
    else if input == "sun"
    {
        Some(6)
    }
    else
    {
        None
    }
}

pub fn codechef_nw1()
{
    let stdin = io::stdin();
    let read_first_line_result = read_line(&stdin);
    if read_first_line_result.is_ok()
    {
        let first_line = read_first_line_result.unwrap();
        let parse_first_line_result = first_line.parse::<i32>();
        if parse_first_line_result.is_ok()
        {
            let t = parse_first_line_result.unwrap();
            for _i in 0..t
            {
                let read_test_line_result = read_line(&stdin);
                if read_test_line_result.is_ok()
                {
                    let test_line = read_test_line_result.unwrap();
                    let find_space_result = test_line.find(' ');
                    if find_space_result.is_some()
                    {
                        let space_index = find_space_result.unwrap();
                        let test_token_1 = &test_line[..space_index];
                        let test_token_2 = &test_line[space_index + 1..];
                        let parse_day_result = test_token_1.parse::<i32>();
                        if parse_day_result.is_ok()
                        {
                            let days = parse_day_result.unwrap();
                            let day_of_week_result = to_day_of_week(test_token_2);
                            if day_of_week_result.is_some()
                            {
                                let mut day_of_week = day_of_week_result.unwrap();
                                let mut stats = [0, 0, 0, 0, 0, 0, 0];
                                for _d in 0..days
                                {
                                    stats[day_of_week] = stats[day_of_week] + 1;
                                    day_of_week = day_of_week + 1;
                                    day_of_week = day_of_week % 7;
                                }
                                println!("{} {} {} {} {} {} {}", stats[0], stats[1], stats[2], stats[3], stats[4], stats[5], stats[6]);
                            }
                        }
                    }
                }
            }
        }
    }
}


texts: Copy-and-Move Concept Using Smart Pointer

texts:
I tried to implement a simple container class using the copy-and-move idiom. I am learning the changes to C++ as of C++11 and later.

Is the code exception safe?
I chose to use a smart pointer. Is std::unique_ptr a safe choice? I read that it should not be copied, but since I am doing the copying of the content explicitly, and since it provides a swap function, I could not see any objection. Is there a preferred practice, considering the array content type might be any type including an object type?
When I let the compiler do the copy for the copy assignment operator (like ...::operator=(MyContainer other)) I got an ambiguity with the move assignment operator. So I chose to put the copy operation into the function (which I prefer visually, it might look naive and oldschool, but as an aging brain I find it more explicit). Also here: Is there another, preferred practice? And to overcome my personal preference: What is the real difference of letting the compiler do the copy? Both are taking place on the stack, aren't they?

Header part

class MyContainer
{
private:
    std::size_t mSize;
    std::unique_ptr<int[]> mArray;

    static void _swap(MyContainer& first, MyContainer& second);
    void _reset(void);

public:
    MyContainer(std::size_t size); // default constructor
    MyContainer(const MyContainer& other); // copy constructor
    MyContainer(MyContainer&& other) noexcept; // move constructor
    MyContainer& operator=(const MyContainer& other); // copy assignment operator
    MyContainer& operator=(MyContainer&& other) noexcept; // move assignment operator
    void dump(void);
    /* ... */
    ~MyContainer(void);
};

Source part

void MyContainer::_swap(MyContainer& first, MyContainer& second) // static
{
    std::swap(first.mSize, second.mSize);
    first.mArray.swap(second.mArray);
}

void MyContainer::_reset(void)
{
    mSize = 0;
    mArray.reset();
}

MyContainer::MyContainer(std::size_t size = 0) // default constructor
    : mSize(size),
    mArray(mSize ? new int[mSize] : nullptr)
{
    // for testing purpose only
    for (int i = 0; i < mSize; i++)
        mArray.get()[i] = i;
}

MyContainer::MyContainer(const MyContainer& other) // copy constructor
    : mSize(other.mSize),
    mArray(mSize ? new int[mSize] : nullptr)
{
    std::copy(other.mArray.get(), other.mArray.get() + mSize, mArray.get());
}

MyContainer::MyContainer(MyContainer&& other) noexcept // move constructor
    : MyContainer() // init using default constructor (C++11)
{
    _swap(*this, other);
}

MyContainer& MyContainer::operator=(const MyContainer& other) // copy assignment
{
    MyContainer tmp(other);
    _swap(*this, tmp);
    return *this;
}

MyContainer& MyContainer::operator=(MyContainer&& other) noexcept // move assignment
{
    if (this != &other)
    {
        _reset();
        _swap(*this, other);
    }
    return *this;
}

void MyContainer::dump(void)
{
    std::cout << "Size: " << mSize << std::endl;
    for (int i = 0; i < mSize; i++)
        std::cout << mArray.get()[i] << std::endl;
}

MyContainer::~MyContainer(void)
{
}