texts: Cleaning up a redundant switch statement

texts:
How can I use a more generic method to clean up the redundancy in the switch statement below?

I'm working on an ASP.NET webforms app that will have five identical user controls that I will be showing and hiding based on the value of a dropdown list. (I have already been down the path of trying to add and remove the controls dynamically--the issue of managing the view states for the controls would have been very complicated, so in the interest of shipping I'm opting for a fixed number of controls.)

The approach I'm currently using works but isn't very elegant:

protected void DisplayUserControls(int numberOfControls)
{
    switch (numberOfControls)
    {
        case 2:
            UserControl1.Visible = true;
            UserControl2.Visible = true;
            UserControl3.Visible = false;
            break;

        case 3:
            UserControl1.Visible = true;
            UserControl2.Visible = true;
            UserControl3.Visible = true;
            break;

        default:
            UserControl1.Visible = true;
            UserControl2.Visible = false;
            UserControl3.Visible = false;
            break;
    }
}

What are some options here? The best I can come up with is using numberOfControls to build the name of the control, but that seems hacky. Suggestions appreciated.

EDIT: I implemented a solution similar to the accepted answer below. I'm stuck on loading up the controls in the list. The commented out code is more along the lines of what I'd like to do but can't get it working. The uncommented code works. Suggestions?

private List<ShiftControl> PopulateShiftControlList()
{
    ShiftControl shiftControlList = new List<ShiftControl>();

    //ControlCollection panelControls = ShiftPanel.Controls;

    //foreach (ShiftControl control in panelControls)
    //{
    //    shiftControlList.Add(control);
    //}

    shiftControlList.Add(ShiftControl1);
    shiftControlList.Add(ShiftControl2);
    shiftControlList.Add(ShiftControl3);
    shiftControlList.Add(ShiftControl4);

    return shiftControlList;
}


texts:
From OOP & OOD point of view, is it good idea to define Java-threads inside of the static method or in this case it's better to use instance-based method?

public class ThreadPool {

    public static void stringAnalysis(ArrayList<String> strData) {
        Thread t;
        t = new Thread(new SentimentAnalysis(strData));
        t.start();
    }
}

public class SentimentAnalysis implements Runnable {

    private ArrayList<String> strData;

    public SentimentAnalysis(ArrayList<String> strData) {
        this.strData = strData;
    }

    public void computeSentiment(ArrayList<String> strData) {
        StanfordNLP_forked.analyze(strData);
    }

    public void run() {
        this.computeSentiment(strData);
    }
}

StanfordNLP_forked is a forked version of StanfordCoreNLP for educational purpose only.  StanfordNLP_forked.analyze(strData) performs text analysis of the strings array and replace each string with sentimental rank value. For the moment, I just check in the debugger the result of the analysis, later I'll add some functionality.


texts: Filling in gym membership prices by joining PANDAS dataframes

texts:
I have two dataframes, df which contains a list of members in addition to the type of contract that they purchased on a given date, df is about 10 000 entries. I have another df_prices which contains the average price of a given contract for a given year and month.

df resembles:

    Member Nbr      Date-Joined         Contract Type
1           1        2010-03-31     1 Year Membership
2           1        2011-04-16     1 Year Membership
3           1        2012-08-06     1 Year Membership
4           1        2013-08-21     1 Year Membership
5           1        2014-08-31     1 Year Membership
6           2        2015-09-03     1 Year Membership
7           2        2012-12-10     4 Month Membership
8           2        2013-03-13     1 Year Membership
9           3        2014-03-15     1 Year Membership
10          3        2010-02-09     1 Year Membership
...
10095    7374        2016-02-29     1 Month Membership
10096    7375        2016-03-01     1 Year Membership
10097    7376        2016-03-01     1 Month Membership
10098    7378        2016-03-04     1 Month Membership
10099    7379        2016-03-06     1 Month Membership
10100    7380        2016-03-05     1 Year Membership
10101    7387        2016-03-10     3 Month Membership

and df_prices

          Date                   Description      Amount
0   2010-01-31            1 Month Membership   54.036316
1   2010-01-31             1 Year Membership  325.000000
2   2010-01-31            4 Month Membership  147.642353
3   2010-01-31            7 Month Membership  227.890000
5   2010-02-28            1 Month Membership   55.283846
6   2010-02-28             1 Year Membership  333.250000
7   2010-02-28            4 Month Membership  146.257358
8   2010-02-28            6 Month Membership  165.000000
9   2010-02-28            7 Month Membership  223.905714
10  2010-02-28                     Pool Only  250.000000
...
462 2015-12-31            4 Month Membership  146.390000
463 2015-12-31            6 Month Membership  204.815000
464 2016-01-31            1 Month Membership   45.037143
465 2016-01-31             1 Year Membership  265.000000
466 2016-01-31            3 Month Membership  112.927273
467 2016-01-31            4 Month Membership  147.413333
468 2016-01-31            6 Month Membership  204.093333
469 2016-02-29            1 Month Membership   45.699444
470 2016-02-29             1 Year Membership  265.000000
471 2016-02-29            3 Month Membership  110.285556
472 2016-02-29            4 Month Membership  139.477500
473 2016-02-29            6 Month Membership  202.650000

I have written some code in python that fills a list based on a customers join date and contract type and adds it to df, which is exactly what I want. The problem that I'm facing is that is is extremely slow to finish, and was hoping for some help to optimize it, especially as I plan on using a this on a larger dataset.

Here is what I have:

#### Standard Libraries ####
import time

#### Third-party libraries ####
import pandas as pd
import numpy as np

def Main():
    start = time.time()
    location = '/home/lukasz/Documents/Xtreme Fitness/Members/AllMembers.xlsx'
    location2 = '/home/lukasz/Documents/Xtreme Fitness/' + \
                'AverageContractPrice.xlsx'

    df = pd.read_excel(location)
    df_prices = pd.read_excel(location2)
    df_prices.fillna(method='ffill',inplace=True)

    prices = []

    for i in range(len(df)):
        df_date = df.loc[i, 'Date-Joined'].year * 1000 + \
                  df.loc[i, 'Date-Joined'].month
        df_contract = df.loc[i, 'Member Type']

        for j in range(len(df_prices)):
            if (df_prices.loc[j, 'Date'].year * 1000 + \
                df_prices.loc[j, 'Date'].month == df_date and
                df_prices.loc[j, 'Description'] == df_contract):

                # print("%s, %s" % (i, df_prices.loc[j, 'Amount']))
                prices.append(df_prices.loc[j, 'Amount'])

    prices
    df.to_excel(location, index=False)
    end = time.time()
    print(end-start)

if __name__ == '__main__':
    Main()


texts:
I think that my code contains a lot of if and else statements that are probably not required.I suppose that this code could be condensed to a shorter form where the logic applied would look clearer than it does now.
Suggestions are welcome and any help in refactoring would be highly appreciated.

public class Segregate{
    public static void doSegregation(int[] a){
        int i = 0;
        int j = a.length-1;

      while(i<=j){
        if(a[i]==a[j]){
          if(a[i]==1 && a[j]==1){
            j--;
          }
        else if(a[i]==0 && a[j]==0){
            i++;
        }
    }
    else{
        if(a[i]>a[j]){
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            i++;
            j--;
        }
        else if(a[i]<a[j]){
            i++;
            }
         }
      }
   }

   public static void main(String[] args){
      int[] a = {1,0,1,0,1,1,0,1,1,1};
      System.out.println("Array before segragation : ");
      for(int i=0; i<a.length; i++){
         System.out.print(a[i]+" ");
      }
      System.out.println();
      doSegregation(a);
      System.out.println("Array after segragation : ");
      for(int i=0; i<a.length; i++){
        System.out.print(a[i]+" ");
       }
    }
 }


texts: Simplify : find if element is in tuples stored in list

texts:
Is there a way to simplify this script using in keyword or anything like this:
searched_value = 3
data = [("a", 1), ("b",2), ("c",3)]

### can be simplified ?
test = None
for i in data:
    if i[1] == searched_value:
        test = i[0]
        break
###

print(test)


texts:
I'm trying to brush up on my Dynamic Programming by doing some example problems. I've got the following...

Given an array of integers, print the longest decreasing segment.

For example {4,3,2,1,5,6,7,6,5,4,3,2,1} would print "7, 6, 5, 4, 3, 2, 1"

The following is my solution.. I think it looks okay and it has a decent O(n) runtime. However, the space complexity is O(n^2) due to the extra "length" array storing state. Is it possible to get rid of it? Any other problems?

int[] segment = {4,3,2,1,5,6,7,6,5,4,3,2,1};
int[] length =  {0,0,0,0,0,0,0,0,0,0,0,0,0};

public String getDecreasingSegment(){

    int maxStart = 0;
    int maxEnd = 0;

    for(int i = 1; i < segment.length; i++){

        if(segment[i] < segment[i-1]){

            length[i] = length[i-1]+1;

            if(length[i] > length[maxEnd]){

                maxEnd = i;
                maxStart = maxEnd - length[maxEnd];

            }

        }else{

            length[i] = 0;

        }

    }

    StringBuffer buff = new StringBuffer();

    for(int i = maxStart; i <= maxEnd; i++){

        buff.append(segment[i] + ", ");

    }

    return buff.toString();
}


texts:
I haven't found any Lightshot Print Screen key linux handler publicly available.

So, I decided to write one today. It is a standard POSIX shell script.

I believe there is always space to get better, so any and all reviews are welcome.

#!/bin/sh

is_number()
{
    # check if exactly one argument has been passed
    test "$#" -eq 1 || print_error_and_exit 5 "is_number(): There has not been passed exactly one argument!"

    # check if the argument is an integer
    test "$1" -eq "$1" 2>/dev/null
}

# ------------------------------------------------------------------------------

print_error_and_exit()
{
    # check if exactly two arguments have been passed
    test "$#" -eq 2 || print_error_and_exit 3 "print_error_and_exit(): There have not been passed exactly two arguments!"

    # check if the first argument is a number
    is_number "$1" || print_error_and_exit 4 "print_error_and_exit(): The argument #1 is not a number!"

    # check if we have color support
    if test -x /usr/bin/tput && tput setaf 1 > /dev/null 2>&1
    then
        bold=$(tput bold)
        red=$(tput setaf 1)
        nocolor=$(tput sgr0)
        echo "$bold$red$2 Exit code = $1.$nocolor" 1>&2
    else
        echo "$2 Exit code = $1." 1>&2
    fi

    exit "$1"
}

# ------------------------------------------------------------------------------

check_for_prerequisite()
{
    # check if exactly one argument has been passed
    test "$#" -eq 1 || print_error_and_exit 2 "check_for_prerequisite(): There has not been passed exactly one argument!"

    # check if the argument is a program which is installed
    command -v "$1" > /dev/null 2>&1 || print_error_and_exit 6 "check_for_prerequisite(): I require $1 but it's not installed :-("
}

# ------------------------------------------------------------------------------

# check if no arguments have been passed to the script
test "$#" -gt 0 && print_error_and_exit 1 "$0: You have passed some unexpected argument(s) to the script!"

# ------------------------------------------------------------------------------

