texts: Showing information about states on a map when clicked

texts:
I'm using JQVMap, and I have my code to where depending on what state you click, it'll reveal info about that state within a single div below the map. However, I feel there's a simplified, more efficient way to set up this code so there's not a lot of repeat, especially once I start adding more states. Is there?

switch(code){
    case"tx":
        $('#info-children').children(':not(#info-tx)').hide("slow");
        $('#info-children').children('#info-tx').show("slow");
        break;
    case"il":
        $('#info-children').children(':not(#info-il)').hide("slow");
        $('#info-children').children('#info-il').show("slow");
        break;
    case"fl":
        $('#info-children').children(':not(#info-fl)').hide("slow");
        $('#info-children').children('#info-fl').show("slow");
        break;
    case"ga":
        $('#info-children').children(':not(#info-ga)').hide("slow");
        $('#info-children').children('#info-ga').show("slow");
        break;
    case"pa":
        $('#info-children').children(':not(#info-pa)').hide("slow");
        $('#info-children').children('#info-pa').show("slow");
        break;
    default:
        $('#state-name').html(region);
        $('#info-children').children(':not(#info-uhoh)').hide("slow");
        $('#info-children').children('#info-uhoh').show("slow");
}


texts: Filtering index using has_many through relationships

texts:
Both Cities and Positions are associated to Jobs through a has_many :through relationship.

On the Jobs#Index page, I have a form, which when submitted allows a user to filter jobs based on a combination of city and positions.

I got this to work, but know the code can be a lot better.

This is my Jobs#Index controller:

  def index
    @cities = City.all
    @positions = Position.all

    @city = City.find(params[:city_id]) if params[:city_id] && params[:city_id] != "0"
    @position = Position.find(params[:position_id]) if (params[:position_id] && params[:position_id] != "0")

    @jobs = Job.all
    @jobs = @jobs.includes(:cities).where(cities: { id: @city }) if @city
    @jobs = @jobs.includes(:positions).where(positions: { id: @position }) if @position
    @jobs = @jobs.paginate(page: params[:page], per_page: 5)

  end

This is my Jobs#Index View:

- provide(:title, 'All Jobs')

.thinstripe_career
  .darken
    .container
      .row
        .span10.offset1
          .jobs_header
            .row
              .span7
                h2 All #{@city.name if @city} #{@position.name if @position} Jobs
              .span3
                == link_to "Sign up for Job Alerts!", "#", :class => "button"

- if current_user && current_user.admin?
  == render 'shared/dashboard_header'

.container
  .row
    .span10.offset1
      .job_search
        == form_tag jobs_path, :method => 'get', :id => "jobs_filter" do
          h2 I'd like jobs in
          .filter_sect
            == select_tag :city_id, content_tag(:option,'all cities...', :value=>"0") + options_from_collection_for_select(@cities, "id", "name", params[:city_id].to_i  ), :class => "basic"
          .filter_sect
            == select_tag :position_id, content_tag(:option,'all roles...',:value=>"0") + options_from_collection_for_select(@positions, "id", "name", params[:position_id].to_i ), :class => "basic"
          .filter_sect.filter_search
            == submit_tag "Search", :class => "button search_button button_black", :name => nil

      ul.jobs
        - if @jobs.any?
          == render @jobs
        - else
          li.non_founds
            h2 No jobs founds.
            p There are currently no jobs founds for these combinations. Sign up to requests

      == will_paginate


texts:
I am creating a dynamic menu whose items appear depending on a set 'mode' (that is passed via AJAX). Off this it creates the menu, disabling and hiding icons that are not associated with that mode.

The problem is, there are a lot of if conditions in my implementation. Can anyone show me a cleaner way of doing what I am trying to achieve?

public function gridMenu()
  {
    $mode = Validate::sanitize($_POST['mode']);

    $modes = array(
        'products' => array('edit', 'delete', 'archive')
    );

    $output = '
';
    for($i = 1; $i < 7; $i++) {
      $img = '';
      $output .= '<div class="hex hex' . $i;
      if($i == 1)
      {
        if(in_array('edit', $modes[$mode]))
        {
          $output .= ' hex-selectable';
          $img = '';
        } else {
          $output .= ' hex-disabled';
        }
      }
      if($i == 2)
      {
        if(in_array('zzz', $modes[$mode]))
        {
          $output .= ' hex-selectable';
        } else {
          $output .= ' hex-disabled';
        }
      }
      if($i == 3)
      {
        if(in_array('delete', $modes[$mode]))
        {
          $output .= ' hex-selectable';
          $img = '';
        } else {
          $output .= ' hex-disabled';
        }
      }
      if($i == 4)
      {
        if(in_array('xxx', $modes[$mode]))
        {
          $output .= ' hex-selectable';
        } else {
          $output .= ' hex-disabled';
        }
      }
      if($i == 5)
      {
        if(in_array('archive', $modes[$mode]))
        {
          $output .= ' hex-selectable';
          $img = '';
        } else {
          $output .= ' hex-disabled';
        }
      }
      if($i == 6)
      {
        if(in_array('zzz', $modes[$mode]))
        {
          $output .= ' hex-selectable';
        } else {
          $output .= ' hex-disabled';
        }
      }

      $output .= '">';
      $output .= $img;
      $output .= '
';
    }
    $output .= '

';
    $output .= '
';
    echo $output;
  }


texts: One try with multiple catch blocks vs nested try

texts:
I am creating program which will parse .csv file and I am using FileReader and Scanner classes from java API.

FileReader throws FileNotFoundException, IOException.

Scanner's method hasNextLine() and nextLine() throw IllegalStateException and NoSuchElementException.

Should I use 1 try and 4 multiple catch blocks? Or try block nested in another try block(which has 2 catch blocks) with 2 catch blocks?

Code 1:

import java.io.*;
import java.util.Scanner;
import java.util.NoSuchElementException;
import java.lang.IllegalStateException;

