texts:
I need to allocate n-dimensional arrays of type T, currently I am using the following functions. Is there a better way to do this? Also, ideally I would like to allocate a 1-D array and access that as a N-D array but I could not figure out a better way of doing that. Using existing matrix library is not an option as I want access to raw pointers.

template <class T, class Ti>
T*** allocate_3d_array(Ti nx, Ti ny, Ti nz){
    T*** A = new T**[nx];
    for(Ti i(0); i < nx; ++i){
            A[i] = new T*[ny];
            for(Ti j(0); j < ny; ++j){
                A[i][j] = new T[nz];
                for(Ti k(0); k < nz; ++k){
                    A[i][j][k]= 0.;
                }
            }
    }
    return A;
}
template <class T, class Ti>
void release_3d_array(T*** A, Ti nx, Ti ny, Ti nz){
    for (Ti i = 0; i < nx; ++i){
            for (Ti j = 0; j < ny; ++j){
                delete[] A[i][j];
            }
            delete[] A[i];
    }
    delete[] A;
}

template <class T, class Ti>
T** allocate_2d_array(Ti nx, Ti ny){
    T** A = new T*[nx];
    for(Ti i(0); i < nx; ++i){
        A[i] = new T[ny];
    }
    return A;
}

template <class T, class Ti>
void release_2d_array(T** A, Ti nx, Ti ny){
    for (Ti i = 0; i < nx; ++i){
        delete[] A[i];
    }
    delete[] A;
}

template <class T, class Ti>
T* allocate_1d_array(Ti nx){
    T *A = new T[nx];
    return A;
}

template <class T, class Ti>
    void release_1d_array(T* A, Ti nx){
    delete[] A;
}


texts: Is it possible to use "reduce" instead of for to set data to MapObject?

texts:
I want to remake and sort an array.
Is it possible to use "reduce" instead of "forEach" or "map"?
return beeProps.valueInfos.reduce (reduce()) would be great.

Anything else looks like it could be improved?

const makeTableArrayMap = (beeProps: beeOfProps) => {
    const rowMap: Map<number, beeOfValue[]> = new Map();

      beeProps.valueInfos.forEach((value, valueInfoIndex) => {
        Array.from(value.values).forEach(element => {
          const indexDate: number = element[0].getTime();
          const dateAndvalue: [
            Date,
            beeOfValue
          ][] = Array.from(value.values.entries());
          const newFateMap: Map<
            number,
            beeOfValue
          > = dateAndvalue.reduce((prev, current) => {
            return prev.set(current[0].getTime(), current[1]);
          }, new Map<number, beeOfValue>());
          // If rowMap includes date , bee will be added end of  beeOfValue. if not new array will be created and set.
          const bee:
            | beeOfValue
            | undefined = newFateMap.get(indexDate);
          if (bee) {
            if (rowMap.get(indexDate) !== undefined) {
              const tentativeArray:
                | beeOfValue[]
                | undefined = rowMap.get(indexDate);
              if (tentativeArray && tentativeArray.length > 0) {
                tentativeArray.push(bee);
                rowMap.set(indexDate, tentativeArray);
              }
            } else {
              rowMap.set(indexDate, [bee]);
            }
          }
        });
      });

    return rowMap;
  };

  type beeOfValue =
  | {
      kind: "on";
    }
  | {
      kind: "off";
    };


texts: Design that avoids undesired dependencies in Kotlin for a chess engine

texts:
I'm trying to come up with a design for a chess engine in Kotlin that hides implementation details, and that ensures that such an implementation cannot accidentally become spaghetti.

Client side example code

I envision that a client would access the chess engine with something like:

package chessprototype

import chessprototype.chess.Chess

class ChessClient {
    fun hello() {
        val searcher = Chess.mateSearcher()
        searcher.board = "k1K/2Q w"
        val move = searcher.findBestMove()
        println("Best move is " + move.toString())
    }
}

To achieve that I created the following.

Main interface code

package chessprototype.chess

// Undesired cyclic dependency needed to expose the MateSearcher
import chessprototype.chess.searchers.MateSearcher

/** Understandable interface for the client */
class Chess {
    interface Move {
        override fun toString(): String
    }
    data class TextMove(val text: String): Move { override fun toString() = text }
    interface Searcher {
        var board: String
        fun findBestMove(): Move
    }
    companion object {
        fun mateSearcher() = MateSearcher()
    }
}

I've put all interfaces that a client would use in a facade-like Chess object.
And I've put basic access types in there as well, such as TextMove

I've put a factory method in the Chess object as well to expose the complicated MateSearcher while hiding its implementation.
I've put it in a companion object so that I can create it without instantiating a Chess class.

Implementation code

package chessprototype.chess.searchers

// Undesired cyclic dependency needed for
// - basic types (Move, TextMove)
// - the interface to implement (Searcher)
import chessprototype.chess.Chess

class MateSearcher: Chess.Searcher {
    override var board: String = ""
    override fun findBestMove(): Chess.Move {
        return doComplicatedSearch()
    }
    // Complicated code that should not be exposed to the client
    private fun doComplicatedSearch(): Chess.Move { return Chess.TextMove("Qb7#") }
}

I've put the implementation in a separate package so that:

it cannot accidentally use code that was not explicitly imported first.
it cannot accidentally allow other code to use implementation details.

As you can see there is a mutual import that seems undesired to me.

My challenges

Ensure that the Searcher cannot 'accidentally' start using low level implementations from other parts of the code.
Ensure that the main interface cannot 'accidentally' leak implementation details.
Ensure that the main interface for the client is as clean and simple as possible.

My immediate problem: how can I eliminate the cyclic dependency of packages?

And more generally, what would you do differently and why?


texts:
When I look at this style of code I feel like there has to be a better way to write this:

    Name:<input type="text" id="cxByNameInput" name="cxByNameInput"/>

    State:
    <select id="cxState">
        <option></option>
    <?$states = getStates();
    while($state = $states->fetch_assoc())
    {?>
        <option value="<?=$state['st']?>"><?=$state['state']?></option>
    <?}?>
    </select>

    Status
    <select id="cxStatus">
        <option></option>
    <?$statusList = getCxStatusList();
    while($status = $statusList->fetch_assoc())
    {?>
        <option value="<?=$status['cxType']?>"><?=$status['cxTypeDescription']?></option>
    <?}?>
    </select>

I'd like to mention that keeping eclipses HTML code coloring would be a huge bonus...


texts: Find the smallest number Q whose product of digits is N

texts:
How do I make this efficient?

#include <stdio.h>
#define MAX 1000000000

int main()
{
    int n,temp,prod,i,j=0;
    scanf("%d",&n);

    for(i=1;i<MAX;i++)
    {
        temp=i;
        prod=1;
        while(temp!=0)
        {
           prod=prod*(temp%10);
           temp=temp/10;
        }
        if(prod==n)
        {
            printf("%d",i);
            j=1;
            break;
        }

    }
    if(j==0)
    {
        printf("-1");
    }
    return 0;
}


texts:
I created just for practice this leapyear script.

What do you think about it?
How can I make it more efficient?

package com.company;

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.printf("Plese enter year: ");
    int chosedYear = input.nextInt();

    leapYearMethod(chosedYear);

}

public static void leapYearMethod (int leapyear) {
    if ( leapyear % 4 == 0 ){
        System.out.println("Yeeees!");
    } else {
        int years = leapyear % 4;
        if(years == 1){
            System.out.println("3 years later there is a leapyear.");
        } else if( years == 2) {
            System.out.println("2 years later there is a leapyear.");
        } else if( years == 3) {
            System.out.println("1 years later there is a leapyear.");
        }
    }
    }
}


texts: FutureTask in Android, wait for a thread to execute the next one

texts:
This code is executed on a background service every 60 seconds on an Android app. Each class instantiated on FutureTask (WifiInfoFetch and WifiApResults) contains an insert to an SQLite database. We changed the original implementation (without a FutureTask) as we think the first insert was still locking the database when the second one tried to do its insert as they were executed very close to each other.

I think that with the code below, the second thread should wait until the first one is finished to start. Is this true? Also, what happens if for any reason thread 1 does not finish? Is there a way to set a timeout to interrupt it?

WifiInfo wifi = wifiManager.getConnectionInfo();
if (wifi == null) return;

WifiInfoFetch wifiInfo = new WifiInfoFetch(getApplicationContext(), wifi);
WifiApResults scanResults = new WifiApResults(getApplicationContext(), wifiManager.getScanResults());

FutureTask<String> futureWifiInfo = new FutureTask<>(wifiInfo);
FutureTask<String> futureScanResults = new FutureTask<>(scanResults);

ExecutorService executor = Executors.newFixedThreadPool(2);
try {
    executor.submit(futureWifiInfo).get();
    executor.submit(futureScanResults);
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}

Thanks!


texts: Getting database values grouped in an array

texts:
I have a database column with dates corresponding to sales orders. I get the count of orders in each month. Currently in my code, I use a switch statement. I know it is not a neat way of coding. So I need to know if there is any way I can do it more precisely. I need the output in such a way as below to form a chart in JavaScript.

$datayearly = array(
    'labels' => array('JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'),
    'series' => array(array(
        'name' => 'series-1',
        'data' => array($jan, $feb, $mar, $apr, $may, $jun, $jul, $aug, $sep, $oct, $nov, $dec)
    ))
);

Php Code for fetching from database and screenshot of the database.

$thisyear =  date("Y");
$jan=$sep=$feb=$mar=$apr=$may=$jun=$jul=$aug=$sep=$oct=$nov=$dec=0;
$year[0] =0;
$stmt = $conn1->prepare("SELECT * FROM salessummary WHERE dateoforder LIKE :key");
$stmt->execute(array('key' => "%{$thisyear}%"));
foreach ($stmt as $row) {
    $month = date('m', strtotime($row['dateoforder']));
    switch ($month) {
        case "01":
        $jan++;
        case "02":
        $feb++;
        case "03":
        $mar++;
        case "04":
        $apr++;
        case "05":
        $may++;
        case "06":
        $jun++;
        case "07":
        $jul++;
        case "08":
        $aug++;
        case "09":
        $sep++;
        case "10":
        $oct++;
        case "11":
        $nov++;
        case "12":
        $dec++;
    }
}
$high = max($jan, $feb, $mar, $apr, $may, $jun, $jul, $aug, $sep, $oct, $nov, $dec) + 10;
$datayearly = array(
    'labels' => array('JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'),
    'series' => array(array(
        'name' => 'series-1',
        'data' => array($jan, $feb, $mar, $apr, $may, $jun, $jul, $aug, $sep, $oct, $nov, $dec)
    ))
);
$temp = json_encode($datayearly);


texts:
This a solution Luhn algorithm for credit validation.

This algorithm is a basic one inspired by wikipedia. I mean no check for length, type, and so on. You can enhance the base code as you want it to be.

The listing code of the following fucntion is tested on MSSQL 2012:

IF OBJECT_ID('dbo.LuhnALGValidation') IS NOT NULL
BEGIN
    DROP FUNCTION dbo.LuhnALGValidation
    IF OBJECT_ID('dbo.LuhnALGValidation') IS NOT NULL
        PRINT '<<< FAILED DROPPING FUNCTION dbo.LuhnALGValidation >>>'
    ELSE
        PRINT '<<< DROPPED FUNCTION dbo.LuhnALGValidation >>>'