# check for prerequisites
check_for_prerequisite "pgrep"
check_for_prerequisite "xdotool"

# ------------------------------------------------------------------------------

# global constants
lightshot_key="Print"
lightshot_name="Lightshot"

# ------------------------------------------------------------------------------

# get the lightshot pid
lightshot_pid=$(pgrep "$lightshot_name")

# test if a pid has been successfully acquired
is_number "$lightshot_pid" || print_error_and_exit 7 "lightshot_pid: The argument is not a number!\\nLightshot is most probably not running."

# ------------------------------------------------------------------------------

# get the window id from lightshot pid
lightshot_wnd=$(xdotool search --limit 1 --all --pid "$lightshot_pid" --name "$lightshot_name")

# test if a window handler has been successfully acquired
is_number "$lightshot_wnd" || print_error_and_exit 8 "lightshot_wnd: The argument is not a number!\\nLightshot is most probably not running."

# ------------------------------------------------------------------------------

# simulate a print screen key press on the lightshot window
xdotool key --window "$lightshot_wnd" "$lightshot_key"

In Linux Mint 18.3 you can simply put this into your custom keyboard shortcuts:


texts: Calculating the perfect squares between two given numbers

texts:
This code is for calculating the perfect squares between two given numbers. User can add the interval as well like for how many intervals he want to check the perfect squares. For example if user enter 4, it means there are 4 different intervals and after that he will insert the tow number for interval 1, similarly two numbers for interval 2 and respectively 3 and 4. I just want to reduce the execution time

import java.io.*;
import java.util.*;

class node{
    private int a;
    private int b;
    node(int a, int b){
        this.a = a;
        this.b = b;
    }
    int getA(){return a;}
    int getB(){return b;}
}

public class Solution {

    public static void main(String[] args) {

        int size;
        Scanner S1 = new Scanner(System.in);
        size = S1.nextInt();
        node a[] = new node[size];
        for(int i = 0; i<a.length; i++){
        /*int number = S1.nextInt();
        int number2 = S1.nextInt();*/
        a[i] = new node(S1.nextInt(), S1.nextInt());
        }
        int total = 0;
        int sqrt = 0;
        for(int i = 0; i<a.length; i++){
                for(int j = a[i].getA(); j<=a[i].getB(); j++){
                    sqrt = (int) Math.sqrt(j);
                    if(sqrt*sqrt == j) {
                        total++;
                    }
                }
             System.out.println(total);
            total = 0;
        }
        }
}


texts: Calculating Euclidean norm for each vector in a sparse matrix

texts:
Below is a naive algorithm to find nearest neighbours for a point in some n-dimensional space.

import numpy as np
import scipy.sparse as ss

# brute force method to get k nearest neighbours to point p
def knn_naive(k, p, X):
    stacked_p = ss.vstack([p for n in range(X.get_shape()[0])])
    D = X - stacked_p
    D = np.sqrt(D.multiply(D).sum(1))
    result = sorted(D)[:k]
    return result

Types for arguments to knn_naive(...) are:

# type(k): int
# type(p): <class 'scipy.sparse.csr.csr_matrix'>
# type(X): <class 'scipy.sparse.csr.csr_matrix'>

An example of dimensions would be:

X.shape: (100, 3004)
p.shape: (1, 3004)

Are there techniques to improve the above implementation in terms of computational time and/or memory?


texts: Bank transaction implementation - side-effects of barriers

texts:
I'm interested in implementing role based code in C++.  I'm also interested in what side effects or barriers (from static strong typing perhaps?) have been added that I am unaware of and if there is a better way.

#include <cstdio>
#include <vector>
#include <string>
#include <numeric>
using namespace std;

// Interfaces to the roles.
class IsourceAccount {
public:
  virtual int availableBalance() = 0;
  virtual void withdraw(int amount) = 0;
};

class IdestAccount {
public:
  virtual int availableBalance() = 0;
  virtual void deposit(int amount) = 0;
};

// MODEL Classes.
class Account: public IsourceAccount, public IdestAccount {
private:
  int balance;
public:
  Account(): balance(0) { }
  int availableBalance() { return balance; }
  void deposit(int amount) { balance += amount; }
  void withdraw(int amount) { balance -= amount; }
};

class Account2: public IsourceAccount, public IdestAccount {
private:
  vector<int> audit;
public:
  Account2() { }
  int availableBalance() { return accumulate( audit.begin(), audit.end(), 0 ); }
  void deposit(int amount) { audit.push_back(amount); }
  void withdraw(int amount) { audit.push_back(-amount); }
};

// How the Model objects interact
class moneyTransferCTX {
  // Role methods (from context and from roleplayers).
  class /*role*/ sourceAccount: public IsourceAccount {
    public:
      void transferTo(moneyTransferCTX *ctx, int amount);
  } *sourceAccount;

  class /*role*/ destAccount: public IdestAccount {
    public:
      void receive(moneyTransferCTX *ctx, int amount);
  } *destAccount;

public:
  moneyTransferCTX(IsourceAccount *src, IdestAccount *dst):
    // Cast the objects (src,dst) to their roles (sourceAccount, destAccount).
    sourceAccount(static_cast<decltype(sourceAccount)>(src)),
    destAccount(static_cast<decltype(destAccount)>(dst))
  { }

  void execute(int amount) {
    this->sourceAccount->transferTo(this, amount);
  }
};

void moneyTransferCTX::sourceAccount::transferTo(moneyTransferCTX *ctx, int amount) {
  if (this->availableBalance() < amount) throw -1;
  this->withdraw(amount);
  ctx->destAccount->receive(ctx, amount);
}

void moneyTransferCTX::destAccount::receive(moneyTransferCTX *ctx, int amount) {
  this->deposit(amount);
}

// Testing...
int main() {
  Account2 *savings = new Account2();
  Account *checking = new Account(); //Changing the class type shouldn't hurt the code.

  moneyTransferCTX *ctx[2];

  savings->deposit(10);
  checking->deposit(100);

  ctx[0] = new moneyTransferCTX(savings, checking);
  ctx[1] = new moneyTransferCTX(checking, savings);

  printf("Opening Status- Savings: %d, Checking: %d\n", savings->availableBalance(), checking->availableBalance());

  try {
    printf("Transfer Savings to Checking 50\n");
    ctx[0]->execute(50);
  } catch(int n) {
    printf("Error: not enough funds\n");
  }

  printf("Savings: %d, Checking %d\n", savings->availableBalance(), checking->availableBalance());

  try {
    printf("Transfer Checking to Savings 30\n");
    ctx[1]->execute(30);
  } catch(int n) {
    printf("Error: not enough funds\n");
  }

  printf("Closing Status- Savings: %d, Checking %d\n", savings->availableBalance(), checking->availableBalance());

  delete ctx[0];
  delete ctx[1];
  delete savings;
  delete checking;
  return 0;
}


texts: Testing lower- and upper bound values in Python

texts:
Code functionality
The following code tests whether the values that a user specifies for a lower bound and upper bound on two properties:

The lower bound is smaller than the upper bound.
The values are larger than 0 (positive).

Since it first checks whether the lower bound is smaller than the upper bound, it implicitly verifies the upper bound is larger than 0, if it tests whether the lower bound is larger than 0. Therefore, my consideration is: I can make the code more compact by omitting the check for "is the upper bound larger than 0".
Code
# Object getting labels
class Get_labels:
    def __init__(self,lower_bound,upper_bound,configuration_name):
        self.lower_bound = lower_bound
        self.upper_bound = upper_bound
        self.configuration_name = configuration_name
        self.check_threshold_validity()

    # Verifies if the chosen thresholds are valid values.
    def check_threshold_validity(self):
        if self.lower_bound>=self.upper_bound:
            raise Exception(f'Sorry, the lower threshold={self.lower_bound} should be smaller than the upper bound={self.upper_bound} for configuration={self.configuration_name}')

        # checks if lower bound (and implicitly upper bound) are above zero
        if self.lower_bound<=0:
            raise Exception(f'Sorry, the lower threshold={self.lower_bound} should be larger than 0 for configuration={self.configuration_name}')

if __name__ == '__main__':
    get_labels = Get_labels(-1,25,"first")

Design choice
However, if the code is modified it might not be obvious the upper bound also needs to be checked because that is done implicitly. That might result in the edge case with upper bound below zero is not being caught after modifications. Hence to prevent this scenario, I can implement two unit test that check if an error is raised for:

The lower bound negative, upper bound negative
The lower bound zero, upper bound negative
The lower bound positive, upper bound negative

Question
Is it recommended to include the explicit check in the main code anyways, even though it is tested in the unit tests?


texts:
I want to know if there is a better way to square numbers in an array. This is what I wrote:

#include <iostream>
using std::cout;
using std::endl;

void square(int []);

int main()
{
    int array[] = {2,4,6,8,10};

    square(array);
    for(auto i : array)
        cout << i << " ";

}

void square(int array[])
{
    int size = sizeof(array)/sizeof(array[0]);
    for(int i=0; i< size; i++)
        array[i] *= array[i];
}


texts:
I am a beginner in Java and am learning collections. I have written the following code to sort the elements in lists.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class descendingOrder implements Comparator<Integer>{
    @Override
    public int compare(Integer numberOne, Integer numberTwo) {
        return -numberOne.compareTo(numberTwo);
    }
}

public class SortsTests {

    public static void main(String[] args) {
        List<Integer> listOne = new ArrayList<>();
        listOne.add(1);
        listOne.add(5);
        listOne.add(10);
        listOne.add(6);
        System.out.println(listOne);
        Collections.sort(listOne, new descendingOrder());
        System.out.println(listOne);
    }
}

Is this the most effective way to sort the lists or are there any better methods?


texts: Fahrenheit / Celsius temperature converter

texts:
This is a simple bash script (hopefully with a little style as well) for converting temperatures from Fahrenheit to Celsius and vice versa.

#!/bin/bash

re='^-*[0-9]+([.][0-9]+)?$'
while true
do
    printf "\n\e[1;39mWhat is the temperature you wish to convert?\e[0m\n\n\t"
    read -p "Enter a numeric value  " n
    while [[ ! $n =~ $re ]]
    do
        printf '\t\e[3;3;31mInvalid selection\n\t\e[3;3;31m\e[0m\n\t'
        read -p "Enter a numeric value " n

    done
    echo
    printf "\n\tIs this \e[1;39m(F)\e[0mahrenheit or \e[1;39m(C)\e[0melsius\e[0m?\n\n"
    while true
    do
        read -sn 1 cf
        case $cf in
            [Ff] ) echo "$n""˚F = $(( ($n - 32) * 5 / 9 ))˚C"; break;;
            [cC] ) echo "$n""˚C = $(( $n * 9 / 5 + 32 ))˚F"; break;;
            * ) printf '\t\e[3;3;31mInvalid selection\n\e[3;3;31m\e[0m'
            printf '\tChoose \e[1;39m(F)\e[0mahrenheit or \e[1;39m(C)\e[0melsius\e[0m\n\n'
        esac
    done
    echo
    while true
    do
        printf "\tPress (1) to convert another\n\tpress (2) to quit"
        read -sn1 bye ; printf "\n\n"
        case $bye in
            [1] )
            break
            ;;
            [2] ) printf "Now exiting" && exit
            ;;
            * )
            printf '\t\e[3;3;31mInvalid selection\n\e[3;3;31m\e[0m'
            ;;
        esac
    done