public class App {
    public static void main(String[] args) {
        try (FileReader file = new FileReader("Doc.csv")) {
            Scanner sc = new Scanner(file);
            while (sc.hasNextLine()) {
                System.out.println(sc.nextLine());
            }
        } catch (IllegalStateException e) {
            System.out.println(e);
        } catch (NoSuchElementException e) {
            System.out.println(e);
        } catch (FileNotFoundException e) {
            System.out.println(e);
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

Code 2:

import java.io.*;
import java.util.Scanner;
import java.util.NoSuchElementException;
import java.lang.IllegalStateException;

public class App {
    public static void main(String[] args) {
        try (FileReader file = new FileReader("Doc.csv")) {
            Scanner sc = new Scanner(file);
            try {
                while (sc.hasNextLine()) {
                    System.out.println(sc.nextLine());
                }
            } catch (IllegalStateException e) {
                System.out.println(e);
            } catch (NoSuchElementException e) {
                System.out.println(e);
            }
        } catch (FileNotFoundException e) {
            System.out.println(e);
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

By the way, I know that System.out.println(e) is not best practice for logging exception. So, please don't write about it


texts: Pointers for C++/CLI library header formatting, layout and design

texts:
I have designed a C++/CLI wrapper library that allows C++ applications on windows, and other platforms that can load C dlls (e.g. Java via JNA or Python) to make calls to my .Net library.

I was wondering if my dll import/export header, which will be used by external developers, complies with the current "best practices" for C++ on windows.
I would be grateful if other developers could point out any examples of poor coding practices or if anything is not as clear as it could be for my header below. For example, I am not sure if I should be using __int32 rather than the int type.

I am also keen to improve so please also post any links or book recommendations for API/DLL design.

    **//-----------------------------------------------------------------------
// <copyright file="dllHeader.h" company="drone">
//     Copyright (c) .
// </copyright>
// <date>26-Apr-2016</date>
// <author>?? (drone@codereview.stackoverflow)</author>
//-<version>???</version>
//-----------------------------------------------------------------------
/// This file contains the dllimports/ dllexports for the wrapper.

// Dependencies:
//      - C runtime Library v120
//      -.net framework version 4.0 or newer
//      - MyDotNetLibrary.dll (managed)

#pragma once
#ifndef dllHeader_h
#define dllHeader_h

// if DLLEXPORTS is defined, define as dllexports,
// otherwise declare dllimport prototypes.

#ifdef DLLEXPORTS
#define DLLAPI __declspec(dllexport)
#else
#define DLLAPI __declspec(dllimport)
#endif
#define DLLCALL __cdecl // Calling convention is __cdecl

// callbacks:
// typedef return_type ( callingconvention *func_pointer) (params)
typedef void(__stdcall *eventCallback)(void); // stdcall used for WINAPI compat.
typedef void(__stdcall *eventNewValueCallback)(unsigned long long); //UInt64

extern "C"      // No name mangling
{
    //  Open or close connection to controller
    //  (arg1: true=Connect, false=Disconn arg2: 0=USB, 1=RS232 3= Simul, arg3: commport number)
    DLLAPI unsigned int       DLLCALL OpenComms(bool, unsigned int, unsigned int); // wrapper to Comms.OpenComms()

    // Methods in alphabetical order
    DLLAPI bool               DLLCALL ApplySampleCals(bool);            // wrapper to Comms.ApplySampleCals() Toggle between uncalibrated and sample calibrated temperatures. Refer to example in html docs.

    DLLAPI bool               DLLCALL CalibrateTstDistance(void);
  //.. etc More exported functions in a similar layout

    DLLAPI bool               DLLCALL SetTstMode(bool);

    // Comms Events
    /*********************************************/
    /* Event and callback methods                */
    /* See "myCApiExample" example in apiDocs      */
    /*********************************************/
    // Start callbacks
    DLLAPI void DLLCALL StartEvents();
    // Stop callbacks
    DLLAPI void DLLCALL StopEvents();

    // Set or Register callbacks. See typedefs above for declaration of *eventCallback and *eventNewValueCallback.
    DLLAPI void DLLCALL SetControllerConnectedCallback(eventCallback);
    DLLAPI void DLLCALL SetNewValueCallback(eventNewValueCallback);
    DLLAPI void DLLCALL SetControllerDisconnectedCallback(eventCallback);
}
#endif


texts: Extending functionality of org.springframework.batch.item.file.transform.DefaultFieldSet

texts:
I would like to be able to set token values (defaultFieldSet.tokens) and names (defaultFieldSet.names) on org.springframework.batch.item.file.transform.DefaultFieldSet using a java.util.Properties object. Specifically, the keys of the Properties object will serve as the names and the corresponding Properties values will serve as the tokens. Here's the code that I have to do this:

import java.util.Properties;
import java.util.Set;

import org.springframework.batch.item.file.transform.DefaultFieldSet;
import org.springframework.batch.item.file.transform.FieldSet;

/**
 * PropertiesFieldSetFactory is a factory to create
 * a {@link FieldSet} from a {@link Properties} object.
*/
public class PropertiesFieldSetFactory {

    /**
     * Creates a {@link FieldSet} by setting its token values equal to the {@link Properties} values
     * and its token names equal to the {@link Properties} keys.
     * Note: Passing a null argument to this method will cause a {@link NullPointerException}
     * to be thrown.
     *
     * @param properties used to populate the {@link FieldSet}
     * @return {@link FieldSet} that has token values and names from the passed in {@link Properties} object
     */
    public static FieldSet create(Properties properties) {
        final Set<String> tokenNamesSet = properties.stringPropertyNames();
        final int numberOfTokens = tokenNamesSet.size();
        final String[] tokenNames = tokenNamesSet.toArray(new String[numberOfTokens]);
        final String[] tokenValues = new String[numberOfTokens];
        for (int tokenPosition = 0; tokenPosition < numberOfTokens; tokenPosition++) {
            String tokenName = tokenNames[tokenPosition];
            tokenValues[tokenPosition] = properties.getProperty(tokenName);
        }
        return new DefaultFieldSet(tokenValues, tokenNames);
    }

}

My concern with this approach is in regards to unit testing. For example, I have the following method (in another class) that needs to be unit tested:

public class CarFieldSetMapper extends BeanWrapperFieldSetMapper<Car> {

    @Override
    public Car mapFieldSet(FieldSet fieldSet) throws BindException {
        Properties fieldProperties = fieldSet.getProperties();

        fieldProperties.put("modelDescription", fieldProperties.get("model"));

        removeDummyIndicator(fieldSet, fieldProperties);

        // build field from properties derived / transformed from the original field set
        FieldSet domainObjectFieldSet = PropertiesFieldSetFactory.create(fieldProperties);

        return super.mapFieldSet(domainObjectFieldSet);
    }

    private void removeDummyIndicator(FieldSet fieldSet, Properties fieldProperties) {
        // dummyIndicator is not a field of any domain object
        final String dummyIndicatorTokenName = "dummyIndicator";
        final String isDummyIndicator = fieldSet.readString(dummyIndicatorTokenName);
        if (isDummyIndicator.equalsIgnoreCase("Y")) {
            fieldProperties.put("model", "");
        }
        fieldProperties.remove(dummyIndicatorTokenName);
    }
}

I do not know of a great way to prevent PropertiesFieldSetFactory.create() from being called when running the unit test ala http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/. Also, I'm really trying to extend the DefaultFieldSet functionality so I question using a factory. Note: On the other hand, Joshua Bloch seems to promote use of static factory methods in Effective Java (Chapter 2: Item 1).

Should I change PropertiesFieldSetFactory to PropertiesFieldSet extending DefaultFieldSet? If so, how can I set the FieldSet tokens and names. Both fields are private on the DefaultFieldSet without any way to set the values other than during construction.

Edit: Added code for removeDummyIndicator and correction of line fieldProperties.put("model", fieldProperties.get("model")); to fieldProperties.put("modelDescription", fieldProperties.get("model"));


texts:
I recently wrote my first C# app that's goal it to take a drive letter and output a CSV list of some basic information. TOTALSPACE,FREESPACE,STATUS.

I've been wondering If it would be possible to make this application even faster. Got any good suggestions?

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace drivespace
{
class Program
{
    static void Main(string[] args)
    {
       //"PATHTOEXE\drivespace.exe" drive-C:
        foreach (String arg in args)
        {
            String[] parts = arg.Split('-');
            if (parts[0].Equals("drive"))
            {
                long toalspace = 0;
                long freespace = 0;
                string status = "NOTFOUND";

                foreach (DriveInfo drive in DriveInfo.GetDrives())
                {
                    if (drive.Name == parts[1] + ":\\")
                    {
                        if (drive.IsReady)
                        {
                            toalspace = drive.TotalSize;
                            freespace = drive.TotalFreeSpace;
                            status = "READY";
                        }
                        else
                        {
                            status = "NOTREADY";
                        }
                        break;
                    }
                }
                //TOTALSPACE,FREESPACE,STATUS
                Console.WriteLine(toalspace.ToString() + "," + freespace.ToString() + ',' + status);
            }
        }
    }
}
}

https://github.com/keverw/drivespace is the Github page, it might have some more useful info.


texts:
The following code finds no-rain periods in a time series that were preceded by rain over a threshold (e.g. 10mm in 2 days [k=48]).

significant_drydowns <- function(rain, threshold=10, k=48) {
    require(zoo)
    require(dplyr)

    # Find drydowns: sequences of 0 rain; give them a group
    starts <- (lag(rain, default=0) > 0) & (rain == 0)
    groups <- cumsum(starts)
    groups[rain > 0] <- NaN
    groups[groups == 0] <- NaN

    # remove drydowns where previous rain is below threshold
    past_rain <- rollsum(rain, k, fill=0, align='right')
    for (t in which(starts)) {
        if (past_rain[t-1] < threshold) {
            groups[groups == groups[t]] <- NaN
        }
    }

    return(groups)
}

The for loop is really slow, partly because of the == comparison. Is there any way to speed this code up?

Example data:

rain <-c(0,0,0,2,3,0,0,0,1,5,0,0,0,0,0,0,6,1,1,1,0,0,0)
names(rain) <- rain

Example output:

R> significant_drydowns(rain, 5, 5)
  0   0   0   2   3   0   0   0   1   5   0   0   0   0   0   0   6   1   1   1   0   0   0
NaN NaN NaN NaN NaN   1   1   1 NaN NaN   2   2   2   2   2   2 NaN NaN NaN NaN   3   3   3
R> significant_drydowns(rain, 7, 4)
  0   0   0   2   3   0   0   0   1   5   0   0   0   0   0   0   6   1   1   1   0   0   0
 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN   3   3   3

So, the group names don't matter, as long as they are unique. Groups are only assigned to dry-downs for which the previous k steps has a sum greater than threshold.


texts: App for allowing the user to type in chemistry formulas using a custom keyboard

texts:
Essentially, I am making an app that allows the user to type in chemistry formulas using a custom keyboard.

The keyboard will have several keys, for example, "Na", "H", and "O". Pressing them in different combinations will result in different formulas. For example, Na + O will result in NaO. Pressing any key consecutively will increase the subscript of that given element. For example, H + H + O will result in H2O.

The code below determines how the textfield combines the different elements to make the formulas. I'm wondering if it's too confusing. Also, I'm not sure if I'm correctly managing the memory.

consecutiveElementCount = 0;
formula = [[NSMutableString  stringWithString:@""] retain]; // released in dealloc

^^^ declared in the init method.

- (void)addElement:(NSString *)currentElement {

    if (![currentElement isEqualToString:lastElementPressed])  {

        // when new element is pressed

        [formula appendString:currentElement];
        lastElementPressed = currentElement;
        consecutiveElementCount = 1;

    }

    else if ([currentElement isEqualToString:lastElementPressed]) {

        // when element is pressed consecutively

        if (consecutiveElementCount == 1) {

            // since there is no '1' subscript, nothing needs to be deleted

            [formula appendString:@"₂"];
            subscriptLength = 1;

        }

        if (consecutiveElementCount > 1) {

            // deletes last subscript and replaces it with new subscript

            NSArray *subscriptList = [[[NSArray alloc] initWithObjects:@"₂", @"₃", @"₄", @"₅", @"₆", @"₇", @"₈", @"₉", @"₁₀", @"₁₁", @"₁₂", nil] autorelease];

            NSRange range = NSMakeRange (([formula length] - subscriptLength), subscriptLength);

            [formula deleteCharactersInRange:range];

            NSString *tempSubscript = [[subscriptList objectAtIndex:consecutiveElementCount - 1] autorelease];
            [formula appendString:tempSubscript];

            subscriptLength = [tempSubscript length];

        }

     // don't increase subscript after 12
        if (consecutiveElementCount < 11)
            consecutiveElementCount ++;

    }

    NSLog(@"%@", formula);
}


texts:
This is a naive implementation - I know that there are algorithms like KMP

However I was trying to implement it as best as I can.

string test = "giladdarmonwhatareyoudoing";
int index = StrStr(test, "are");

//Returns an index to the first occurrence of str2 in str1,
//or a -1 pointer if str2 is not part of str1.

public int StrStr(string test, string strToFind)
{
    for (int i = 0; i < test.Length; i++)
    {
        if (test[i] == strToFind[0])
        {
            int j;
            for (j = 0; j < strToFind.Length; j++)
            {
                if (test[i + j] != strToFind[j])
                {
                    break;
                }
            }
            if (j == strToFind.Length)
            {
                return i;
            }
        }
    }
    return -1;
}


texts: Generate all combinations of length N through M

texts:
I've started learning programming and as matter of practice I've decided to make a program that will output all possible string combinations and put them in a file.
I've manged to do that and it works perfectly fine. Then I added the option to generate words of different length, so the output looks something like this for words between 2 and 4 characters:

aa
ab
ac
ad
....
zzzz

Now I'm wondering what I can improve and what are different approaches to this problem? For learning purposes I'm trying to do this without using any library facilities, not even the standard library. Looking forward to code review and tips.

#include <fstream>

void gen(std::ofstream& f_out, char* word, int pos=0)
{
    if(!word[pos]) return;
    int length=0;
    for(int i=0; word[++i]; length++);
    while(word[pos]<='z') {
        gen(f_out, word, pos+1);
        if(pos==length) f_out << word << std::endl;
        word[pos]++;
    }
    word[pos]='a';
}

int main()
{
    std::ofstream f_out;
    f_out.open("gen.txt");

    char* word;
    int min=2, max=4;
    for(int i=min; i<=max; i++) {
        char* buffor = new char[i+1];
        for(int x=0; x<i; buffor[x]='a',  x++);
        buffor[i]='\0';
        word=buffor;
        gen(f_out, word);
        delete [] word;
    }

    f_out.close();
    return 0;
}


texts: Simple unit test in C of input using freopen

texts:
Here is an initial attempt at unit test of user input in C.  The thing that feels unusual is the use of freopen to send the test data to stdin.  Are there better ways to implement this kind of test?

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

static size_t get_num(size_t tmpnum) {
    if (scanf("%zu", &tmpnum) != 1) {
        fprintf(stderr, "ERROR: system error: failed to read input, exiting.\n");
        exit(1);
    }
    return tmpnum;
}

int main(void)
{
    int return_status = 0;

    /* Test 1 */
    if (freopen("test-data.txt", "r", stdin) != NULL) {
        size_t tmpnum = 0;
        tmpnum = get_num(tmpnum);
        assert(tmpnum >= 1 && tmpnum <= 20);
        printf("ok: tmpnum == %ld\n", tmpnum);
        freopen("/dev/stdin", "r", stdin);
    } else {
        printf("ERROR: failed to open test-data.txt\n");
        return_status = EXIT_FAILURE;
    }

    return return_status;
}


texts:
I am working with a Star Wars API from http://swapi.co/api/. Here's the problem that I was working on for the Star Wars API problem. And the code works and prints out the exact output that I desired. I would like to get some code review.

>

# You are a Coordinator for the Star Wars rebel forces and are responsible for planning troop deployments.
# You need a tool to help find starships with enough passenger capacity and pilots to fly them.

# Build a CLI tool that takes as its single argument the number of people that
# need to be transported and outputs a list of candidate pilot and starship names
# that are each a valid possibility.
# Assume that any pilot can be a candidate regardless of allegiance.
# Assume the entire group of passengers must fit in a single starship.

# You may skip starships with no pilots or with unknown passenger capacity.
# Your tool must use the Star Wars API (http://swapi.co) to obtain the necessary data.

# You may not use any of the official Star Wars API helper libraries but can use any other libraries you want
# (http client, rest client, json).

  Example:

> # print-pilots-and-ships with minimum of 20 passengers
>
> # Luke Skywalker, Imperial shuttle
>
> # Chewbacca, Imperial shuttle
>
> # Han Solo, Imperial shuttle
>
> # Obi-Wan Kenobi, Trade Federation cruiser
>
> # Anakin Skywalker, Trade Federation cruiser

Python 3 solution:

import sys
import requests
import json
import urllib.parse

#number of pages in JSON feed

def print_page(page_num, num_passenger):
    endpoint = "https://swapi.co/api/starships/?"
    type = 'json'

    #specifies api parameters
    url = endpoint + urllib.parse.urlencode({"format": type, "page": page_num})

    #gets info
    json_data = requests.get(url).json()
    # number_of_ship = json_data['count']
    if 'results' in json_data:
      for ship in json_data['results']:
          if has_pilot(ship) and has_enough_passenger(ship, num_passenger):
              print_pilots_on(ship)

def get_pilot_name(pilot):
    type = 'json'

    #specifies api parameters
    url = pilot

    #gets info
    json_data = requests.get(url).json()
    return json_data["name"]

def print_pilots_on(ship):
    for pilot in ship['pilots']:
       print(get_pilot_name(pilot), ship['name'])

def has_pilot(ship):
    if ship['pilots']:
      return True
    return False

def has_enough_passenger(ship, num):
    if ship['passengers'] != "unknown" and int(ship['passengers']) >= num:
      return True
    return False

def print_pilots_and_ships(num_passenger):

    page_list = [1,2,3,4,5,6,7,8,9]
    # list to store names

    for page in page_list:
        print_page(page, num_passenger)

if __name__ == '__main__':
    num_passenger = int(20)
    print_pilots_and_ships(num_passenger)


texts:
I have  this code that asks the user for inputs and validates the inputs if they are Integers (no other inputs are allowed). I'd like to ask for some help in terms of elegance of the code or performance, or just the overall code.

Also, I have found myself repeating these lines of code

Console.Write("Enter weight of parcel:  ");
string input = Console.ReadLine();

and I think I really need to refactor the code because of this, but can't think of a  simple and straightforward way to refactor it.

Here is my code below:

class Program
{
    private static int _depth = 0;
    private static int _height = 0;
    private static int _weight = 0;
    private static int _width = 0;
    private static bool _isInvalidInput = true;
    static void Main(string[] args)
    {
        GetWeightInput();
        GetHeightInput();
        GetWidthInput();
        GetDepthInput();

        Console.ReadLine();
    }
    private static void GetWeightInput()
    {
        while(_isInvalidInput)
        {
            Console.Write("Enter weight of parcel:  ");
            string input = Console.ReadLine();

            #region User Weight Input Validation
            if (int.TryParse(input, out _weight))
            {
                _isInvalidInput = false;
                //TODO: Add More Validations of User Input
            }
            else
            {
                Console.WriteLine("***Only Integer Inputs Are Allowed***");
                _isInvalidInput = true;
            }
            #endregion User Weight Input Validation
        }

        _isInvalidInput = true;//reset value to true
    }
    private static void GetHeightInput()
    {
        while (_isInvalidInput)
        {
            Console.Write("Enter weight of parcel:  ");
            string input = Console.ReadLine();

            #region User Weight Input Validation
            if (int.TryParse(input, out _height))
            {
                _isInvalidInput = false;
                //TODO: Add More Validations of User Input
            }
            else
            {
                Console.WriteLine("***Only Integer Inputs Are Allowed***");
                _isInvalidInput = true;
            }
            #endregion User Weight Input Validation
        }

        _isInvalidInput = true;//reset value to true
    }
    private static void GetWidthInput()
    {
        while (_isInvalidInput)
        {
            Console.Write("Enter weight of parcel:  ");
            string input = Console.ReadLine();

            #region User Weight Input Validation
            if (int.TryParse(input, out _width))
            {
                _isInvalidInput = false;
                //TODO: Add More Validations of User Input
            }
            else
            {
                Console.WriteLine("***Only Integer Inputs Are Allowed***");
                _isInvalidInput = true;
            }
            #endregion User Weight Input Validation
        }

        _isInvalidInput = true;//reset value to true
    }
    private static void GetDepthInput()
    {
        while (_isInvalidInput)
        {
            Console.Write("Enter weight of parcel:  ");
            string input = Console.ReadLine();

            #region User Weight Input Validation
            if (int.TryParse(input, out _width))
            {
                _isInvalidInput = false;
                //TODO: Add More Validations of User Input
            }
            else
            {
                Console.WriteLine("***Only Integer Inputs Are Allowed***");
                _isInvalidInput = true;
            }
            #endregion User Weight Input Validation
        }

        _isInvalidInput = true;//reset value to true
    }
}


texts:
When creating multiple constructors, I usually do the following;

public ConstructorName(int count)
{
    this(count, 0);
}

public ConstructorName(String count)
{
    this(Integer.parseInt(count), 0);
}

public ConstructorName(int count, int other)
{
    // Do something here
}

However, I can also do it this way;

public ConstructorName(String count)
{
    this(Integer.parseInt(count)); // Chain to the constructor that just takes a number
}

public ConstructorName(int count)
{
    this(count, 0);
}

public ConstructorName(int count, int other)
{
    // Do something here
}

Is there any actual difference here? Which would be better to use when coding?


texts: Substring a String from given start index and given substring length

texts:
I want to substring a String from given start index and given substring length.

if the string is empty then returns String.Empty
if the string length is greater than start index then it substrings from given start index to given length...
if the string length is less than start index then it returns  from start index to last index

I just want to know if it can be improved and shorter with all these checks.

if the string is null or empty
if the start index is not less than zero
if the start index is less than the length of given input string.
if the given input string length is less than the desired substring length.
if the given input string length is greater than the desired substring length.

Sample Input and Ouput for my program:

SplitEntity("", 1, 15)               =>   ""
SplitEntity("abcdef", 0, 3)          =>   "abc"
SplitEntity("abcdef", 3, 100)        =>   "def"
SplitEntity("abcdef", 0, 100)        =>   "abcdef"
SplitEntity("abcdef", -1, 100)        =>   ""

My function is below:

Public Function SplitEntity(entity As String, startIndex As Integer,
                                       subStringLength As Integer) As String
            Dim spilttedString As String = String.Empty

            If (Not String.IsNullOrEmpty(entity) AndAlso startIndex >=0 ) Then

                If (entity.Length > startIndex) Then
                    If entity.Length >= (startIndex + subStringLength) Then
                        spilttedString = entity.Substring(startIndex, subStringLength)

                    ElseIf entity.Length < (startIndex + subStringLength) Then
                        spilttedString = entity.Substring(startIndex, (entity.Length - startIndex))
                    End If

                End If

            End If

            Return spilttedString

        End Function


texts:
I'm currently learning Ruby and need help in editing code to be more idiomatic. I have the method below I could use some pointers on how to make more "Ruby" :-)

def print_cal(day_of_week, month_len)
  days = %w(Mon Tue Wed Thu Fri Sat Sun)
  days.each { |day| print "#{day} " }

  puts

  day_num = 1
  month_started = false
  while day_num <= month_len
    (1..7).each do |i|
      if  day_of_week > i && month_started == false
        print '    '
      else
        month_started = true
        print ' ' if day_num < 10
        print " #{day_num} " if day_num <= month_len
        day_num += 1
      end
    end
    puts
  end
end


texts:
I wanted to know if this is the best approach for the Single Responsibility Principle.
The responsibility of this class is to remind users whose accounts are about to expire due to inactivity.

On the 30th day of inactivity, the user gets an email.
On the 45th day of inactivity, the user does not get an email; they get disabled.

public class AccountReminder
{

    private readonly IUnitOfWork _uow;
    private readonly ISendExpiringEmail _sendExpiringEmail;

    public AccountReminder(IUnitOfWork uow, ISendExpiringEmail sendExpiringEmail)
    {
        _uow = uow;
        _sendExpiringEmail = sendExpiringEmail;
    }

    public void NotifyUpcomingExpiringAccounts()
    {

        // Establish dates
        DateTime accountWarningDateTime = DateTime.Now.AddDays(-30).Date;
        DateTime expirationDateTime = DateTime.Now.AddDays(-45).Date;

        // Retrieve users whose accounts are either about to expire or have already expired
        var users = _uow.UserRepository
            .FindBy(element => (DbFunctions.TruncateTime(element.LastLoginDate) == accountWarningDateTime));

        // Send a reminder
        foreach (var user in users)
        {
            string htmlBody = "";
            htmlBody += "<meta http-equiv=...";
            htmlBody += "";

            //following line for only outlook to display image
            htmlBody += "<v:shape id=\>...</v:shape>";
            htmlBody += "<table width='100%'...
";
            htmlBody += "";

            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
            AlternateView plainView = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/plain");
            LinkedResource pic1 = new LinkedResource("images/Logo.jpg", MediaTypeNames.Image.Jpeg);
            pic1.ContentId = "Logo";
            htmlView.LinkedResources.Add(pic1);

            _sendExpiringEmail.SendTo(new[] { user.Email }, "EmailSubject", htmlView, plainView);

        }

        DisableExpiringAccounts(expirationDateTime);
    }

    private void DisableExpiringAccounts(DateTime expirationDateTime)
    {
        var expiredUsers = _uow.UserRepository.FindBy(element => element.Enabled && (DbFunctions.TruncateTime(element.LastLoginDate) <= expirationDateTime));

        foreach (var user in expiredUsers)
        {
            user.Enabled = false;
        }

        if (expiredUsers.Count > 0)
        {
            _uow.SaveChanges();
        }
    }

}


texts: Assigning raffle numbers to users in Rails

texts:
Background

One part of our Rails app is running a Raffle, usually twice a month, with around 600k entrants each round. Each raffle ticket record will have at least a unique raffle number (consisting of 4 integers between 1 and 36) and partial user data. We're using Postgres.

The current way of assigning codes is a potential performance bottleneck and I've been working on a more performant implementation. It seems to work, but I'd like to validate my approach, ask if you see any issues and ask for alternative approaches. Maybe there's some best practice already for creating unique raffle numbers that I don't know.

Current implementation

Instantiate a new raffle Ticket
Add user data to Ticket
Validate that

the Ticket has proper user data
that the user has no other Ticket in
the round
the user didn't win a round in the last year

Then, in one database transaction:

get the next serial value stored in a record in the Raffles table
increment it by one
generate the raffle number for our user,
based on that serial value

By using a database transaction that locks the Raffles table, we make sure the serial values and hence the raffle numbers will be unique. However, since we query the Raffles table in general a lot, we think this lock might be a cause for some of our performance issues.

My implementation

Run checks on the user:

make sure the user has proper data
the user didn't win a round in the last year
make sure the user doesn't have a ticket in this round yet

Create a ticket for user

add user data to ticket
get the serial value from a Postgres Sequence, set up just for this purpose
generate the raffle number for our user, based on that serial value

By using a Postgres Sequence, we let the database take care that the serial values will be unique and we don't have to worry about race conditions.

Current code

 def Ticket#generate_serial_from_raffle
   if raffle.present? && serial.blank?
     ActiveRecord::Base.transaction do
       raffle = Raffle.lock(true).find(raffle_id)
       self.serial = raffle.max_serial + 1
       self.code   = TicketFunctions.serial_to_code(serial)
       raffle.update_columns max_serial: serial, max_code: code
     end
   end
 end

My code

def User#generate_raffle_code
    raffle = Raffle.current_raffle
    if raffle.nil?
      log_a_warning(a)
      return false
    elsif !has_complete_raffle_data?
      log_a_warning(b)
      return false
    elsif is_suspended_from_raffle_entry?
      log_a_warning(c)
      return false
    elsif has_current_raffle_code?
      log_a_warning(d)
      return false
    else
      tickets.create(raffle: raffle)
    end
  end

  def Ticket#set_serial_and_code
    self.serial = ApplicationRecord.connection.execute("SELECT nextval('ticket_serials_seq');")
      .first['nextval']
    self.code = TicketFunctions.serial_to_code(serial)
  end


texts:
I am trying to improve my coding skills. As a result, I solved the T9 Spelling question from the Google Code Jam dashboard. I will appreciate it if anyone could critique the code, and provide illustrations (if possible) of how I could make my code clean and simple. For me, simple is really beautiful.

Google judges the output of the code to be correct.  Here is the problem statement.

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <fstream>

using namespace std;
string process_ln(string line);

int main(){
    ifstream infile;
    ofstream outfile;
    infile.open("C-large-practice.in");
    outfile.open("C-large-practice-result.in");

    int i=0,n=1;
    int N;
    string line;
    vector<string> all;

    infile>>N;  //number of test cases
    while(i<N+1){
        if(i<1){
        getline(infile,line);
        i++;
    }
    else{
      string result;
      getline(infile,line);
      result = process_ln(line);
      all.push_back(result);
      outfile<<"Case #"<<n<<": "<<all[i-1]<<endl;
     n++,i++;
    }
}
return 0;
}

string process_ln(string line){
    int j;
    char letter;
    vector<string> val,temp;
    vector<char> v;
    string keep;

for(j=0; j<line.length(); j++)
    v.push_back(line[j]);

for(int i=0; i<j; i++){
switch(v[i]){
    case ' ': val.push_back("0"); temp.push_back("0"); break;
    case 'a': val.push_back("2"); temp.push_back("2"); break;
    case 'b': val.push_back("2"); temp.push_back("22"); break;
    case 'c': val.push_back("2"); temp.push_back("222"); break;
    case 'd': val.push_back("3"); temp.push_back("3"); break;
    case 'e': val.push_back("3"); temp.push_back("33"); break;
    case 'f': val.push_back("3"); temp.push_back("333"); break;
    case 'g': val.push_back("4"); temp.push_back("4"); break;
    case 'h': val.push_back("4"); temp.push_back("44"); break;
    case 'i': val.push_back("4"); temp.push_back("444"); break;
    case 'j': val.push_back("5"); temp.push_back("5"); break;
    case 'k': val.push_back("5"); temp.push_back("55"); break;
    case 'l': val.push_back("5"); temp.push_back("555"); break;
    case 'm': val.push_back("6"); temp.push_back("6"); break;
    case 'n': val.push_back("6"); temp.push_back("66"); break;
    case 'o': val.push_back("6"); temp.push_back("666"); break;
    case 'p': val.push_back("7"); temp.push_back("7"); break;
    case 'q': val.push_back("7"); temp.push_back("77"); break;
    case 'r': val.push_back("7"); temp.push_back("777"); break;
    case 's': val.push_back("7"); temp.push_back("7777"); break;
    case 't': val.push_back("8"); temp.push_back("8"); break;
    case 'u': val.push_back("8"); temp.push_back("88"); break;
    case 'v': val.push_back("8"); temp.push_back("888"); break;
    case 'w': val.push_back("9"); temp.push_back("9"); break;
    case 'x': val.push_back("9"); temp.push_back("99"); break;
    case 'y': val.push_back("9"); temp.push_back("999"); break;
    case 'z': val.push_back("9"); temp.push_back("9999"); break;
    default : break;
      }//end switch
  if(i>0 && val[i]==val[i-1])
     keep +=" ";
  keep += temp[i];
   }//end for loop
   return keep;
}//end process_ln


texts: Printing the values on each level of a Binary Tree

texts:
The below code is for printing level-by-level in a binary tree:

//level order printing
public static void levelOrderPrint(Node root){
    Queue<Node> que = new LinkedList<Node>();
    Node mark = new Node(0);
    if(root != null){
        que.add(root);
        que.add(mark);
    }
    while(!que.isEmpty()){
        Node temp = que.poll();
        if(temp != mark)
        System.out.print(temp.key);
        if(temp == mark){
            if(que.peek() == mark || que.isEmpty()){
                return;
            }
            que.add(mark);
            System.out.println();
        }
        if(temp.left != null){
            que.add(temp.left);
        }
        if(temp.right != null){
            que.add(temp.right);
        }
    }
}

I would like to know if there are any bugs or possible optimizations.


texts: Improving GUI update call from a worker thread in winforms

texts:
I have a winforms app and I've been using the following approach to update controls on the main form from worker threads:

GamepadManager class has:

public static event EventHandler OnGamepadConnected;

Main app class has:

GamepadManager.OnGamepadConnected += OnGamepadConnected;
private void OnGamepadConnected()
{
    Invoke((Action)(() => { gamepadStatusLabel.Text = "Connected"; }));
}

That looks kinda bad, but without the Invoke thing I get a cross-thread operation exception because I can't update controls from worker threads (from where the call comes from).

Is there a way to reduce the number of parentheses used? Maybe there's a whole other, better way to do this?

Previously I've been using timers to check for every small thing like that, which ran on GUI thread (apparently?) and there was no trouble simply calling controlName.Text = "something"; without all the Invoke() stuff. But that means even more code and more processing cost due to constant checks.


texts: Bash script that updates Intel e1000e driver

texts:
I am now writing a small bash script that updates an Intel NIC driver to the latest version from the official website. Is there any way to improve\simplify the script? I want to avoid a lot of "if...else" stuff. Helpful tips will be appreciated!

#! /bin/bash

DRV_PKG_NAME="e1000e-3.0.4.tar.gz"
DRV_PKG_URL="http://downloadmirror.intel.com/15817/eng/e1000e-3.0.4.tar.gz"

# Downloading driver and extracting it to current directory
echo "Downloading and extracting driver package..."

if wget -q ${DRV_PKG_URL} && tar zxvf ${DRV_PKG_NAME} >/dev/null ; then
    echo "Done!"
else
    exit 1
fi

# Installing required build dependencies if necessary
echo "Installing build dependencies..."

if apt-get install -y build-essential linux-headers-$(uname -r) >/dev/null ; then
    echo "Done!"
else
    exit 1
fi

# Going into the driver source directory
cd e1000e-3.0.4/src/

# Building driver and updating initramfs
echo "Building module and updating initramfs..."

if { make install && update-initramfs -k all -u; } >/dev/null ; then
    echo "Done!"
else
    exit 1
fi

echo "Purging unnecessary build dependencies..."

if apt-get -y purge build-essential >/dev/null ; then
    echo "Done!"
else
    exit 1
fi

# Restarting iface
echo "Restarting iface!"

{ ifdown eth0  && ifup eth0; } &>/dev/null

# Checking installed driver version
if [[ $(modinfo -F version e1000e) == "3.0.4-NAPI" ]] ; then
    echo "Driver succesfully installed!"
    exit 0
else
    echo "Something Wrong...Try to re-install!"
    exit 1
fi


texts: Optimization of code for searching in db

texts:
This is my code:

var test = (from x in myDb.myTable
            where (x.name == tmp || x.name == tmp2 || x.name == tmp3) && x.unit == u
            select x).FirstOrDefault();

if (test == null)
    test = (from x in myDb.myTable
            where (x.name == tmp || x.name == tmp2 || x.name == tmp3)
            select x).FirstOrDefault();

How to optimize it>?


texts: Computing butterflies with better performance

texts:
I have a code that computes butterflies and from a little profiling I found out that it is a little bit slow. So, it seemed that the better way to optimize its performance is vectorizing it using Intel SIMD Intrinsics.

This is the scalar version of the code that I want to optimize:

float bfly0_re, bfly1_re, bfly2_re, bfly3_re;
float bfly0_im, bfly1_im, bfly2_im, bfly3_im;
float x_n2, x_N2, x_N2_2, x_N2_3;
float y_n2, y_N2, y_N2_2, y_N2_3;
float a_c_add_re, a_c_add_im, a_c_sub_re, a_c_sub_im;
float b_d_add_re, b_d_add_im, b_d_sub_im, b_d_sub_re;

x_n2 =      x[n2];
x_N2 =      x[N2];
x_N2_2 =    x[N2_2];
x_N2_3 =    x[N2_3];

y_n2 =      y[n2];
y_N2 =      y[N2];
y_N2_2 =    y[N2_2];
y_N2_3 =    y[N2_3];

ADD(a_c_add_re, x_n2, x_N2_2)//ADD(res,op1,op2){res=op1+op2}
ADD(a_c_add_im, y_n2, y_N2_2)
SUB(a_c_sub_re, x_n2, x_N2_2)//SUB(res,op1,op2){res=op1-op2}
SUB(a_c_sub_im, y_n2, y_N2_2)
ADD(b_d_add_re, x_N2, x_N2_3)
ADD(b_d_add_im, y_N2, y_N2_3)
SUB(b_d_sub_im, y_N2, y_N2_3)
SUB(b_d_sub_re, x_N2, x_N2_3)

ADD(bfly0_re, a_c_add_re, b_d_add_re)
ADD(bfly0_im, a_c_add_im, b_d_add_im)
ADD(bfly1_re, a_c_sub_re, b_d_sub_im)
SUB(bfly1_im, a_c_sub_im, b_d_sub_re)
SUB(bfly2_re, a_c_add_re, b_d_add_re)
SUB(bfly2_im, a_c_add_im, b_d_add_im)
SUB(bfly3_re, a_c_sub_re, b_d_sub_im)
ADD(bfly3_im, a_c_sub_im, b_d_sub_re)

And Then this is the SIMD version that I intend to use:

__m128 Xn2_vec,XN22_vec;
__m128 YN2_vec,YN22_vec;

__m128 YXN2_vec,YXN23_vec;
__m128 XYN2_vec,XYN23_vec;

__m128 A_vec,B_vec,C_vec,D_vec;
__m128 bfly_iv,bfly_rv;

/*A_vec = {a_c_add_re, a_c_sub_re, a_c_add_re, a_c_sub_re}*/
Xn2_vec  = _mm_broadcast_ps(X[n2]);
XN22_vec = _mm_broadcast_ps(X[N22]);
A_vec    = _mm_addsub_ps   (Xn2_vec,XN22_vec);

/*C_vec = {a_c_add_im, a_c_sub_im, a_c_add_im, a_c_sub_im}*/
Xn2_vec  = _mm_broadcast_ps(Y[n2]);
XN22_vec = _mm_broadcast_ps(Y[N22]);
C_vec    = _mm_addsub_ps   (Yn2_vec,YN22_vec);

/*B_vec = {b_d_add_re, b_d_sub_im, b_d_add_re, b_d_sub_im}*/
YXN2_vec  = _mm_set_ps   (X[N2], Y[N2], X[N2], Y[N2] );
YXN23_vec = _mm_set_ps   (X[N23],Y[N23],X[N23],Y[N23]);
B_vec     = _mm_addsub_ps(YXN2_vec,YXN23_vec);

/*D_vec = {b_d_add_im, b_d_sub_re, b_d_add_im, b_d_sub_re}*/
XYN2_vec  = _mm_shuffle_ps(YXN2_vec, YXN2_vec, _MM_SHUFFLE(2,3,0,1));
XYN23_vec = _mm_shuffle_ps(YXN23_vec,YXN23_vec,_MM_SHUFFLE(2,3,0,1));
D_vec     = _mm_addsub_ps(XYN2_vec,XYN23_vec);

bfly_rv   = _mm_addsub_ps(A_vec, B_vec);
bfly_iv   = _mm_addsub_ps(C_vec, D_vec);
/*Then Do another shuffling instructions on the butterflies to reorder them*/

n2, N2, N22, N23 are just indices because the values are not contiguous. I am using a Haswell architecture.

Here are my questions:

Is this code worth optimizing or not, knowing that it is repeated more than 1000 times?
Shall I use the _mm_load1_ps() instead of the _mm_broadcast_ps()intrinsic, or is there no difference?
Do you think that there is a better way of doing it?


texts:
I wrote this prime factors program as a programming exercise.

Any comments or constructive criticisms are welcome.

One question: prime[] is an array which stores the number's prime factors and associated exponents. How many elements, at most, does this array require? That is, what is the greatest number of prime factors needed to express any number between 1 and 4294967295? As an example 750 would need 3 elements since 750 = 2 * 3 * 5 ^ 3. I could do an exhaustive test using a static variable to keep track of the maximum value of pIndex but the 2.4 billion numbers would take at least 12 hours on my single core machine. Is there a quicker way to determine the answer?

/* primeexponents.c

   display a number's prime factors using exponents and also its number of
   divisors

   note: unsigned 32 bit numbers (1 - 4294967295)
*/

#include <stdio.h>
#include <stdbool.h>

void primeExponents (unsigned long int number, unsigned int list[])
{
    printf ("\nnumber = %lu\n", number);

    struct
    {
        unsigned long int factor;
        int exponent;
    } prime[20] = { { 0, 0 } };

    unsigned long int num = number;
    int pIndex = 0, lIndex = 0;

    prime[pIndex].factor = (unsigned long int) list[lIndex];

    while ( prime[pIndex].factor <= num / prime[pIndex].factor ) {
        if ( num % prime[pIndex].factor == 0 ) {
            ++prime[pIndex].exponent;
            num /= prime[pIndex].factor;
        }
        else {
            if ( prime[pIndex].exponent > 0 )
                ++pIndex;
            ++lIndex;
            prime[pIndex].factor = (unsigned long int) list[lIndex];
        }
    }

    // num = greatest prime factor

    if ( num == prime[pIndex].factor )
        ++prime[pIndex].exponent;
    else {
        if ( prime[pIndex].exponent > 0 )
            ++pIndex;
        prime[pIndex].factor = num;
        prime[pIndex].exponent = 1;
    }

    printf ("prime factors =");

    unsigned long int product = 1;
    int divisors = 1;

    for ( int i = 0; i <= pIndex; ++i ) {
        printf (" %lu", prime[i].factor);
        if ( prime[i].exponent > 1 )
            printf (" ^ %i", prime[i].exponent);
        if ( i < pIndex )
            printf (" *");
        // calculate product of prime factors to verify result
        for ( int j = 1; j <= prime[i].exponent; ++j )
            product *= prime[i].factor;
        // calculate number of divisors
        divisors *= prime[i].exponent + 1;
    }
    printf ("\n");

    printf ("product of prime factors = %lu", product);
    if ( product != number )
        printf (" <<< error >>>");
    printf ("\n");

    printf ("divisors = %i\n\n", divisors);
}

void generateList (unsigned int list[])
{
    // generate a list of prime numbers to use as trial factors, i.e.
    // list[0] = 2, [1] = 3, [2] = 5, [3] = 7, [4] = 11, ... [6541] = 65521

    bool isPrime;
    list[0] = 2;
    list[1] = 3;
    int index = 2;

    for ( unsigned int i = 5; i <= 65535; i += 2 ) {
        isPrime = true;

        for ( int j = 1; (i / list[j] >= list[j]) && isPrime; ++j ) {
            if ( i % list[j] == 0 )
                isPrime = false;
        }

        if ( isPrime ) {
            list[index] = i;
            ++index;
        }
    }
}

int main (void)
{
    printf ("\nPrime Factors with Exponents Program\n\n");

    unsigned int list[6542];

    generateList (list);

    unsigned long int number;

    do {
        printf ("enter a number (from 1 to 4294967295, 0 to exit): ");
        scanf ("%lu", &number);

        if ( number != 0 )
            primeExponents (number, list);
    }
    while ( number != 0 );

    return 0;
}


texts: Conditionally write to a compressed stream

texts:
My Import method takes some data and writes it to a stream.  If the CompressedStore property is true, the contents of that stream should be compressed.

This code works, however I just don't like it.  For one, I call serializer.Serialize() twice.  I feel this code can be made more concise.  Any ideas?

public void Import(IProvisionSource source)
{
   InitializeStore();

   // Call source.Export and populate local data store
   var data = source.Export();
   var serializer = new XmlSerializer(data.GetType());

   var file = CompressedStore ? "KPCData.gz" : "KPCData.xml";
   var path = Path.Combine(DataDirectory, file);
   using (var fileWriter = new FileStream(path, FileMode.Create))
   {
      if (CompressedStore)
      {
         using (var writer = new GZipStream(fileWriter, CompressionLevel.Optimal))
         {
            serializer.Serialize(writer, data);
         }
      }
      else
      {
         serializer.Serialize(fileWriter, data);
      }
   }
}


texts:
Here's my Queue implementation in ES6,

class Queue{
    constructor(){
        this.head = null;
        this.tail = null;
    }
    offer(item){
        const p = new Node(item);
        if(!this.head){
            this.head = p;
            this.tail = p;
            return;
        }
        this.tail.next = p;
        this.tail = p;

    }
    poll(){
        const item = this.head;
        this.head = this.head.next;
        return item;

    }
    peek(){
        return this.head.val;
    }
    isEmpty(){
        return this.head === null;
    }
}

Please review on all fronts.


texts: Composing CPU instructions by merging four short hex strings

texts:
My code shares some values with its neighbor. The names "Instructions, Registers" can be ignored in the comments; just see them as "names". What's important is how they are shared, which can be seen in the calculations.

What I want is to improve this code, because it looks awful and one can barely understand what's going on.

hexShared = {"80","3E","14"}; //lwz r31, -0x0018(r20)

    //Merge Hex Values that are shared (Basically every other is shared with the next one except the Address)
    private static string mergeHex(string[] hexShared)
    {

        //[ ][ ][ ][ ]
        //[0  1][2  3]
        string s1 = hexShared[0]; //Instruction
        string s2 = hexShared[1]; //Register 1
        string s3 = hexShared[2]; //Register 2

        char c1 = s1[1]; //Instruction Shared with Register 1
        char c2 = s2[0]; //Register 1 Shared with Instruction
        char c3 = s2[1]; //Register 1 Shared with Register 2
        char c4 = s3[0]; //Register 2 Shared with Register 1
        char c5 = s3[1]; //Register 2

        string hex = AddHex(c1, c2);

        string hex2 = AddHex(c3, c4);

        hex = s1[0] + hex + hex2 + c5;

        return hex;
    }

I will try explain with an example (though I barely get it myself).

We have a Hexdecimal of 8 characters (that's the structure always).

83340247

Now we can split it up, the last 4 are the "Address" and it can be taken out.
So what remains are Hexdecimals that share values.

8334

Now for example the code:

lwz r0, 0x0000(r0)

will translate to: 80000000
So lwz == "8" here.

lwz r1, 0x0000(r0) == 80200000

So the first "r1" equals "2" right?

lwz r1, 0x0000(r1) == 80210000

It all looks fine, everything is separated, the other "r1" is simply "1".

Now here is the dilemma, when they reach values higher than one Hexdecimal can represent.

lwz r1, 0x0000(r31) == 803F0000
lwz r31, 0x0000(r31) == 83FF0000

So as you can see, when they increase size, they will Add into the place "Left" of their starting point.
So r1 (which is 2) will become "3" when the second "r31" becomes large enough so it needs to use that space.

I suck at explaining but i hope this Examples helps a bit at least:)

    //Convert Hex in String to Integer
    public static int HexToInt(string Hex)
    {
        return int.Parse(Hex, NumberStyles.AllowHexSpecifier);
    }

//Sum Two Hex Chars and return it as Hex String (1 character)
        public static string AddHex(char hex1, char hex2)
        {
            int i1 = HexToInt(hex1.ToString());
            int i2 = HexToInt(hex2.ToString());
            int sum = i1 + i2;
            return sum.ToString("X1");
        }


texts:
Isn't it annoying when you can't find a file you recently created? Especially when you either have a very disorganized drive or a directory with lots of files.

Even if you don't care, isn't it nice to have a program be able to locate a file for you?

I did this because I have files that I can't seem to locate, but I know roughly where it is. The FileFinder class can:

Find your file
Copy it to somewhere else

The only feature-lack:

Files with the same name in a different directory are not handled well.

Only one of the files will be returned.

I will add that feature once I can think of a way to implement it.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class FileFinder {

    protected final File root;
    protected Map<String, File> files;

    protected final Pattern matchingRegex;

    public FileFinder(File root, String matchingRegex) {
        if (root.isFile()) {
            throw new IllegalArgumentException("root must be a directory.");
        }
        this.root = root;
        this.files = getAllFiles(root);
        this.matchingRegex = Pattern.compile(matchingRegex);
    }

    protected Map<String, File> getAllFiles(File root) {
        File[] files = root.listFiles();
        Map<String, File> result = new HashMap<>();
        for (File file : files) {
            if (file.isDirectory()) {
                result.put(file.getName(), file);
                result.putAll(getAllFiles(file));
            } else if (matchingRegex.matcher(file.getName()).matches()) {
                result.put(file.getName(), file);
            }
        }
        return result;
    }

    public File getRoot() {
        return root;
    }

    public File find(String fileName) throws FileNotFoundException {
        File result = files.get(fileName);
        if (result == null) {
            throw new FileNotFoundException("Cannot find file " + fileName
                    + " in root.");
        }
        return result;
    }

    public boolean copy(File file, File dest) {
        if (dest.isFile()) {
            throw new IllegalArgumentException(
                    "The destination must be a directory.");
        }
        if (!(file.exists() && dest.exists())) {
            throw new IllegalArgumentException(
                    "One or more of the files do not exist.");
        }
        try {
            Files.copy(file.toPath(), new File(dest, file.getName()).toPath(),
                    StandardCopyOption.REPLACE_EXISTING,
                    StandardCopyOption.COPY_ATTRIBUTES);
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public void findAndCopy(File dest, String fileName)
            throws FileNotFoundException {
        copy(find(fileName), dest);
    }

}

Concerns:

Is this OOP enough?
Anything in the java.nio package that makes this easier?
Anything else?


texts: Calculation of elasticity for non-linear curve

texts:
I've written this code to calculate the elasticity for econometric analysis. Basically, this algorithm estimate the function:

$$\epsilon(x) = \frac{x}{f(x)}\ f'(x)$$

###############################################

    elasticity<-function(y.p,x.p,band){
        require(KernSmooth)
        as.vector(y.p);as.vector(x.p)
            loess.fun<-locpoly(x.p,y.p,bandwidth=band)
                plot(loess.fun,type='l',lwd=2,lty=4,
                    ylim=c(0,100),xlab="Price",
                    ylab="Share", col=2,
                    main="Local Polynomials Estimation")
            loess.der<-locpoly(x.p,y.p,drv=1,bandwidth=band,
                          gridsize = length(y.p))
            y1<-as.vector(loess.der$y)
            eps<-matrix(NA,length(y.p),2)
            eps[,1]<-x.p
                for(i in 1:length(y.p)){
                    eps[i,2]<-x.p[i]/y.p[i]*y1[i]
                }
            j<-order(x.p)
            colnames(eps)<-c("Price","Elasticity")
        return(eps[j,])
    }

###############################################

Can I improve this algorithm?


texts: Generic Extension Method To Count Descendants

texts:
I've created a extension method to count every available descendant starting from a single, given key.

The data is a flat list, there's is no hierarchical structure. (Well, not entirely true. There is an hierarchy in the data-model, but not in the list itself)

self-reference      parent-reference   some other members
10045     =>        0                   ..
10046     =>        10045               ..
10044     =>        10063               ..
10061     =>        10044               ..
10063     =>        10046               ..
10064     =>        10046               ..
10021     =>        10061               ..
10028     =>        10000               ..
10030     =>        10000               ..
10031     =>        10000               ..
10000     =>        10000               ..

As an example, counting the descendant of the entry with the self-reference number 10046 would result in 6.

Let's take 10021 as an possible related entry to entry 10046, for example.

  10021 refers to 10061, 10061 refers to 10044, 10044 refers to 10063,
  10063 refers to 10046
  => related!

My extension method is actually split up in two different methods.

public static int CountDescendants<TSource, T>(
    this IEnumerable<TSource> source,
    T startKey,
    Func<TSource, T> selfReference,
    Func<TSource, T> parentReference)
{
    if(source == null) {
        throw new ArgumentNullException("source");
    }

    return Count(source, startKey, selfReference, parentReference);
}

startKey defines our filter, the key we're looking for. In the example above I've used

  10046

selfReference defines a unique key a dataset can be identified with.

parentReference defines a unique key which refers to another dataset.

The actual algorithm looks like this.

private static int Count<TSource, T>(
            IEnumerable<TSource> source,
            T key,
            Func<TSource, T> selfReference,
            Func<TSource, T> parentReference)
{
    // hash-map + .Where is faster than using IEnumerable + .Where
    ReadOnlyDictionary<T, T> consolidatedSource =
        new ReadOnlyDictionary<T, T>(source.ToDictionary(selfReference, parentReference));
    int count = 0;

    // to keep track of every reference which is somehow related to "key"
    HashSet<T> keys = new HashSet<T> {
        key
    };

    // using a stack instead of recurison
    Stack<KeyValuePair<T, T>> stack = new Stack<KeyValuePair<T, T>>();

    // get all first level entries with the given key
    foreach(KeyValuePair<T,T> item in consolidatedSource.Where(x => x.Value.Equals(key))) {
        stack.Push(item);
    }

    // using .Any over .Count because we don't care how many items we have but rather that the stack is not empty
    while (stack.Any()) {
        KeyValuePair<T, T> current = stack.Pop();

        if (keys.Contains(current.Value)) {
            count++;
            keys.Add(current.Key);

            // get all first level entries with the new key
            foreach (KeyValuePair<T, T> item in consolidatedSource.Where(x => x.Value.Equals(current.Key) && !x.Key.Equals(current.Key))){
                stack.Push(item);
            }
        }
    }

    return count;
}

The method can be called like this

this.AllProfiles.CountDescendants(CurrentProfile.Ref, x => x.Ref, x => x.ParentRef);

Is stuff like using a Dictionary to speed up things micro-optimization which I shouldn't worry about? Personally, wherever I can impact performance, I try to get the best out of it. Or at least not make it any worse.

Also, I'm not entirely sure if there are any constraints I can apply to the generic types. I don't think there's one that actually fits and is needed.


texts: Tweets per second calculator (Talent Buddy)

texts:
This challenge is from Talent Buddy:

    Tweets per second

  Japan Castle in the Sky airing broke a Twitter record on August 3,
  2013. At one point during the classic anime movie showing, people submitted 143,199 tweets per second. This particular spike was about
  25 times greater than Twitter’s steady state.

  Given an array of integers representing the number of tweets recorded
  every second and an integer value K, your task is to write a function
  that prints to the standard output (stdout) the highest number of
  tweets recorded between each second in the array and the past K
  seconds before it

  Note that your function will receive the following arguments: tps,
  which is an array of integers representing the number of tweets
  recorded every second, and k, which is the integer number mentioned
  above.

  Data constraints: the length of the array above will not exceed
  500,000 numbers

  Efficiency constraints: your function is expected to print the
  requested result and return in less than 2 seconds

  Example Input

  tps: 6, 9, 4, 7, 4, 1

  k: 3 Output

  6 9 9 9 7 7 Please Note: The above program should run in below 2
  seconds

Below is my code in c#

public void tweets_per_second(int[] tps, int k) {
    // Write your code here
    // To print results to the standard output you can use Console.WriteLine()
    // Example: Console.WriteLine("Hello world!");

    for(int i=0; i<tps.Length;i++)
    {
        Console.WriteLine(FindMaxLastK(tps, i, k));

    }
}
// method to check the maximum of last k items in the array
public int FindMaxLastK(int[] tps, int start, int k)
{
    k = k-1;
    int max = 0;
 while(k >= 0 && start >= 0)
 {
     max = tps[start] > max? tps[start]:max;
     k--;
     start--;
 }
    return max;
}

The code has been accepted by the website,  but somehow I feel it can be done better. Any suggestions?


texts:
Here is my OrderBy method which includes concatenated column names.
Can this be achieved more efficiently?

public static IQueryable<T> Sort<T>(this IQueryable<T> query, List<SortationDto> sortations)
    where T : BaseEntity
{
    sortations.ForEach(s =>
    {
        Expression value = null;
        ParameterExpression parameter = Expression.Parameter(query.ElementType, "item");

        // if sortation is a concatenation of two columns
        if (s.Concatenated.Count > 0)
        {
            Expression concat = null;
            s.Concatenated.ForEach(c =>
            {
                //get first property
                value = c.Column.Split('.').Aggregate((Expression)parameter, Expression.PropertyOrField);

                //if first property add as initial property
                if (concat == null)
                {
                    concat = value;
                }
                else //else concatenate with first property
                {
                    MethodInfo concatMethod = typeof(String).GetMethod("Concat", new Type[] { typeof(string), typeof(string), typeof(string) });
                    value = Expression.Call(concatMethod, concat, Expression.Constant(" "), value);
                }
            });
        }
        else //else use one and only property
        {
            value = s.Column.Split('.').Aggregate((Expression)parameter, Expression.PropertyOrField);
        }

        //build lambda expression
        LambdaExpression predicate = Expression.Lambda(value, parameter);

        //define orderby method name based on current iteration of sortations
        string methodName = (sortations.IndexOf(s) == 0 ? "Order" : "Then") + (s.Direction == "asc" ? "By" : "ByDescending");

        //call method
        MethodCallExpression orderBy = Expression.Call(typeof(Queryable), methodName, new Type[] { query.ElementType, value.Type }, query.Expression, Expression.Quote(predicate));

        //add final expression to query
        query = query.Provider.CreateQuery<T>(orderBy);
    });

    return query;
}


texts:
I am extracting data from a text file. Some of the lines from which I want to extract the data consist of a text description with single spaces, followed by a multiple-space gap preceding four fields containing the data, each separated by multiple spaces. A field might either contain the indicator "N/A" or else it will contain an integer < 10,000 (possibly comma-ed) such as 15 or 7,151 followed by a valid percentage in parentheses. The percentage will always have a single decimal point; for example, (0.0%) or (19.8%) or (100.0%) . If the field contains "N/A", then I want to write out "NA,NA" and if the field contains a number and percentage, then I want to write those two values out separated by a comma.

At the moment, I use the following regex to describe a single field:

$naNumberGroup = qr/(N\/A|(([0-9]{1,3}(,[0-9]{3})*) \(([0-9]{1,2}\.[0-9])\%\)))/

and then the following code to get the various pieces from the current line, which is $line :

if( $line =~ m/$naNumberGroup +$naNumberGroup +$naNumberGroup +$naNumberGroup/ ) {
 if("N/A" eq $1) {
  print "NA,NA";
 } else {
  print ",$3,$5";
 }

 if("N/A" eq $6) {
  print ",NA,NA";
 } else {
  print ",$8,$10";
 }

 if("N/A" eq $11) {
  print ",NA,NA";
 } else {
  print ",$13,$15";
 }

 if("N/A" eq $16) {
  print ",NA,NA";
 } else {
  print ",$18,$20";
 }
 print "\n";
}

It seems horribly clumsy; for example, it's easy to make a mistake in counting the parentheses and getting the pairs of fields correctly referenced ... but I am unsure of even what sorts of things I should be looking at to improve it (assuming that's possible). I would appreciate some guidance or comment. Even, "it seems fine" would at least indicate that I shouldn't waste time on improving it!

An example line of text is:

Adults who actively pursue work opportunities
             197 (82.8%)              30 (12.6%)                  N/A                     N/A

The description at the beginning of the line changes depending on the data. The output that I want for this line is:

197,82.8,30,12,6,NA,NA,NA,NA

Similarly, if the line were:

Adults who actively pursue work opportunities
             197 (82.8%)              N/A              30 (12.6%)                  N/A

then I want the output:

197,82.8,NA,NA,30,12.6,NA,NA


texts: This LINQ Model Query seems extremely inefficient

texts:
I'm new to LINQ, but I have some background in T-SQL. I know there are probably 100 different ways to design a T-SQL statement that would run this much more efficiently, but I'm not sure how I would do it in LINQ and I would like to stick with LINQ.

This works perfectly well, I just hate the way it looks and am unsure of how to fix it.

I am using MVC3, C#, LINQ, Entity Framework 4.3

public class CollectionRepository : ICollectionRepository {
    private CollectionEntities db = new CollectionEntities();

    public IEnumerable<Collection> GetCollectionByUid(long id) {
        var _collection = (from c in db.UserCollections
                          where c.uid == id
                          orderby c.CreateDate descending
                          select new Collection {
                              Name = c.CollectionName,
                              Type = (from t in db.CollectionTypes
                                      where t.ctypeid == c.Type
                                      select t.CollectionTypeName).FirstOrDefault(),
                              Created = c.CreateDate,
                              Count = (from f in db.Figures
                                       where f.CollectionID == c.cid
                                       select f).Count()
                          }).ToList();
        return _collection;
    }
}

The constructors it points to:

public class Collection {
    public string Name { get; set; }
    public string Type { get; set; }
    public DateTime Created { get; set; }
    public int Count { get; set; }
}


texts:
I’m planning on creating a Mortal Kombat-inspired game in JavaScript. I’ve written a basic game engine that manages my game states and creates a game loop.

I just wondered if it could be improved at all? As I’m a web developer by trade and this is my first foray into programming games.

/**
 * Game engine.
 */
function GameEngine() {
    this.states = new Array();
    this.currentState;
    this.running = false;
};

GameEngine.prototype.init = function() {
    this.running = true;
};

GameEngine.prototype.changeState = function(state) {
    this.currentState = state;
};

GameEngine.prototype.isRunning = function() {
    return this.running;
};

GameEngine.prototype.handleEvents = function() {
    this.currentState.handleEvents(this);
};

GameEngine.prototype.update = function() {
    this.currentState.update(this);
};

GameEngine.prototype.draw = function() {
    this.currentState.draw(this);
};

/**
 * Base game state state.
 */
function GameState() {};

/**
 * Intro state.
 */
function IntroState() {};

IntroState.prototype = Object.create(GameState.prototype);

IntroState.prototype.handleEvents = function(game) {
    console.log('IntroState::handleEvents');
};

IntroState.prototype.update = function(game) {
    console.log('IntroState::update');
};

IntroState.prototype.draw = function(game) {
    console.log('IntroState::draw');
};

/**
 * Initialises the game.
 */
(function() {
    var game = new GameEngine();
    var gameLoop;
    var frameLength = 500;

    game.init();
    game.changeState(new IntroState());

    gameLoop = setInterval(function() {
        game.handleEvents();
        game.update();
        game.draw();
    }, frameLength);
})();


texts: Create two random teams from a list of players

texts:
The task is to create two random teams from a list of players.

Given an example of players = ["John", "Mike", "Alice", "Bob"]

One example random team would be:

team1 = ["Mike", "Alice"];
team2 = ["John", "Bob"];

This is my solution but I'm not sure how efficient it is because random can create same number for a number of times.

The question to separate equally and randomly without repeating the same player.

using System;
using System.Collections.Generic;

public class Program
{

    public static void Main(string[] args)
    {
        Random rnd = new Random();
        var numbers = new List<int>();

        var ilkListe = new List<int>();

        var ikinciListe = new List<int>();

        numbers.Add(1);
        numbers.Add(2);
        numbers.Add(3);
        numbers.Add(4);
        numbers.Add(5);
        numbers.Add(6);
        numbers.Add(7);
        numbers.Add(8);
        numbers.Add(9);
        numbers.Add(10);
        Console.WriteLine("LIST 1: " + numbers.Count);

        do {
            int sayi = numbers[rnd.Next(numbers.Count)];
            if (!(ilkListe.Contains(sayi))) {
                Console.WriteLine(sayi);
                ilkListe.Add(sayi);
            }
        }

        while (ilkListe.Count < numbers.Count / 2);

        Console.WriteLine("Ikinci liste");

        do {
            int sayi = numbers[rnd.Next(numbers.Count)];
            if (!(ilkListe.Contains(sayi)) && !(ikinciListe.Contains(sayi))) {
                Console.WriteLine(sayi);
                ikinciListe.Add(sayi);
            }
        }

        while (ikinciListe.Count < numbers.Count / 2);
    }
}


texts: Pagination links for a publications list

texts:
$pageUN = $conn->query("SELECT slug_link FROM bn_publicacao WHERE entry_type = 'pagina' and id = 2")->fetchAll();

$maxlinks = 4;
$pagina   = (isset($_GET['pagina'])) ? (int)$_GET['pagina'] : 1;
$maximo   = 12;
$inicio   = (($maximo * $pagina) - $maximo);

$stmtUN = "SELECT * FROM bn_publicacao WHERE entry_type = 'post' ORDER BY id DESC LIMIT $inicio, $maximo";
$pUN    = $conn->query($stmtUN)->fetchAll();

<?php foreach ($pUN as $UN): ?>

<a href="index.php?post=<?php echo htmlentities($UN['slug_link'], \ENT_QUOTES, 'UTF-8', false); ?>"><?php echo htmlentities($UN['title'], \ENT_QUOTES, 'UTF-8', false); ?>

<?php endforeach; ?>

$stmtPG = $conn->prepare("SELECT * FROM bn_publicacao WHERE entry_type = 'post'");
$stmtPG->execute();
$total = $stmtPG->rowCount();
$total_paginas = ceil($total/$maximo);

if($total > $maximo){

echo '';

  echo '
';

    echo '
';

      foreach($pageUN as $PUN){

        echo 'Primeira';

      }

    echo '
';

for ($i = $pagina - $maxlinks; $i <= $pagina -1; $i++) {

  if ($i >= 1) {

    echo '
';

      foreach($pageUN as $PUN) {

        echo ''.$i.'';

      }

    echo '
';

  }
}

echo ''.$pagina.'';
for ($i= $pagina +1; $i <= $pagina + $maxlinks; $i++) {
  if ($i <= $total_paginas) {

    echo '
';

      foreach($pageUN as $PUN) {

        echo ''.$i.'';

      }

    echo '
';

  }
}

echo '
';

  foreach($pageUN as $PUN) {

    echo 'Última';

    }

  echo '
';

echo '';

}

$conn = null;

I want to know if my pagination is safe and if it's not, where's the problems and what can i do to make it safe.

What you guys think?

Edit:

 $stmtPG = $conn->query("SELECT count(*) FROM bn_publicacao WHERE entry_type = 'post'");
 $stmtPG->execute();
 $total = $stmtPG->fetchColumn();
 $total_paginas = ceil($total/$maximo);


texts: Covert html to pdf, calculate the vertical space to the end of the last page faster

texts:
I'm working on a custom puppeteer script which converts dynamic generated HTML to an A4 PDF.
This script converts HTML to a near perfect A4 PDF file, the only issue I have is speed. Document conversion is anywhere between 1-10 minutes.

I have tracked the slowness to the part where we calculate how much vertical space needs to be added to the last page
in order to have a full page. If we don't do this the background we have will be clipped.

Next up the relevant code, which is called as followed;

node convert.js "{\"url\":\"file://$(pwd)/generated.html\",\"options\":{\"path\":\"$(pwd)/generated.pdf\"}}"

async function addPadding(page) {
    await page.emulateMedia('print');

    await page.evaluate(
        _ => {
            let container = document.querySelector('#padding-container');

            if (container)
                container.style.height = '1145px'
        }
    );

    return Promise.resolve()
}

function getPageAmount(buffer) {
    let index = buffer.indexOf('/Count ');
    let string = buffer.slice(index + '/Count '.length, index + '/Count '.length + 32).toString();
    return ~~string.trim().split(/\n|\/|\[|\>/)[0]
}

convert.js

(async _ => {
    const browser = await puppeteer.launch({
        headless: true,
        args: [
            isDocker ? '--no-sandbox' : ''
        ],
        defaultViewport: {
            width: 724,
            height: 1145 * 32
        }
    });
    const page  = await browser.newPage();

    await page.emulateMedia('print');
    await page.goto(request.url, { waitUntil: 'networkidle0' });
    await page.setViewport({ width: 724, height: 1145 });

    let buffer = await render(page);
    let originalPages = getPageAmount(buffer);
    let maxPasses = 3;
    let passes = 0;

    await addPadding(page);

    buffer = await render(page);

    while(getPageAmount(buffer) !== originalPages && passes < maxPasses) {
        await page.evaluate(
            _ => {
                let paddingContainer = document.querySelector('#padding-container');
                let value = ~~paddingContainer.style.height.replace('px', '');
                paddingContainer.style.height = `${value / 2}px`
            }
        );

        buffer = await render(page);

        if (getPageAmount(buffer) === originalPages) {
            while (getPageAmount(buffer) === originalPages) {
                await page.evaluate(
                    _ => {
                        let paddingContainer = document.querySelector('#padding-container');
                        let value = ~~paddingContainer.style.height.replace('px', '');
                        paddingContainer.style.height = `${value * 1.5}px`
                    }
                );

                buffer = await render(page)
            }
        }

        passes++
    }

    while(getPageAmount(buffer) !== originalPages) {
        await page.evaluate(
            _ => {
                let paddingContainer = document.querySelector('#padding-container');
                let value = ~~paddingContainer.style.height.replace('px', '');
                paddingContainer.style.height = `${value - 1}px`
            }
        );

        buffer = await render(page)
    }

    if (request.options.path)
        fs.writeFileSync(request.options.path, buffer);

    browser.close()
})();

I really would appreciate any feedback/help on this.


texts: Basic Database Class with PDO functionality

texts:
Is my following (very basic) class considered good use for PDO integration?
Or is there a better, more efficient way?

class Page {

    public $title;
    public $db;

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

    public function connect($host, $dbname, $username, $password) {
        $this->db = new PDO('mysql:host='.$host.';dbname='.$dbname, $username, $password);
    }

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

}


texts: Booking validation in a big if-elseif block

texts:
I have pasted a part of my event handler code block. I understand this code really looks like a mess specially the object that is created every time the message is changing. Is cleanup possible in this code? Any inputs will help.

btn.addEventListener('click', procs.debounce(bookDiningBtnHandler, 400));
var bookDiningBtnHandler = function() {
    btnContext = this, message = {};
    btnContext.touchEnabled = false;
    btnContext.children[0].bubbleParent = 'false';
    hideKeyBoard();
    // Avoid overlap of keyboard with the prompt..
    removeDatePicker();
    // Avoid overlap of picker with the prompt..

    var isValidEmail = procs.checkValidEmail(email.value);
    var isIntPositive = procs.isPositiveInteger(guest.value);

    if (name.value != '' && isValidEmail != false && isIntPositive != false && guest.value > 0 && date.text != 'Date' && time.text != 'Time') {
        if (guest.value > guestLimit) {
            message = {
                "ref" : 0,
                "title" : "Attention",
                "text" : "Booking for more than 6, Please book through XYZ!"
            };
            customAlert(message);
            return;
        }
        booking = {
            "action" : "diningBook",
            "emailReservations" : Alloy.Globals.data.dining.ER,
            "name" : name.value,
            "email" : email.value,
            "guest" : guest.value,
            "date" : date.text,
            "time" : time.text
        };

        if(checkLastBooked(booking, Alloy.Globals.BDD)){
            message = {
                "ref" : 0,
                "title" : "Attention",
                "text" : "Bookings were made earlier!"
            };
            customAlert(message);
            return;
        }
        Alloy.Globals.BDD = booking;
        procs.sendEmail(booking, function(e) {
            treatTheAnswer(e);
            customAlert(message);
            //Ti.API.info('email  passed!');
        });
        function treatTheAnswer(resultSentEmail) {
            if (resultSentEmail) {
                message = {
                    "ref" : 0,
                    "title" : "Booking sent",
                    "text" : "A member of our team will contact you to confirm your BK"
                };
            } else {
                message = {
                    "ref" : 1,
                    "title" : "Error ",
                    "text" : "Something went wrong. Please try again later!"
                };
            }
        }

    } else {
        message = {
            "ref" : 0,
            "title" : "Missed info",
            "text" : "Missing information, Please fill in all fields!"
        };
        if (!isValidEmail && isIntPositive) {
            message = {
                "ref" : 1,
                "title" : "Error",
                "text" : " Invalid Email Address. Please re-enter valid Address!"
            };
        }
        customAlert(message);
        //Ti.API.info(' validation  failed!');

    }
};


texts:
Continud from Playing “craps” for the win v0.2

  You roll two dice. Each die has six faces, which contain one, two,
  three, four, five and six spots, respectively. After the dice have
  come to rest, the sum of the spots on the two upward faces is
  calculated. If the sum is 7 or 11 on the first throw, you win. If the
  sum is 2, 3 or 12 on the first throw (called “craps”), you lose (i.e.,
  the “house” wins). If the sum is 4, 5, 6, 8, 9 or 10 on the first
  throw, that sum becomes your “point.” To win, you must continue
  rolling the dice until you “make your point” (i.e., roll that same
  point value). You lose by rolling a 7 before making your point.

// Craps.java

package co.vu.xxx.craps;

import java.security.SecureRandom;

public class Craps {
    public static enum Outcome {UNDEFINED, WIN_FIRST, WIN_POINT, LOSE_FIRST, LOSE_POINT};
    private int currentNumber;
    private int point;
    private Outcome gameResult = Outcome.UNDEFINED;
    private static SecureRandom randomNumbers = new SecureRandom();

    public static int rollDice() {
        int randN = 2 + randomNumbers.nextInt(6) + randomNumbers.nextInt(6);
        return randN;
    }

    public void firstRoll() {
        currentNumber = rollDice();
        switch (currentNumber) {
            case 7:case  11:
                gameResult = Outcome.WIN_FIRST;
                break;
            case 2:case 3:case 12:
                gameResult = Outcome.LOSE_FIRST;
                break;
            default:
                point = currentNumber;
        }
    }

    public void moreRolls() {
        currentNumber = rollDice();
        if(currentNumber == point) {
            gameResult = Outcome.WIN_POINT;
        } else if(currentNumber == 7) {
            gameResult = Outcome.LOSE_POINT;
        }
    }

    public Outcome getGameResult() {
        return gameResult;
    }

    public int getPoint() {
        return point;
    }

    public int getCurrentNumber() {
        return currentNumber;
    }
}

// UseCraps.java

package co.vu.xxx.craps;

import java.io.IOException;
import java.util.Scanner;

public class UseCraps {
    public static void main(String[] args) throws IOException {
        Craps crapObj = new Craps();
        waitUser();
        crapObj.firstRoll();
        declareResult(crapObj);
        while(crapObj.getGameResult() == Craps.Outcome.UNDEFINED) {
            waitUser();
            crapObj.moreRolls();
            declareResult(crapObj);
        }
    }
    public static void declareResult(Craps pCrap) {
        System.out.printf("You got a %d\n", pCrap.getCurrentNumber());
        int point = pCrap.getPoint();
        if(point != 0) {
            System.out.printf("You need to make your point: %d\n", point);
        }
        switch (pCrap.getGameResult()) {
            case LOSE_FIRST:
                System.out.println("You have lost because of hitting crap in the first round.");
                break;
            case WIN_FIRST:
                System.out.println("You have won, you got a lucky number in the first round!");
                break;
            case LOSE_POINT:
                System.out.println("You have lost, you hit 7 before making your point!");
                break;
            case WIN_POINT:
                System.out.println("You have won, you made your point!");
                break;
            case UNDEFINED:
                System.out.println("Game continues...\n");
                break;
        }
        System.out.println();
    }

    private static void waitUser() {
        Scanner inputScan = new Scanner(System.in);
        System.out.print("Press enter to start rolling: ");
        String input = inputScan.nextLine();
    }
}


texts: bash script for constructing RNA pipeline

texts:
I have written a bash script that consists of multiple commands and Python scripts. The goal is to make a pipeline for detecting long non coding RNA from a certain input. Ultimately I would like to turn this into a app and host it on some bioinformatics website. One problem I am facing is using getopt tools in bash. I couldn't find a good tutorial that I understand clearly. In addition any other comments related to improving on the code is much appreciated.

#!/bin/bash
if [ "$1" == "-h" ]
then
    echo "Usage: sh $0 cuffcompare_output reference_genome blast_file"
    exit
else
wget https://github.com/TransDecoder/TransDecoder/archive/2.0.1.tar.gz && tar xvf 2.0.1 && rm -r 2.0.1
makeblastdb -in $3 -dbtype nucl -out $3.blast.out
grep '"u"' $1 | \
gffread -w transcripts_u.fa -g $2 - && \
python2.7 get_gene_length_filter.py transcripts_u.fa transcripts_u_filter.fa && \
TransDecoder-2.0.1/TransDecoder.LongOrfs -t transcripts_u_filter.fa
sed 's/ .*//' transcripts_u_filter.fa | grep ">" | sed 's/>//' > transcripts_u_filter.fa.genes
cd transcripts_u_filter.fa.transdecoder_dir
sed 's/|.*//' longest_orfs.cds | grep ">" | sed 's/>//' | uniq > longest_orfs.cds.genes
grep -v -f longest_orfs.cds.genes ../transcripts_u_filter.fa.genes > longest_orfs.cds.genes.not.genes
sed 's/^/>/' longest_orfs.cds.genes.not.genes > temp && mv temp longest_orfs.cds.genes.not.genes
python ../extract_sequences.py longest_orfs.cds.genes.not.genes ../transcripts_u_filter.fa longest_orfs.cds.genes.not.genes.fa
blastn -query longest_orfs.cds.genes.not.genes.fa -db ../$3.blast.out -out longest_orfs.cds.genes.not.genes.fa.blast.out -outfmt 6
python ../filter_sequences.py longest_orfs.cds.genes.not.genes.fa.blast.out longest_orfs.cds.genes.not.genes.fa.blast.out.filtered
grep -v -f longest_orfs.cds.genes.not.genes.fa.blast.out.filtered longest_orfs.cds.genes.not.genes.fa > lincRNA_final.fa
fi

Here is how I run it:

sh test.sh cuffcompare_out_annot_no_annot.combined.gtf /mydata/db/Brapa_sequence_v1.2.fa TE_RNA_transcripts.fa


texts: Performance of mask (1,2,4,8,16) convertor in python

texts:
My mask translator is performing poorly in scenario where I have 30 masks and 10,000 ownerships. This is a bit field and similar to bit masks such as enum.IntFlag.

I though about creating a list with all combinations of masked values and names (1 - alex, 2 - ben, 3 - alex/ben, 4 - clark, 5,... sum from 1 to 30 = 465) and then doing a simple lookup rather than evaluating the function for each ownership item. What do you think about this approach?

def findbits(num,object):
  for i in range(128):
      if num & 1 << i:
          y = "{0}".format(i + 1)
          output.append([names[int(y)-1], object])

output = []
map = [['1','alex'],['2','ben'],['4','clark'],['8','dean'],['16','eric']]
mask = [row[0] for row in map] #['1', '2', '4', '8', '16']
names = [row[1] for row in map] #['alex', 'ben', 'clark', 'dean', 'eric']
ownership = [['radio','3'],['telly','31']]

for item in ownership:
  findbits(int(item[1]),item[0])

print(output)
#[['alex', 'radio'], ['ben', 'radio'], ['alex', 'telly'], ['ben', 'telly'], ['clark', 'telly'], ['dean', 'telly'], ['eric', 'telly']]

In a nutshell: I have to find which names own which objects, that is to decompose masked number for each object (e.g. radio: 31 = 16 + 8 + 4 + 2 + 1) and look up values (names) for each sub-number (16 - eric, 8 - dean, ...).

And a large scale example:

import random
import string

def get_ownerships(nbr):
    for i in range(nbr):
        objects = ''.join(random.choice(string.ascii_letters) for m in range(4))
        ownership.append([objects,mask[i]])
    return ownership

def findbits(num,object):
  for i in range(int(num**0.5)+1): #roundup to nearest integer; this is crucia for performance. Shall be dependent on num,
  #precisely the position of the highest subnumer. If num = 17, then 17 = 16 + 1 where 16 is 5th element (1 - 2 - 4 - 8 - 16),
  #hence 5 elements = roundup(17^0.5). Could be improved though
      if num & 1 << i:
          y = "{0}".format(i + 1)
          output.append([names[int(y)-1], object])

ownership = []
mask = [random.randrange(1, 32767) for _ in range(1000)]
get_ownerships(1000)
output = []
map = [['1','al'],['2','be'],['4','cl'],['8','de'],['16','er'],['32','fa'],['64','ga'],['128','ha'],['256','ia'],['512','ja'],['1024','ka'],['2048','la'],['4096','ma'],['8192','na'],['16384','oa']]
mask = [row[0] for row in map] #['1', '2', '4', '8', '16']
names = [row[1] for row in map] #['alex', 'ben', 'clark', 'dean', 'eric']

for item in ownership:
  findbits(int(item[1]),item[0])


texts: jQuery function to link nested checkboxes

texts:
$.fn.linkNestedCheckboxes = function () {
    var childCheckboxes = $(this).find('input[type=checkbox] ~ ul li input[type=checkbox]');
    childCheckboxes.change(function () {
        var checked = $(this).attr('checked');
        checked = checked || ($(this).closest('li').siblings('li').find('input:checked').length > 0)
        childCheckboxes.parent().closest('ul').siblings('input[type=checkbox]').attr('checked', checked);
    });

    var parentCheckboxs = childCheckboxes.parent().closest('ul').siblings('input[type=checkbox]')
    parentCheckboxs.change(function () {
        $(this).siblings('ul').find('input[type=checkbox]').attr('checked', $(this).attr('checked'))
    })
    return $(this);
};

Example of use:

<form>
    <input type="checkbox" name="parent" />

<input type="checkbox" name="child1" />

<input type="checkbox" name="child2" />

</form>

The result of this is:

When parent is checked/unchecked all the child checkboxes will be out into the same state
If nothing is checked & one of the children are then checked, the parent will be checked
When the last child is unchecked the parent will be unchecked

What I'd like to know is:

Have I just re-invented the wheel?
If not, is there a more efficient way of doing this? The selectors above seem a bit convoluted.
This works on my machine, but I haven't tested it beyond my limited requirements for one form, will this break anything other than my simplistic example HTML?


texts: DTO interfaces for implementing web service integration

texts:
I am trying to define some interfaces to implement some web service integration middleware.
The SOA pattern that fits this system is probably the Multi-Channel Endpoint.

I expect a lot of mapping of data formats happening in this integration so I am trying to come up with some interfaces to implement this.

For each web service client I would like to provide a Service Facade that will map the input data to a common data structure (DTO) that will then be interpreted by the middleware which will orchestrate the services that  connect to the legacy applications.

My attempt at coding the interfaces goes like this:

// Protocol for mapping POJOs to some Map-like data structure
public interface Dto {

    // Map from POJO fields to DtoData
    public DtoData toData();

    // Map from DtoData to POJO
    public void fromData(DtoData data);

}

public class DtoData {
    Map<String, Object> data;

    public Map<String, Object> getData() {
        return data;
    }

    public void setData(Map<String, Object> data) {
        this.data = data;
    }
}

// This class provides default mapping methods from POJOs to Maps.
// Uses Jackson and Dozer for mapping back and forth between objects.
// TODO use DI to create mapper objects.
public abstract class AbstractDto implements Dto {

    @Override
    public DtoData toData() {
        ObjectMapper mapper = new ObjectMapper();
        DtoData map = mapper.convertValue(this, DtoData.class);
        return map;
    }

    @Override
    public void fromData(DtoData data) {
        DozerBeanMapper mapper = new DozerBeanMapper();
        mapper.map(data, this);
    }

}

public class DtoImpl extends AbstractDto implements Dto {

    private DtoData dtoData;

    public DtoData getDtoData() {
        return dtoData;
    }

    public void setDtoData(DtoData dtoData) {
        this.dtoData = dtoData;
    }

}

Any suggestions on how to improve this and pitfalls that I can expect?


texts: Powershell Refolder by Filename Before Delim

texts:
I'm pretty new to Powershell but have been using it more and more to automate tasks at work. Now I'm reaching out for some help. I typically use the scripts I write in a way where I copy and paste the ps1 into the directory I want to perform the task on. Then double-clicking. That is why you'll see that the ps1 filename is used to create a variable. It allows me to create a sort of preset of ps1 depending on what I use them for. Ex: 00-Refolder.tif.ps1
In the example, files are grouped into a single folder based on the filename before an underscore. They are then moved using multithreading. I'm using Powershell 7.1.3. If anyone knows a way to dynamically set threads based on the PC for the -Throttlelimit parameter that would be great to know.
Github version of this script.
Is there a more optimized way of performing this re-folder task? Whether it's a different way or just a more optimized version of the code below. If my formatting is off please let me know, that includes if you think a comment isn't worded correctly or could be more clear. I appreciate any help.
# Set the delim - all characters in the filenames before the delim will become the new folders.
$refolderDelim = '_'

# Set Threads for multithreading
$threads = 6

# Get the filename of the script to then use substrings of the filename to set variables.
$scriptPath = $MyInvocation.MyCommand.Path
$scriptName = Split-Path $scriptPath -leaf

# The file type before .ps1 is used as the filter, The two .'s are used to replace, Text before the two .'s in the filename can be changed.
$fileType = $scriptName -replace ('^.+?\.','.') -replace ('.ps1')

Measure-Command {

# Filters files in the script's directory by filetype in script filename.
Get-ChildItem -File -Filter *$fileType |
    Group-Object { $_.Name -replace ($refolderDelim + '.*') } |
        ForEach-Object -Parallel {

# Checks if folder exists and creates it if not
            if ( -Not ( Test-Path -Path $_.Name ) ) {
                $dir = New-Item -Type Directory -Name $_.Name
            }

# If folder does exist it only sets the $dir variable
            else {
                $dir = $_.Name
            }
# Filenames are moved to the repective folder
            $_.Group | Move-Item -Destination $dir
        } -ThrottleLimit $threads
}

Write-Output 'REFOLDER FINISHED: Ready for Next Step'

# Remove lines below if you want Powershell to close automatically after running.
Read-Host -Prompt "Press Enter to exit"
exit