END
go
CREATE FUNCTION dbo.LuhnALGValidation
(
@Luhn VARCHAR(8000)
)
RETURNS BIT
AS
BEGIN
IF @Luhn LIKE '%[^0-9]%'
RETURN 0
DECLARE @Index SMALLINT,
@Multiplier TINYINT,
@Sum INT,
@Flag INT,
@temp TINYINT,
@Plus TINYINT
SELECT @Index = LEN(@Luhn),
@Multiplier = 1,
@Flag = 0,
@Sum = 0
WHILE @Index >= 1
BEGIN
    SELECT @temp = CAST(SUBSTRING(@Luhn, @Index, 1) AS TINYINT)
    IF @Flag = 1
    BEGIN
        SELECT @temp = 2 * CAST(SUBSTRING(@Luhn, @Index, 1) AS TINYINT)
        IF @temp > 9
        BEGIN
            SELECT @temp = @temp - 9
        END
    END

    SELECT @Sum = @Sum + @temp

    IF @Flag = 1
        SELECT @Flag = 0
    ELSE
        SELECT @Flag = 1
    SELECT @Index = @Index - 1
END
RETURN CASE WHEN @Sum % 10 = 0 THEN 1 ELSE 0 END
END
go
IF OBJECT_ID('dbo.LuhnALGValidation') IS NOT NULL
    PRINT '<<< CREATED FUNCTION dbo.LuhnALGValidation >>>'
ELSE
    PRINT '<<< FAILED CREATING FUNCTION dbo.LuhnALGValidation >>>'
go

I want it to work in database side. No matter in performance.

If you can help me to enhance this code.


texts:
I've been programming Clojure for a little while and recently started learning Common Lisp. One of my favorite things about Clojure is the threading operator ->, which greatly simplifies long chains of nested function calls. Naturally I wanted to have this in Common Lisp.

I found an implementation here:

(defmacro -> (x &rest args)
  (destructuring-bind (form &rest more)
      args
    (cond
      (more `(-> (-> ,x ,form) ,@more))
      ((and (consp form)
            (or (eq (car form) 'lambda)
                (eq (car form) 'function)))
       `(funcall ,form ,x))
      ((consp form) `(,(car form) ,x ,@(cdr form)))
      (form `(,form ,x))
      (t x))))

This uses a recursive macro expansion; I've read that it's better to use iteration over recursion in CL when you can, so I wrote my own version:

(defmacro -> (x &rest forms)
  (labels ((expand-form (x form)
             (if (consp form)
                 (if (or (eq (car form) 'lambda)
                         (eq (car form) 'function))
                     `(funcall ,form ,x)
                     `(,(car form) ,x ,@(cdr form)))
                 `(,form ,x))))
    (do ((forms forms (cdr forms))
         (x x (expand-form x (car forms))))
        ((not forms) x))))

I'm relatively new to Lisp so I don't know how to judge which way is better. Any comments, suggestions?

EDIT: I knew something was fishy! You don't have to use any looping constructs at all, a plain old reduce will cut it:

(defmacro -> (x &rest forms)
  (flet ((expand-form (x form)
           (cond
             ((atom form)
              `(,form ,x))
             ((member (car form) '(lambda function))
              `(funcall ,form ,x))
             (t
              `(,(car form) ,x ,@(cdr form))))))
    (reduce #'expand-form forms :initial-value x)))


texts:
I'm developing a game in Unity 5.3.5, I have a player statistics system with 10 different stats, as in probably every game the user is able to see the points put in each stats and also the benefit each stats is giving him. I have 2 panels with 2 text the first one is responsible for the points in each stats and the second one for the increase each stats is giving. The player has a class which holds all the stats in there and also implements <IEnumberable> so I can be able to iterate over this class picking all the different stats, I also have an enum which is used only for the displaying of those statistics and it's in such order that it matches the player's class that holds all the stats. Only 1 panel can be active at a time. That's how I'm updating the statistics info :

    private void UpdateStatusLabels(PanelType panelType)
    {
        List<Stats.Stats> playerStats = Player.BaseStats.ToList();
        string playerStatsText = string.Empty;
        Array values = Enum.GetValues(typeof(StatsOrders));
        string[] names = (from object value in values select value.ToString()).ToArray();
        for (int i = 0; i < names.Length; i++)
        {
            playerStatsText += panelType == PanelType.Stats
                ? names[i].SplitOnCapitalLetters() + @" : " + playerStats[i].Increase(playerStats[i].PointsInStats)
                : names[i].SplitOnCapitalLetters() + @" : " + playerStats[i].PointsInStats;
            playerStatsText += Environment.NewLine;
        }
        SetText(panelType == PanelType.Points ? panelPoints : panelStats, "EditorOnly", playerStatsText);
    }

    private static void SetText(GameObject inputGameObject, string textTag, string textToSet)
    {
        inputGameObject.GetComponentsInChildren<Text>().Single(comp => comp.tag == textTag).text = textToSet;
    }

here are some extra objects you might need :

public enum StatsOrders
{
    MagicPower,
    DebuffDuration,
    Defense,
    MagicDefense,
    CriticalPower,
    CriticalChance,
    Multistrike,
    CooldownReduction,
    Evasion,
    Resistance
}
private enum PanelType
{
    Stats,
    Points
}

private GameObject panelStats;
private GameObject panelPoints;

What concern's me is that it looks over-complicated, can the code be shorten or improved in some way ?


texts: DRYing two very similar SQL conditional inserts

texts:
I have two very similar SQL statements

INSERT INTO user_profile (user_id, setting_id, value)
    SELECT id, 18, true
    FROM users
        WHERE NOT EXISTS (
            SELECT user_id, setting_id FROM user_profile
            WHERE id=user_id AND setting_id=18);

INSERT INTO user_profile (user_id, setting_id, value)
    SELECT id, 16, true
    FROM users
        WHERE NOT EXISTS (
            SELECT user_id, setting_id FROM user_profile
            WHERE id=user_id AND setting_id=16);

I'm repeating everything except for the setting_id. Is there a way to combine these two statements?


texts:
How can I make this better?

import random

def roll():
    input("Press Enter to roll")
    dice = random.randint(1, 6) + random.randint(1, 6)
    print("You rolled a {}" .format(dice))
    return dice

def checkRoll(dice):
    if dice == 7 or dice == 11:
        print("You win")
        playAgain()
    elif dice == 2 or dice == 3 or dice == 12:
        print("You lose")
        playAgain()
    else:
        print("Time to try to roll the point")
        reRoll(dice)

def reRoll(point):
    dice = roll()
    if dice == point:
        print("You win")
        playAgain()
    elif dice == 7:
        print("You lose")
        playAgain()
    else:
        reRoll(point)
def play():
    print("Do you wanna play Craps? Y/n ")
    response = input(">>> ").lower()
    if response == "y":
        checkRoll(roll())
    else:
        input("ENTER to quit")

def playAgain():
    response = input("Play Again? Y/n >>>").lower()
    if response == "y":
        checkRoll(roll())
    else:
        input("ENTER to quit")

play()


texts: Create a C++ string using printf-style formatting

texts:
It's often convenient to use C-style printf format strings when writing C++.  I often find the modifiers much simpler to use than C++ I/O manipulators, and if I'm cribbing from existing C code, it helps to be able to re-use the existing format strings.

Here's my take on creating a new std::string given a format and the corresponding arguments.  I've given it an annotation so GCC can check the argument types agree when the format is a literal, but I don't know how to help other compilers.

I've provided a more memory-efficient version for C++17, which provides read/write access to the underlying array of a string.  My copy of CPP Reference still says "Modifying the character array accessed through data() has undefined behavior", but the Web version has been edited (May 2017) to indicate that it's only the const version that has that constraint.

For earlier standards (I require minimum C++11), we may need to allocate a temporary array, as we can't write to a string's data.  Unfortunately, this requires an extra allocation and copy.

#include <string>

std::string format(const char *fmt, ...)
#ifdef __GNUC__
    __attribute__ ((format (printf, 1, 2)))
#endif
    ;

// Implementation

#include <cstdio>
#include <cstdarg>

#if __cplusplus < 201703L
#include <memory>
#endif

std::string format(const char *fmt, ...)
{
    char buf[256];

    va_list args;
    va_start(args, fmt);
    const auto r = std::vsnprintf(buf, sizeof buf, fmt, args);
    va_end(args);

    if (r < 0)
        // conversion failed
        return {};

    const size_t len = r;
    if (len < sizeof buf)
        // we fit in the buffer
        return { buf, len };

#if __cplusplus >= 201703L
    // C++17: Create a string and write to its underlying array
    std::string s(len, '\0');
    va_start(args, fmt);
    std::vsnprintf(s.data(), len+1, fmt, args);
    va_end(args);

    return s;
#else
    // C++11 or C++14: We need to allocate scratch memory
    auto vbuf = std::unique_ptr<char[]>(new char[len+1]);
    va_start(args, fmt);
    std::vsnprintf(vbuf.get(), len+1, fmt, args);
    va_end(args);

    return { vbuf.get(), len };
#endif
}

// Test program

#include <iostream>
int main()
{
    std::clog << "'" << format("a")
              << "'" << std::endl;
    std::clog << "'" << format("%#x", 1337)
              << "'" << std::endl;
    std::clog << "'" << format("--%c--", 0) // an embedded NUL
              << "'" << std::endl;
    std::clog << "'" << format("%300s++%6.2f", "**", 0.0).substr(300)
              << "'" << std::endl;
}

void provoke_warnings()
{
    // warning: zero-length gnu_printf format string
    // [-Wformat-zero-length]
    std::clog << "'" << format("") << "'" << std::endl;

    // warning: format ‘%c’ expects argument of type ‘int’, but
    // argument 2 has type ‘const char*’ [-Wformat=]
    std::clog << "'" << format("%c", "bar") << "'" << std::endl;
}

I've compiled the code with both C++17 and C++11 compilers, and verified them both under Valgrind using this test program.

I'd welcome any comments on the code itself or on my testing.


texts: Deep filter value using functional programming principles

texts:
deepFilter function uses a predicate to filter properties which may be nested deeply in the given value (object or array). It returns filtered object or array.

The code works for most inputs (arbitrary levels of nesting and input without cyclic references). I'm more interested in comments on my approach to FP than correctness of the code. Though I wouldn't mind if you point a mistake.

const and = (f1, f2) => v => f1(v) && f2(v);

const or = (f1, f2) => v => f1(v) || f2(v);

const isArray = v => Array.isArray(v);

const isObject = v => typeof v === 'object' && v !== null;

const hasProps = v => Object.keys(v).length > 0;

const selector = (predicate, v1, v2) => v => (predicate(v) ? v1 : v2);

const isObjectOrArray = or(isArray, isObject);

const hasValue = and(isObjectOrArray, hasProps);

const initial = selector(isArray, [], {});

function deepFilter(value, predicate) {
  if (isObjectOrArray(value)) {
    return Object.keys(value).reduce((filtered, key) => {
      if (predicate(key)) {
        return { ...filtered, [key]: value[key] };
      }
      const v = deepFilter(value[key], predicate);
      return hasValue(v) ? { ...filtered, [key]: v } : filtered;
    }, initial(value));
  }
  return value;
}


texts:
I want to get the key from value / and value from key ,can anyone help to do in better way ? or can we implement the below code using java enum or spring or apache enumutils or java generic ?

Note : I used to get string from frond end(.jsp) and I want to store store this value into database table as integer.

Frond end  Database table
Admin   ---   1
Manager ---   2
Employee ---  3

import java.util.HashMap;
import java.util.Map;

public class   MyRole  {

    static HashMap<Integer,String> result= new HashMap<Integer,String>();
    static{
    result.put(1,"Admin");
    result.put(2,"Manager");
    }

    public static int getId(String role){
          Integer key=-1;
          for(Map.Entry entry: result.entrySet()){
                if(role.equals(entry.getValue())){
                    key = (Integer) entry.getKey();
                    break;
                }
            }

      return key;

    }
    public static String getRole(int id){
        return result.get(id);
    }

    public static void main(String args[]){

        String result=MyRole.getRole(1);
        System.out.println("role name"+result);
        int roleId=MyRole.getId("Admin");
        System.out.println("role id "+roleId);
    }
}

I want make sure , whether the above program is fine or can we achieve via Java enum or generic or spring api or apache enumutils api ?


texts: Determine if subset in int array adds up to a given input integer

texts:
Given a set of non-negative integers, and a value sum, determine if there is a subset
of the given set with sum equal to given sum. On similar lines, Partition problem is to determine whether a given set can be partitioned into two subsets such that the sum of
elements in both subsets is same.

Complexity:

\$O(n \times m)\$, \$n\$ is the array length and \$m\$ is the sum.

Looking for code-review, optimizations and best practices.

public final class SubSetSum {

    private SubSetSum() {}

    /**
     * Partition problem is to determine whether a given set can be partitioned into two subsets such that the sum of
     * elements in both subsets is same.
     *
     * A negative value in array would case unpredicatable results.
     *
     * Examples
     *
     *  arr[] = {1, 5, 11, 5}
     *   Output: true
     *   The array can be partitioned as {1, 5, 5} and {11}
     *
     * arr[] = {1, 5, 3}
     * Output: false
     *   The array cannot be partitioned into equal sum sets.
     *
     * @param a     the input array
     * @return      true if array can be partitioned into subsets, else false.
     */
    public static boolean canPartition(int[] a) {
        int sum = 0;
        for (int i = 0; i < a.length; i++) {
            sum  = sum + a[i];
        }
        if ((sum % 2) == 1) return false;

        return subsetSum(a, sum % 2);
    }

    /**
     * Given a set of non-negative integers, and a value sum, determine if there is a subset
     * of the given set with sum equal to given sum.
     *
     *  Examples: set[] = {3, 34, 4, 12, 5, 2}, sum = 9
     *  Output:  True  //There is a subset (4, 5) with sum 9.
     *
     *  A negative value in array would case unpredicatable results.
     *
     * @param a     the input array
     * @param sum   the input sum
     * @return      true if some subset of elements add up to the sum.
     */
    public static boolean subsetSum(int[] a, int sum) {

        boolean[][] m = new boolean[sum + 1][a.length + 1];
        for (int j = 0; j < m[0].length; j++) {
            m[0][j] = true;
        }

        for (int i = 1; i < m.length; i++) {
            for (int j = 1; j < m[0].length; j++) {
                m[i][j] = m[i][j - 1];
                if (i >= a[j - 1]) {
                    m[i][j] = m[i][j - 1] || m[i - a[j-1]][j-1];
                }
            }
        }

        return m[sum][a.length];
    }
}

public class SubSetSumTest {

    @Test
    public void testCanPartition() {
        int[] a1 = {1, 2, 3, 4};
        assertTrue(SubSetSum.canPartition(a1));

        int[] a2 = {1, 2, 3, 4, 5};
        assertFalse(SubSetSum.canPartition(a2));

        int[] a3 = {1, 2, 3, 4, 5, 6};
        assertFalse(SubSetSum.canPartition(a3));

        int[] a4 = {1, 2, 3, 4, 5, 7};
        assertTrue(SubSetSum.canPartition(a4));
    }

    @Test
    public void testSubsetSum() {
        int[] a = {1, 3, 8, 9};
        assertTrue(SubSetSum.subsetSum(a,  1));
        assertFalse(SubSetSum.subsetSum(a,  2));
        assertTrue(SubSetSum.subsetSum(a,  3));
        assertTrue(SubSetSum.subsetSum(a,  4));
        assertFalse(SubSetSum.subsetSum(a,  5));
        assertFalse(SubSetSum.subsetSum(a,  6));
        assertFalse(SubSetSum.subsetSum(a,  7));
        assertTrue(SubSetSum.subsetSum(a,  8));
        assertTrue(SubSetSum.subsetSum(a,  9));
        assertTrue(SubSetSum.subsetSum(a, 10));
        assertTrue(SubSetSum.subsetSum(a, 11));
        assertTrue(SubSetSum.subsetSum(a, 12));
        assertTrue(SubSetSum.subsetSum(a, 12));
        assertTrue(SubSetSum.subsetSum(a, 13));
        assertFalse(SubSetSum.subsetSum(a, 14));
        assertFalse(SubSetSum.subsetSum(a, 15));
        assertFalse(SubSetSum.subsetSum(a, 16));
        assertTrue(SubSetSum.subsetSum(a, 17));
        assertTrue(SubSetSum.subsetSum(a, 18));
        assertFalse(SubSetSum.subsetSum(a, 19));
        assertTrue(SubSetSum.subsetSum(a, 20));
        assertTrue(SubSetSum.subsetSum(a, 21));
    }

}


texts:
I wrote an encryption/decryption algorithm for the Caesar Cipher. It works fine, but I'm curious if there are any constructive critiques, tips, tricks, comments, or advice anyone may have on how the code operates, performs, looks, etc.

# Caesar Cipher
def chooseMode():
    while True:
        mode = raw_input("\nChoose a mode (encryption or decryption):\n 1) Encrypt \n 2) Decrypt\n 3) Brute Force\n\n")
        if mode in ['1', '2', '3']:
            return mode

def collectMessage():
    message = raw_input("Enter the message you would like to translate:\n\n")
    return message

def collectKey():
    while True:
        key = raw_input("What is the key for your message? (Enter a number from 0 to 26): \n")
        try:
            if int(key) in range(27):
                return int(key)
            else:
                print("Please enter an integer between 0 and 26.\n")
                continue
        except ValueError:
            print("Please enter an integer between 0 and 26.\n")
            continue

def translateMessage(text, cipher_mode, caeser_key):
    translation = ''
    # If decrypting, convert key to negative.
    if cipher_mode == '2':
        caeser_key = -caeser_key

    for symbol in text:
        # Convert only Alphabetical Symbols
        if symbol.isalpha():
            num = ord(symbol)

            # Shift num down to 1 through 26 for more easier to visualize modulous.
            # Then Apply the Key; then Modulate; then Move Back Up; then Build into Chr and Translation
            if symbol.isupper():
                num -= ord('A')
                num += caeser_key
                num %= 26
                num += ord('A')
                translation += chr(num)

            else:
                num -= ord('a')
                num -= caeser_key
                num %= 26
                num += ord('a')
                translation += chr(num)
        else:
            translation += symbol
    return translation

def bruteForce(text, cipher_mode):
    if cipher_mode == '3':
        for index in range(26):
            print "A Caeser Key of ", str(index), "reveals:\t", translateMessage(text, cipher_mode, 26 - index)
        exit()
    else:
        return None

choice_of_mode = chooseMode()
entered_message = collectMessage()

bruteForce(entered_message, choice_of_mode)

entered_key = collectKey()
final_form = translateMessage(entered_message, choice_of_mode, entered_key)
print final_form


texts: Removing duplication in AngularJS Factory

texts:
I have multiple API calls so I created a service however I would like to find a way to remove the duplication

myAppServices.factory('apiService', function ($http, $q) {
    return {
        getDocuments: function () {
            return $http.get('/api/autodeskdocuments/1')
                .then(function (response) {
                    if (typeof response.data == 'object') {
                        return response.data;
                    } else {
                        // invalid response
                        return $q.reject(response.data);
                    }
                }, function (response) {
                    // something went wrong
                    return $q.reject(response.data);
            });
        },

        getSharePoint: function () {
            return $http.get('/api/sharepointheaderdata/1')
                .then(function (response) {
                    if (typeof response.data == 'object') {
                        return response.data;
                    } else {
                        // invalid response
                        return $q.reject(response.data);
                    }
                }, function (response) {
                    // something went wrong
                    return $q.reject(response.data);
                });
        }
    };
});

As you can see both functions has some duplication with the .then(...) Any suggestions as to make this cleaner?


texts: Monoalphatic and Polialphabetic cipher in Ruby

texts:
This code encrypts a text with  mono-alphabetic and poli-alphabetic substitutions ciphers.

For further info see:

Mono-alphabetic/Caesar Cipher
Poli-alphabetic cipher

require 'arrow_test'

ALPHABET = ("a".."z").to_a

# Moves a letter forward in the alphabet by
# the given key wrapping around.
#
#
# shift('a', 2) #=> 'c'
#
#
#
# shift('z', 2) #=> 'b'
#

def shift(letter, key)
  ALPHABET[ (ALPHABET.index(letter) + key) % ALPHABET.length]
end

# Encrypts a text using by shifting all its letters by
# the given key. All characters that are not lower and alphabetic
# are deleted.
#
#
# monoalphabetic_cipher('abcd', 2) #=> 'cdef'
#
#
#
# monoalphabetic_cipher('cdef', 2, decode=true) #=> 'abcd'
#

def monoalphabetic_cipher(text, key, decode=false)
  text
      .chars
      .select { |char| ALPHABET.include?(char) }
      .map {|char| shift(char, (decode ? 26 - key : key) )}
      .join
end

# Given a word, returns the positions of its letters
# in the aplhabet.
#
#
# word_to_alphabetic_positions('abcz') #=> [0, 1, 2, 25]
#

def word_to_alphabetic_positions(word)
  word.chars.map {|char| ALPHABET.index(char) }
end

# Encrypts a text by shifting each letter by
# the amount specified by the corresponding key number,
# wraps around over the key if the plain text is longer than it.
#
#
# polialphabetic_cipher('abcd', [1,3,4,0]) #=> 'begd'
#
#
#
# polialphabetic_cipher('begd', [1,3,4,0], false, decode=true) #=> 'abcd'
#

def polialphabetic_cipher(text, keys, keys_as_word=false, decode=false)
  keys = word_to_alphabetic_positions(keys) if keys_as_word
  text
      .chars
      .select { |char| ALPHABET.include?(char) }
      .each_with_index
      .map do |char, index|
        key = keys[index % keys.length]
        shift(char, (decode ? 26 - key : key))
      end
      .join
end

arrow_test


texts: Unit testing async functions in node/express

texts:
I am looking for the cleanest pattern to test middleware that contains async code using Mocha, Node's assert library, and Sinon. Here's a paired-down example of the function I'm testing.

function some_middleware(req,res, next){
    var input = req.body;
    if (some_test(input)) {
        lib.async_function(input)
            .then((returned_object) => {
                res.locals.data = returned_object;
                res.render('stop-list');
            })
            .catch((err) => {
                res.render('message', {message: err})
            })
        }
    else{ next() }
}

None of these functions return the promise returned by lib.async_function(). Returning the promise would make testing in Mocha much easier. We could just change:

...
return lib.async_function(input)
...

we could test like this use:

it('Should responsd set locals.data to fetched object', function(){
    // Stubs -- most of this goes in a beforeEach block but here for the example
    var res = {render: sinon.stub(), locals: {}}
    var req = {body: "returned_value" }
    var next = sinon.stub()
    var async_stub = sinon.stub('lib', async_function)
    async_stub.resolves(fakedata.stoptimes)

    next.throws("Next Shouldn't be called")
    return some_middleware(req, res, next)
    .then((ret) => assert.equals(res.locals.data, "returned_value" ))

})

Question one: Is it a bad practice to insist functions return a value, which isn't required, simply to make testing easier? Are there any side effects of this?

If making all the async middleware functions return a promise is a bad idea, we can still design tests, but they start to get a little wordy. For example, we could use the stubbed out res.render() and test like this:

it('Should responsd set locals.data to fetched object', function(done){
    // Stubs
    var res = {locals: {}}
    var req = {body: "returned_value" }
    var next = sinon.stub()
    var async_stub = sinon.stub('lib', async_function)
    async_stub.resolves(fakedata.stoptimes)

    next.throws("Next Shouldn't be called")
    res.render = result => {
        try {
            assert.equals(res.locals.data, "returned_value" )
            done()
        } catch (e) {done(e)}
    }
    some_middleware(req, res, next)

})

We need to wrap the assert in a try/catch block otherwise done() never gets called when the test fails and the test times-out. This seems like a lot of code for such a simple test. Which leads to:

Question two: is there a better way or an accepted best-practice that gracefully handles test failures?


texts: Loop through column cells and compare value with a Collection

texts:
I have a Collection of 166 elements:

Dim MyCollection As New Collection
MyCollection.Add ("%")
MyCollection.Add ("%O")
MyCollection.Add ("D")
MyCollection.Add ("CMS")
...

I want to compare them to the value of the cells in a column. If the value of a cell is not in MyCollection, I change the background color to red.

For i = 2 To lastRow
    IsValid = False
    For Each Unit In MyCollection
        If Range("A" & i).value = Unit Then
            IsValid = True
        End If
    Next Unit
    If Not IsValid Then
        Range("A" & i).Interior.Color = 192
    End If
Next i

However, it takes a long time to finish executing when there is a large number of row and I would like to improve this. Maybe by using something else than a Collection and some VBA functions.


texts: ServiceBus QueueClient and TopicClient object resue

texts:
I'm writing an Azure function using Visual Studio (multi-layers project), where I'm managing all Azure ServiceBus related code in one class.

(follow-up)

public class MessageBroker : IMessageBroker, IDisposable
{
    private readonly IAppConfiguration appConfiguration;
    private TopicClient topicClient;
    private QueueClient queueClient;

    public MessageBroker(IAppConfiguration appConfiguration)
    {
        this.appConfiguration = appConfiguration;
    }

    public async Task SendMessageToQueueAsync(string queueName, string message)
    {
        this.queueClient = QueueClient.CreateFromConnectionString(appConfiguration.BrokerConnectionString, queueName);
        BrokeredMessage brokeredMessage = new BrokeredMessage(message);
        await queueClient.SendAsync(brokeredMessage);
    }

    public async Task SendMessageToTopicAsync(string topicName, string message)
    {
        this.topicClient = TopicClient.CreateFromConnectionString(appConfiguration.BrokerConnectionString, topicName);
        BrokeredMessage brokeredMessage = new BrokeredMessage(message);
        await topicClient.SendAsync(brokeredMessage);
    }

    public void Dispose()
    {
        this.queueClient.Close();
        this.topicClient.Close();
    }
}

I use the [Inject] attribute to use DI in the Azure function. Whenever I need to send any message into a queue or topic, I inject IMessageBroker and call thr SendMessageToQueueAsync method. I see a Microsoft recommendation here to reuse QueueClient and TopicClient.

IMessageBroker is Singleton in my DI configuration.

Will the QueueClient.CreateFromConnectionString method create a new object every time or reuse a connection internally based on the same ConnectionString or queuename?

Is there anything I can do better on this code?


texts: Find if an array is arithmetic or geometric

texts:
This seems to be working fine. I am pretty sure there is a better way to do it. How can my code be improved performance-wise? The main thing bothering me is the nested for-loop.

function arithGeo (arr) {
    var isGeometric = false;
    var isArithmetic = false;
    var diff = arr[2] - arr[1];
    var ratio = arr[2] / arr[1];
    for (var i = 0; i < arr.length - 1; i++) {
        var j = i + 1;
        if (diff !== arr[j] - arr[i]) {
            for (var k = 0; k < arr.length - 1; k++) {
                var l = k + 1;
                if (ratio !== arr[l] / arr[k]) {
                    break;
                } else if (l === arr.length-1) {
                    isGeometric = true;
                    break;
                }
            }
        } else if (j === arr.length - 1) {
            isArithmetic = true;
        }
    }

    if (isGeometric === true) {
        return "geometric";
    } else if (isArithmetic === true) {
        return "arithmetic";
    }
    else {
        return -1;
    }
}

console.log(arithGeo([2,4,6,8]));
console.log(arithGeo([2,6,18,54]));
console.log(arithGeo([2,6,1,54]));


texts: Optimizing Dijkstra on grid Python (Microsoft Interview)

texts:
Given a square grid of size N, each cell of which contains integer cost which represents a cost to traverse through that cell, we need to find a path from top left cell to bottom right cell by which the total cost incurred is minimum.
From the cell (i,j) we can go (i,j-1), (i, j+1), (i-1, j), (i+1, j).
Note: It is assumed that negative cost cycles do not exist in the input matrix.
Example 1:

Input: grid = {{9,4,9,9},{6,7,6,4},
{8,3,3,7},{7,4,9,10}}
Output: 43
Explanation: The grid is-
9 4 9 9
6 7 6 4
8 3 3 7
7 4 9 10
The minimum cost is-
9 + 4 + 7 + 3 + 3 + 7 + 10 = 43.

My working code:
global INT_MAX

# value of n is passed by the driver along with the grid
INT_MAX = 3 ** 38

class Solution:

    # <- this returns the minVertex's co-orinates ->
    def minimumVertex(self,distMat,visited):
        minVertexi = 0
        minVertexj = 0
        max1 = INT_MAX
        for i in range(n):
            for j in range(n):
                if distMat[i][j] < max1 and visited[i][j] == False:
                    max1 =  distMat[i][j]
                    minVertexi = i
                    minVertexj = j
        return minVertexi, minVertexj

    def minimumCostPath(self, grid):

        # <- visited matrix is created with all False ->
        visited = []
        for i in range(n):
            eachRow = []
            for j in range(n):
                eachRow.append(False)
            visited.append(eachRow)
        # <- distMat is created with all values initialized with INT_MAX ->
        distMat = []
        for i in range(n):
            eachRow1 = []
            for j in range(n):
                eachRow1.append(INT_MAX)
            distMat.append(eachRow1)
        distMat[0][0] = grid[0][0]

        drow = [-1, 1, 0, 0]
        dcol = [0, 0, -1, 1]

        for _ in range(n):
            for currj in range(n):
                mini,minj = self.minimumVertex(distMat,visited)

                visited[mini][minj] = True
                for k in range(len(drow)):
                    nbri = mini + drow[k]
                    nbrj = minj + dcol[k]
                    # print("outside nbri = ",nbri,"outside nbrj = ",nbrj)
                    if nbri >=0 and nbrj >= 0 and nbri < n and nbrj < n:
                        if visited[nbri][nbrj] == False:
                            # print("inside nbri = ",nbri,"inside nbrj = ",nbrj)

                            if distMat[nbri][nbrj] >  distMat[mini][minj] + grid[nbri][nbrj]:
                                distMat[nbri][nbrj] = distMat[mini][minj] + grid[nbri][nbrj]
        return distMat[n-1][n-1]

Expected Time Compelxity: O(n2*log(n))
Expected Auxiliary Space: O(n2)
Problem with my code:
My logic is alright however it is exceeding the time limit, how do I optimize it?
NOTE: The grid is always a square grid and N (dimension) is passed to the function along with the grid. I took N = 4 here because I was debugging the code for a single test case.


texts:
I am fresh at OOP and I am curious if the code below is object oriented and can be improved:

class cTitleBreadcrumb {

public function __construct($sAction, $sItem){
    $this->sAction = $sAction;
    $this->sItem = $sItem;
}

public function displayAction(){
    if($this->checkUrlAction($this->sAction) === true){
        return $this->sAction;
    }
}
public function displayItem(){
    if($this->checkUrlItem($this->sItem) === true){
        return $this->sItem;
    }
}
private function checkUrlAction($sAction){

    if($sAction == 'insert' || $sAction == 'view' || $sAction == 'update' || $sAction == 'delete'){
        return true;
    }
}

private function checkUrlItem($sItem){
    if($sItem == 'imagelist' || $sItem == 'mkdir' || $sItem == 'rdir'){
        return true;
    }
    else{
        $objShowPDO = new mShowPDO();
        $result = $objShowPDO->allTables();
        while($array = $result->fetch()){
            if($array[0] == $this->sItem){
                return true;
            }
        }
    }
}

$objTitleBreadcrumb = new cTitleBreadcrumb($sAction,$sItem);

echo ucfirst($objTitleBreadcrumb->displayAction());

echo ucfirst($objTitleBreadcrumb->displayItem());


texts:
I am teaching a python class to some high school seniors. I was thinking of doing an "oracle" game where the computer would come up with a number, and the player would guess it. These are brand new coders, and I'll teach them what they need to know to get there, but is this a good first project? I have my code here as my implementation of this game. I want to make sure that I don't teach them anything bad or give them bad habits.

My software requirements are:

Must generate a random (or psuedo-random) number
Must import a library
Must use a loop
Must take user input
Must tell the user to guess higher or lower

# imports
import random
import time
import sys
import os

# set global variables
MIN_NUMBER = 1
MAX_NUMBER = 10

# important functions
def get_random(min, max):
    print "Coming up with a number."
    time.sleep(2)
    random_number = random.randint(min, max)
    print "Got it!"
    return random_number

def to_int(x):
    try:
        x = int(x)
        return x
    except ValueError:
        print "That is not a whole number."
        return False

def how_close(guess, right_answer):
    return right_answer - guess

def hi_low_done(delta):
    if delta < 0:
        print "Guess lower."
        return False
    elif delta > 0:
        print "Guess higher."
        return False
    else:
        print "You got it!"
        return True

# main Program

#clear screen
os.system('cls')  # on windows
print "Welcome. I am the Oracle."
print "I will think of a number between %s and %s. Guess it and you will win!" % (MIN_NUMBER, MAX_NUMBER)

while True:
    user_answer = raw_input("Ready? <y/n> ")
    if user_answer.lower() == 'y' or user_answer.lower() == 'yes':
        print "Great! Let's go."
        break;
    elif user_answer.lower() == 'n' or user_answer.lower() == 'no':
        print "Okay. Consult the Oracle when you are ready."
        sys.exit()

oracles_number = get_random(MIN_NUMBER, MAX_NUMBER)

number_of_guesses = 0
while True:
    number_of_guesses = number_of_guesses + 1
    user_answer = raw_input("\nGuess> ")
    user_answer = to_int(user_answer)
    # if user answer is outside min max... else...
    if user_answer:
        delta = how_close(user_answer, oracles_number)
        done = hi_low_done(delta)
        if done:
            break;

print "It took you %s guesses to guess my number." % (number_of_guesses)

I guess my concerns with my code are:

Is this simple enough? It isn't the first thing they will code, but the first project they will do. (maybe group project?)
Did I make any blatant errors or "In python, you should do this instead" errors? Python isn't my first language so I'm not sure.

I have created a gist file with my most up-to-date version of this.


texts: External variable in callback for chunk()

texts:
I am trying to implement search in Laravel. I want to search on models. Since there can be many records in the database, I am trying the chunk function.

public function searchLeads($param)
    {
        $results = array();

        // get all leads
        Lead::chunk(100, function($leads) use ($results, $param) {
            // search in name
            $results = array_merge($results, $this->repository->searchInName($leads, $param));

            // search in email
            $results = array_merge($results, $this->repository->searchInEmail($leads, $param));

           // and so on ...
    }

    // eliminate duplicates
    $collection = collect($results);
    $collection = $collection->unique();

    $results = $collection->all();

    dd($results);
    // return $results;
}

Note: The searchIn... functions return array of results and are working as expected.

When I try the above code, I get an empty array. So I changed the following line (added a reference & to $results).

Lead::chunk(100, function($leads) use (&$results, $param) {

Now I get the expected output.

Am I doing this the correct way? Have I stumbled upon the right solution, or am I missing something that might introduce bugs in the code?


texts:
I have a method in a Python app to write a list of records to a CSV file.  Each record is a "football player", which is really just a dictionary.  But one of the dictionary items contains a list of weekly scores.  I want to write out to CSV a record for each player, and then flatten the list of scores and write that out, too.

My code:

def write_csv_file(filename, year, list_of_players):
    print str(datetime.now()) + ' Writing file {0}'.format(OUTPUT_CSV_PATH + filename + '.csv')
    print list_of_players
    with open(OUTPUT_CSV_PATH + filename + '.csv', 'w+') as f:

        writer = csv.writer(f, quotechar='"', quoting=csv.QUOTE_MINIMAL, lineterminator = '\n')

        writer.writerow(['YEAR', 'FILENAME', 'PLAYER_KEY', 'PLAYER_NAME', 'SEASON_TOTAL', 'CALCULATED_SEASON_TOTAL', 'MEAN', 'MEDIAN', 'STD_DEVIATION', 'CV',
            'WK1', 'WK2', 'WK3', 'WK4', 'WK5', 'WK6', 'WK7', 'WK8', 'WK9', 'WK10', 'WK11', 'WK12', 'WK13', 'WK14', 'WK15', 'WK16'])
        for item in list_of_players:
            writer.writerow([year, filename, item['player_key'], item['player_name'], item['season_total'],
                item['calculated_season_total'], item['mean'], item['median'], item['std_deviation'], item['coefficient_of_variation'],
                #item['performance_score'],
                item['scores'][0],
                item['scores'][1],
                item['scores'][2],
                item['scores'][3],
                item['scores'][4],
                item['scores'][5],
                item['scores'][6],
                item['scores'][7],
                item['scores'][8],
                item['scores'][9],
                item['scores'][10],
                item['scores'][11],
                item['scores'][12],
                item['scores'][13],
                item['scores'][14],
                item['scores'][15]
                ])

It's the handling of item['scores'] that I'm sure there's a better way.  I tried getting a list comprehension to work but never could get it going.

How can I do this better?


texts:
I'm reading the awesome Head First Design Patterns book. As an exercise I converted first example (or rather a subset of it) to Python. The code I got is rather too simple, i.e. there is no abstract nor interface declarations, it's all just 'classes'. Is that the right way to do it in Python? My code is below, original Java code and problem statement can be found at http://books.google.com/books?id=LjJcCnNf92kC&pg=PA18

class QuackBehavior():
    def __init__(self):
        pass
    def quack(self):
        pass

class Quack(QuackBehavior):
    def quack(self):
        print "Quack!"

class QuackNot(QuackBehavior):
    def quack(self):
        print "..."

class Squeack(QuackBehavior):
    def quack(self):
        print "Squeack!"

class FlyBehavior():
    def fly(self):
        pass

class Fly():
    def fly(self):
        print "I'm flying!"

class FlyNot():
    def fly(self):
        print "Can't fly..."

class Duck():
    def display(self):
        print this.name

    def performQuack(self):
        self.quackBehavior.quack()

    def performFly(self):
        self.flyBehavior.fly()

class MallardDuck(Duck):
    def __init__(self):
        self.quackBehavior = Quack()
        self.flyBehavior = Fly()

if __name__ == "__main__":
    mallard = MallardDuck()
    mallard.performQuack()
    mallard.performFly()
    mallard.flyBehavior = FlyNot()
    mallard.performFly()


texts: Listing all numbers that are more composite than every number less than it

texts:
This code is my first naive attempt at writing a program that lists all numbers less than a given value that are more composite (have more divisors) than any number less than that number (for example, 12 is more composite than any number less than it).

def composite_count(limit):
    answer = []
    most_divisors = 0
    for i in range(limit):
        tally = 0
        for j in range(i):
            if not (i + 1) % (j + 1):
                tally += 1
        if tally > most_divisors:
            most_divisors = tally
            answer.append((i + 1))
    return answer

After running the program a few times, I started to see some patterns like the fact that all of the listed answers were even, that all answers greater than 12 are divisible by 12, or that all answers greater than 60 are divisible by 60. I also ran some tests involving prime factorization and found that although the more composite numbers do not always have more prime factors, the sum of their prime factors are always larger. Despite all this information I was not able to figure out any changes to the algorithm that would create significant time saves.

Can someone please help me make this code meaningfully faster?


texts:
This works fine and returns an object from a nested "structure" by Id.

I would like to know if you could suggest a better approach, possible a faster one.

<script>
var data = {
    item: [
        {
            itemNested: [
                {
                    itemNested2: [{
                        id: "2"
                    }
                    ]
                }
            ]
        }
    ]
};

function findById(obj, id) {
    var result;
    for (var p in obj) {
        if (obj.id === id) {
            return obj;
        } else {
            if (typeof obj[p] === 'object') {
                result = findById(obj[p], id);
                if (result) {
                    return result;
                }
            }
        }
    }
    return result;
}

var result = findById(data, "2");
console.log(result);
</script>


texts: Is this a good and simple example for Singleton Pattern

texts:
This is a scenario where we keep a single instance(as in Singleton Pattern) to get the configuration of an application.

Below is the main class and i set values to the configuarion values here and call the methods of the other classes to check if they are getting the correct values.

public class A{
    public static void main(String []args){
        System.out.println("My Singleton example");
        System.out.println("Setting values to configs\n");
        configs conf = configs.getInstance();
        conf.setName("Home Page");
        conf.setUrl("www.google.com");

        B.showConfigValues();
        C.showConfigValues();

    }
}

Below is the singleton class.

public class configs{

    private static configs appConfig;
    private String name;
    private String url;

    private configs(){}

    public static configs getInstance(){
        if( appConfig == null){
            appConfig = new configs();
        }
        return appConfig;
    }

    public void setUrl(String url){
        this.url = url;
    }

    public void setName(String name){
        this.name = name;
    }

    public String getUrl(){
        return url;
    }

    public String getName(){
        return name;
    }
}

Below is class B and C. They access the configuration values in their methods.

public class B{

    public static void showConfigValues(){
        configs conf = configs.getInstance();
        System.out.println("Geting configs in Class B");
        System.out.println("url : "+conf.getUrl());
        System.out.println("name : "+conf.getName()+"\n");
    }
}

public class C{

    public static void showConfigValues(){
        configs conf = configs.getInstance();
        System.out.println("Geting configs in Class C");
        System.out.println("url : "+conf.getUrl());
        System.out.println("name : "+conf.getName()+"\n");
    }
}

Below is the output.

$ java A
My Singleton example
Setting values to configs

Geting configs in Class B
url : www.google.com
name : Home Page

Geting configs in Class C
url : www.google.com
name : Home Page

My question is, is this a good example to explain the singleton pattern?


texts: String encryption function in admin section

texts:
I have been using this function locally to encrypt strings for example a username.

If the user successfully logged in, place the encrypted username into a session, decrypt the username in the admin section and use for various things.

Is it a strong method and are there any security concerns with the way I'm using it?

Cipher Function:

    public function cipher($string, $method) {
        $key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

        if($method === 1) {
            $string = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_CBC, $iv);
            $string = $iv . $string;
            $encryptedString = base64_encode($string);
    return trim($encryptedString, "\0");
    }
        if($method === 2) {
            $string = base64_decode($string);
            $iv_dec = substr($string, 0, $iv_size);
            $ciphertext_dec = substr($string, $iv_size);
            $decryptedString = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);
    return trim($decryptedString, "\0");
        }
    }

Function Usage:

//Encrypt
$_SESSION['username'] = $backend->cipher($username, 1)

// Decrypt
echo $backend->cipher($_SESSION['username'], 2)


texts:
I just started using Laravel 4. I read some tutorials on how to implement CRUD in Laravel, and I was able to develop a portion of it. What I am going to show you is more on Controller and Eloquent ORM.

I have here 2 models "Group" which can only have one Country, but Country can be assigned to different Group ("one to many").

Group Model

class Group extends Eloquent
{
    protected $table = 'group';
    protected $guarded = array('group_id');
    protected $primaryKey = 'group_id';

    public function country()
    {
        return $this->belongsTo('country', 'country_id');
    }
}

Country Model

class Country extends Eloquent
{
    protected $table = 'country';
    protected $primaryKey = 'country_id';

    public function group() {
        return $this->hasMany('group', 'country_id');
    }
}

In my controller, I have index() function which accepts user search filter and pagination request.

Group Controller

public function index()
{
    // search variables here
    $s_name = Input::get("s_name");
    $s_status = Input::get("s_status");

    // order variables here
    $sortBy = Input::get("sort_by");
    $orderBy = Input::get("order_by");

    // get all the groups
    $groups = Group::with('country')
        ->join('country', 'country.country_id', '=', 'group.country_id');

    // search conditions
    $groups = $groups->whereIn('group_status', array(ACTIVE, INACTIVE));
    if (!empty($s_name)) {
        $groups = $groups->where('group_name', 'LIKE', "%$s_name%");
    }

    if (!empty($s_status)) {
        $groups = $groups->where('group_status', 'LIKE', "%$s_status%");
    }

    // order
    if (!empty($sortBy)) {
        $orderBy = (empty($orderBy)) ? ASCENDING : $orderBy;
        if ($sortBy == "o_name") {
            $groups = $groups->orderBy('group_name', $orderBy);

        } else if ($sortBy == "o_country") {
            $groups = $groups->orderBy('country_short_name', $orderBy);

        } else if ($sortBy == "o_status") {
            $groups = $groups->orderBy('group_status', $orderBy);

        }
    } else {
            $groups = $groups->orderBy('group.created_at', DESCENDING);

    }

    $groups = $groups->paginate(PAGINATION_LIMIT);
}


texts: Find all local maxima in a one-dimensional array

texts:
I implemented the following class (it works) and I just want to hear your opinions about best practices and what can be improved. The idea was to do it using mostly arrays.

The class just finds the peak elements in an array with respect to their neighbors. The first element and the last element are ignored.

Example: {3, 15, 5, 20, 10}
Answer:  {15, 20}

package findpeak;

import java.util.ArrayList;
import java.util.List;

public class ArrayPeak
{
    private final int[] ARRAY;
    private final int LEN;
    private static final int IGNORE_FIRST_POSITION = 0;
    private final int IGNORE_LAST_POSITION;

    public ArrayPeak(int[] array)
    {
        this.ARRAY = array;
        this.LEN = this.ARRAY.length;
        this.IGNORE_LAST_POSITION = this.LEN - 1;
    }

    public List<Integer> findPeaks()
    {
        List<Integer> peaks = new ArrayList<>();
        for (int position = 0; position < LEN; position++)
        {
            int output = 0;
            if (position != IGNORE_FIRST_POSITION && position != IGNORE_LAST_POSITION)
            {
                int[] trippleArray =
                {
                    ARRAY[position - 1], ARRAY[position], ARRAY[position + 1]
                };
                output = checkPeak(trippleArray);
            }
            peaks.add(output);
        }

        return filterZeros(peaks);
    }

    private static int checkPeak(int[] inputArray)
    {
        int peak = 0;
        if (inputArray[1] > inputArray[0] && inputArray[1] > inputArray[2])
        {
            peak = inputArray[1];
        }
        return peak;
    }

    private static List<Integer> filterZeros(List<Integer> list)
    {
        List<Integer> filteredList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++)
        {
            if (list.get(i) != 0)
            {
                filteredList.add(list.get(i));
            }
        }
        return filteredList;
    }
}


texts:
I wrote an email syncing program in my ASP.NET MVC website that syncs e-mails from multiple e-mail accounts to my database.

Each e-mail account has to be independent from other accounts and they have to run asynchronously.

Are there are any issues with my code such as efficiency, bugs or can there be made improvements?

   public void Start()
    {
        new Thread(StartSyncing).Start();
    }

   private void StartSyncing()
    {
        foreach (var emailAccount in _emailAccountRepository.GetList())
        {
            // Create a local copy
            EmailAccount copyEmailAccount = emailAccount;

            // Start a new thread for each email account
            new Thread((x => SyncAccount(copyEmailAccount))).Start();
        }
    }

   private void SyncAccount(EmailAccount emailAccount)
    {
        // Sync forever
        while (true)
        {
            // Set the next syncing date
            _nextSyncingDate = DateTime.Now.AddMinutes(5);

            // Create a fresh start for the database context
            InitRepositories();

            // Connect to the mail server
            using (var emailProvider = new ReceiveEmailProvider(emailAccount.Email,
                emailAccount.Password, emailAccount.Host, emailAccount.Port, emailAccount.Secure))
            {
                // For each email
                for (int emailCounter = emailProvider.GetAmountEmails(); emailCounter > 0; emailCounter--)
                {
                    // As long the email is new
                    while (IsNewEmail(emailCounter))
                    {
                        // Get email
                        var email = emailProvider.GetEmail(emailCounter, emailAccount.Id);

                        // Check if the email isn't spam
                        if (!IsSpam(GetEmailDomain(email.FromEmail), emailAccount.User.UserId))
                        {
                            // Add the new email
                            var dbEmail = AddNewEmail(email, emailAccount.Id, emailCounter);

                            // Add email to category
                            AddEmailToCategory(emailAccount.User.UserId, dbEmail);
                        }
                    }
                }
            }
            // Set end starting sync date
            _endSyncingDate = DateTime.Now;

            // Get the difference in time between the end and starting date
            var timeDifference = _nextSyncingDate - _endSyncingDate;

            // Sleep if we haven't wait for 5 minutes
            if (_nextSyncingDate > _endSyncingDate)
            {
                // Sleep till the 5 minutes have passed
                Thread.Sleep((int)timeDifference.TotalMilliseconds);
            }
        }
    }

I added the methods that seem relevant to me. If you require more code, let me know!


texts: Lotus Domino API - Parsing through NotesItems

texts:
I have an application that opens a bunch of .nsf databases (73 for now, and that might increase in the future), reads the documents, and reads the items of these documents. Based on the item name, I get the item value to populate a list of custom objects (the pdbdoc you will see below).

Currently, my code is like this:

NotesDatabase notedb = notesSession.GetDatabase(myrootpath, myDBfilename);
NotesDocumentCollection notesColl = notedb.AllDocuments;
if (notesColl.Count > 0)
{
    NotesDocument doc = notesColl.GetFirstDocument();
    try
    {
        while (doc != null)
        {
            if (doc.Items != null)
            {
                foreach (Domino.NotesItem item in doc.Items)
                {
                    if (item.Values != null)
                    {
                        switch (item.Name)
                        {
                            //PDB DATA
                            case "DocArea": pdbdoc.DocArea = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "DocDisc": pdbdoc.DocDisc = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "DocObject": pdbdoc.DocObject = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "DocOrigin": pdbdoc.DocOrigin = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "DocRef": pdbdoc.DocRef = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "DocRefClient": pdbdoc.DocRefClient = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "DocRevDt": pdbdoc.DocRevDt = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "DocRevNo": pdbdoc.DocRevNo = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "DocTitle": pdbdoc.DocTitle = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "DocUnit": pdbdoc.DocUnit = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "INCABINET": pdbdoc.InCabinet = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            //VDB DATA
                            case "VendorDocNm": pdbdoc.DocTitle = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "VendorDocRef": pdbdoc.DocRefClient = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "VendorDocRevNo": pdbdoc.DocRevNo = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "DocUse": pdbdoc.DocObject = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "VendorDocRevDt": pdbdoc.DocRevDt = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "VendorDocClientRef": pdbdoc.DocRef = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                            case "VendorNm": pdbdoc.VendorName = LotusUtils.LotusUtils.LotusItemToString(item.Values); break;
                        }
                    }
                }
            }
            doc = notesColl.GetNextDocument(doc);
        }
    }
    catch (Exception ex)
    {
        //Exception handling
    }
}

I think you can spot my question: is there a cleaner and faster way to parse though NotesItems? I don't know the count of documents I read, but it must be around 700.000, each of them with approx. 140 items, that makes around 100.000.000 items to read. That takes some times..

I tried to use doc.GetItemValue(string itemname), but unfortunately, those databases store various kind of documents, and I am only interested in some of them. GetItemValue would require me to first check of the item exists, and then get its value, so basically, that would read twice the items.

Do any of you have another way to parse thought Lotus documents items?


texts: A temporary directory that exists only during run time of user-specified code

texts:
For a research analysis, I'm writing a small bash script that serves as a frontend to Singularity. The reason is that I want to save in this script which options are needed for singularity. For example, I want the working directory to appear at a fixed path in the container, regardless of the actual working directory path.

Singularity has the --contain option for this, but this requires me to manually define a temporary directory for the container. I use mktemp for that. After the end of the script, I use trap to
delete that directory. However, I fear that there might be a corner case where trap "rm -rf '$tmpdir' might delete the wrong directory.

The script, called cexec, executes an arbitrary command inside the container. For example ./cexec R starts R inside the container.

Is there a corner case in the following script where the script deletes a directory that it didn't create?

#!/bin/bash
# Execute a command in the container
set -ue

thisdir="$(dirname "$BASH_SOURCE")"
container="rserver_200211_commitd117c677.sif" # get such a file by using `singularity pull ...`

# Create a temporary directory
tmpdir="$(mktemp -d -t cexec-XXXXXXXX)"
# We delete this directory afterwards, so its important that $tmpdir
# really has the path to an empty, temporary dir, and nothing else!
# (for example empty string or home dir)
if [[ ! "$tmpdir" || ! -d "$tmpdir" ]]; then
  echo "Error: Could not create temp dir $tmpdir"
  exit 1
fi
# check if temp dir is empty
tmpcontent="$(ls -A "$tmpdir")"
if [ ! -z "$tmpcontent" ]; then
  echo "Error: Temp dir '$tmpdir' is not empty"
  exit 1
fi
# Delete the temporary directory after the end of the script
trap "rm -rf '$tmpdir'" EXIT

singularity exec \
  -B "$tmpdir:/tmp" \
  --contain \
  -H "$thisdir:/data" \
  "$container" \
  "$@"


texts: Splitting an array of numbers into all possible combinations

texts:
This takes an array of numbers then splits it into all possible combinations of the number array of size 4 then in another array puts the leftovers.  As I want to take the difference in averages of the first column and the second.

import itertools

#defines the array of numbers and the two columns
number = [53, 64, 68, 71, 77, 82, 85]
col_one = []
col_two = []

#creates an array that holds the first four
results = itertools.combinations(number,4)

for x in results:
    col_one.append(list(x))

#attempts to go through and remove those numbers in the first array
#and then add that array to col_two
for i in range(len(col_one)):
    holder = list(number)
    for j in range(4):
        holder.remove(col_one[i][j])
    col_two.append(holder)

col_one_average = []
col_two_average = []

for k in col_one:
    col_one_average.append(sum(k)/len(k))

for l in col_two:
    col_two_average.append(sum(l)/len(l))

dif = []

for i in range(len(col_one_average)):
    dif.append(col_one_average[i] - col_two_average[i])

print dif

So for example, if I have

a = [1,2,3]

and I want to split it into an array of size 2 and 1, I get

col_one[0] = [1,2]

and

col_two[0] = [3]

then

col_one[1] = [1,3]

and

col_two[1] = [2]

After I get all those I find the average of col_one[0] - average of col_two[0].

I hope that makes sense.  I'm trying to do this for a statistics class, so if there is a 'numpy-y' solution, I'd love to hear it.


texts: Cumulative counts of items in a Pandas dataframe

texts:
i'm using a dataframe full of headers/field names to develop a schema and I need unique values for each header - but each header should be represented. I want to loop though the dataframe list of fields and the second time I come across a field name, I want to add an ever increasing number to it. The order is important.

e.g.

headers['name'] =pd.DataFrame['vegetable', 'fruit', 'meat', 'dairy', 'meat', 'fruit', 'fruit']

I need the output to be:

name      | name+count
vegetable | vegetable
fruit     | fruit
meat      | meat
dairy     | dairy
meat      | meat1
fruit     | fruit1
fruit     | fruit2

for header in headers['names']:
       row = headers.loc[headers['names'] == header].index
       if len(row) > 1:
           for i in range(2, len(row)):
               headers['name+count'][row[i]] = headers['names'][row[i]] + str(i-1)
               print(headers['name+count'][row[i]])


texts:
I am a beginner in Java programming. Here is my simple calculator. I hope you could scan through my coding and let me know if there is any error in my coding or how I could simplify the code.

import java.util.Scanner;

public class Decimal {
    /**
     * @param args
     */
    public static void main(String[] args) {
        double n1, n2;
        String operation;
        Scanner scannerObject = new Scanner(System.in);

        System.out.println("Enter first number");
        n1 = scannerObject. nextDouble();

        System.out.println("Enter second number");
        n2 = scannerObject. nextDouble();

        Scanner op = new Scanner(System.in);
        System.out.println("Enter your operation");
        operation = op.next();

        switch (operation)  {
        case "+":
            System.out.println("Your answer is " + (n1 + n2));
            break;

        case "-":
            System.out.println("Your answer is " + (n1 - n2));
            break;

        case "/":
            System.out.println("Your answer is " + (n1 / n2));
            break;

        case "*":
            System.out.println("Your asnwer is " + (n1 * n2));
            break;

        default:
            System.out.println("Je ne sais pas");

        }
    }
}


texts: Slicing a string into three pieces, and also controlling/manipulating through loops

texts:
# Filename: P05_Strings.py
# Author: Joseph Chua
# Date: 10/18/2016
# Purpose: Slicing a string into THREE pieces.
# Other: http://repeatercreeper.me

#=======================================================================
# Logic - Assignment #1
#=======================================================================
userInp = input("Enter Here: ")

while (len(userInp) % 3) != 0: # Keep adding whitespace until divisible by 3
    userInp += " " # Concatenation of whitespace

def split(str, num):
    return [ str[i:i+num] for i in range(0, len(str), num) ]

print ("Original String: " + userInp)
# Creates 3 variables to store each slices. Sliced using 'split' function.
slice1, slice2, slice3 = split(userInp, int(len(userInp) / 3))

# Prints the results in THREE slices.
print("Slice #1: " + slice1)
print("Slice #2: " + slice2)
print("Slice #3: " + slice3)

#=======================================================================
# Logic - Assignment #2
#=======================================================================
quote = input("Enter a quote: ")
i = 0

if (len(quote.split(' '))) >= 2:
    splitQuote = quote.split(' ')
    while i != 3:
        if i == 0:
            print("Split: ", splitQuote)
        elif i == 1:
            ccString = ""
            for j in range(0, len(splitQuote)):
                ccString += splitQuote[j]
            print("Concatinate: ", ccString)
        else:
            charUse = ","
            print("Join: ", charUse.join(splitQuote))

        i += 1
else:
    print("You entered an invalid quote!")

I'm mostly looking at my Assignment #2. It looks like it has plenty of room for improvements, but if you find something to improve on Assignment #1 to make it more concise that would be amazing.

So for Assignment #2 objective was as follows (copy & paste directly from the book):

  Activity 2: Write the Python code to split, join, and concatenate a string.

  a)  Allow the user to input a string (a famous quote) that will be manipulated within a While loop.a.   Print the string that was entered.

  b)    Within a WHILE loop that iterates three (3) times, manipulate the string.

  If the loop iteration is the first time, split the quote into separate words and print the result of the split operation.
  If the loop iteration is the second time, concatenate the split string (list of words) in an order you choose and print the result of the concatenation operation.
  If the loop iteration is the third time, join the split string content (list of words) with a character(s) of your choosing and print the result of the join operation.


texts:
Are there any corner cases missing here?

class Node
{
    int data;
    Node next;
    Node prev;
}

Node reverseDLL(Node head)
{
    if(head == null || head.next == null)
       return head;

    Node previousNode = head.prev;
    Node currentNode = head;
    Node nextNode;

    while(currentNode!=null)
    {
       nextNode = currentNode.next;

       currentNode.next = previousNode;
       currentNode.prev = nextNode;

       previousNode = currentNode;
       currentNode = nextNode;
    }

    head = previousNode;
    return  head;
}


texts: Filtering input characters for a numeric text field using logical operators

texts:
I did my code for "Bronze Challenge: Disallow Alphabetic characters" exercise in "iOS programming" book by Big Nerd Ranch (p.85). When I did the exercise I also changed code of func textField which was given in the book.

The exercise was to disallow alphabetic characters when user either use Bluetooth keyboard or by passing copied text from clipboard. Also the func does not allow to enter several decimal separators:

func textField(_ textField: UITextField,
               shouldChangeCharactersIn range: NSRange,
               replacementString string: String) -> Bool {

    let existingTextHasDecimalSeparator = textField.text?.range(of: ".")
    let replacementTextHasDecimalSeparator = string.range(of: ".")

    //check letters in replacement text:
    let letters = NSCharacterSet.letters
    let isRangeInReplacementString = string.rangeOfCharacter(from: letters)

    //check if there are double decimal separators (operator AND)
    //OR if there is a letter
    //then returnValueBool will be TRUE
    let returnValueBool = ((existingTextHasDecimalSeparator != nil)
        && (replacementTextHasDecimalSeparator != nil))
        || (isRangeInReplacementString != nil)

    //So returnValueBool is true if there is double digital separator or there is a letter. Function returns False in this case
     return !returnValueBool

    }

My code works well in simulator but I would like somebody experienced in Swift to have a look at my code and to comment on using logical operators.


texts: Take a list of nums and return max and min

texts:
Exercise 6: Rewrite the program that prompts the user for a list of numbers and prints out the maximum and minimum of the numbers at the end when the user enters “done”. Write the program to store the numbers the user enters in a list and use the max() and min() functions to compute the maximum and minimum numbers after the loop completes.

num_list = []

num = input('Please enter a number: ')

while num != 'done' and num != 'DONE':
    try:
        num_list.append(int(num))
        num = input('Please enter a number: ')
    except:
        num = input("Not a number. Please enter a number Or 'done' to finish: ")

try:
    print('Maximum number: ', max(num_list))
    print('Minimum number: ', min(num_list))
except:
    print('NO INPUT!')


texts: Is there a cleaner way to add DEBUG comments?

texts:
I have a rather large class that needs to provide a reasonable amount of output for debugging purposes. I've done this with the following:

#if DEBUG
Console.WriteLine("Source Site Set to: {0}", archiveQueueEntity.SourceSite);
Console.WriteLine("Source List Set to: {0}", archiveQueueEntity.SourceUrl);
Console.WriteLine("Destination Site Set to {0}", archiveQueueEntity.DestinationSite);
Console.WriteLine("Destination List Set to: {0}", archiveQueueEntity.DestinationUrl);
#endif

Is there a better way to do this though?

After googling this I tried using Debug.WriteLine but it appears that this will only output to the 'output' window in Visual Studio, and not the console.

Am I missing something?


texts:
I had three multi-select boxes from this page. I want to customize each box so I simply repeat the code three times with different options: Check the fiddle

$(".choose").multiselect({
   header: "Choose only One item!",
   multiple: false,
   noneSelectedText: "Select an Option",
   selectedList: 1
});

$(".pick").multiselect({
    header: "Pick Any",
selectedList: 5
});

$(".filter").multiselect({
    header: "Filter Three",
   selectedList: 3
});

It's working fine but I'm curious if there's any better way to do that.


texts: Promise.jsm demo of Promise.all and Promise.defer

texts:
I created this demo example for MDN documentation to show how to use Promise.all and Promise.defer in user created promise. I used lets because I thought if I didn't it would mess it up.

People are recommending I avoid let because the standard is not there yet and it looks like when it lands it will be a little different.  Can you please advise?

The code downloads images from an array and after all images are downloaded it completes the main promise.

Components.utils.import("resource://gre/modules/Promise.jsm");

var myPromise = myUserDefinedPromise();
myPromise.then(
  function(aSuccessReason) {
    alert('myPromise was SUCCESFUL and reason was = "' + aSuccessReason + '"');
  },
  function(aRejectReason) {
    alert('myPromise FAILED for reason = "' + uneval(aRejectReason) + '"');
  }
);

function myUserDefinedPromise() {
  try {
    var mySubPromises = [];

    var imagePaths = ['http://www.mozilla.org/media/img/firefox/favicon.png', 'https://developer.cdn.mozilla.net/media/redesign/img/favicon32.png'];
    [].forEach.call(imagePaths, function(path) {
      let myImage = new Image();
      let loadThisImagePromise = Promise.defer();
      mySubPromises.push(loadThisImagePromise.promise);
      myImage.onload = function() {
        loadThisImagePromise.resolve('Succesfully loaded image at path = "' + path + '" the width of this image is = "' + this.naturalWidth + '".');
        if (!this.naturalWidth) {
          loadThisImagePromise.reject('Image loaded but it has 0 width at path = "' + path + '" the naturalWidth was 0');
        }
      }
      myImage.onerror = function(e) {
        loadThisImagePromise.reject('An error occured while loading path = "' + path + '". The error = ' + uneval(e));
      }
      myImage.onabort = function(e) {
        loadThisImagePromise.reject('Image load was aborted loading path = "' + path + '".');
      }
      myImage.src = path;
    });

    return Promise.all(mySubPromises);
  } catch(ex) {
    return Promise.reject(ex);
  }
}


texts:
I've developed a template to modularize JavaScript code I write for client work. The example below is a simple class with 1 attribute and 3 functions.

Rationale:

Standardized constructor to add or modify settings/ options
Functions as variables used later to return only "public" functions, all else are private
Using local "call" variable to easily replace functions in unit testing

Are there any improvements you can recommend or general best practices to look for in terms of improvement?

var dataStatus = function( constructorOptions )
{
    "use strict";

    var options = {
        displayId: 'dataStatus',
        statii: {
            'settingUp': {
                tooltip: 'Setting Up...',
                color: '808080'
            },
            'loading': {
                tooltip: 'Data Loading...',
                color: '99ee90'
            },
            'loaded': {
                tooltip: 'Data Loaded',
                color: '006400'
            },
            'changed': {
                tooltip: 'Data Changed',
                color: '8b0000'
            },
            'saving': {
                tooltip: 'Saving...',
                color: 'ffd700'
            }
        },
        defaultStatus: 'settingUp'
    };

    var local = {
        status: false
    };

    var init = function( optionsToSet )
    {
        jQuery.extend( options, optionsToSet);

        call.setStatus( options.defaultStatus );
        return this;
    };

    var inject = function (functionToReplace, injectedFunction)
    {
        call[functionToReplace] = injectedFunction;
        return injectedFunction;
    };

    var getStatus = function()
    {
        return local.status;
    };

    var setStatus = function( status, signal )
    {
        local.status = status;
        if (typeof signal == 'undefined' || signal != false){
            call.signal( call.getStatus() );
        }
    };

    var signal = function ( status ){
        if (status in options.statii){
            jQuery( '#' + options.displayId )
                .html( '<i class="fa fa-circle" title="' + options.statii[status].tooltip + '"></i>')
                .css( 'color', '#' + options.statii[status].color )
                .css( 'background-color', '#ffffff');
        }
    };

    var call = {
        init: init,
        options: options,
        inject: inject,
        getStatus: getStatus,
        setStatus: setStatus,
        signal: signal
    };

    if(typeof myPublicTestNamespace == "undefined"){//http://stackoverflow.com/a/9172377/123594
        return {
            init: init,
            getStatus: getStatus,
            setStatus: setStatus,
            signal: signal
        };
    }else{
        return call;
    };

    init( constructorOptions );
};


texts: Loading data from a web API to be displayed in a tableview

texts:
In my object Dish xxx.Dish, I want to access the Choice class    price and name to display . dish data load from web API and I tested data loaded success full and put the data to the object dish and it return the object list to viewcontroller to load tableview.

Output of printed console

  Optional([xxx.Dish, xxx.Dish])

and in the dish class before append optionList?.append(_obj)

  xxx.DishOption

I am new to swift and is it right way to implement? Please suggest me?

class Dish {
        let dishId : String
        var optionList : [DishOption]?

        init?(fromAPIResponse resposne : Dictionary<String,AnyObject>) {

            guard let dishId = resposne["dishId"] as? String else {
                return nil

            }
            self.dishId = dishId
            if let objs =  resposne["options"] as?  [[String: AnyObject]]{
                optionList = [DishOption]()
                for obj in objs {
                    if  let _obj = DishOption(fromAPIResponse: obj){

                        optionList?.append(_obj)

                    }
                }
            }
        }

//another file

   class DishOption {

                let optionId : String

                var choiceList : [Choice]?

                init?(fromAPIResponse resposne : Dictionary<String,AnyObject>) {

                    guard let  optionId = resposne["optionId"] as? String else {
                        return nil
                    }

                    self.optionId = optionId

                    if let objs =  resposne["choices"] as?  [[String: AnyObject]]{
                        choiceList = [Choice]()
                        for obj in objs {
                            if  let _obj = Choice(fromAPIResponse: obj){

                                choiceList?.append(_obj)

                            }
                        }
                    }
                }
            }

 class Choice{
           let choiceId : String
                    let name : String
                    let price : String

                    init?(fromAPIResponse resposne : Dictionary<String,AnyObject>) {
                        guard let choiceId = resposne["choiceId"] as? String ,
                            let name = resposne["name"]  as? String,
                            let price = resposne["price"] as? String else {

                                return nil
                        }
                        self.choiceId = choiceId
                        self.name = name
                        self.price = price

                    }

            }

Usage:

     var  dishMenuList = [Dish]()
            guard let objs = json["menu_list"] as? [[String : AnyObject]] else {
                return
            }

            for obj in objs {

                if let _obj = Dish(fromAPIResponse: obj){

                 print(_obj.optionList) //always print nil

                if let options = _obj.optionList {

                    for data in options {

                        print(data.displayAsButton)

                    }
                   }
                   dishMenuList.append(_obj)
                }

            }


texts: Computing the average of several numbers

texts:
I am learning C++. This is a simple program I had to write for class. Is there anything I should fix?

#include <iostream>
using namespace std;

int main()
{
    const int ListSize = 5;
    int ValuesProcessed = 0;
    float ValueSum = 0;

    cout << "Please enter " << ListSize << " numbers" << endl;

    while(ValuesProcessed < ListSize){
        float Value;
        cin >> Value;
        ValueSum += Value;
        ++ValuesProcessed;
    }
    float Average = ValueSum / ValuesProcessed;
    cout << "Average: " << Average << endl;

    return 0;
}


texts: Simplify ASP.Net StreamWriter for appendtext to file

texts:
Is there anyway to simplify this code so there aren't so many redundant w = File.AppendText(filePath) and w.flush() and w.close() in each if statement?

Anything else I have tried ends up locking the file, and crashing the site because to text file is in use by another process.

Public filePath As String = "c:\inetpub\logs\login.txt"
Public w As StreamWriter

Protected Sub LoginUser_LoginError(ByVal sender As Object, ByVal e As System.EventArgs) Handles LoginUser.LoginError

    Dim UserName As TextBox = DirectCast(LoginUser.FindControl("UserName"), TextBox)

    Dim CurrentUser As MembershipUser = Membership.GetUser(LoginUser.UserName)

    Dim logLoginError As New Thread(
        Sub()
            If (CurrentUser IsNot Nothing) Then

                If (CurrentUser.IsLockedOut = True) Then
                    w = File.AppendText(filePath)
                    w.WriteLine(CurrentUser.ToString & "'s (" & IPAddress & ") account is locked out - " & DateAndTime.Now)
                    w.Flush()
                    w.Close()
                ElseIf (CurrentUser.IsApproved = False) Then
                    w = File.AppendText(filePath)
                    w.WriteLine(CurrentUser.ToString & " (" & IPAddress & ") is attempting to login, but the account is disabled - " & DateAndTime.Now)
                    w.Flush()
                    w.Close()
                Else
                    w = File.AppendText(filePath)
                    w.WriteLine(CurrentUser.ToString & "'s (" & IPAddress & ") login credentials failed - " & DateAndTime.Now)
                    w.Flush()
                    w.Close()
                End If

            Else
                w = File.AppendText(filePath)
                w.WriteLine("Unknown user " & UserName.Text & " (" & IPAddress & ") attempting to login - " & DateAndTime.Now)
                w.Flush()
                w.Close()
            End If
        End Sub
    )
    logLoginError.Start()

End Sub


texts:
I've created a repo for some Docker containers that work together with docker-compose to make a very easy and quick installation for Laravel including nginx, mariadb, and redis. Laravel is known for having one somewhat annoying step to get it started, which is that the storage and bootstrap/cache directories have to be writable by the webserver/php process:

chmod -R 777 storage bootstrap/cache

However, docker containers that use shared volumes between the container and host tend to have permission issues because of discrepancies between uids and guids differing between the container and the host.

This is a Mac-only project until I get these basic issues solved.

I would greatly appreciate solutions for how to have the php process user in the php container have write permissions on those directories in the shared volume.

This install script (called by typing ./install into the terminal) is what should be theoretically setting the permissions:

install

#!/bin/bash
echo "installing and building docker containers..."
docker-compose up -d

echo "installing laravel/installer via composer..."
rm -rf code
if [[ $(composer global show) != *laravel/installer* ]]
  then
    composer global require "laravel/installer"
fi

echo "installing laravel..."
laravel new code

echo "changing working directory to code..."
cd code

echo "setting permissions..."
chmod -R 777 storage bootstrap/cache
docker exec ${PWD##*/}_php_1 chgrp -R www-data /code
docker exec ${PWD##*/}_php_1 chmod -R 777 storage bootstrap/cache

echo "installing predis..."
composer require "predis/predis"

echo "installing correct database settings to laravel..."
sed -i '' "s/DB_HOST=127.0.0.1/DB_HOST=mariadb/" .env
sed -i '' "s/DB_DATABASE=homestead/DB_DATABASE=laravel/" .env
sed -i '' "s/DB_USERNAME=homestead/DB_USERNAME=laravel/" .env
sed -i '' "s/REDIS_HOST=127.0.0.1/REDIS_HOST=redis/" .env
sed -i '' "s/CACHE_DRIVER=file/CACHE_DRIVER=redis/" .env
sed -i '' "s/SESSION_DRIVER=file/SESSION_DRIVER=redis/" .env

echo "returning working directory to previous state..."
cd ..

echo "installation complete"

docker-compose.yml

version: '2'
services:
  web:
    image: nginx:alpine
    ports:
    - "80:80"
    volumes:
    - ./code:/code
    - ./site.conf:/etc/nginx/conf.d/site.conf
    networks:
    - front-tier
    - back-tier
  php:
    image: laravel_pdo_php
    build: ./php
    working_dir: /code
    volumes:
    - ./code:/code
    - ./php.ini:/usr/local/etc/php/php.ini
    networks:
    - back-tier
    expose:
    - "9000"
  mariadb:
    image: mariadb:latest
    ports:
    - "3306:3306"
    volumes:
    - mariadb:/var/lib/mysql
    networks:
    - back-tier
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: laravel
      MYSQL_USER: laravel
      MYSQL_PASSWORD: secret
    expose:
    - "3306"
  redis:
    image: redis:alpine
    networks:
    - back-tier
    expose:
    - "6379"
volumes:
  mariadb:
    driver: local
networks:
  front-tier:
    driver: bridge
  back-tier:
    driver: bridge

php/Dockerfile

FROM php:7-fpm
RUN docker-php-ext-install pdo pdo_mysql
CMD ["php-fpm"]


texts: Create archive webpage for newsletters based on nested array

texts:
I am creating a webpage for my newsletter archives.  The archives are divided by year (currently there is only 1, but there could be many), then by topic, before listing each newsletter.  There will always be exactly five topics, but the number of newsletters in each topic will vary.

I add the name of the newest newsletter in only one place - at the end of the array. I have a link to the most recent newsletter above the rest of the archives.

This code works fine, but the way that I am retrieving the most recent newsletter seems somewhat hacky

The newsletters are currently stored in my server as # segment year.

$newsletter = array(
        "Year 1" => array(
                "First Topic" => array(
                            "a","b","c","d","e","f","g","h","i",
                            ),
                "Second Topic" => array(
                            "j","k","l","m","n","o","ab",
                            ),
                "Third Topic" => array(
                            "cd","ef","fo","er","abd","cdf","eee",
                            ),
                "Fourth Topic" => array(
                            "fff","wet","csg","qqq",
                            ),
                "Fifth Topic" => array(

                            ),
                )
        );

$archive_design = "";

foreach($newsletter as $gilYear => $book){
    $i=1;
    $archive_design .= "

";
    foreach($book as $book => $segment){
        $archive_design .= "

            $book

            ";
        foreach($segment as $segment){
            $link = "$i ".strtolower($segment)." ".$gilYear;
            $recent = $segment;
            $i++;
            $archive_design .= "

                                $segment

";
        }
        $archive_design .= "

";
    }
    $archive_design .=  "

";
}
?>

        <a href="http://example.org/newsletter/<?php echo $link; ?>.pdf" target=_blank> Current Issue - <?php echo $recent;?>

Click on the segment to view, download and enjoy the archives!

<?php
echo $archive_design;
?>


texts: Invoking only the last registered event handler

texts:
We are building a game and we have a dialog system. Dialogs may open and stack on top of one another.

When every dialog opens, it registers itself to handle the BackButtonPressed event:

AppHelper.OnBackPressed += HandleBackPressed;

When the dialog closed, it unhooks from the event:

AppHelper.OnBackPressed -= HandleBackPressed;

The problem is, we'd like the event to raise the event handler of the active dialog only (the active dialog is the last one registered to the event.

A proposed solution was to:

Manually create the add and remove methods for the event
Keeping registered handlers in a list.
When raising the event, call the last handler in the list

Here's an example in code, is this the proper way of doing this?

private static List<BackPressed> backPressed = new List<BackPressed>();

public static event BackPressed OnBackPressed
{
    add
    {
        backPressed.Add(value);
    }
    remove
    {
        if(backPressed.Contains(value))
        {
            backPressed.Remove(value);
        }
    }
}

Raising the event:

backPressed[backPressed.Count - 1].Invoke();