done

Is there anything I could do to improve upon this? I am also curious if this would be portable / POSIX compliant. Everyone always says to use printf if portability is a concern. Is echo not portable?


texts: Scanning a directory and listing contents in an HTML file

texts:
My program simply accepts the name of a directory from the user, scans said directory and generates an HTML file that lists the contents.

Is there any way that this can be improved?

/*
    Basically, take the path of a directory, get a list of all files in the directory
    and output that list to an html document
*/
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedWriter;
import java.nio.file.FileSystemException;

public class HTMLFileListGenerator{
    static void writeDirectoryFilesToHTML(File directory) throws IOException{
        ArrayList<String> contents = new ArrayList<String>(Arrays.asList(directory.list()));

        File output = new File("output.html");
        try(BufferedWriter writer = new BufferedWriter(new FileWriter(output))){
            writer.write("\n\t\n\t\t
Contents of " + directory.getCanonicalPath() + ":
\n\t\t
\n\t\t\t");

            for(int counter = 0; counter < contents.size(); counter++){
                System.out.println(contents.get(counter));
                writer.write("\t\t\t
 " + contents.get(counter) + "
\n");
            }
            writer.write("\t\t
\n\t\n");
        }
    }
    public static void main(String[] args){
        try(Scanner userInput = new Scanner(System.in)){
            File testInput;
            do{
                System.out.print("Please enter the name of the directory: ");
                String input = userInput.next();
                testInput = new File(input);
            }
            while(!testInput.isDirectory());
            writeDirectoryFilesToHTML(testInput);
        }
        catch(IOException io_exc){
            System.out.println("An error occurred: " + io_exc.getMessage());
        }
    }
}


texts:
I need to develop a dictionary program so I used a trie data structure to implement it. I have created a array of object with size of 26 - so each object of class Dict will have 26 sub objects like a child.

This program takes no input from user for now. I gave my input in main function. but it will print all the words in the trie.

This program works fine. Is this program somewhat efficient? do I have to replace the fixed sized array of object of class Dict with any other technique?

public class Dict {
        boolean isWord;
        Dict obj[];
        Dict()
        {
            obj=new Dict[26]; // as there are 26 letters in english
            isWord=false;
        }
        Dict insertWord(Dict Node,String str, int it) // used to insert a word into trie
        {
            if(it<str.length())
            {
            int Linkno=((int)(str.charAt(it)))-97; //97 is the ascii value of 'a'.
            if(Node.obj[Linkno]==null)
            {
                Node.obj[Linkno]=new Dict();
            }
            insertWord(Node.obj[Linkno],str,it+1);
            }
            else
            {
                Node.isWord=true;
            }
            return Node;
        }
        void displayAll(Dict Node,String str) // used to display all the words in the trie
        {
            for(int i=0;i<26;i++)
            {
                if(Node.obj[i]!=null)
                {
                    if(Node.obj[i].isWord==true)
                        System.out.println(str+((char)(i+97)));
                    displayAll(Node.obj[i],(str+((char)(i+97))));
                }
            }
        }
        public static void main(String ar[])
        {
            Dict root=new Dict();
            root.insertWord(root,"trasaction",0);
            root.insertWord(root,"transformation",0);
            root.insertWord(root,"transmission",0);
            root.insertWord(root,"trance",0);
            root.insertWord(root,"trap",0);
            root.displayAll(root,"");
        }
    }


texts: Polymorphic pointers-to-functions whose parameters are void pointers as arguments in C

texts:
My question is about this sort of table that's simplified here. Often, I find myself putting this element, (int (*)(const void *, const void *))&strcmp for bsearch. I go between prototyping with void pointers, creating dummy functions, and casting, but none is really a satisfactory, especially when the functions are complex.

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

static void number(int *const);
static void letter(char *const);

static void (*const action[])(void *const) = {
    (void (*)(void *))&number,
    (void (*)(void *))&letter
};

/* corresponds to the 'action' index */
enum Type { NUMBER = 0, LETTER = 1 };

struct Thing {
    enum Type type;
    void *data;
};

int main(void) {
    const char aah  = 'a';
    const int  five = 5;
    const int  six  = 6;
    const struct Thing things[] = {
        { LETTER, (void *)&aah },
        { NUMBER, (void *)&five },
        { NUMBER, (void *)&six }
    };
    const int things_size = sizeof things / sizeof(struct Thing);
    const struct Thing *t;

    /* prints a 5 6 */
    for(t = things; t < things + things_size; t++) {
        action[t->type](t->data);
    }

    return EXIT_SUCCESS;
}

static void number(int *const dp) {
    printf("%d\n", *dp);
}

static void letter(char *const cp) {
    printf("%c\n", *cp);
}

This https://stackoverflow.com/questions/559581/casting-a-function-pointer-to-another-type/559671#559671 seems to suggest that it's dubious to do this. What is the cleanest, most correct way to achieve this sort of polymorphism?


texts: Effectively convert little endian byte slice to int32

texts:
I have a data stream of bytes and I'd like to get a little endian encoded int32 from four bytes. Is there a better way than to do this like the following code?

package main

func read_int32(data []byte) int32 {
    return int32(uint32(data[0]) + uint32(data[1])<<8 + uint32(data[2])<<16 + uint32(data[3])<<24)
}

func main() {
    println(read_int32([]byte{0xFE,0xFF,0xFF,0xFF})) // -2
    println(read_int32([]byte{0xFF,0x00,0x00,0x00})) // 255
}

The code above seems to work fine, but perhaps there is a built-in function in Go that I've missed or there is a super cool hack that does that in one instruction?


texts: Pascal's triangle for an interview in PHP

texts:
I saw that one of the interview questions could be building a pascal triangle.
Is there anything wrong with this particular solution I came up with?

function pascal_r($r){

   $local = array();

   if($r == 1){
       return array(array(1));
   } else {
       $previous = pascal_r($r - 1);

       array_push($local, 1);

           for($i = 0; $i < $r - 2 && $r > 2; $i++){
               array_push($local, $previous[$r-2][$i] + $previous[$r-2][$i + 1]);
           }

       array_push($local, 1);
   }

   array_push($previous, $local);

   return $previous;

}

print_r(pascal_r(100));


texts: Inserting and deleting elements in a list

texts:
In my code, I use fast method of reading input and a custom model of list. After reading the input into my 'list'.

The problem is that, when I test my code, most answers are correct, but for some INPUT my algorithm works slow. I unfortunately don't know the input data, but 6 from 12 tests finished with the wrong time. Maybe for some input data, some of the loops do not stop.

Where time is 1.01 or 2.01 -> wrong

  TASK

  Consider any indexed sequence of natural numbers C, which define the
  concept of the present position. Next, we introduce two operations on
  the elements of this sequence: If amount of sequence of natural
  numbers is even number ->

  R, remove the item 'c' on index POS + 1, then move the pointer POS on
  'c' elements to the right, otherways ->

  X, inserting element 'c' on the position (POS + 1) value 'c-1' from
  POS, and then moving the pointer on the POS 'c' elements to the right.

  INPUT:

  the number of times of repetition scheme of operations R and X, the
  sequence of natural numbers 'C'

  OUTPUT:

  numbers after operations from the position of index

  LIMITS

  The time complexity of O (tn), where 'n' is the length of 'C' and 't'
  - times of repetition operations R and X.

#include<iostream>
#include<stdlib.h>
#define gc getchar_unlocked

struct Element
{
    unsigned int c;
    Element* next;
    Element(unsigned int value)
    {
        c = value;
        next = NULL;
    }
};

void scan_integer(unsigned int* o )
{
    unsigned int c = gc();
    int x = 0;
    for( ; ((c<48 || c>57)); c = gc() );

    for( ;c>47 && c<58; c = gc() ) {
        x = (x << 1) + (x << 3) + c - 48;
    }
    *o = x;
}

int main()
{
    unsigned int rounds;
    scan_integer(&rounds);
    if(!feof(stdin))
    {
        unsigned int elements = 0;
        unsigned int tmp;
        scan_integer(&tmp);
        Element* first = new Element(tmp);
        elements++;
        Element* current = first;
        while(!feof(stdin))
        {
            scan_integer(&tmp);
            current->next = new Element(tmp);
            current = current->next;
            elements++;
        }
        current->next = first;
        current = first;
        for(int i = 0; i < rounds; i++)
        {
            if(elements == 0){
                fprintf(stdout, "%u", -1);
                break;
            }
            unsigned int value;
            if(current->c & 1)
            {
                value = current->c;
                Element* newC = new Element(value-1);
                newC->next = current->next;
                current->next = newC;
                elements++;
            }
            else
            {
                value = current->next->c;
                Element* toDelete = current->next;
                current->next = toDelete->next;
                delete toDelete;
                elements--;
            }

            if(elements > 0 && value != 0){
                for(int j = 0; j < value; j++){
                    current = current->next;
                }
            }
        }
        if (elements == 0) {
            fprintf(stdout, "%u", -1);
        }
        if(elements > 0)
        {
            first = current;
            fprintf(stdout, "%u", current->c);
            current = current->next;
            while(first != current)
            {
                fprintf(stdout, " %u", current->c);
                current = current->next;
            }
        }
    }else{
        return -1;
    }

    return 0;
}


texts: Is this right way to implement Abort, Retry and Ignore activity pattern?

texts:
I've a bunch of sequential activities. These are long running. Once an activity is complete, it can't be rolled back. Now something deep down the line fails. Now I've few options

Report this to end user and ask him to fix something. And then Retry same thing.
End user has no clue on what to do. He can choose to ignore. (Just retry won't fix things)
Abort/Pause? Now this is something tricky. This will stop the program. If program is rerun, it should resume from this failed point and not from the starting point.

I'm thinking to implement this by defining a custom exception, Action delegate set, coming from exception object. So my question is
Do you see any issue with this pattern? Any better way to do the same?

[Serializable]
public class SafetyNetException : Exception
{
    public SafetyNetException(SafetyNet callBack) { Net = callBack; }
    public SafetyNetException(SafetyNet callBack, string message) : base(message) { Net = callBack; }
    public SafetyNetException(SafetyNet callBack, string message, Exception inner) : base(message, inner) { Net = callBack; }
    protected SafetyNetException(
      System.Runtime.Serialization.SerializationInfo info,
      System.Runtime.Serialization.StreamingContext context)
        : base(info, context) { }

    public SafetyNet Net { get; private set; }
}

public class SafetyNet
{
    public Action Abort;

    public Action Retry;

    public Action Ignore;
}

[TestClass()]
public class SafetyNetTest
{
    [TestMethod()]
    public void APIUsageTest()
    {
        try
        {
            DoSomething();
        }
        catch (SafetyNetException targetException)
        {
            Debug.WriteLine(targetException.Message);

            SafetyNet target = targetException.Net;
            switch (AskUser())
            {
                case "r":
                    target.Retry();
                    break;
                case "a":
                    target.Abort();
                    break;
                case "i":
                    target.Ignore();
                    break;
            }
        }
    }

    private void DoSomething()
    {
        try
        {
            // try something
        }
        catch (Exception ex)
        {
            SafetyNet net = new SafetyNet();
            net.Abort = () => DoSomething_Abort();
            net.Retry = () => DoSomething();
            net.Ignore = () => DoNextThing();

            throw new SafetyNetException(net, "Ask user", ex);
        }
    }


texts:
I have the following piece of code and I would like to see what different approaches would be to solve that in a more elegant way.

The thing is that I don't know whether is better to have the null checks or the try/catch block there or maybe the code below should not happen in the first place.  Maybe one can give another solution so that I can get the thumb URL from a images list that is set on a people object without having to check for null on each getter call.

if (people.getImages() != null && people.getImages().size() > 0 && people.getImages().get(0).getUrl() != null) {
    Url thumbUrl = people.getImages().get(0).getUrl().getThumb();
    // do something with the thumbUrl
}

Or I can have:

try {
    Url thumbUrl = people.getImages().get(0).getUrl().getThumb();
    // do something with the thumbUrl
} catch (Exception e) {
    // handle the null pointer exception
}

EDIT

For more information, I am interested more in knowing if there any other ways to avoid calling getter methods one after another until I get my desired data from an object and if the above code is good enough anyway.

The code works ok in both cases but I don't like to have the multiple null checks in that if statement and also catching exceptions is not a good solution either.

The getImages() method returns a list of Image objects and getThumb() returns an Url object that I need in order to fetch an image over the internet.


texts:
I have implemented a queue data structure using linked list in C#. I have also associated my implementation with unit tests. Is this implementation correct? Any suggestion?

namespace QueueDataStructure
{
    internal class Node
    {
        internal int value;
        internal Node next;
    }

    public class Queue
    {
        private Node head;
        private int size;

        public Queue(){}

        public void Enqueue(int n)
        {
            if(head == null) // queue is empty
            {
                head = new Node{
                    value = n,
                    next = null
                };
            }
            else // queue has items
            {
                var oldHead = head;
                head = new Node
                {
                    value = n,
                    next = oldHead
                };
            }
            size++;
        }

        public int? Dequeue()
        {
            if (size == 0)
                return null;

            var node = head;
            Node previous = node;
            while (node.next != null)
            {
                previous = node;
                node = node.next;
            }
            previous.next = null;
            size--;
            return node.value;
        }

        public int Count
        {
            get { return size; }
        }

        public string PrintElements()
        {
            var node = head;
            int[] elements = new int[size];
            int i = 0;
            while (node != null)
            {
                elements[i++] = node.value;
                node = node.next;
            }
            return string.Join(" ", elements);
        }
    }
}

using Microsoft.VisualStudio.TestTools.UnitTesting;
using QueueDataStructure;

namespace TestQueue
{
    [TestClass]
    public class Tests
    {
        [TestMethod]
        public void TestQueue()
        {
            var queue = new Queue();
            Assert.AreEqual(0, queue.Count);
            Assert.AreEqual(null, queue.Dequeue());

            queue.Enqueue(1);
            queue.Enqueue(2);
            queue.Enqueue(3);
            Assert.AreEqual(3, queue.Count);
            Assert.AreEqual("3 2 1", queue.PrintElements());

            Assert.AreEqual(1, queue.Dequeue());
            Assert.AreEqual(2, queue.Dequeue());
            Assert.AreEqual(3, queue.Dequeue());
            Assert.AreEqual(0, queue.Count);
        }
    }
}


texts: Recording loans of access cards to people in a company

texts:
I'm fairly new to Python and currently building a small application to record loans of access cards to people in a company. I'm using wxPython for the GUI and SQLAlchemy for the CRUD. I'm loosely following Mike Driscoll's tutorial for a similar application but I want to add some extra things that he hasn't implemented (he has most controls in the same window, but I'm passing things a lot between dialogues and windows and it's starting to look messy).

Particularly concerned about the following method in dialogs.py:

def OnCardReturn(self, event):
    """
    Call the controller and get back a list of objects. If only one object
    return then set that loan as returned. If none returned then error, no
    loans currently on that card. If more than one returned something has
    gone wrong somewhere, but present a list of the loans against that card
    for the user to pick the correct one to return.
    """

    value = self.txtInputGenericNum.GetValue()
    loans = controller.getQueriedRecords(self.session, "card", value)    #returns a list of objects
    numLoans = len(loans)
    if numLoans == 1:
        controller.returnLoan(self.session, value)    #returns nothing
        successMsg = "Card " + str(value) + " has been marked as returned"
        showMessageDlg(successMsg, "Success!")
    elif numLoans == 0:
        failureMsg = "Card " + str(value) + " is not currently on loan"
        showMessageDlg(failureMsg, "Failed", flag="error")
    elif numLoans > 1:
        failureMsg = """
        More than one loan for " + str(value) + " exists. Please select
        the correct loan to return from the next screen.
        """
        showMessageDlg(failureMsg, "Failed", flag="error")
        selectReturnLoan = DisplayList(parent=self, loanResults=loans,
                                                        returnCard=True)
        selectReturnLoan.ShowModal()
        selectReturnLoan.Destroy()

The controller is still under construction, so no complete code yet, but I've commented in what is returned by the calls to it so it's still possible to see what the functionality is.


texts: Transforming the case of text using Excel VBA

texts:
I created a simple user form for my VBA course.

I then created the following VBA code:

Private Sub btnModify_Click()

Dim modRange As Range
Set modRange = Selection

Dim modString As String
modString = modRange.Value

    If obUpperCase.Value = True Then

        modRange.Value = UCase(modString)

        btnModify.Value = False

    ElseIf obLowerCase.Value = True Then

        modRange.Value = LCase(modString)

        btnModify.Value = False

    ElseIf obProperCase.Value = True Then

        modRange.Value = Application.Proper(modString)

        btnModify.Value = False

    End If

End Sub

Is it possible to split the btnModify_Click into two procedures?

The first procedure would check which OptionButton is clicked and return a "formatting" type.

The second would be the actual btnModify_Click. It would take the active selection and apply the formatting type returned from the first procedure.

My apologies for not posting any code along these lines but I don't have a grasp of how procedures work yet. I have an idea but this seems like a simple enough example to get me started (perhaps too simple?).

On a minor note, I don't like the style of the buttons. They have a classic look, and even though there is a time an place for this specific style, is there any way to obtain "better" looking buttons?


texts:
I wrote a Cordova plugin for an app that I'm working on, and now I'm trying to write an Angular definition to wrap my plugin.  So far, I've followed the model in ng-cordova.js:

angular.module('ngCordova.plugins.audioPlugin', [])
.factory('$audioPlugin', ['$q', function($q) {

    return {
        init: function(sessionKey) {
            var q = $q.defer();

            AudioPlugin.init(sessionKey, function(response) {
                q.resolve(response);
            }, function (error) {
                q.reject(error);
            });
            return q.promise;
        },

        playAudio: function(contentId) {
            var q = $q.defer();

            AudioPlugin.playAudio(contentId, function(response) {
                q.resolve(response);
            }, function (error) {
                q.reject(error);
            });
            return q.promise;
        },

        seekChapter: function(contentId, partIndex, chapterIndex) {
            var q = $q.defer();

            AudioPlugin.seekChapter(contentId, partIndex, chapterIndex function(response) {
                q.resolve(response);
            }, function (error) {
                q.reject(error);
            });
            return q.promise;
        },

        getCurrentPosition: function() {
            var q = $q.defer();

            AudioPlugin.getCurrentPosition(function(response) {
                q.resolve(response);
            }, function (error) {
                q.reject(error);
            });
            return q.promise;
        },

        getCurrentChapter: function() {
            var q = $q.defer();

            AudioPlugin.getCurrentChapter(function(response) {
                q.resolve(response);
            }, function (error) {
                q.reject(error);
            });
            return q.promise;
        }

    }

}]);

I'm looking for feedback on how to structure this wrapper.  I'm a little unhappy with the amount of repetition involved to convert the callback-based architecture in the Cordova plugin to the angular promise-based style.


texts: Construct URLs out of filenames of zero-byte images and open them in Firefox for re-downloading

texts:
It's a problem with FlashGot: it sometimes download zero-byte files. I think it's because I didn't use something like DownThemAll! to limit the number of concurrent downloads, but I wrote this script anyway to solve my problem.

The script basically sets up a RunspacePool and in each of the spawned thread, checks if either of the constructed Danbooru image URL is valid and appends it to a list that becomes the input to Firefox.

I guess the main problem I encountered was a scoping issue. I can not use custom functions inside a script block unless it's defined in there, which is what I did, or its definition is passed as a parameter to the script block and sourced, which is ugly.

I would be interested in reviews that point out any cargo cult programming, performance quirks and/or violation of "best practices". I'm still a beginner so I'd appreciate more if feedback comes with working code rather than hand-waving.

<#
    .SYNOPSIS
      Opens the Danbooru URLs of zero-byte images in Firefox for re-downloading by FlashGot.
#>

#Requires -Version 3.0
#Requires -Modules Microsoft.PowerShell.Utility, Microsoft.PowerShell.Management, CimCmdlets

Set-StrictMode -Version Latest

$PrepareUrl = {

    param (
        [string]$domain,
        [string]$file
    )

    begin {
        function Get-UrlStatusCode([string]$Url) {
            try {
                [int](Invoke-WebRequest -Uri $Url -UseBasicParsing -DisableKeepAlive -Method Head).StatusCode
            }
            catch [Net.WebException] {
                [int]$_.Exception.Response.StatusCode
            }
        }
    }

    process {
        $url = "$domain/data/$file"
        if ((Get-UrlStatusCode -Url $url) -ne 200) {
            $url = "$domain/cached/data/$file"
            if ((Get-UrlStatusCode -Url $url) -ne 200) {
                $url = $null
            }
        }
        Write-Output $url
    }

}

#region Setting Up Jobs
$domain = 'https://danbooru.donmai.us'
$sourceDir = 'C:\fakepath'
Write-Progress -Activity 'Getting the filenames' -Status "Searching under $sourceDir" -SecondsRemaining -1
filter isEmptyImage {
    if ($_.PSIsContainer -eq $false -and $_.Length -eq 0 -and $_.Name -match '__.+\.(jpg|png|gif)') { $_ }
}
$emptyFiles = Get-ChildItem -Path $sourceDir -Recurse | isEmptyImage | Select-Object -ExpandProperty Name
$NumberOfLogicalProcessors = (Get-CimInstance Win32_Processor).NumberOfLogicalProcessors
$rp = [runspacefactory]::CreateRunspacePool(1, 2 * $NumberOfLogicalProcessors)
$rp.Open()
$jobs = New-Object System.Collections.Generic.List[System.Object]
foreach ($file in $emptyFiles) {
    $job = [powershell]::Create().AddScript($PrepareUrl).AddArgument($domain).AddArgument($file)
    $job.RunspacePool = $rp
    $jobs.Add(
        (New-Object PSObject -Property @{
            Job = $job
            Result = $job.BeginInvoke()
        })
    )
}
#endregion
#region Collecting Jobs
$urlList = New-Object System.Collections.Generic.List[System.Object]
$jobCount = $jobs.Count
while ($jobs.Count -gt 0) {
    $WriteProgressParams = @{
        Activity = 'Waiting for jobs to complete'
        Status = "$($jobs.Count) jobs remaining"
        PercentComplete = (($jobCount - $jobs.Count) / $jobCount * 100)
    }
    Write-Progress @WriteProgressParams # splatting
    Start-Sleep -Milliseconds 50
    foreach ($job in $($jobs | Where-Object { $_.Result.IsCompleted -eq $true })) {
        $result = [string]$job.Job.EndInvoke($job.Result)
        if ($result) {
            $urlList.Add($result)
        }
        $job.Job.Dispose()
        [void]$jobs.Remove($job)
    }
}
#endregion
if ($urlList) {
    Start-Process -FilePath 'C:\Program Files\Mozilla Firefox\firefox.exe' -ArgumentList $urlList
}
$rp.Close()
$rp.Dispose()

Set-StrictMode -Off


texts:
This is the code that I'm using. I'm working on LINQ TO SQL and I'm using this model in my program:

How can I model this class in a database

The person must have to enter the level, for example 1.2, 1.1.4, etc. The program must check if  the level is available or busy. The function ToIntArray is an extension and consists of splitting the text and converting the resulting string[] to int[].

The first condition, as you can see, is an inconsistency which I have in this post:

Problems with nullable types in a LINQ function

private void AddButton_Click(object sender, RoutedEventArgs e)
{
    NorthwindDataContext cd = new NorthwindDataContext();

    int[] levels = LevelTextBox.Text.ToIntArray('.');
    string newGroupName = NameTextBox.Text;

    Objective currentObjective = null;
    int? identity = null;

    for (int i = 0; i < levels.Length - 1; i++ )
    {
        int currentRank = levels[i];

        if (identity == null)
        {
            currentObjective = (from p in cd.Objective
                                where p.Level == currentRank && p.Parent_ObjectiveID == null
                                select p).SingleOrDefault();
        }
        else
        {
            currentObjective = (from p in cd.Objective
                                where p.Level == currentRank && p.Parent_ObjectiveID == identity
                                select p).SingleOrDefault();
        }

        if (currentObjective == null)
        {
            MessageBox.Show("Levels don't exist");
            return;
        }
        else
        {
            identity = currentObjective.ObjectiveID;
        }
    }

    if (currentObjective != null)
    {
        if (levels.Last() == currentObjective.Level)
        {
            MessageBox.Show("Level already exists");
            return;
        }
    }
    else
    {
        var aux = (from p in cd.Objective
                   where p.Parent_ObjectiveID == null && p.Level == levels.Last()
                   select p).SingleOrDefault();

        if (aux != null)
        {
            MessageBox.Show("Level already exists");
            return;
        }
    }

    var newObjective = new Objective();
    newObjective.Name = NameTextBox.Text;
    newObjective.Level = levels.Last();
    newObjective.Parent_ObjectiveID = currentObjective == null ? null : (int?)currentObjective.ObjectiveID ;

    cd.Objective.InsertOnSubmit(newObjective);
    cd.SubmitChanges();

    MessageBox.Show("The new objective has added successfully");
    NameTextBox.Clear();
    LoadObjectives();
}


texts:
Is it possible to write this in fewer lines of code?

If you input an integer it will output it as an ordinal number if it is less than 100. The below code works perfectly, but I'm wondering if it could be written more succinctly.

def ordinal(self, num):
    """
      Returns ordinal number string from int, e.g. 1, 2, 3 becomes 1st, 2nd, 3rd, etc.
    """
    self.num = num
    n = int(self.num)
    if 4 <= n <= 20:
      suffix = 'th'
    elif n == 1 or (n % 10) == 1:
      suffix = 'st'
    elif n == 2 or (n % 10) == 2:
      suffix = 'nd'
    elif n == 3 or (n % 10) == 3:
      suffix = 'rd'
    elif n < 100:
      suffix = 'th'
    ord_num = str(n) + suffix
    return ord_num


texts:
I'm going through the CoffeeScript book by Trevor Burnham, and I was curious as to what the best style is for a function I was writing.

In the book the author writes the function like so:

strToCoordinates = (input) ->
    halves = input.split(',')
    if halves.length is 2
        x = parseFloat halves[0]
        y = parseFloat halves[1]
        if !isInteger(x) or !isInteger(y)
            console.log "Each coordinate must be an integer."
        else if not inRange x - 1, y - 1
            console.log "Each coordinate must be between 1 and #{GRID_SIZE}."
        else
            {x, y}
    else
        console.log 'Input must be of the form `x, y`.'

I wrote my function like so:

strToCoordinates = (input) ->
    halves = input.split(',')
    if halves.length isnt 2
        console.log 'Please enter coordinates in format: x,y'; return
    [x, y] = (parseFloat s for s in halves)
    unless isInteger(x) and isInteger(y)
        console.log 'The coordinates must be integers.'; return
    if not inRange(x, y)
        console.log "Coordinates must be between 1 and #{GRID_SIZE}."; return
    {x, y}

Is my use of just if statements and using return to stop the flow if the check fails an okay style?

I like the fact that with this style the error messages are right after the check unlike with if/else, and also you don't have to have large sections indented.


texts: Batch Insert Figures Into Powerpoint Slides with VBA

texts:
I have a series of images ("1.bmp", "2.bmp", "3.bmp",... ,"30.bmp" in "F:\Images" folder) and I am trying to insert these images one by one into Microsoft PowerPoint with VBA program. The base slide (as template) has been set down in page 2. The image object which is named Image1 in that template slide is going to be replaced into "F:\Images\1.bmp", "F:\Images\2.bmp"... separately in new slides after the base slide.
The experimental implementation
The main entry method is InsertFigures.
Sub InsertFigures()
    'Reference: (Show object name) https://stackoverflow.com/a/52088805
    'Reference: (Replace image) https://stackoverflow.com/a/18083223

    Dim BaseSlideNumber As Integer
    Dim StartNum, EndNum As Integer
    StartNum = 1
    EndNum = 30
    BaseSlideNumber = 2
    Dim LoopNumber As Integer
    For LoopNumber = StartNum To EndNum
      Set newSlide = ActivePresentation.Slides(BaseSlideNumber).Duplicate
    Next LoopNumber

    For LoopNumber = StartNum To EndNum
        NewPictureFilename = "F:\Images\" & CStr(LoopNumber) & ".bmp"  ' Source Image Path
        Dim TargetSlideNumber As Integer
        TargetSlideNumber = BaseSlideNumber + (LoopNumber - StartNum + 1)
        Set ObjectForGettingProperties = getShapeByName("Image1", TargetSlideNumber)
        'Capture properties of exisitng picture such as location and size
        With ObjectForGettingProperties
            TopProperty = .Top
            LeftProperty = .Left
            HeightProperty = .Height
            WidthProperty = .Width
            'SoftEdgeProperty = .SoftEdge
        End With
        ObjectForGettingProperties.Delete                       ' Delete origin placeholder

        Set NewImageObject = ActivePresentation.Slides(TargetSlideNumber).Shapes.AddPicture(NewPictureFilename, msoFalse, msoTrue, LeftProperty, TopProperty, WidthProperty, HeightProperty)
        NewImageObject.Name = "NewImage"                  ' Set image name
        NewImageObject.SoftEdge.Radius = 8.86
    Next LoopNumber

End Sub

Function getShapeByName(shapeName As String, Slide As Integer)
    'Reference: https://stackoverflow.com/a/5527604
    Set getShapeByName = ActivePresentation.Slides(Slide).Shapes(shapeName)
End Function

All suggestions are welcome.


texts:
I understand that this animation code is outdated:

[UIView beginAnimations:@"Move" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIView setAnimationDelay:0.08];
self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[UIView commitAnimations];

What are the modern best practices for achieving the same result?


texts:
I want to do simple encryption using PHP 5.5. By “simple” I mean I want to use native PHP functions. I have created this code that works, can it be improved? It's to encrypt/decrypt strings and binary files that are to be stored in a database and accessed via a website. Assume that it is done over SSL and that the password isn't hard-coded or stored anywhere on the web server.

Here's what I have (and it works). Is this secure? All the examples I found do not use PHP 5.5's hash_pbkdf2 function. I wanted a simple example that uses this.

Are there any downsides to using MCRYPT_MODE_CFB? Are 5000 iterations enough for PBKDF2 in this context?

// Check hash_pbkdf2 exists as it's not available < 5.5
if(function_exists('hash_pbkdf2') === false) {

    // A fallback could be implemented here
    exit('hash_pbkdf2() does not exist');

}

// Settings
$stringToEncrypt                = 'This was encrypted';        // The plain text string to encrypt; binary files should be base64 encoded
$encryptionPassword             = 'MyP@$$w0rd';                // The password; the only data that should be kept private
$pbkdf2Iterations               = 5000;                        // More iterations = more secure, 1000 should be used as a minimum
$pbkdf2HashAlgo                 = 'sha256';                    // 256-bit key size
$cipher                         = MCRYPT_RIJNDAEL_128;         // Note: 128 refers to block size, not key size; MCRYPT_RIJNDAEL_128 is similar to 256-bit AES
$blockMode                      = MCRYPT_MODE_CFB;            // CFB mode requires a random IV and does not require padding
$ivSource                       = MCRYPT_DEV_URANDOM;        // URANDOM is faster than RANDOM in some environments

// Create key using PBKDF2 hash
$ivSize                         = mcrypt_get_iv_size($cipher, $blockMode);
$pbkdf2Salt                     = mcrypt_create_iv($ivSize, $ivSource);
$key                            = hash_pbkdf2($pbkdf2HashAlgo, $encryptionPassword, $pbkdf2Salt, $pbkdf2Iterations);

// Pack the key into a binary hex string
$key                            = pack('H*', $key);

// Create random IV
$iv                             = mcrypt_create_iv($ivSize, $ivSource);

// Encrypt the data
$encryptedData                  = mcrypt_encrypt($cipher, $key, $stringToEncrypt, $blockMode, $iv);

// Prepend the IV as it's needed for decryption
$encryptedData                  = $iv . $encryptedData;

// Base64 encode it
$encryptedData                  = base64_encode($encryptedData);

// Decrypt
$decryptedData                  = base64_decode($encryptedData);

// Get the IV
$ivDecrypted                    = substr($decryptedData, 0, $ivSize); // Don't need to use mb_substr as it's hexadecimal

// Get the encrypted data on its own
$decryptedData                  = substr($decryptedData, $ivSize);

// Decrypted data
$decryptedData                  = mcrypt_decrypt($cipher, $key, $decryptedData, $blockMode, $ivDecrypted);

// Output for testing
echo "
stringToEncrypt: $stringToEncrypt
";
echo "
encryptionPassword: $encryptionPassword
";
echo "
pbkdf2Iterations: $pbkdf2Iterations
";
echo "
pbkdf2HashAlgo: $pbkdf2HashAlgo
";
echo "
ivSize: $ivSize
";
echo "
iv: $iv
";
echo "
pbkdf2Salt: $pbkdf2Salt
";
echo "
key: $key
";
echo "
encryptedData: $encryptedData
";
echo "
ivDecrypted: $ivDecrypted
";
echo "
decryptedData: $decryptedData
";


texts: Calculate and displays the sum of all numbers from 1 to 20

texts:
This is a beginner's class. I just need help verifying if this code is correct, or edit the parts that need fixing.
n = int(input("Enter a number"))
sum = 0
for i in range(1,n+1):
    sum = sum + i
    print("The sum is:", sum)


texts:
I have referred some class diagram to actually create visitor.

#include <iostream>

using namespace std; //know should not be used, but for simplicity

class Book;
class Pen;
class Computer;

class ICartVisitor
{
public:
    virtual int Visit(Book &) = 0;
    virtual int Visit(Pen &) = 0;
    virtual int Visit(Computer &) = 0;
};

class IElement
{
public:

    virtual int accept (ICartVisitor& cartVisitor) = 0;
    virtual int getPrice () = 0;

};

class Book : public IElement
{

public:

    int accept (ICartVisitor& cartVisitor)
    {
        return cartVisitor.Visit(*this);
    }

    int getPrice ()
    {
        return 100;
    }
};

class Pen : public IElement
{
public:

    int accept (ICartVisitor& cartVisitor)
    {
        return cartVisitor.Visit(*this);

    }

    int getPrice ()
    {
        return 5;
    }
};

class Computer : public IElement
{
public:

    int accept (ICartVisitor& cartVisitor)
    {
        return cartVisitor.Visit(*this);

    }

    int getPrice ()
    {
        return 10000;
    }
};

class CartVisitor : public ICartVisitor
{
public:

    //inlining all the functions for simplicity
    int Visit(Book & book)
    {
        return book.getPrice();
    }

    int Visit(Pen & pen)
    {
        return pen.getPrice();

    }

    int Visit(Computer & computer)
    {
        return computer.getPrice();

    }
};

int main(int argc, char* argv[])
{
    int total = 0;

    ICartVisitor *cartVisitor = new CartVisitor();

    total += cartVisitor->Visit(*(new Computer()));
    total += cartVisitor->Visit(*(new Book()));
    total += cartVisitor->Visit(*(new Pen()));

    cout<<total;

    return 0;
}


texts: getword that properly handles undersores, string constants, comments, or preprocessor control lines

texts:
Our version of getword does not properly handle underscores, string constants, comments, or preprocessor control lines. Write a better version.

This is the exercise 6-1 and can be foud on K&R 2 at page 150.
http://net.pku.edu.cn/~course/cs101/2008/resource/The_C_Programming_Language.pdf

My solution:

static int isValidKeyWord(char c) {
    if(isalnum(c) || c == '_') {
        return 1;
    }
    return 0;
}

int getword(char *word, int lim) {
    int c;
    char *w = word;

    int ordinaryKeyWord = 0;
    int comment         = 0;
    int stringConstant  = 0;

    while(isspace((c = getch())))
        ;

    if(c == '#' || c == '_' || isalpha(c)) {
        ordinaryKeyWord = 1;
        *w++ = c;
    }
    else if(c == '/') {
        *w++ = c;
        c = getch();
        if(c == '*') {
            *w++ = c;
            comment = 1;
        }
        else {
            *w = '\0';
            return *--w;
        }
    }
    else if(c == '\"') {
        *w++ = c;
        stringConstant = 1;
    }
    else {
        *w++ = c;
        *w = '\0';
        return c;
    }

    for(; --lim; w++) {
        *w = getch();
        if(ordinaryKeyWord && (!isValidKeyWord(*w))) {
            ungetch(*w);
            break;
        }
        else if(stringConstant && *w == '\"') {
            w++;
            break;
        }
        else if(comment && *w == '*') {
            *++w = getch();
            if(*w == '/') {
                w++;
                break;
            }
            else {
                ungetch(*w);
                w--;
            }
        }
    }

    *w = '\0';
    return word[0];
}

There are 3 main cases:

case 1: comments, if the first two characters are / and *. In this case the function should return when the corresponding * and / are met.
case 2: string constants, if the first character is a ", then the function should return when the closing " is met.
case 3: words that begin with #, _ and letters. In this case, the program should return when a character different that _ or an alphanumeric character is met.

First, the program analyzes which case is. Based on that, "it knows" when to stop, then  it returns the first character of that word.


texts: Splitting the Java builder to avoid writing same code multiple times

texts:
I have a piece of code which looks like below:

Problem hashProblem;
String indexName;
if(condition.getOwner() != null) {
    indexName = sourceLocation ;
    hashProblem = new Problem().builder()
        .locationID(condition.getLocationID())
        .sourceLocation(condition.getSourceLocation())
        .build();
}
else {
    indexName = currentLocation;
    hashProblem = new Problem().builder()
        .locationID(condition.getLocationID())
        .currentLocation(criteria.getcurrentLocation())
        .build();
}

Is there a way to write this code in a more elegant way? While building the hashProblem object setting the locationID is always required. I am unable to think of a way to split the builder so that I could write .locationID only once.


texts: Using database connections in PHP classes

texts:
I need some advice\suggestions on how to create\handle database connections for a project I'm working on. I'm creating a simple work order system for my company using PHP 5.4.3, right now there isn't any type of authentication as I'm not ready for that complexity.

So far I'm planning on the following structure:

class Db {
    private static $dbh = null;

    static function open_connection() {
        self::$dbh = new PDO(... }

    static function query($sql) {
        $result = self::$dbh->... }

    static function fetch_array($result){
        ...}
...

}

class Workorder extends Db {

    protected static $table_name = ...
    ...

    public $wonum;
    ...

    function instantiate {
    //return workorder objects
    ...}

    fucntion findallwos {
    //find all work orders...
    ...}

...}

I think this will work fine for pages that I need to display all of the work orders or put in new work orders.  But I have a few pages that require very simple queries, for example one of the reporting pages will just have a drop down list of the 3 technicians we have working for us, if I was using a global $dbh variable I could just do:

function create_dropdown () {
    GLOBAL $dbh;

    $sql = "select...";
    $sth = $dbh->prepare($sql);
    $sth->execute();
    $arry = $sth->fetchAll(PDO::FETCH_ASSOC);
    .....

But I'd rather stay away from global variables as eventually I would like to add future complexity to this site which might not work with globals. (Including multiple users with authentication etc).

My questions are:

Should I not use the Db class as I have it designed, and instead use some sort of connection_factory class instead that passes out connections? (and not have my workorder class be an extension of anything)
Should I just use static calls to the Db class to pull in simple queries? db::fetch_array...
Do you have any other suggestions?  I've come across a lot of different ways to go about this, but ideally I'd like to design this so that I don't have to completely recode everything when I get to the point where I'm adding multiple users with different permissions etc.


texts:
There are 2 csv:
1 - areaMap.csv
2 - currencyMap.csv

Enum AreaMapFromCsv is the Singleton to store the Map<String, Enum> read from 1 csv.
Enum CurrencyMapFromCsv is the Singleton to store the Map<String, String> read from 2 csv.
Interface IMapFromCsv provides default method for reading Map from csv.

AreaMapFromCsv and CurrencyMapFromCsv looks almost identical. They differs only in FILE_TO_LOAD, argument passing to the interface default method and second type of Map parameters. Any ideas how to DRY?

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.function.Function;

public interface IMapFromCsv{

    public default <T> Map<String, T> getMap(String FILE_TO_LOAD, Function<String, T> convertValue){
        Map<String, T> mapResult = new HashMap<>();
        File f = new File(FILE_TO_LOAD);
        try (Scanner sc = new Scanner(f)) {
            while (sc.hasNextLine()) {
                String tmp = sc.nextLine();
                String[] tmp2 = tmp.split(";");
                mapResult.put(tmp2[0], convertValue.apply(tmp2[1]));
            }
        } catch (FileNotFoundException fntf) {
            System.err.println("File " + f.getPath() + "was not found.");
        } catch (Exception e) {
            System.err.println("Something went wrong with reading " + f.getPath());
        }
        return mapResult;
    }
}

.

import java.util.Map;
import java.util.function.Function;

public enum AreaMapFromCsv implements IMapFromCsv {

    INSTANCE;
    final String FILE_TO_LOAD = "resources/areaMap.csv";
    private Map<String, String> map;

    private AreaMapFromCsv() {
        init();
    }

    private void init() {
        this.map = getMap(FILE_TO_LOAD, Function.identity());
    }

    public void reload() {
        init();
    }

    public Map<String, String> get() {
        return map;
    }

}

.

import java.util.Map;

public enum CurrencyMapFromCsv implements IMapFromCsv {

    INSTANCE;
    final String FILE_TO_LOAD = "resources/currencyMap.csv";
    private Map<String, Double> map;

    private CurrencyMapFromCsv() {
        init();
    }

    private void init() {
        this.map = getMap(FILE_TO_LOAD, Double::parseDouble);
    }

    public void reload() {
        init();
    }

    public Map<String, Double> get() {
        return map;
    }

}


texts: Computing nth roots of a number - SICP exercise 1.45

texts:
From SICP

  Exercise 1.45:

  We saw in 1.3.3 that attempting to compute square roots
  by naively finding a fixed point of x/y does not converge, and that
  this can be fixed by average damping.

  The same method works for
  finding cube roots as fixed points of the average-damped x/y^2.

  Unfortunately, the process does not work for fourth roots—a single
  average damp is not enough to make a fixed-point search for x/y^3
  converge.

  On the other hand, if we average damp twice (i.e., use the
  average damp of the average damp of x/y^3) the fixed-point search does
  converge.

  Do some experiments to determine how many average damps are
  required to compute nth roots as a fixed-point search based upon
  repeated average damping of x/y^n-1.

  Use this to implement a simple
  procedure for computing nth roots using fixed-point, average-damp, and
  the repeated procedure of Exercise 1.43.

  Assume that any arithmetic
  operations you need are available as primitives.

The definitions of the helper procedures stated in the exercise are:

(fixed-point f x) applies f to x repeatedly until x does not change very much.
((average-damp f) returns a procedure that gets the average of x and the value of (f x).
(repeated f n) returns a procedure with one argument x and applies f to x n times.

First, here is the definition for the newton's method. This code is from the book:

(define dx 0.00001)

(define (deriv g)
  (lambda (x)
    (/ (- (g (+ x dx)) (g x))
       dx)))

(define (newton-transform g)
  (lambda (x)
    (- x (/ (g x)
            ((deriv g) x)))))

(define (fixed-point-of-transform
         g transform guess)
  (fixed-point (transform g) guess))

Here is my code for computing nth root.

I first created a procedure called least-expt that computes how many times average-damp should be applied based on the number of roots. Through some experiments, I found that the number of times average-damp should be applied is the value x-1 of 2^x where x will never be greater than the number of roots. The least-exp procedure does this process exactly.

(define (least-expt n)
    (define (least x)
      (if (> (expt 2 x) n)
          (- x 1)
          (least (+ x 1))))
    (least 1))

Here is my main procedure:

  (define (roott n)
    (lambda (x)
      (fixed-point-of-transform
       (lambda (y)
         (/ x
            (expt y (- n 1))))
       (repeated
        average-damp
        (least-expt n))
       1.0)))

Now, as far as I know, this procedure works exactly fine. But I am extremely confused by this part of the exercise:

  Assume that any arithmetic operations you need are available as
  primitives.

I don't understand this statement. I did not use any unusual arithmetic operations. Are there something in my code that should take advantage of these arithmetic operations ?

How can I improve this code and make it faster?


texts:
MyText.txt

This is line 1
This is line 2
Time Taken for writing this#      0 days 0 hrs 1 min 5 sec
Nothing Important
Sample Text

Objective

To read the text file and find if "Sample Test is present in the file. If present print the time taken to write the file (which is a value already inside the file)"

My Code

with open('MyText.txt', 'r') as f:
    f.readline()
    for line in f:
        if 'Sample Text' in line:
            print "I have found it"
            f.seek(0)
            f.readline()
            for line in f:
                if 'Time Taken' in line:
                    print line
                    print ' '.join(line.split())
f.close()

The code is working fine.  I want to know if this code can be made even better. Considering I am new to Python, I am sure there would be a better way to code this.  Can anyone suggest alternative/faster approaches for this?


texts:
Philosophical question: How far should I break down my objects?

Inuit.css and Bootstrap have islands, islets, wells, grayboxes, and other objects that have repeating properties. I don't think it was DRY enough, so I created a generic .box object & a few skins. I am just not sure if this is overkill?

Box Object

Used to fly out content from the rest of the document.

.box
{
    margin-bottom: 24px;

    padding: 24px;
}

.box--s
{
    padding: 12px;
}

.box--l
{
    padding: 48px;
}

Round Skin

Used to round the corners of an element.

.round
{
    border-radius: 4px;
}

.round--s
{
    border-radius: 2px;
}

.round--l
{
    border-radius: 8px;
}

Gray Skin

Generic color

.gray
{
    background-color: #eeee
}

Well Skin

Box specific skin to create wells

.well
{
    box-shadow: inset 2px 2px 2px rgba(0,0,0,.5);
}

It does seem more flexible - but still not sure if I am breaking them down way too much.


texts: URL decode a string but log an error after second exception

texts:
I have a method which does URL decoding on the string value passed along with using Charset:

  public String decodeValue(String value, Charset charset) {
    if (!Strings.isNullOrEmpty(value)) {
      try {
        value = URLDecoder.decode(value, charset.name());
      } catch (UnsupportedEncodingException ex) {
        // log error
        return null;
      }
    }
    return value;
  }

Now if URLDecoder.decode throws UnsupportedEncodingException the first time, then I want to run the same value against these three lines:

value = value.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
value = value.replaceAll("\\+", "%2B");
value = URLDecoder.decode(value, charset.name());

And if then again URLDecoder.decode line throws exception second time, then I will log the error but only second time and return null value otherwise return the value which is decoded so I came up with this:

  public String decodeValue(String value, Charset charset) {
    if (!Strings.isNullOrEmpty(value)) {
      try {
        value = URLDecoder.decode(value, charset.name());
      } catch (UnsupportedEncodingException ex) {
        try {
          value = value.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
          value = value.replaceAll("\\+", "%2B");
          value = URLDecoder.decode(value, charset.name());
        } catch (UnsupportedEncodingException uex) {
          // log error
          return null;
        }
      }
    }
    return value;
  }

I'd like to see if there is any better way to write the above code. As of now, it duplicates the code.


texts: Why my listview style change when I loop the javascript twice?

texts:
I develop an android native application using phonegap and jquery mobile. I've made a function to create a listview style dynamically using looping for... When I run the function for the first time, it works, the listview style is working, and match with the content. but when I press back button and run the function again, the style change (the listview style is gone) but the content still there. is my function wrong? how to solve this problem?

the screenshoot for more explanation:

this is the result when I press the back button and run the function again

the codes for more detail:

function detail(kodenegara, koderesult)
        {
            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: "http://10.80.3.73/webservice/Service1.svc/json/weeklyflash/"+kodenegara,
                dataType: "json",
                success:function(data){
                    var result = koderesult;

                    maks = -1;
                    for(i = 0; i < data[result].length; i++) {
                        if(data[result][i].bulan > maks)
                        maks = data[result][i].bulan;
                    }

                    var loop_tipe = countTypesForBulan(data[result], maks);
                    var innerHtml = "";

                    for (i = 0; i < loop_tipe; i++){
                        a=i+loop_tipe;
                        b=a+loop_tipe;
                        innerHtml +=
                        "
"+
                        "
"+data[result][i].type+"
"+
                        "
"+
                            "
"+
                                "&nbsp;	"+
                                ""+data[result][i].bulan+"/2012	"+
                                ""+data[result][a].bulan+"/2012	"+
                                ""+data[result][b].bulan+"/2012	"+
                            "
"+
                            "
"+
                                "Cash	"+
                                ""+data[result][i].uang+"	"+
                                ""+data[result][a].uang+"	"+
                                ""+data[result][b].uang+"	"+
                            "
"+
                            "
"+
                                "Qty	"+
                                ""+data[result][i].total+"	"+
                                ""+data[result][a].total+"	"+
                                ""+data[result][b].total+"	"+
                            "
"+
                        "
"+
                        "
";
                    }
                    $('#tipe').html(innerHtml);
                    $.mobile.changePage("#detail", "slide", false, true);

                    //show the page
                },
                error: function () {
                    alert("ERROR");
                }
            });
        }

        function countTypesForBulan(resultArray, bulanVal) {
            var i,
                types,
                count = 0;
            for (i=0, types = {}; i < resultArray.length; i++)
                if (resultArray[i].bulan === bulanVal && !types[resultArray[i].type]) {
                types[resultArray[i].type] = true;
                count++;
            }
            return count;
        }

here is for simulation my project with jsfiddle


texts:
I am looking for feedback on coding style. I know this function already exists, and I would never use my version over a well tested one. I am just practicing.

double Clib_atof(char s[])
{
    double val, power, rtn;
    int i, sign;
    for (i = 0; isspace(s[i]); i++);
    sign = (s[i] == '-') ? -1 : 1;
    if (s[i] == '+' || s[i] == '-') ++i;
    for (val = 0.0; isdigit(s[i]); ++i) {
        val = 10.0 * val + (s[i] - '0');
    }
    if (s[i] == '.') {
        ++i;
    }
    for (power = 1.0; isdigit(s[i]); ++i) {
        val = 10.0 * val + (s[i] - '0');
        power *= 10.0;
    }
    rtn = (sign * val / (power));

    // Next work on exponent
    if (s[i] == 'e') {
        int j, esign;
        int eval = 0;
        fprintf(stdout, "e found\n");
        for (j = i + 1; isspace(s[j]); ++j);
        esign = (s[j] == '-') ? -1 : 1;
        if (s[j] == '+' || s[j] == '-') ++j;
        for (; isdigit(s[j]); ++j) {
            eval = 10 * eval + (s[j] - '0');
        }
        fprintf(stdout, "eval = %d\n", eval);
        int l;
        for (l = 0; l < eval; l++) {
            (esign >= 0) ? (rtn *= 10) : (rtn /= 10);
        }
    }

    // Finally return the solution
    return rtn;
}


texts: Author class, with constructor validations and rich comparisons

texts:
I wrote the following Author class in Python for a project I'm working on. I wanted to make sure that the rich comparisons and the methods I used to validate the constructor parameters were done properly.

Author class:

class Author:

    def __init__(self, id, firstname, lastname):
        self._validateid(id, "ID")
        self._validate_author(firstname, "First Name")
        self._validate_author(lastname, "Last Name")

        self._id = id
        self._firstname = firstname
        self._lastname = lastname

    def _validateid(self, id, error_message):
        if id < 1:
            raise ValueError(error_message + " is invalid")

    def _validate_author(self, parameter, error_message):
        if not parameter:
            raise TypeError(error_message + " is missing")

    @property
    def iden(self):
        return self._id

    @property
    def first_name(self):
        return self._firstname

    @property
    def last_name(self):
        return self._lastname

Rich Comparisons:

    def __lt__(self, other):
        if isinstance(other, Author):
            return (self.iden, self.first_name.lower(), self.last_name.lower()) < (other.iden, other.first_name.lower(), other.last_name.lower())
        return NotImplemented

    def __le__(self, other):
        if isinstance(other, Author):
            return (self.iden, self.first_name.lower(), self.last_name.lower()) <= (other.iden, other.first_name.lower(), other.last_name.lower())
        return NotImplemented

    def __eq__(self, other):
        if isinstance(other, Author):
            return (self.iden, self.first_name.lower(), self.last_name.lower()) == (other.iden, other.first_name.lower(), other.last_name.lower())
        return NotImplemented

    def __ne__(self, other):
        if isinstance(other, Author):
            return (self.iden, self.first_name.lower(), self.last_name.lower()) != (other.iden, other.first_name.lower(), other.last_name.lower())
        return NotImplemented

    def __ge__(self, other):
        if isinstance(other, Author):
            return (self.iden, self.first_name.lower(), self.last_name.lower()) >= (other.iden, other.first_name.lower(), other.last_name.lower())
        return NotImplemented

    def __gt__(self, other):
        if isinstance(other, Author):
            return (self.iden, self.first_name.lower(), self.last_name.lower()) > (other.iden, other.first_name.lower(), other.last_name.lower())
        return NotImplemented

    def __hash__(self):
        return hash((self.iden, self.first_name.lower(), self.last_name.lower()))


texts:
GlueArrays is used for iterating over an array of arrays, and it looks like this:

Main.java

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Main {

    public static class GlueArrays<T> implements Iterable<T> {

        private final T[][] arrays;

        public GlueArrays(T[]... arrays) {
            this.arrays = arrays;
        }

        @Override
        public Iterator<T> iterator() {
            return new GlueArrayIterator(arrays);
        }

        private static class GlueArrayIterator<T> implements Iterator<T> {

            private final T[][] arrays;
            private int arrayIndex = 0;
            private int localIndex = 0;

            GlueArrayIterator(T[][] arrays) {
                this.arrays = arrays;
            }

            @Override
            public boolean hasNext() {
                if (arrayIndex == arrays.length) {
                    return false;
                }

                return arrayIndex < arrays.length ||
                       localIndex < arrays[arrayIndex].length;
            }

            @Override
            public T next() {
                if (!hasNext()) {
                    throw new NoSuchElementException("Nothing to iterate.");
                }

                T returnValue = arrays[arrayIndex][localIndex];

                if (localIndex < arrays[arrayIndex].length) {
                    localIndex++;

                    if (localIndex == arrays[arrayIndex].length) {
                        localIndex = 0;
                        arrayIndex++;
                    }
                }

                return returnValue;
            }
        }
    }
    public static void main(String[] args) {
        Number[] arr1 = {1, 2, 3};
        Number[] arr2 = {4f, 5f, 6f};
        Number[] arr3 = {7.0, 8.0, 9.0};

        for (Number number : new GlueArrays<>(arr1, arr2, arr3)) {
            System.out.println(number);
        }
    }
}

As always, any critique is welcome.


texts: Correct using of try/catch clause on database execution

texts:
When a statement to a DB returns null, I am catching it this way:

private int GetLastRoundNumber(int period)
{
    int id;
    try
    {
        using (NpgsqlConnection con = new NpgsqlConnection(_entwConnection))
        {
            con.Open();
            using (NpgsqlCommand cmd = new NpgsqlCommand())
            {
                cmd.Connection = con;
                cmd.CommandText = "SELECT roundNumberId FROM race.folders WHERE period = @period ORDER BY roundNumberId DESC LIMIT 1;";
                cmd.Parameters.AddWithValue("period", period);
                return id = (int)cmd.ExecuteScalar();
            }
        }
    }
    catch (NullReferenceException e)
    {
        Debug.Write(e.Message);
        Debug.WriteLine("Because of a new period, started with 1 again. Period: " + period + ".");
        return id = 1;
    }
}

So to this codepart my questions:

Is it okay to have the try/catch block outside the using statement
block?
Is there a better way to handle the exception?
Do I need to hit the catch block?

I am asking because as I learned it by now, for me it isn't a real exception, because when a new period starts, there is no Id inside.

Is this the correct way to deal with it?


texts: Parse input string into vector of i16 in Rust

texts:
I'm new to Rust and I'm working through the exercises found at the bottom of this page. The following code parses a space deliminated input string from the user into a Vec<i16>. If the input string is invalid, the code loops and prompts again. If the string is valid, it prints out the debug value of the Vec<i16> and prompts again.

The code works, but I feel there is a more idomatic Rust way to deal with this. Particularly, in the get_input function's looping and how its assigning the return value. Behold.

use std::io::Write;

fn main() {
    while let Some(ary) = get_input() {
        println!("{:?}", ary);
    }

    println!("Peace!");
}

fn get_input() -> Option<Vec<i16>> {
    let mut out: Option<Vec<i16>> = None;
    let mut valid = false;
    while !valid {
        // Get user input.
        print!("Enter series-> ");
        std::io::stdout().flush().unwrap();
        let mut input = String::new();
        std::io::stdin().read_line(&mut input).unwrap();

        // Parse it.
        match input.trim() {
            "q" => {
                valid = true;
                out = None;
            }
            _ => {
                let parsed = parse_input(input);
                if let Ok(_) = parsed {
                    out = Some(parsed.unwrap());
                    valid = true;
                }
            }
        }
    }
    out
}

fn parse_input(input: String) -> Result<Vec<i16>, std::num::ParseIntError> {
    input
        .split_whitespace()
        .map(|token| token.parse::<i16>())
        .collect::<Result<Vec<i16>, _>>()
}


texts:
I have just finished the sololearn C++ course and wanted to create a basic login program in the vein of a basic operating system.

#include "ubuntu_login"
#include <iostream>
#include <string>
using namespace std;

Ubuntu_Login::Ubuntu_Login()
{
    cout << "\t Welcome to Ubuntu!\n" << endl;
}

void Ubuntu_Login::usr_login()
{

cout << "Please enter a username" << endl;
getline(cin,username);

cout << "Please enter a password" << endl;
getline(cin,password);

while(username_input != username || password_input != password)
  {
    cout << "\n|Ubuntu Login|" << endl;

    cout << "Please enter your username" << endl;
    getline(cin, username_input);

    cout << "Please enter your password" << endl;
    getline(cin, password_input);

    if(username_input != username || password_input != password)
      {
        cout << "Incorrect username or password" << endl;
      }
  }
}

#include "ubuntu_login.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{
  Ubuntu_Login UO;
  UO.usr_login();
}

Header file:

#ifndef UBUNTU_LOGIN_H
#define UBUNTU_LOGIN_H
#include <string>
using namespace std;

class Ubuntu_Login
{
public:
  Ubuntu_Login();
  void usr_login();
private:
  string username;
  string password;
  string username_input;
  string password_input;
};

#endif // UBUNTU_LOGIN_H

Any help on improving my code by getting rid of useless code or replacing it with better code would be greatly appreciated.


texts: Should I return true or false if both of the IP address strings are empty?

texts:
I am validating two IP addresses. I simply wrote a peice of code like

if(string.IsNullOrEmpty(ip1) && string.IsNullOrEmpty(ip2)
  return true;

But is this logically correct? What should we done with empty strings? If both are empty strings, is it okay to return true?

May be a complete code snipet can give better insight.

public static bool IsIPAddressMatching(string ipAddressA, string ipAddressB)
        {
            try
            {
                if(string.IsNullOrEmpty(ipAddressA) || string.IsNullOrEmpty(ipAddressB))
                    return true;
                var address1 = IPAddress.Parse(ipAddressA);
                var address2 = IPAddress.Parse(ipAddressB);

                if (address1.AddressFamily == address2.AddressFamily)
                    return (address1.Equals(address2));

               // some code here to check mapped IP addresses

            }
            catch (Exception)
            {
                return false;
            }
        }


texts:
I'm trying to write a method to validate an image from a URL. The method will accept an array of image URL. The image should be validated by its type, size and dimensions. Right now, I'm able to implement it but I'm having a problem on how long it takes to finish the validation.

Is there any alternative on my current approach that might speed up the validation process?

public function validate_attachment($attachment){
    $image = "";
    if(strpos($attachment,",") !== false){
      $image = explode(",", $attachment);
    }else{
      $image = array($attachment);
    }

    foreach ($image as $url) {

      $ch = curl_init($url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_exec($ch);

      switch (curl_getinfo($ch, CURLINFO_CONTENT_TYPE)) { //validate file type

        case 'image/png' :
        case 'image/jpg' :
        case 'image/jpeg':
        case 'image/gif' :
          echo curl_getinfo($ch, CURLINFO_CONTENT_TYPE) ."
";
          $type = true;
          $filesize =  curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD)/1024 ."
"; // validate image size
          echo $filesize;
          if($filesize <= 70){
            echo $filesize;
            list($width, $height) = getimagesize(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL)); // validate image dimensions
            if($width <= 800 && $height <= 600){
              echo "width: " . $width . "
";
              echo "height: " .  $height ."
";
            }else{
              echo "Image too large";
            }
            curl_close($ch);

          }else{
            echo "file size should be below 70kb";
          }
          break;
        default:
          echo "Invalid file type.";
          break;
      }
    }
  }


texts: Is this predicate valid to delete single shared_ptr's?

texts:
I wrote a predicate used in a remove_if call that deletes shared_ptr's of type StemmedSentence from an vector of sentences.

The predicate:

class EraseSentenceIf {
    ArrayStemmedSnippet * m_ass;

public:
    EraseSentenceIf(ArrayStemmedSnippet *ass)
    : m_ass(ass) {
    }

    bool operator()(const std::shared_ptr<
        ArrayStemmedSnippet::StemmedSentence>& s) {
        std::shared_ptr<ArrayStemmedSnippet::StemmedSentence> tmp = s;

        // --- set StemmedSentnce object in ArrayStemmedSnippet class
        s->setParent(m_ass);

        // --- if true delete this sentence)
        if (s->trimStopWords()) {
            tmp.reset();

            return true;
        }

        return false;
    }
};

The remove_if call:

EraseSentenceIf esi(this);
sentences.erase(
    std::remove_if(
        sentences.begin(), sentences.end(), esi),
    sentences.end()
);

Declaration:

std::vector<shared_ptr<StemmedSentence> > sentences;

The construction of the sentences objects looks like this:

sentences.push_back(shared_ptr<StemmedSentence>(
    new StemmedSentence(index, i - 1 )));

The code seems to run fine, valgrind / gdb does not moan. I just want to get sure that I handle  the deletion (or release) of the shared_ptr in a correct way. Can somebody please confirm this? Maybe I can improve something or I overlooked an important point. Thanks for your comments!


texts:
I'm new to sockets and servers in general and I would like to know if I'm doing something really wrong in the following server loop for spawning threads to process requests.

private static ServerSocket server;
private static final Object request_counter_lock = new Object();
private static int request_counter = 0;
private static boolean exit = false;

public static void main(String[] args) {
    try {
        server = new ServerSocket(8000,100);
        // Loop until one of the clients sends an exit request.
        while (!exit) {
            try {
                final Socket socket = server.accept();
                // When a connection is accepted we increment the request
                // counter so when the server starts to shut down it waits
                // until all requests are finished processing.
                synchronized(request_counter_lock) { request_counter++; }
                // Fire up a new thread to process requests.
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            processConnection(socket);
                        } catch (IOException e) {
                            logger.error("unable to process request: " + e.getMessage());
                        } finally {
                            // Make sure we close the socket.
                            SocketCloser.close(socket);
                            // Also decrement the request counter because we just closed
                            // the request socket which means we are done with this client.
                            synchronized(request_counter_lock) { request_counter--; }
                        }
                    }
                }).start(); // Fire up the thread.
            } catch (IOException e) {
                logger.error("error accepting socket connection: " + e.getMessage());
            }
        }
    } catch (IOException e) {
        logger.fatal("unable to start server: " + e.getMessage());
    } finally {
        // If the while loop breaks that means we received an exit request from
        // one of the clients but it's possible that there are still some requests
        // in progress so we can't shut down the server right away. We have to wait
        // until the request counter drops down to 0.
        synchronized(request_counter_lock) {
            logger.info("acquired lock for request_counter");
            while(request_counter > 0) {
                logger.info("request counter is above 0 so waiting");
                try {
                    // Wait 1 second for ongoing clients to finish with their work.
                    request_counter_lock.wait(1000);
                } catch (InterruptedException e1) {
                    logger.error("error in request_counter synchronized block: " + e1.getMessage());
                }
            }
        }
        logger.info("request counter reached 0 so going to close server");
        try {
            server.close();
        } catch (IOException e1) {
            logger.error("unable to close server: " + e1.getMessage());
        }
    }
}


texts: List of tuples generated through list comprehension

texts:
The function returns a list of tuples which is generated through list comprehension:

getUserRatings :: String -> [Film] -> [(String,Int)]
getUserRatings search database = [(title,rate) | (Film title _ _ ratings) <- database, (user,rate) <- ratings, search == user]

Film is defined as:

type Rating = (String, Int)
data Film = Film {  title,director :: String,
                    year :: Int,
                    ratings :: [Rating] } deriving (Read,Show)

such that a database is:

testDatabase :: [Film]
testDatabase = [(Film "Blade Runner" "Ridley Scott" 1982 [("Amy",5),("Bill",8),("Ian",7),("Kevin",9),("Emma",4),("Sam",7),("Megan",4)])]

The function getUserRatings takes in a the users name and the database, searches the ratings in the database, then compiles the the tuple so that its in the format of:

  film name (String), user rating (Int)

How might I write this more efficiently using higher order functions? I've attempted a few times but to no success using filters and maps; I don't know whether to post those attempts here or not. So I won't until advised otherwise.