texts:
I have a function that needs to evaluate some parameters to determine if they're valid or not. They all need to be evaluated individually, so I have some code like below.

#Configure widgets held in a layout
def layoutConfigurer(name, widgetType, minW, minH, maxH, maxW, flat, focus, image, position=False):
    widgetType.setObjectName(_fromUtf8(name))
    if minW or minH is not None:
        widgetType.setMinimumSize(QtCore.QSize(minW, minH))

    if maxH or maxW is not None:
        widgetType.setMaximumSize(QtCore.QSize(maxH, maxW))

    if flat:
        widgetType.setFlat(True)

    if focus:
        widgetType.setFocusPolicy(QtCore.Qt.NoFocus)

    if image:
        widgetType.setPixmap(QtGui.QPixmap(_fromUtf8(image)))

    if position:
        widgetType.setAlignment(QtCore.Qt.AlignCenter)

This code works, but is kind of ugly. I'm using the multiple if statements, because I need them all to be evaluated and not just the first true statements.

I'm not sure if there is a better way of evaluating command line arguments or not, but I would like to make the above code seem prettier. At the moment, it seems a little inefficient


texts:
In Python, we use __all__ to explicitly denote the public API of a module or package. That looks like this:

__all__ = ['Foo', 'bar', 'BAZ_CONSTANT']

BAZ_CONSTANT = None

class Foo:
    pass

def bar():
    pass

... except that modules can go on for thousands of lines, and then it is not immediately apparent, without revisiting the heading of the file, which objects are for external use, and which are not.

We are also required to write the names of the objects twice for each of these objects. (At a minimum. Even more for unittests - and we write our tests first, don't we?)

What I want is a decorator that allows me to shift the declaration of the public API away from the heading and to the object and constant definitions, where we, in most cases, can only write the name to be exported once.

Here's a serviceable preliminary draft, targeted to Python 3.6+ - perhaps the simplest thing that could possibly work:

import sys

class ExportError(Exception):
    """Exception if redundant names attempted exporting"""

def export(obj, global_namespace: dict=None) -> 'obj arg':
    """export adds names of functions and classes via decorator
    and module level variables via call (with globals() argument)
    to __all__.
    Usage:
    from exportlib import export

    export("BAZ_CONSTANT", globals()) # I don't like globals() call...
    BAZ_CONSTANT = None

    @export
    class Foo:
        pass

    @export
    def bar():
        pass
    """
    name = obj if isinstance(obj, str) else obj.__name__
    if global_namespace is None:
         try:
             global_namespace = obj.__globals__
         except AttributeError as error:
             raise AttributeError(
               f'no globals, try export({name!r}, globals())')
    __all__ = global_namespace.setdefault('__all__', [])
    if name in __all__: # Do we care if redundant exports? Assuming so:
        raise ExportError(f'{name} already exported')
    __all__.append(name)
    return obj

Ok, could probably be a little simpler with fewer features. I do like the documenting features of the annotations. I couldn't identify a more appropriate Exception to subclass or use directly than Exception.

I don't like the globals() call required when adding a module level variable that doesn't know its own name or module, but the only alternative, that I can think of, is to do what super does and climb a stackframe up and get the globals there, or pass in __all__ instead (which would require creating it explicitly). Stackframe climbing would preclude export from being wrapped/extended.

But I think this makes a sufficiently sophisticated starting point.


texts: How can I make this implementation of Euler's method more efficient?

texts:
I have an implementation of an Euler method for solving N-many 1st order coupled differential equations, but I feel that I did not write it as efficiently as I could, due to lack of programming experience.

Here is the implementation:

def eulerMethod(f, init0, h, om, mesh):
    """
    f          - array of ODES
    init0      - intial values
    h          - step size
    om         - array of symbols
    mesh       - time mesh to evolve over

    This implements Euler's method for finding numerically the
    solution of the 1st order system of N-many ODEs

    output in form of: [t:, om0:, om1:, om2:, ... ]
    """

    numOfDE = len(f)
    t00 = mesh[0]
    soln = [[t00]]
    for i in xrange(numOfDE): # create intitial soln
        soln[0].append(init0[i])

    subVal = {} # for diff eq substituion
    for i in xrange(len(om)):
        subVal.update({om[i]:init0[i]})

    g = sympy.symbols('g0:%d'%len(om))
    s = sympy.symbols('s0:%d'%len(om))

    # set up dictionary for equations
    eqDict = {g[0]:init0[0]}
    for i in xrange(1,len(om)):
        eqDict[g[i]] = init0[i]

    for i in xrange(6): # number of steps
        for i in xrange(len(om)): # performs euler steps
            eqDict[s[i]] = eqDict[g[i]] + h*1.0*(f[i].subs(subVal))

        for i in xrange(len(om)): # set recursive values
            eqDict[g[i]] = eqDict[s[i]]

        t00 += h
        soln.append([t00])
        for i in xrange(numOfDE): # append rest of solutions
            soln[len(soln)-1].append(eqDict[s[i]])

        subVal = {} # update values to be subsititied
        for i in xrange(len(om)):
            subVal.update({om[i]:eqDict[g[i]]})

    return soln

I know my naming is sort of confusing, but I just wanted to see how solid my algorithm is. I will be using this to typically solve 1000 coupled differential equations.


texts:
I'm just writing my first PHP-Mysqli sample (think about a Wiki 0.0.1) and I would like to ask you if this example is secure or not or if there are any other problems/suggestions you might recommend?

I would like to use prepared statements and not care about sanitizing the input from $_GET, but I don't know if this code is considered secure and OK?

Also, any comments regarding how this functionality (reading a latest revision from a database) should be done is welcome.

require_once 'connect.php';

$id = $_GET['id'];

if ( $stmt = $mysqli->prepare("SELECT text, rev FROM wiki WHERE id = ? ORDER BY rev DESC LIMIT 0,1") ) {

    $stmt->bind_param( "s", $id );
    $stmt->execute();
    $stmt->bind_result( $text, $rev );
    $stmt->fetch();

    echo "rev: " . $rev . ": " . $text;
    echo '<br>';

    $stmt->close();
}

$mysqli->close();

connect.php

$mysqli = new mysqli("localhost", "xxx", "yyy", "zzz");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

Is it safe to keep connect.php at the same folder as the other php files?

Is there any chance someone could read the plain password in connect.php file?


texts: Factorising and Finding Prime numbers with list comprehension

texts:
I have created a simple code which finds the factors of any given integer. It then compares the value of the input to the range of numbers. Because a prime number can factorize into 1 and itself. Then I search length of the factor list. If the list contains 2 or less elements it is added to the all_primes list. I have flattened the list and also produced a list with the composite numbers missing for pattern recognition.

Is this a good method to find the Prime numbers and factors of a value and is there any bugs I can encounter?

all_primes = []

def user_in(num):
    while True:
        if num <= 2:
          break
        num -= 1
        numbers = [i for i in range(1, num + 1)]
        factors = [i for i in numbers if num % i == 0]
        primes = [i for i in factors if len(factors) <= 2 and i != 1]
        all_primes.append(primes)
        print('Number: {}\nFactors: {}\nFactor count: {}\nSum of factor: {}\nSum of numbers: {}\nSum of Primes: {}\n\n'.format(num, factors, len(factors), sum(factors), sum(numbers), sum(primes), primes))

x = int(input('Enter number: '))
user_in(x)
all_primes.reverse()
flat_list = [i for k in all_primes for i in k]
print('Flat list of Primes: {}\n\nSum of all primes: {}\n\nAll Primes: {}'.format(flat_list, sum(flat_list) + x, all_primes))

This example is part of the output:

Number: 5
Factors: [1, 5]
Factor count: 2
Sum of factor: 6
Sum of numbers: 15
Sum of Primes: 5

Number: 4
Factors: [1, 2, 4]
Factor count: 3
Sum of factor: 7
Sum of numbers: 10
Sum of Primes: 0

Number: 3
Factors: [1, 3]
Factor count: 2
Sum of factor: 4
Sum of numbers: 6
Sum of Primes: 3

Number: 2
Factors: [1, 2]
Factor count: 2
Sum of factor: 3
Sum of numbers: 3
Sum of Primes: 2

Flat list of Primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Sum of all primes: 378

All Primes: [[2], [3], [], [5], [], [7], [], [], [], [11], [], [13], [], [], [], [17], [], [19], [], [], [], [23], [], [], [], [], [], [29],[], [31], [], [], [], [], [], [37], [], [], [], [41], [], [43], [], [], [], [47], [], []]


texts:
I have never done testing, and I have 5 end points which have methods such as GET, POST, and DELETE to test. I wrote test cases using the go's in built testing package. I'm worried that I'm missing some cases which are not striking to my mind. For example: I have an end point which goes like this:

a.Router.HandleFunc("/1/sig/id/{id:[0-9]+}", a.sigHandler).Methods("GET", "POST", "DELETE")

And the Test case goes like this:

func TestSigHandler(t *testing.T){

    test_cases := []string{"2021205"}
    // GET Testing
    for _, method := range test_cases{
        usersUrl = fmt.Sprintf("%s/1/sig/id/%s", server.URL, method) //Grab the address for the API endpoint
        request, err := http.NewRequest("GET", usersUrl, nil)
        res, err := http.DefaultClient.Do(request)

        if err != nil {
            t.Error(err) //Something is wrong while sending request
        }

        if res.StatusCode != 200  {
            t.Errorf("Page not found : ", res.StatusCode) //Uh-oh this means our test failed
        }
    }

    // POST Testing
        sig := []byte( `{
        "raw": "a new sig"
    }`)
        usersUrl = fmt.Sprintf("%s/1/sig/id/2021205", server.URL) //Grab the address for the API endpoint
        request, err := http.NewRequest("POST", usersUrl, bytes.NewBuffer(sig))
        if err != nil{
            t.Error(err)
        }
        request.Header.Set("Content-Type", "application/json")
        res, err := http.DefaultClient.Do(request)

        if err != nil {
            t.Error(err) //Something is wrong while sending request
        }

        if res.StatusCode != 200  {
            t.Errorf(" Internal Server Error: ", res.StatusCode) //Uh-oh this means our test failed
        }

        // DELETE Testing

        sigs_delete_cases := []string{ "1000345"}
        for _, sig_to_be_deleted := range sigs_delete_cases{
            usersUrl = fmt.Sprintf("%s/1/sig/id/%s", server.URL, sig_to_be_deleted) //Grab the address for the API endpoint
            request, err := http.NewRequest("DELETE", usersUrl, nil)
            res, err := http.DefaultClient.Do(request)

            if err != nil {
                t.Error(err) //Something is wrong while sending request
            }

            if res.StatusCode != 200  {
                t.Errorf("Tried to delete a reserved Id : ", res.StatusCode) //Uh-oh this means our test failed
            }
        }

}

The problem is that, most of my test cases follow similar pattern where I post data in different formats and checking the response codes. I strongly feel like I'm missing something that will break my API when I push it to prod. I need some insight on testing these routes so that I can be confident to push the api to prod.

And my main test function goes like this:

func TestMain(m *testing.M) {
    server = httptest.NewServer(a.InitializeRouter())
    a.InitializeDB(fmt.Sprintf("postgres://****:****@localhost/db?sslmode=disable", os.Getenv("POSTGRES_URL")))
    code := m.Run()
    if code == 0 {
        fmt.Println("Success!")
    } else {
        fmt.Println("One or more Test Cases have failed! Please use  go test -v  for more details")
    }

    os.Exit(code)
}


texts: 355 - The Bases Are Loaded (math numbers conversion)

texts:
Recently I found this task, which is to convert numbers between arbitrary bases.

My code is working fine, but time limit exceeded.

#include <cstring>
#include <cstdio>

int broj[50], n;
char uzorak[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};

long long ToDec(char a[], long long base)
{
    long long dec = 0, b = 1;
    int l = strlen(a);
    for(int i = l-1; i >= 0; i--)
    {
        if(a[i] >= '0' && a[i] <= '9')
            dec += (a[i]-'0') * b;
        else
            dec += (a[i] - 'A' + 10) * b;
        b *= base;
    }

    return dec;
}

void ToB2(long long a, int b2)
{
    n = 0;
    while(a > 0)
    {
        broj[n] = a%b2;
        a = (a-broj[n])/b2;
        n++;
    }
    for(int i = n-1; i>=0; i--)
        printf("%c", uzorak[broj[i]]);
}

int main()
{
    char a[50];
    int b1, b2, l;
    while(scanf("%i %i %s", &b1, &b2, &a))
    {
        int base = 1;
        l = strlen(a);
        for(int i = 0; i < l; ++i)
        {
            if(a[i] >= '0' && a[i] <= '9')
                    base = (base > a[i]-'0') ? base : a[i]-'0';
            else if(a[i] >= 'A' && a[i] <= 'Z')
                    base = (base > a[i]-'A'+10) ? base : a[i]-'A'+10;
            else
            {
                base = -1;
                goto Break;
            }
        }
        base++;
        Break:
        if((base <= b1)&&(base != -1))
        {
            printf("%s base %i = ", a, b1);
            ToB2(ToDec(a, b1), b2);
            printf(" base %i\n", b2);
        }
        else
            printf("%s is an illegal base %i number\n", a, b1);
    }
    return 0;
}

I would appreciate any suggestions on optimizing my code, thanks!

Is there any faster methods to convert numbers from one base to another or you have to go over base 10?


texts:
I have written some code for calculating a count of common factors. Please help me remove anything unnecessary and shorten it.

Please tell me if any function in Python 3 can calculate common factors directly!

# a string of 2 numbers
# is input e.g. '10 15'

a,b=str(input()).split(' ')
a,b=int(a),int(b)
n=0
if a>=b:
    lim=a
else:
    lim=b
for num in range(1,lim):
    if a%num==0 and b%num==0:
        n+=1
print(n)


texts: Installing and removing kernel module RPMs

texts:
First, the script checks to see if it is installing two kernel module packages or removing them by looking at the first parameter. If no parameter is provided it complains and exits.

If installing, it checks if each of the packages even needs to be installed by looking at the version of the existing module. If they do need to be installed, install them; If they don't, simply say so and the rest of the script runs its course.

If I am removing them just run the command to do so.

The problem is, I have a lot of if...else...fi and if...elif...fi blocks setting two variables and then testing different combinations of the two. Even though the script works as is I feel like there should be a better way to do this.

I moved one block into a function even though this just put it somewhere else. It didn't actually clean it up at all.

#!/bin/bash

awk='/bin/awk'
enic_pkg="/home/$(logname)/kmod-enic-2.1.1.75-rhel6u5.el6.x86_64.rpm"
fnic_pkg="/home/$(logname)/kmod-fnic-1.6.0.12b-1.el6.x86_64.rpm"
modinfo='/sbin/modinfo'

if [ ! $1 ]; then
    echo "Script must be executed with either 'install' or 'remove' as a paramter"
    exit

else
    method=$1

fi

test_ood() {
    if [ ! $enic = "2.1.1.75" ]; then
      enic_ood=true

    else
      echo "enic module is already up-to-date: $enic"

    fi

    if [ ! $fnic = "1.6.0.12b" ]; then
      fnic_ood=true
    else
      echo "fnic module is already up-to-date: $fnic"

    fi

}

if [ $method == "install" ]; then
    yum='/usr/bin/yum -y localinstall'
    enic=$(${modinfo} enic |grep "^version" |${awk} '{print $2}')
    fnic=$(${modinfo} fnic |grep "^version" |${awk} '{print $2}')

    test_ood

    if [ $enic_ood -a $fnic_ood ]; then
      echo "Both enic and fnic modules are out of date."
      echo "enic: $enic"
      echo "fnic: $fnic"
      echo "Installing kmod-enic and kmod-fnic..."
      ${yum} $enic_pkg $fnic_pkg

    elif [ $enic_ood -a ! $fnic_ood ]; then
      echo "Only the enic module is out of date: $enic"
      echo "Installing kmod-enic..."
      ${yum} $enic_pkg

    elif [ ! $enic_ood -a $fnic_ood ]; then
      echo "Only the fnic module is out of date: $fnic"
      echo "Installing kmod-fnic..."
      ${yum} $fnic_pkg

    else
      echo "Both modules are up-to-date. Nothing to do; exiting..."
      exit

    fi

    test_ood

elif [ $method == "remove" ];then
    yum='/usr/bin/yum -y remove'

    ${yum} kmod-enic kmod-fnic

else
    echo "Unrecognized option: $method"
    exit

fi

I was thinking I could make the $method if tests case switches and put the code for each of those if blocks into methods of their own. That would at least eliminate the outer if...elif...fi block. Although, I'd only be converting it to another type of block.


texts: jQuery plugin creation and declaration for usage with $(). or $

texts:
Simple idea: just have a plugin (more a basic function). That I can use with jQuery in different ways it offers, means:

var myNewVar = $.myNewFunction( myVar );
var myNewVar = $().myNewFunction( myVar );

I want to know if what I did is the good way to doesn't repeat the code, or if their is a better way to.

Here my plugin:

// New function to jquery to change an array (from form) to an object
$.formArrayToObject = function( array ) {
    var form = {};
    $(array).each(function(){
        if( !form[this.name] ) {
            form[this.name] = this.value;
        }
        else {
            if ( !Array.isArray(form[this.name]) ) {
                form[this.name] = [form[this.name]];
            }
            form[this.name].push(this.value);
        }
    });
    return form;
};

// Second declaration to be able to call both $. and $().
jQuery.fn.formArrayToObject = function() {
    $.formArrayToObject();
};


texts: Sign In or Sign Up - either way don't repeat yourself

texts:
I have one application with two views. One to sign in and one to sign up. Each view has an Email entry as main identifier.

I want to add some itemTemplates to my application, because for now I repeat all UI properties twice.

In the code, a block is a listItem. Some blocks have the same name, but icons is different, and that's why I put it as an argument.

This is the new architecture I want to set up:

internal class SignUp : ViewModelBase
{
    private readonly List<object> _content = new List<object>();

    public SignUp()
    {
        _content.Add(BlockFactory.Create("Email"));
        _content.Add(BlockFactory.Create("Address"));
    }
}

internal class SignIn : ViewModelBase
{
    private readonly List<object> _content = new List<object>();

    public SignIn()
    {
        _content.Add(BlockFactory.Create("Email"));
    }
}

//So SignUp.Content[1].BlockItems.ElementAt(0) will be different to
// SignUp.Content[0].BlockItems.ElementAt(0)

public class BlockItem
{
    public bool IsVisible;
    public string Name;
    public string Template;
    public object Value;
}

public class Block
{
    public List<BlockItem> BlockItems = new List<BlockItem>();
    public string Icon;
    public string Name;

    public Block(string name, string icon)
    {
        Name = name;
        Icon = icon;
    }
}

public static class BlockFactory
{
    public static Block Create(string name)
    {
        switch (name)
        {
            case "Email":
                return new Block("Email", "")
                {
                    BlockItems = new List<BlockItem>
                    {
                        new BlockItem
                        {
                            Name = "Email",
                            Value = "",
                            IsVisible = true,
                            Template = "Entry"
                        }
                    }
                };
            case "Address":
                return new Block("Address", "")
                {
                    BlockItems = new List<BlockItem>
                    {
                        new BlockItem
                        {
                            Name = "Street",
                            Value = "",
                            IsVisible = true,
                            Template = "Entry"
                        },
                        new BlockItem
                        {
                            Name = "Zip",
                            Value = "",
                            IsVisible = true,
                            Template = "Entry"
                        },
                        new BlockItem
                        {
                            Name = "City",
                            Value = "",
                            IsVisible = true,
                            Template = "AnotherTemplate"
                        }
                    }
                };
        }
        return null;
    }
}

Is it possible to review my code and share possible improvements?

In the UI side, I'll have only one list with itemTemplate and based on the BlockItems.Count. I'll display elements in one line or more.


texts: Parse HTTP header using Python and tcpflow

texts:
I wrote a program that reads a pcap file and parses the HTTP traffic in the pcap to generate a dictionary that contains HTTP headers for each request and response in this pcap.

My code does the following:

Uses tcpflow to reassemble the tcp segments
Read the files generated by tcpflow and check if it related to HTTP
If the file contains HTTP traffic, my code will read the file and generate a corresponding dictionary that contains the HTTP header fields.

I test my code with multiple test cases, but honestly I don't have a good experience in Python, so could anyone check it for me please?

import os
from os import listdir
from os.path import isfile, join
from StringIO import StringIO
import mimetools
def getFields(headers):
    fields={}
    i=1
    for header in headers:
        if len(header)==0:
           continue

        # if this line is complement for the previous line
        if header.find(" ")==0 or
           header.find("\t")==0:
           continue

        if len(header.split(":"))>=2:
           key = header.split(":")[0].strip()

           # if the key has multiple values such as cookie
           if fields.has_key(key):
              fields[key]=fields[key]+" "+header[header.find(":")+1:].strip()
           else:
              fields[key]=header[header.find(":")+1:].strip()

              while headers[i].find(" ")==0 or
                    headers[i].find("\t")==0 :
                    fields[key]=fields[key]+" "+headers[i].strip()
                    i=i+1
              # end of the while loop
          # end of the else

        else:
             # else for [if len(header.split(":"))>=2: ]
             print "ERROR: RFC VIOLATION"

      # end of the for loop
    return fields

def main():
    # you have to write it in the terminal "cd /home/user/Desktop/empty-dir"
    os.system("tcpflow -r /home/user/Desktop/12.pcap -v")

    for f in listdir("/home/user/Desktop/empty-dir"):
        if f.find("80")==19 or f.find("80")==41:
           with open("/home/user/Desktop/empty-dir"+f) as fh:
                fields={}
                content=fh.read()  #to test you could replace it with content="any    custom http header"
                if content.find("\r\n\r\n")==-1:
                   print "ERROR: RFC VIOLATION"
                   return
                headerSection=content.split("\r\n\r\n")[0]
                headerLines=headerSection.split("\r\n")
                firstLine=headerLines[0]
                firstLineFields=firstLine.split(" ")
                if len(headerLines)>1:
                   fields=getFields(headerLines[1:])
                if len(firstLineFields)>=3:
                   if firstLine.find("HTTP")==0:
                      fields["Version"]=firstLineFields[0]
                      fields["Status-code"]=firstLineFields[1]
                      fields["Status-desc"]=" ".join(firstLineFields[2:])
                   else:
                      fields["Method"]=firstLineFields[0]
                      fields["URL"]=firstLineFields[1]
                      fields["Version"]=firstLineFields[2]
                else:
                  print "ERROR: RFC VIOLATION"
                  continue
                print fields
                print "__________________"

    return 0

if __name__ == '__main__':
 main()


texts: Implementing find middle element of singly linked list without using 2 pointers

texts:
There is a solution floating around about using 2 pointers. But I decide to keep the implementation much simpler by using basic constructs that works use to build basic methods of a singly list list data structure.

The code works. My question is, am I off the hook from making it better as long as the code works? Is the code sufficient?

 public Object findMiddleElement()
        {
            Node node = head;

            if(size % 2 != 0)
            {
                for(int i = 0; i < size/2 ;i++ )
                {
                    node = node.getNext();

                }
            }
            else
            {
                    System.out.println("there is no middle element");
                    node.setElement(null);;

            }
                    return node.getElement();
        }


texts:
I've got a fairly simple task here, but I think it's worth trying to perfect the implementation, because I can probably learn a thing or two about using .NET's enumerables correctly in the process.

I have two "lists" of strings, let's call them values and separators. The former is one element longer than the latter, and I want to interleave them into a single string (so I want to riffle the separators in between the values). Example:

var values = new []{ "abc", "def", "ghi" };
var separators = new []{ "123", "456" };

// expected result: "abc123def456ghi"

I need this in a few places, and in my actual code these might be Lists or other enumerables, so I figured I'd add an extension method to IEnumerable<string>, which I call on the values and pass the separators as an argument. Here's what I've got:

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

namespace Retina.Extensions
{
    public static class EnumerableExtension
    {
        public static string Riffle(this IEnumerable<string> values, IEnumerable<string> separators)
        {
            if (values.Count() != separators.Count() + 1)
                throw new Exception("Riffled enumerable needs to be one shorter than this enumerable.");

            var builder = new StringBuilder();

            var zipped = values.Zip(separators, (val, sep) => new { val, sep });

            foreach (var pair in zipped)
            {
                builder.Append(pair.val);
                builder.Append(pair.sep);
            }

            builder.Append(values.Last());

            return builder.ToString();
        }
    }
}

As I understand it, IEnumerable is generally a lazy list, so both Count() and Last() potentially incur an additional iteration through the entire list, which seems unnecessary. Also, the intermediate zipped enumerable seems awkward for something as simple as alternatingly iterating through two lists.

Is there a more idiomatic way to implement this and make better use of .NET's collections/enumerables? Is IEnumerable even the correct choice here?


texts:
I have made the following function that gives the combinations permuted of n elements with a constrain/rule. This consist on creating a dataframe with all combination of numbers from 0 to n that sums n.

Function

import pandas as pd
import itertools
import numpy as np

def combinations_permuted(n_elm):
    items = list(range(0,n_elm+1,1))
    combinations = pd.DataFrame(list(filter(lambda x: np.sum(x)==n_elm,list(itertools.combinations_with_replacement(items, n_elm)))))
    comb_permuted = pd.DataFrame()
    for index, combination in combinations.iterrows():
        comb_permuted=comb_permuted.append(list(filter(lambda x: np.sum(x)==n_elm,list(itertools.permutations(combination.tolist(), n_elm)))))

    return(comb_permuted.drop_duplicates().as_matrix())

Example

array([[0, 0, 3],
       [0, 3, 0],
       [3, 0, 0],
       [0, 1, 2],
       [0, 2, 1],
       [1, 0, 2],
       [1, 2, 0],
       [2, 0, 1],
       [2, 1, 0],
       [1, 1, 1]], dtype=int64)

The problem is that is taking a long time when n_elm is "big" for example 9. I think this code can be improving in terms of time performance.

Maybe by replacing the for loop with a map function.

Any help to get it?


texts:
I'm trying to solve exercises where I am required to use recursion. I wrote this:

static String reverse(String word){
    if(word.length()<2){
        return word;
    }
    else{
        int index = word.length() - 1;
        return word.charAt(index) + reverse(word.substring(0, index));
    }
}

But the answer for that question was the following code:

static String reverseRecursively(String str) {
    //base case to handle one char string and empty string
    if (str.length() < 2) {
        return str;
    }

    return reverseRecursively(str.substring(1)) + str.charAt(0);

}

And now let's suppose that you are a recruiter and got the first solution. Do you accept it? If not, why? What should I do better?


texts:
I'm working with thousands of large image files in a regularly updated library. The following script does the job (on average reduces my file size ~95%) but costs me around 25 seconds to compress one image. Obviously, I can just let the script run overnight, but it would be cool if I can shave some time off this process. I'm mostly looking for any unnecessary redundancies or overhead in the script that can be trimmed out to speed up the process. I'm still new to Python, so go easy on me.

from PIL import Image
from pathlib import Path
import os, sys
import glob

root_dir = "/.../"

basewidth = 3500

for filename in glob.iglob(root_dir + '*.jpg', recursive=True):
    p = Path(filename)
    img = p.relative_to(root_dir)
    new_name = (root_dir + 'compressed/' + str(img))
    print(new_name)
    im = Image.open(filename)
    wpercent = (basewidth/float(im.size[0]))
    hsize = int((float(im.size[1])*float(wpercent)))
    im = im.resize((basewidth,hsize), Image.ANTIALIAS)
    im.save(new_name, 'JPEG', quality=40)


texts: Implementing simple and fast inheritance in JavaScript

texts:
I have been using the John Resig JavaScript class implementation in my web apps, but the tests shows it is really slow. I really find it useful for the way of extending objects, and the benefits got from having a better code and less redundancy.

In some post was explained that it was slow because of the how the _super method is handled. Since super is Java style, and most of time I develop in PHP, I made my own version of Resig implementation using the parent:: style (used in PHP), with the aim to make this faster:

(function () {
  this.Class = function () {
  };
  Class.extend = function extend(prop) {
    var prototype = new this();
    prototype.parent = this.prototype;

    for (var name in prop) {
      prototype[name] = prop[name];
    }

    function Class() {
      this.construct.apply(this, arguments);
    }
    Class.prototype = prototype;
    Class.prototype.constructor = Class;
    Class.extend = extend;

    return Class;
  };
}) ();

Case of use:

var Person = Class.extend({
  construct: function (name) {
    this.name = name;

  },
  say: function () {
    console.log('I am person: '+this.name);
  },

});

var Student = Person.extend({
  construct: function (name, mark) {
    this.parent.construct.call(this, name);
    this.mark = 5;
  },
  say: function () {
    this.parent.say.call(this);

    console.log('And a student');
  },
  getMark: function(){
   console.log(this.mark);
  }
});

var me = new Student('Alban');
me.say();
me.getMark();
console.log(me instanceof Person);
console.log(me instanceof Student);

Any opinion about this? Is this  fast? What about correctness? Some test shows that is the fastest for the moment.

My next improvement will be to remove the scope .call(this):

this.parent.say.call(this);

to

this.parent.say();

For some strange unexplained (but explained) reasons this test is not working any more, raising a too much recursion error (but it worked some days ago!)

I updated the test and fix the issue with this test. This is leading to strange results. On Chrome 39 it reports to be the fast class definition, on Firefox 35 it seems to be slow.


texts:
Can this be made any simpler/shorter/more efficient?

This function will compute paycheck amount according to hours worked and rate per hour.

def compute_pay(hours: int, rate: float) -> float:
    """Computes pay according to hours worked and rate per hours.

    For every hour worked after the 40th hour the rate per hour
    is multipled by 1.5
    """

    pay = 0

    if hours > 40:
        pay += 40 * rate
        hours -= 40
        pay += hours * rate * 1.5
    else:
        pay = hours * rate

    return pay

hrs = int(input('Hours: '))
hrs_rate = float(input('Rate: '))

print('Pay:', compute_pay(hrs, hrs_rate))

This is my second take on the above function:

def compute_pay(hours: int, rate: float) -> float:
    """Computes pay according to hours worked and rate per hours.

    For every hour worked after the 40th hour the rate per hour
    is multipled by 1.5
    """

    hours -= 40

    if hours > 0:
        pay = 40 * rate + (hours * rate * 1.5)
    else:
        pay = (hours + 40) * rate

    return pay

hrs = int(input('Hours: '))
hrs_rate = float(input('Rate: '))

print('Pay:', compute_pay(hrs, hrs_rate))

My aim is to have begginers' friendly logic while introducing Python features.


texts:
I wrote a solution to HackerRank Strange Counter:

  The counter counts down in cycles.  At t = 1, the counter displays the number 3.  At each subsequent second, the number displayed by the counter decrements by 1.

  Each time the counter reaches 1, the number becomes 2× the initial number for that countdown cycle.

  The sequence goes:

    3, 2, 1, 6, 5, 4, 3, 2, 1, 12, 11, 10, 9, 8, 7, …

  Print the value of the counter the time t, where 1 ≤ t ≤ 1012.  For example, if t = 4, print 6.

My code works for inputs up to 100 million but when I enter number 1 billion or greater then I get TLE.

#include<stdio.h>
#include<iostream>

using namespace std;

int main()
{
    long long n;

    cin >> n;

    long long  x = 3;
    long long count = x;
    for(long long i = 2; i <= n;i++)
    {
        count--;
        if(i == n)
        {
            break;
        }

    else if(count == 1)
        {    i++;
             x = 2*x;
             count = x;

        }
    }

    cout << count;

    return 0;
}


texts:
This my first java program. I wrote this as a Nim Game so that I could learn java while writing it. I would love to see how could this be made better.
Sample Game:

Code:
import java.util.Scanner;

public class Nim {

  public static boolean isArrayZero(int[] arr){
    for(int i: arr){
      if(i > 0)
      return false;
    }
    return true;
  }

  public static int getPile(char pile){
    switch (pile) {
      case 'A': return 0;
      case 'B': return 1;
      case 'C': return 2;
      default:  return -1;

    }
  }
  public static String playerTurn(String pl1, String pl2, int nbOfTurns){
    if(nbOfTurns % 2 == 0)
       return pl1;
       return pl2;
  }
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String player1, player2, player;
    int[] pile = {3,5,7};
    int pileNb, howMany = 0, chosenPile = 0, nbOfTurns = 0;
    char pileName;
    //Get names of players
    System.out.print("Player1 name: ");
    player1 = input.next();

    System.out.print("Player2 name: ");
    player2 = input.next();

    do {
      System.out.println(String.format("\nA:%s\tB:%s\tC: %s", pile[0], pile[1], pile[2]) );
      player = playerTurn(player1, player2, nbOfTurns);
      do{
          System.out.print(String.format("\n%s,Choose a pile: ", player));
          pileName = Character.toUpperCase(input.next().charAt(0));
          pileNb = getPile(pileName);
          if(pileNb == -1)
            continue;
          chosenPile = pile[pileNb];
          if(chosenPile == 0)
            continue;
          System.out.println(String.format("How many to remove from pile %s", pileName));
          howMany = input.nextInt();
      }while((howMany > chosenPile) || (howMany <= 0));
      pile[pileNb] = chosenPile - howMany;
      nbOfTurns += 1;
    } while (!isArrayZero(pile));
    System.out.println(String.format("%s, You loose", player) );
  }
}


texts:
I have a server that is pretty stable (disk capacity) until a certain event occurs and then the drive grows over the course of two days until it is full. I wrote a very simple bash script but I'm not too happy with parts of it. First, I want to be able to see the capacity as a percent down to the tenths place. Also, doing an evaluation I had to strip my value of any decimal places to compare it against my defined threshold. Lastly I feel that I made too much use of cut where I could've been more efficient. I'd love to get some tips for improvement.

#! /bin/bash

monDrive=/opt
prevReading=/root/diskcheckreading.txt
percentThreshold=1
emailAlert=alerts@domain.com

#Check if log file exists

if [ ! -f $prevReading ]
    then
        touch $prevReading
        prev=$(printf "%0.2f\n" $(bc -l <<< $(df /opt | grep opt | cut -d' ' -f24)/$(df /opt | grep opt | cut -d' ' -f23)*100))
        echo $prev > $prevReading

fi

#Get current percentage used of monitored drive
current=$(printf "%0.2f\n" $(bc -l <<< $(df /opt | grep opt | cut -d' ' -f24)/$(df /opt | grep opt | cut -d' ' -f23)*100))

#import previous reading
prev=$(cat $prevReading)

#Calculate the difference
results=$(bc -l <<< $current-$prev )

#Convert to percentage
results100=$(bc <<< $results*100)

#Remove any number after decimal place so that bash can evaluate
rescleanup=$(echo $results100 | cut -d'.' -f1)

#Convert to percentage
percentThreshold100=$(bc -l <<< $percentThreshold*100)

#Check if the difference exceeds the threshold
if  [ $rescleanup -gt $percentThreshold100 ]
     then printf "\"$monDrive\" has grown $results%% in the past hour.\n\n$(hostname):$(pwd)/$(basename $0)" | mail -s "Disk Alert - $(hostname):$monDrive" $emailAlert

fi

#log current reading for next check
emailecho $current > $prevReading


texts: Checking that a password contains a '$', a digit, and an uppercase letter

texts:
I have this code, which reads in a string password from the user and checks if it has a dollar sign $, a number, and an upper case letter. If it has all three, it prints:

  Your password is correct

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

#define MAXSIZE 100

void password_read(char password[]);
int password_check(char password[]);

int
main(int argc, char *argv[]){

    char password[MAXSIZE];
    int sum;

    password_read(password);

    sum = password_check(password);

    if (sum) {
        printf("Your password is correct\n");
    } else {
        printf("Your password sucks\n");
    }

    return 0;
}

void
password_read(char password[]) {
    printf("Enter password:\n");
    scanf("%s", password);
}

int
password_check(char password[]) {
    int upper = 0;
    int digit = 0;
    int dollar = 0;
    int i;

    for (i = 0; i < strlen(password); i++) {

        if (isupper(password[i])) {
            upper = 1;
        }

        else if (isdigit(password[i])) {
            digit = 1;
        }

        else if (password[i] == '$') {
            dollar = 1;
        }
    }
    return (upper && digit && dollar);
}

I'm pretty shabby with C and I was just wondering if there was a way to reduce part of the code. I also just want to check if the pointer/array handling is correct, since I've only just started using it properly.


texts: VBA- Retrieving data from an access database by referencing a column in excel

texts:
I am not able to run the  for loop when number of rows exceed 8-9k.
Can you suggest an alternate method for this? can you suggest the syntax to referencing the data using a tablename(or column name) instead of looping over the cells one by one?

Sub ddd()
Const dbloc As String = "C:\Users\system1\Downloads\Database11.accdb"
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim xlbook As Workbook
Dim xlsheet As Worksheet
Dim a As Long
Dim SQL As String

Set xlbook = ActiveWorkbook
Set xlsheet = xlbook.Worksheets(1)
xlsheet.Range("B2:Z100000").ClearContents

Set db = OpenDatabase(dbloc)

SQL = "SELECT Material, MPN  "
SQL = SQL & "FROM Sheet2 "

  SQL = SQL & "WHERE Material IN ("
  Dim r As Range
  For Each r In Range("A2:A6768")
   SQL = SQL & r.Text & ","
  Next r
  SQL = Left(SQL, Len(SQL) - 1) 'Drop last comma
  SQL = SQL & ")"

Set rs = db.OpenRecordset(SQL, dbOpenSnapshot)
If rs.RecordCount = 0 Then
MsgBox "No data retrieved from database", vbInformation + vbOKOnly, "No
 Data"
    GoTo SubExit
Else
    rs.MoveLast
    recCount = rs.RecordCount
    rs.MoveFirst
End If
 xlsheet.Range("C2").CopyFromRecordset rs

End Sub


texts:
Is this authentication mechanism vulnerable to SQL injection?
If so, how could one exploit it, and what is the most effective way to mitigate this?

if (isset($_POST['userid']) && isset($_POST['password'])){

$username = $_POST['userid'];
$password = crypt($_POST['password'],'34l5kj');

    $query = "SELECT * FROM users WHERE name =:username and pass=:password";
$db->query($query);
$db->bind(':username', $username);
$db->bind(':password', $password);
$db->execute();
$data = $db->single();

            $_SESSION['valid_user'] = $username;
            $_SESSION['user_id'] = $data['id'];
            $_SESSION['pwd']=$_POST['password'];


texts:
Some time ago I've written a small parser (about 250 LoC) which is capable of executing the four arithmetic operators +-*/ as well as a dice-roll operator, NdM, which "rolls a dice", DnD style. The source contains only integers, but of course due to division, not only integers are handled. Floating-point errors are silently ignored and mocked.

Now that I've come across it again today, I feel a bit meh about it. It's not horrible, but it definitely could be better.

Since it's a bit longish, I'll only paste here the two functions I feel most uncomfortable about: The one which goes through the token lists and decides which to execute, and the one which actually executes the operators.

To clear up some details if you don't wish to see the entire source: The parser tokenizes input left->right, inserting numbers and operators into numberStack and operatorStack respectively. The "executer" (don't have a clue what's the proper name for it) goes right->left on the operator stack, and uses the simple operator-precedence logic to see which ones to execute. All these functions exist on one object. The rest should be straightforward from the variable/property names.

execute : function () {
    var idx;

    while ( (idx = this.operatorStack.length) ) {
        //execute, BACKWARDS! OH THE INSANITY
        while ( 0 <=-- idx ) {
            execute.call( this, this.operatorStack[idx], idx );
        }
    }

    function execute ( token, index ) {
        var last = this.operatorStack[ index + 1 ];

        //last one is more important than we are
        if ( last && last.precedence > token.precedence ) {
            //execute it
            this.operate( index + 1 );
        }
        //we're about to finish and the last one isn't as all-mighty as we
        // thought
        else if ( !index ) {
            //execute za operator!
            this.operate( index );
        }
    }
}

//snip

operate : function ( index ) {
    //grab the two numbers we care about
    //since the source string looks like: 2 + 1
    // and the index param is actually the index of the operator to use,
    // we grab the index-th number and the index-th+1 number
    //in the above example, index = 0, we grab numberStack[0] and
    // numberStack[1]
    var couplet = this.numberStack.slice( index, index + 2 );
    //in addition to the numbers we operate on, there's also a dice-roll
    // operator, so we take it into consideration
    couplet.push( this.rolls );

    //arr.splice removes items and returns the removed items as an array
    //we remove the index-th item from the operatorStack and grab its
    // "value", which is the operator symbol (+, * etc)
    //when we have that value, we grab the corresponding operator object
    var op = operators[ this.operatorStack.splice(index, 1)[0].value ];

    //arr.splice, as well as removing items, can also add items
    //so, we slice-n-dice at the two numbers, grab the result of executing
    // the operator, and add that result where we finished slicing
    //for example:
    // [0, 1, 2].splice( 0, 2, 42 )
    //will make the array look like
    // [42, 2]
    this.numberStack.splice( index, 2, op.exec.apply(null, couplet) );
}

Full code can be found here: https://gist.github.com/1761880


texts: Simple Neural Network from scratch using NumPy (Python)

texts:
I added learning rate and momentum to a neural network implementation from scratch I found at: https://towardsdatascience.com/how-to-build-your-own-neural-network-from-scratch-in-python-68998a08e4f6

However I had a few questions about my implementation:

Is it correct? Any suggested improvements? It appears to output
adequate results generally but outside advice is very appreciated.
With a learning rate < 0.5 or momentum > 0.9 the network tends to
gets stuck in a local optimum where loss = ~1. I assume this is
because step size isn't big enough to escape this but is there a way
to overcome this? Or is this inherent with the nature of the data
being solved and unavoidable.

import numpy as np
import matplotlib.pyplot as plt

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def sigmoid_derivative(x):
    sig = 1 / (1 + np.exp(-x))
    return sig * (1 - sig)

class NeuralNetwork:
    def __init__(self, x, y):
        self.input      = x
        self.weights1   = np.random.rand(self.input.shape[1], 4)
        self.weights2   = np.random.rand(4, 1)
        self.y          = y
        self.output     = np.zeros(self.y.shape)
        self.v_dw1      = 0
        self.v_dw2      = 0
        self.alpha      = 0.5
        self.beta       = 0.5

    def feedforward(self):
        self.layer1 = sigmoid(np.dot(self.input, self.weights1))
        self.output = sigmoid(np.dot(self.layer1, self.weights2))

    def backprop(self, alpha, beta):
        # application of the chain rule to find derivative of the loss function with respect to weights2 and weights1
        d_weights2 = np.dot(self.layer1.T, (2*(self.y - self.output) * sigmoid_derivative(self.output)))
        d_weights1 = np.dot(self.input.T,  (np.dot(2*(self.y - self.output) *
                                            sigmoid_derivative(self.output), self.weights2.T) *
                                            sigmoid_derivative(self.layer1)))
        # adding effect of momentum
        self.v_dw1 = (beta * self.v_dw1) + ((1 - beta) * d_weights1)
        self.v_dw2 = (beta * self.v_dw2) + ((1 - beta) * d_weights2)
        # update the weights with the derivative (slope) of the loss function
        self.weights1 = self.weights1 + (self.v_dw1 * alpha)
        self.weights2 = self.weights2 + (self.v_dw2 * alpha)

if __name__ == "__main__":
    X = np.array([[0, 0, 1],
                  [0, 1, 1],
                  [1, 0, 1],
                  [1, 1, 1]])
    y = np.array([[0], [1], [1], [0]])
    nn = NeuralNetwork(X, y)

    total_loss = []
    for i in range(10000):
        nn.feedforward()
        nn.backprop(nn.alpha, nn.beta)
        total_loss.append(sum((nn.y-nn.output)**2))

    iteration_num = list(range(10000))
    plt.plot(iteration_num, total_loss)
    plt.show()
    print(nn.output)


texts: Spawning child processes and event-listening

texts:
This function scrapes data from a webpage by spawning a process that executes a CasperJS web scraping script. The spawned process outputs data to stdout.

This function has an event listener for stdout and this is how the parent process (Node) gets the scraped data back. How can I make this more modular? Also, would creating a child_process class make more sense?

function scrapeLinks(location, callback) {

    // stores any data emitted from the stdout stream of spawned casper process
     var processData = "";

     // stores any errors emitted from the stderror stream of spawned casper process
     var processError = "";

    // initialises casperjs link scraping script as spawned process
    var linkScrapeChild = child_process.spawn(casperjsPath, ['casperLinkScript.js ' + location]);

     linkScrapeChild.stdout.on('data', function onScrapeProcessStdout(data) {
         processData += data.toString();
         console.log(data.toString())
     });

     linkScrapeChild.stderr.on('data', function onScrapeProcessError(err) {
         processError += err.toString();
     });

     linkScrapeChild.on("error", function onScrapeProcessError(err) {
         processError = err.toString();
     });

    //once spawned casper process finishes execution call the callback
    linkScrapeChild.on('close', function onScrapeProcessExit(code) {

        console.log('Child process - Location Scrape:  ' + location + ' - closed with code: ' + code);

         processData = convertToArray(processData);

         // filter out non valid listing links
         listingLinks = filterLinks(processData);

         //console.log(listingLinks);

         // filter duplicates
         var uniqueLinks = [ ...new Set(listingLinks) ];

        if(uniqueLinks.length === 0){
            processError += 'No valid listings found for ' + location
        }

         logScrapeResults(processError, uniqueLinks, location);

         callback(processError || null, uniqueLinks);
    });
}


texts: Converting from MySQLi to PDO account activation

texts:
I had been working on a project for some time, and then it went on the way back burner after my daughter was born.  I'm back to it, and now I discover that I'm best off using PDO over MySQLi.  So, I'm working on the conversion, and I'd like to get some confirmation that I'm handling things well.  Essentially: Does this code look secure and sound?  [It's just my account activation php.]

<?php
require_once ('common.php');

$x = $y = FALSE;
if (isset($_GET['x']) && filter_var($_GET['x'], FILTER_VALIDATE_EMAIL)) {
    $x = $_GET['x'];
}
if (isset($_GET['y']) && (strlen($_GET['y']) == 32 )) {
    $y = $_GET['y'];
}

if ($x && $y) {
    $query = "SELECT 1 FROM users WHERE (email=:email AND confirm IS NULL)";
    $query_params = array( ':email' => $x );
    try {
        $stmt = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch(PDOException $ex) {
        die("Failed to run query: " . $ex->getMessage());
    }

    $count = $stmt->rowCount();
        if($count == 1) {
            echo "
Your account is already activated. No need to activate again. You may now log in.
";
            exit();
        } else { // Not an active user
            $query = "UPDATE users SET confirm=NULL WHERE (email=:email AND confirm=:confirm) LIMIT 1";
            $query_params = array(
                ':email' => $x,
                ':confirm' => $y
            );

            try {
                $stmt = $db->prepare($query);
                $result = $stmt->execute($query_params);
            }
            catch(PDOException $ex) {
                die("Failed to run query: " . $ex->getMessage());
            }

            $count = $stmt->rowCount();
                if($count == 1) {
                    echo "
Your account is now active. You may now log in.
";
                    exit();
                } else {
                    echo '
Your account could not be activated. Please re-check the link or contact the system administrator.
';
                    exit();
                }
        }

} else {
    $url = BASE_URL . 'index.html';
    ob_end_clean();
    header("Location: $url");
    exit();
}

?>

I am aware that the $ex->getMessage() needs to go before production.


texts:
I don't know it is some design pattern for it or I can't do it in a different way the code looks like this:
Iteam iteam = itemRepository.findByNameAndNoAndCountryCodeAndCurrencyCode(name, countryCode, currencyCode);
    if(item == null){
        item = itemRepository.findByNameAndNoAndCountryCodeAndCurrencyCode(name, "US", currrencyCode)
    }
    if(item == null){
        item = itemRepository.findByNameAndNoAndCountryCodeAndCurrencyCode(name, countryCode, "USD")
    }
    if(item == null){
        item = itemRepository.findByNameAndCountryCode(name, countryCode)
    }
    if(item == null){
        item = itemRepository.findByNameAndCurrencyCode(name, currrencyCode)
    }

And I have a lot of this (like 15) kind of queries with the condition it is possible to do not make to many conditions and use some trick for this code?


texts:
I'm creating list of Tokens from input [Char] stream using Parsec v3. The definition of Token looks like this:

data Token = CharKeyword | OpeningBracket | Identifier String | Natural Int

As result of calling parse lexComb "" inputStream i have [Token]. Everything OK so far.

Now i want to parse this list of tokens using another parse invocation, but i've found myself writing such boilerplate code for every Token constructor:

psOpBracket = tokenPrim s np p
    where
        s _ = "'{'"
        p (OpeningBracket) = Just Nothing
        p _ = Nothing
        np pos _ _  = pos

another example:

psPacketName = tokenPrim s np p
    where
        s x = x
        p (Identifier x) = Just x
        p _ = Nothing
        np pos _ _  = pos

I wonder if it's right to use tokenPrim at all. And if so, is there any way to automatically generate parsers for every token? Maybe Template Haskell?


texts:
I have a long list of sorted strings in a Workbook, and I have to find a lot of values in it. I was hoping to build a binary search Class Module that will find them for me faster than Excel's built-in search formulas/methods.

Can anyone think of a faster way, or maybe more bug proof?

Values() As String
Value2 as String
Upper As Integer
Lower As Integer
Middle As Integer
Private Function Move_Array() As Integer
    Middle = Round((Upper - Lower) / 2, 0)
    Move_Array = Compare(Values(Middle), Value2)
End Function
Function Search(Cells As Range, Value As String) As Integer
    If Cells.Count < 1 Then
        Values() = Cells.value
    End If
Value2 = Value
Again:
    Select Case Move_Array()
        Case -1
            Lower = Middle
        Case 1
            Upper = Middle
        Case 0
            Search = Middle
            Exit Function
    End Select
    GoTo Again
End Function

This is a Sub that would call this class. However, this is subject to change.

Sub Start_BINSearch()
    Dim Search_operation As BINSearch
    Dim Cells As Range
    Dim Value As String

    Set Search_operation = BINSearch
    Set Cells = Application.InputBox( _
        Prompt:="Enter Range to Search", _
        Type:=8)
    Value = Application.InputBox( _
        Prompt:="Enter value that you waant to look for")
    Position = Search_operation.Search(Cells, Value)
End Sub


texts: Managing inherited dependency properties in WPF

texts:
Exposing Inherited Members

I have a WPF Custom Control library (ContentToggleButton) and an app (spec) to test it. The Custom Controls, which derive from Presentation Framework elements, expose inherited properties as well as new properties to the consumer.

This means that the consuming app depends on the Framework Elements as well as the Custom Controls as shown by the four dependencies from the top and bottom of MainWindow in the following diagram.

Reimplementing Inherited Members

The references were due to the IsChecked dependency property of the ToggleButton base class of the ContentToggle object and the Click event of the ButtonBase base class of the ButtonContent object. The former was bound in the XAML to a method on the MainWindow class in the View, code behind.

<b:ContentToggle Name="Toggle" Height="30"
                 Options="{Binding ToggleButtonView.Options,
                            RelativeSource={StaticResource View}}"
                 IsChecked="{Binding ToggleButtonView.InitialState,
                            Mode=OneWay,
                            RelativeSource={StaticResource View}}" />
<b:ContentButton x:Name="Plain" Height="30"
                 Options="{Binding PlainButtonView.Options,
                            RelativeSource={StaticResource View}}" />

The RelativeSource resource is defined in Resource Dictionary in App.xaml.

<!--Get a reference to the window to establish View Context-->
<RelativeSource x:Key="View" Mode="FindAncestor"
            AncestorType="{x:Type Window}" />

The second dependency was due to subscribing to the Click event inherited from ButtonBase in the MainWindow class.

Plain.Click += (s, e) => {
    Toggle.IsEnabled = !Toggle.IsEnabled;
};

By adding a custom DP called InitialState on ContentToggle and binding to that instead then using it to initialise IsChecked in the Loaded event, one of the dependencies was eliminated.

public static readonly DependencyProperty
    InitialStateProperty = DependencyProperty.Register(
    "InitialState", typeof(bool?), typeof(ContentToggle),
    new PropertyMetadata(false));

public bool? InitialState
{
    get { return (bool?) GetValue(InitialStateProperty); }
    set { SetValue(InitialStateProperty, value); }
}

The second dependency was eliminated by reimplementing the Click event in the custom property and routing the original event through it.

public static readonly RoutedEvent ClickEvent = EventManager.RegisterRoutedEvent(
    "Click", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ContentToggle));

public new event RoutedEventHandler Click
{
    add { AddHandler(ClickEvent, value); }
    remove { RemoveHandler(ClickEvent, value); }
}

void RaiseClickEvent (object o, RoutedEventArgs e)
{
    RoutedEventArgs newEventArgs = new RoutedEventArgs(ContentToggle.ClickEvent);
    RaiseEvent(newEventArgs);
}
public ContentToggle()
{
    base.Click += RaiseClickEvent;

}

As a result, the consuming app is unaware of the primitive components with dependencies only on the CC Library.

Is this a good idea or a bad one? Is it worth the extra code?


texts:
This is a personal project of mine.  I made a simple seven day agenda program in Python that stores tasks as a string, saves it into a .dat file, and returns that task when you input a day of the week.  This works on a terminal.  I'm new to programming in general.
This is Python 3.8.2, 32 bit, and in a virtual environment.
# Pickle module allows you to save data after program closes
import pickle

week = {"Sunday": [], "Monday": [], "Tuesday": [],
        "Wednesday": [], "Thursday": [], "Friday": [], "Saturday": []}

def agenda():
    option = input(
        "What would you like to do?  (A - look at agenda, B - create task, C - clear list, or D - quit) ").upper()
    if option == "A":
        look_at_agenda()
    elif option == "B":
        create_task()
    elif option == "C":
        clear_list()
    elif option == "D":
        print("Have a nice day!")
    else:
        print("Invalid option.")
        agenda()

# global allows day variable in other functions to work even without declaring it

def valid_days():
    global day
    day = input("Which day? ").capitalize()
    week_list = [day_list for day_list in week.keys()]
    if day not in week_list:
        print("Invalid day.")
        valid_days()

# Loads whatever string from week.dat file
def look_at_agenda():
    see_all = input("See entire week? Y - yes, N - no. ").upper()
    if see_all == "Y":
        week = pickle.load(open("week.dat", "rb"))
        print(week)
    elif see_all == "N":
        valid_days()
        week = pickle.load(open("week.dat", "rb"))
        print(week[day])
    else:
        print("Invalid option.")
        look_at_agenda()
    agenda()

def create_task():
    valid_days()
    task = input("Describe your task. ")
    # Loads string from week.dat file; when program restarts, it allows you to create a task without deleting the saved ones
    week = pickle.load(open("week.dat", "rb"))
    week[day].append(task)
    # Saves string into week.dat file so it remembers when you open the program again
    pickle.dump(week, open("week.dat", "wb"))
    agenda()

def clear_list():
    clear_all = input("Clear all lists? Y - yes, N - no ").upper()
    if clear_all == "N":
        valid_days()
        week[day].clear()
        print(f"List cleared for {day}!")
        # saves the new list into a week.dat file
        pickle.dump(week, open("week.dat", "wb"))
    elif clear_all == "Y":
        [week[day].clear() for day in week]
        # saves the now empty list into a week.dat file
        pickle.dump(week, open("week.dat", "wb"))
    else:
        print("Invalid option.")
        clear_list()
    agenda()

agenda()


texts: Taking some JSON data, converting the date format and calculating a user average

texts:
I'm originally a Java developer taking a stab at some Scala development. One of the main reasons I'm posting is because I know that in Scala you can write your code in a Java (OOP) way and it will run but that makes it bad Scala code.

I was hoping I could get a review of my code and maybe somebody could point out how I could be doing things a bit more in a functional way.

A method to get a set of JSON objects from a directory:

def createJsonSessionSet(filePaths: Set[String]) : Set[JSONObject] = {
    val sessions: Set[JSONObject] = Set()
    val parser: JSONParser = new JSONParser

    for (filePath <- filePaths) {
      val jsonObject: JSONObject = parser.parse(new FileReader(filePath)).asInstanceOf[JSONObject]
      sessions.add(jsonObject)
    }

    return sessions
}

A method that lists directories from a file path:

def getListOfJsonFilePaths(file: File): Set[String] = {
    val filePaths: Set[String] = Set()

    for (file <- file.listFiles) {
      filePaths.add(file.getAbsolutePath)
    }

    return filePaths
}

A method that takes a set of json objects and converts the time:

def convertTimeZone(sessions: Set[JSONObject]): Set[JSONObject] = {

val convertedSessions: Set[JSONObject] = Set()
val parser: JSONParser = new JSONParser

val utcFormat: DateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"))

val newFormat: DateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
newFormat.setTimeZone(TimeZone.getTimeZone("Etc/GMT+7"))

for (session <- sessions) {

  val date: Date = utcFormat.parse(session.get("UTCStartTime").toString)

  implicit val formats = Serialization.formats(NoTypeHints)

  val convertedSession = Map(
    "SessionId" -> session.get("SessionId").toString,
    "UserId" -> session.get("UserId").toString,
    "Score" -> session.get("Score").toString,
    "ETCStartTime" -> newFormat.format(date)
  )

  val jsonObject: JSONObject = parser.parse(write(convertedSession)).asInstanceOf[JSONObject]

  convertedSessions.add(jsonObject)

}
return convertedSessions
}

A method that returns a set of JSON objects based on a set of JSON objects:

def getOutputData(convertedSessions: Set[JSONObject]): Set[JSONObject] = {

val outputData: Set[JSONObject] = Set()

val distinctUserIds: Set[String] = Set()
val distinctDays: Set[String] = Set()

for (session <- convertedSessions) {
  distinctUserIds.add(session.get("UserId").toString)
  distinctDays.add(session.get("ETCStartTime").toString.split("T")(0))
}

for (day <- distinctDays) {
  for (userId <- distinctUserIds) {

    implicit val formats = Serialization.formats(NoTypeHints)

    val data = Map(
      "UserId" -> userId,
      "Day" -> day,
      "AverageScore" -> 10
    )
    val parser: JSONParser = new JSONParser

    val jsonObject: JSONObject = parser.parse(write(data)).asInstanceOf[JSONObject]

    if (!jsonObject.get("AverageScore").toString.contains("NaN"))
       outputData.add(jsonObject)

  }
}

return outputData
}

I went about this mini project by first writing it in Java which was easy enough. I had trouble with the next method that returned fine in Java, but not so well in Scala.  I think it has something to do with the fact that in Java I used ArrayLists but Scala not supporting that I used sets.

def getUserDailyAverageScore(userId: String, day: String, sessions:  Set[JSONObject]): Double = {
    var sum: Double = 0
    var sessionSize: Int = 0

    for (session <- sessions) {
      println("test")
      if (session.get("UserId").toString.equals(userId) && session.get("ETCStartTime").toString.startsWith(day)) {
        sum += session.get("Score").asInstanceOf[Double]
        sessionSize += 1
      }
    }

    return sum / sessionSize
}

From debugging, the code never steps into the if statement whilst in Java it does.


texts:
The problem:  find and return the first nonrepeating character in a string, if the string does not have a nonrepeating character return an empty string. For purposes of finding the nonrepeating character it's case insensitive so 't' and 'T' appearing in the string would imply that that 't' and 'T' are not candidates for a nonrepeating character.  When you return the character you must return it as its original case.

My Solution:

def non_repeat(_str):
    counts = {}
    for pos, letter in enumerate(_str.lower()):
        if letter not in counts:
                counts[letter] = (0, pos)
        incr_val = counts[letter][0] + 1
        counts[letter] = (incr_val, pos)
    for letter in _str.lower():
        if counts[letter][0] == 1:
            return _str[counts[letter][1]]
    return ''

How can I improve the readability of my solution?  In particular, I don't like:

counts[letter][0] because the 0 index is a bit ambiguous.
calculating the incremented value as another line, incr_val; it'd be nice to do the incrementing and updating of the dict in one line.

Anything else you could make more readable? I should add that I'm aware of collections.Counter; for this solution I'd like to avoid using it.


texts: Written worker using sidekiq for activerecord class

texts:
I have two model classes as follows:

class FileInfo < ActiveRecord::Base
  STATUS = {:UNAPPROVED => 1, :APPROVED => 2, :PROCESSED => 3 }
  attr_accessible :id, :status
  validates :status, :inclusion => {:in => STATUS.values}
end

FileInfo has id and status fields. Each file can multiple file-entries (rows) of the type FileEntry. FileEntry has id, file_info_id (foreign key of FileInfo) and status fields.

class FileEntry < ActiveRecord::Base
  STATUS = {:UNAPPROVED => 1, :READY => 2 , :SENT => 3 }
  attr_accessible :id, :file_info_id, :status, :reason
  validates :status, :inclusion => {:in => STATUS.values}
end

I want to write a worker to asynchronously process all files whose status field is APPROVED (FileInfo model). Each of the thread should process all file-entries for that particular file whose status is READY. The thread should finish once all the entries are processed for that file. Assuming that File-entries having status UNAPPROVED will also become READY.

Once each entry is processed, its status should be updated as SENT. Once all the file-entries all have SENT status for a particular file, update that file's status as PROCESSED.

I have code this much so far. Not able to figure out how to code the worker:

class FileInfoObserver < ActiveRecord::Observer
  def after_save(file_info)
    if file_info.status.eql? 2
       FileProcessingJob.perform_async(file_info.id)
    end
  end
end

The worker is as follows:

class FileProcessingJob
  include Sidekiq::Worker
  def perform(file_id)
    puts "job"
    flag =1
    while flag==1
      count = 0
      FileRow.where("file_info_id = #{file_id}").find_each do |file_row|
        if(file_row.status == 2)
          puts "update" //Some PUT request, instead wrote a puts statement
          FileRow.update(file_row.id, :status => 3)
        elsif(file_row.status == 0 || file_row.status ==1)
          count = count + 1
        end
      end
      if(count == 0)
        flag = 0
      end
    end
  end
end

Is this correct way of doing it? How to enable retry mechanism? Is this code thread-safe?


texts: Function that shows markers all at once or with a delay

texts:
I have some markers on an image. At some point all these markers are inactive (i.e. a class name is added to the element, which hides them) and need to be shown again. This is done by the method showAll() of a class (it's not a loose function).

This function works like this:

if no delay is given as a parameter, all markers are shown right away
if delay is "true", the markers are shown one after another

This is my implementation:

showAll(delay) {
    for (let i = 0; i < this.elements.length; ++i) {
        const element = this.elements[i];

        if (delay) {
            element.classList.remove('inactive');
        } else {
            setTimeout(e => {
                element.classList.remove('inactive');
            }, this.delay * i);
        }
    }
}

A few words to understand all variables:

this.elements is a list of cached DOM elements
this.delay is simply the delay in ms

I'm concerned about the branching and the repetition of element.classList.remove('inactive');. However I'm not a fan of this solution:

setTimeout(e => {
    element.classList.remove('inactive');
}, delay ? this.delay * i : 0);

It seems unecassary to call setTimout() anyway.

Is there any way to improve this code?


texts: Make a version of make-rat that handles positive and negative arguments

texts:
Given the following task from SICP

  Exercise 2.1

  Define a better version
  of make-rat that handles both positive
  and negative arguments. Make-rat
  should normalize the sign so that if
  the rational number is positive, both
  the numerator and denominator are
  positive, and if the rational number
  is negative, only the numerator is
  negative.

And these prerequisite functions:

(define (gcd a b) (if (= b 0) a (gcd b (remainder a b))))

(define (numer a) (car a))
(define (denom a) (cdr a))
(define (print-rat a)
  (newline)
  (display (numer a))
  (display "/")
  (display (denom a)))

(define (add-rat a b)
  (make-rat (+ (* (numer a) (denom b))
               (* (numer b) (denom a)))
            (* (denom a) (denom b))))
(define (sub-rat a b)
  (make-rat (- (* (numer a) (denom b))
               (* (numer b) (denom a)))

            (* (denom a) (denom b))))
(define (mul-rat a b)
  (make-rat (* (numer a) (numer b))
            (* (denom a) (denom b))))
(define (div-rat a b)
  (make-rat (* (numer a) (denom b))
            (* (numer b) (denom a))))

I wrote this version of (make-rat ... ).  What do you think?

(define (make-rat n d)
  (define (sign n d) (if (> (* n d) 0) + -))
  (let* ((abs-n (abs n))
         (abs-d (abs d))
         (div (gcd abs-n abs-d)))
    (cons ((sign n d) (/ abs-n div))
          (/ abs-d div))))


texts: Converting between std::wstring and std::string

texts:
While researching ways to convert back and forth between std::wstring and std::string, I found this conversation on the MSDN forums.

There were two functions that, to me, looked good. Specifically, these:

std::wstring s2ws(const std::string& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

std::string ws2s(const std::wstring& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, 0, 0, 0, 0);
    char* buf = new char[len];
    WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, buf, len, 0, 0);
    std::string r(buf);
    delete[] buf;
    return r;
}

However, the double allocation and the need to delete the buffer concern me (performance and exception safety) so I modified them to be like this:

std::wstring s2ws(const std::string& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
    std::wstring r(len, L'\0');
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, &r[0], len);
    return r;
}

std::string ws2s(const std::wstring& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, 0, 0, 0, 0);
    std::string r(len, '\0');
    WideCharToMultiByte(CP_ACP, 0, s.c_str(), slength, &r[0], len, 0, 0);
    return r;
}

Unit testing indicates that this works in a nice, controlled environment but will this be OK in the vicious and unpredictable world that is my client's computer?


texts: Extracting necessary records from LinkedIn

texts:
I wanted to create a scraper in python which can fetch required data from LinkedIn. I tried with python in many different ways but I could not make it until I used selenium in combination with. However, I have created it and got it working as I wanted.

The most difficult part I had to face while making this crawler is that there are hundreds of profile pages which can be located with mostly three different XPath patterns. I somehow managed to cement the three different XPath patterns into one. Now it is working great.

This scraper firstly clicks on the view all recommendation tab in home page then parse 200 profiles [customized in this case] by going to the main page of each profile. I've tried to make it error-free. Here is what I've done:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def producing_links(driver, wait):

    driver.get('https://www.linkedin.com/')

    driver.find_element_by_xpath('//*[@id="login-email"]').send_keys('someusername')
    driver.find_element_by_xpath('//*[@id="login-password"]').send_keys('somepassword')
    driver.find_element_by_xpath('//*[@id="login-submit"]').click()

    wait.until(EC.visibility_of_element_located((By.XPATH, "//a[contains(@class,'feed-s-follows-module__view-all')]")))
    driver.find_element_by_xpath("//a[contains(@class,'feed-s-follows-module__view-all')]").click()

    while True:
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

        wait.until(EC.visibility_of_element_located((By.XPATH, "//a[contains(@class,'feed-s-follow-recommendation-card__profile-link')]")))
        links = [item.get_attribute("href") for item in driver.find_elements_by_xpath("//a[contains(@class,'feed-s-follow-recommendation-card__profile-link')]")]
        if (len(links) == 200):
            break

    for link in links:
        get_docs(driver, wait, link)

def get_docs(driver, wait, name_link):

    driver.get(name_link)
    try:
        for item in driver.find_elements_by_xpath("//div[contains(@class,'pv-top-card-section__information') or contains(@class,'org-top-card-module__details') or (@class='org-top-card-module__main-column')]"):
            name = item.find_element_by_xpath(".//h1[@title]|.//h1[contains(@class,'pv-top-card-section__name')]").text
            title = item.find_element_by_xpath(".//span[contains(@class,'company-industries')]|.//h2[contains(@class,'pv-top-card-section__headline')]").text
    except Exception as e:
        print(e)

    finally:
        try:
            print(name, title)
        except Exception as ex:
            print(ex)

if __name__ == '__main__':

    driver = webdriver.Chrome()
    wait = WebDriverWait(driver, 10)

    try:
        producing_links(driver, wait)
    finally:
        driver.quit()


texts:
I've tried implementing priority queue with fixed size in Java using TreeSet and overriding add() method:

public class FixedSizePriorityQueue<E> extends TreeSet<E> {
    private final int capacity;

    public FixedSizePriorityQueue(final int capacity) {
        this.capacity = capacity;
    }

    public FixedSizePriorityQueue(
            final int capacity,
            final Comparator<? super E> comparator) {

        super(comparator);
        this.capacity = capacity;
    }

    @Override
    public boolean add(final E e) {
        // initialized with 0 or less than zero capacity
        if (capacity <= 0) {
            return false;
        }

        // keep adding until we fill the queue
        if (size() < capacity) {
            return super.add(e);
        }

        if (comparator() != null
                && comparator().compare(this.last(), e) < 0) {
            pollLast();
            return super.add(e);
        }

        return false;
    }
}

I would really appreciate your thoughts, hints and comments.


texts: Functionally retrieving rows from a database in Scala

texts:
Consider the following piece of code:

var result = List[Measurement]()

val dbResult = conn.createStatement.executeQuery(unsentMeasurements)

while(dbResult.next) {
  result ::= Measurement(dbResult.getString("stuff"), dbResult.getString("morestuff"))
}

result.reverse

Versus this:

val dbResult = conn.createStatement.executeQuery(unsentMeasurements)

Stream.continually(dbResult).takeWhile(_.next) map { r =>
  Measurement(r.getString("stuff"), r.getString("morestuff"))
}

Any flaws in my rationale? Any improvements?


texts: Detect whether a string has a letter 'b' 3 characters after 'a'

texts:
I'm relatively new to JavaScript and wonder whether my code is 'acceptable' for a practice exercise. Essentially, the function (successfully) returns true or false if the provided string has a letter 'b' 3 characters after a letter 'a' - e.g.:

Input:"after badly" - Output:"false"
Input:"Laura sobs" - Output:"true"

Could somebody advise me how it could be improved? Although it works, I wonder whether the best functions are used and whether its 'readability' could be improved (i.e. return trueOrFalse.some(answer) ).

function bThreeAfterA(a) {
 var b = (a.split(' ').join('')).split('a'); // creates array

 var trueOrFalse = b.map(function(c, i){ // puts into array true/false for each index
  if (c[2] == 'b') {
   console.log('value: ' + c[2] + ' is b; true');
   return true;
  } else {
   console.log('false');
   return false;
  }
 });

 var answer = function(el) {
 // checks whether any index is true
  return el === true;

};

 return trueOrFalse.some(answer); // return true/false
}


texts: Recursively find files of certain types and log their paths (C++)

texts:
I've written a function that takes a list of extensions and recursively finds files of those types, and logs their paths to a text file.

Usage example (finding image files in a home directory):

// set up filestream for unicode
const std::locale utf8_locale = std::locale(std::locale(), new std::codecvt_utf8<wchar_t>());
std::wofstream log("image_paths.txt", std::ios::app); // append mode
log.imbue(utf8_locale);

const std::set<std::wstring> image_extensions = {L".jpeg", L".jpg", L".tiff", L".gif", L".bmp", L".png"};
get_files(L"C:\\Users\\username", image_extensions, log);

Output to image_paths.txt:

C:\Users\username\image.jpg
C:\Users\username\image.png
C:\Users\username\directory\ajdsk.bmp
C:\Users\username\directory\subdirectory\other file.tiff
C:\Users\username\directory with spaces\file with spaces.jpeg

Function Code:

// return 0 -- all good
// return 1 -- root doesn't exist
// return 2 -- root isn't a directory
// return 3 -- no matching files found or error opening first file
// return 4 -- hit recursion limit
auto get_files(_In_ const std::wstring root, // root dir of search
        _In_  const std::set<std::wstring> &ext, // extensions to search for
        _Out_ std::wofstream &log, // file to write paths to
        _In_  unsigned limit = 10 /* default recursion limit */) -> int
{
    if(limit == 0) return 4;

    // check root path
    {
        DWORD root_attrib = GetFileAttributesW(root.c_str());

        if(root_attrib == INVALID_FILE_ATTRIBUTES) return 1;    // root doesn't exist
        if(!(root_attrib & FILE_ATTRIBUTE_DIRECTORY)) return 2; // root isn't a directory
    }

    LPCWSTR dir; // root directory + "\*"
    HANDLE file = INVALID_HANDLE_VALUE; // handle to found file
    WIN32_FIND_DATAW file_info; // attributes of found file

    // prepare path for use with FindFile functions
    std::wstring root_slash = root;
    root_slash.append(L"\\*");
    dir = root_slash.c_str();

    file = FindFirstFileW(dir, &file_info);

    if(file == INVALID_HANDLE_VALUE) return 3; // no matching files found or error opening first file

    do { // for each file in directory

        // for some reason
        // file_info != L"." && file_info != L".."
        // won't work unless file_info.cFileName is assigned to a var
        std::wstring name = file_info.cFileName;

        std::wstring path = root; // full path to current file
        path.append(L"\\").append(name);

        if(!(file_info.dwFileAttributes & FILE_ATTRIBUTE_READONLY)        // not read-only
                && !(file_info.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE) // not physically moved to offline storage
                && !(file_info.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)  // not a system file
                && file_info.dwFileAttributes != INVALID_FILE_ATTRIBUTES  // not invalid
                && (name != L"." && name != L"..")) { // not "." or ".."
            if(file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // file is a directory
                get_files(path, ext, log, --limit);
            else // file is not a directory
                if(ext.find(PathFindExtensionW(path.c_str())) != ext.end()) // extension matches
                    log << path << '\n' << std::flush; // log path to file
        }
    } while(FindNextFileW(file, &file_info) != 0);

    FindClose(file);

    return 0;
}


texts:
For a plugin I'm writing in jQuery, I have two optional parameters. For each parameter I do a check for its value. However, I'm curious if I can't write it shorter.

jsFiddleiddle

(function ($) {
    $.rgbGenerator = function (color, options) {
        var args = $.extend({
            returnAsObj: false,
            addAlpha: false
        }, options);

        var d = $("<div>");
        d.css("color", color).appendTo("body");
        var rgb = d.css("color");
        rgb = rgb.replace(/(^rgba?\(|\)$|\s)/g, "").split(",").map(Number);
        d.remove();
        if (args.addAlpha === false) {
            if (rgb.length == 3) {
                if (!args.returnAsObj === true) {
                    return "rgb(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")";
                } else {
                    return {
                        r: rgb[0],
                        g: rgb[1],
                        b: rgb[2]
                    };
                }
            } else if (rgb.length == 4) {
                if (!args.returnAsObj === true) {
                    return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + rgb[3] + ")";
                } else {
                    return {
                        r: rgb[0],
                        g: rgb[1],
                        b: rgb[2],
                        a: rgb[3]
                    };
                }
            }
        } else {
            if (!args.returnAsObj === true) {
                return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + args.addAlpha + ")";
            } else {
                return {
                    r: rgb[0],
                    g: rgb[1],
                    b: rgb[2],
                    a: args.addAlpha
                };
            }
        }
    };
})(jQuery);

Basically, what it does is:

Check args.addAlpha whether it's false (default)
Check the length of rgb (when it's 3 it's RGB, when it's 4 it's rgba)
Check args.returnAsObj. If it's set to true, return an object rather than a string

Especially the part where I check the length of rgb seems unnecessary, but I'm not sure how I could write it any other way. Something like this would be nice:

return {
    r: rgb[0],
    g: rgb[1],
    b: rgb[2],
    a: function () {
        if (rgb.length == 4 || !args.addAlpha === false) {
            return rgb[3] || args.addAlpha;
        }
    }
};

But I assume that's not possible.


texts: Struggling to unit test Angular, was this module the best approach?

texts:
As a development team we've recently started to transition from MVC to Angular. None of us have had prior experience with it so a lot of creating the new client was very much trial and error. I've been put in charge of sorting out unit tests however I'm finding it very difficult to unit test.

In my experience if something is difficult to unit test it generally means some refactoring is in order. Problem is I do not have enough experience with Angular to say yay or nay on this.

Main angular module:

angular.module('serviceApp', ['mgcrea.ngStrap', 'ngRoute', 'LocalStorageModule', 'account.module', 'admin.module', 'design-code-review.module', 'early-load-test.module', 'integration-load-test.module', 'production-validation.module', 'risk-modelling.module', 'unit-test-profiling.module','error.module'])
.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/login', {
            templateUrl: '/views/account/login.html',
            controller: 'account.controller'
        })
         .when('/admin', {
             templateUrl: '/views/admin/project-admin.html',
             controller: 'admin.controller'
         })
        .when('/register', {
            templateUrl: '/views/account/register.html',
            controller: 'account.controller'
        })
        .otherwise('/login');
}])
.config(function($httpProvider){
    $httpProvider.interceptors.push('authentication.interceptor')
})
.run(['authentication.service', function (authentication) {
    authentication.populateAuthentication();
}]);

Declared in other js files are factories and services for our serviceApp

Example factory class:

angular.module('serviceApp')
.factory('storage.factory', ['$http', 'applicationSettings', 'localStorageService', function ($http, applicationSettings, localStorageService) {

    var getItems = function () {
        return $http.get(applicationSettings.apiLocation + 'Items/GetAll').then(function (response) {
            localStorageService.set('items', response.data);
        },
        function (error) {
            console.log("Could not retrieve data.");
        });
    };

    return {
        getItems: getItems
    };
}]);

Currently I'm having a lot of trouble trying to test these factories and services because of the sheer number of dependencies that serviceApp has. When looking for examples online I see that a lot of modules have only 1 or 2 dependencies which got me thinking whether the above is typical of an Angular application. Is having a lot of dependencies for a module like this ok in Angular? Or am I being a bit dense and need to get my unit testing in order?


texts: Solving Exact Cover by Three Products in Python

texts:
I'm a computer-science hobbyist and found an NP-complete problem that is similar to both subset-product and Exact Cover by 3-sets.

Here is a Reduction of Exact-Cover into my problem. I am multiplying all integers in sets of C.

Input prior to reduction
s:  [1, 2, 3, 4, 5, 6]
c:  [[5, 2, 1], [6, 4, 3]]
Output after reduction
s : [1, 2, 3, 4, 5, 6]
c : [10, 72]
Integers needed for True subset-product
[[5, 2, 1], [6, 4, 3]]

Algorithm

import itertools
from itertools import combinations
from itertools import permutations
import operator
from operator import mul
from functools import reduce

s = [1,2,3,4,5,6]
c = 10,72

# Preparing all possible
# three-element sets

find_X_thr_covers=[];
for jj in permutations((s), 3):
    if len(jj) == len(set(jj)):
        # I will "remember" multiplied sets in c for later use.
        if reduce(mul, jj) in c:
            find_X_thr_covers.append(jj)

# Here, I will use len(s)//3 combinations
# for a special case of the Exact Cover
# problem by 3-sets.

solutions = []
solutions_two = []
for jj in combinations(find_X_thr_covers, len(s)//3):
    # Here I will verify that every possible combination
    # is indeed a true solution.
    jj_flat = [item for sub in jj for item in sub]
    jj_set = set(jj_flat)
    if set(s) == jj_set and len(jj_set) == len(jj_flat):
        solution = list(jj)
        # I will use a for loop to multiply all elements in
        # the Exact Three Cover solutions.
        for a in range(0, len(solution)):
            solution[a] = reduce(mul, solution[a])
            if a == len(solution) - 1:
                solutions.append(solution)
                solutions_two = jj
                break

# removing repeating sets
solutions =[solutions[x] for x in range(len(solutions)) if not(solutions[x] in solutions[:x])]

print(solutions)
print(solutions_two)
print('Found Exact Three Product Cover')

Output

[[10, 72], [72, 10]]
((5, 2, 1), (6, 4, 3))
Found Exact Three Product Cover

Questions

Is using fixed permutations of 3 a bad way to solve this problem?

What's the slowest parts of my Python script and how do I improve execution speed with Algorithm X?

The Algorithm X isn't necessary to be provided as a solution but should only be explained if possible in a pythonic manner. I'm fine with an answer that only explains the problems with my code.


texts: Prompting user for connection parameters to SQL Server

texts:
I try to avoid keeping passwords etc. in memory or in plain text anywhere. But I am on a huge time crunch and this will only be used internally this week then probably won't get touched again. I just want to make sure this is secure and if not, what the risk is.

I'm mostly concerned about the password sitting in memory. I'm not sanitizing data but for this particular case it isn't needed.

My specific questions are:

From a security perspective, would this code be acceptable in a SQL Importer?
Besides data sanitation, is there a best practice somewhere that I'm missing in this?

Console.WriteLine("Enter the Server Name. Ex: SQLMASTER"); //Gets the server to connect to, an IP address is also acceptable.
ServerName = Console.ReadLine();
Console.WriteLine("Enter the Database. Ex: Accounts"); //The actual database to use.
DatabaseName = Console.ReadLine();
Console.WriteLine("Use Windows authentication? Y/N"); //you will usually use this.
YesNo = Console.ReadLine();

if (YesNo.ToLower() != "y")
{
    Console.WriteLine("Enter your Username (Domain name may be required). Ex: MyName");
    UserName = Console.ReadLine();
    Console.WriteLine("Enter your Password. Ex: ********");
    Password = ReadPassword();

    //Builds the connection string with the data we collected above. We're going to send this to the SQL Connection. (Username and Password)
    ConnectionString = "Data Source = " + ServerName + "; Initial Catalog = " + DatabaseName + "; User ID = " + UserName + "; Password = " + Password;

    Password = ""; //We do this to clear the password from memory
    UserName = ""; //Clearing username from memory
}
else
{
    //Builds the connection string with the data we collected above. We're going to send this to the SQL Connection. (Windows Authentication)
    ConnectionString = "Data Source = " + ServerName + "; Initial Catalog = " + DatabaseName + "; Integrated Security=SSPI"; //User ID = " + UserName + "; Password = " + Password;
}

//Create a new connection with above connection string
SQLCon = new SqlConnection(ConnectionString);
ConnectionString = ""; //Again, doing this to purge the credentials from memory

try
{
   SQLCon.Open();
   Console.WriteLine("\nConnected!\n");
   Console.WriteLine("Working...\n");
   .... etc
}
catch (Exception ex)
{
   MessageBox.Show("Failed! See console for details");
   Console.WriteLine(ex.Message);
}


texts:
This code handles a response from an RSS feed. It organizes and appends to content. If there's a video embeded then separate it from the rest of the content. I would like a review mainly on performance/efficiency but I'm open to any other suggestions as well. That star selector is really nagging me but I don't know of a better way to iterate over all the contained elements.

function getFeed(url, element, callback) {
    $.getJSON("https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q="+encodeURIComponent(url), function(response) {
        var content = "",
            $element = $(element);

        for (var i = 0; i < response.responseData.feed.entries.length; i++) {
            content = content + response.responseData.feed.entries[i].content; //Join all the feed entries
        }

        $element.find(".content").html(content).addClass($element.find("embed").length? "withVideo" : "");

        $element.find("*").each(function() {
            var $this = $(this);

            $this.removeAttr("style width align"); //Reset all the crap that comes with the response

            if ($this.is("embed")) {
                $element.append("

");
                $this.attr("width", 640).attr("height", 360).parent().appendTo(element + " .video");
            };
        });

        if (typeof callback === 'function') {
            callback();
        };
    });
}

This is then called like so:

getFeed("http://www.kent.k12.wa.us/site/RSS.aspx?PageID=3854", "#TechExpo", optionalCallback);

Here's what a response might look like

Some text blah blah blah.

Some more text

Video Title

<embed src="http://..." width="360" height="202" type="application/x-shockwave-flash"></embed>
Watch the 7th annual Tech Expo highlights.


texts: Updates href values for a limited collection of links on a page

texts:
As much as it hurts, I've been tasked with writing a script that prepends integration, QA, etc. environment segments to anchor href attributes that link to a series of sites within two specific domains.

Since we can't be certain of adherence to the requirement that content authors always use production URLs (without these segments) this script covers cases where the wrong segment is present in a particular downstream environment.

We do know the domains and finite list of environments.

/*
    Updates URL environment segments in page links (anchor hrefs)

    1. Determines the current environment by parsing location.hostname.
    2. Selects a list of links with absolute URIs or network-path references:
    (`a[href^="http"], a[href^="//"]`).
    3. Loops over the list of links and takes action only on items that contain
    _domainone.com_ or _domaintwo.com_ in the `href` attribute.
        a. If environment is production, removes the environment segment
        b. If downstream environment, adds or updates environmnet segment to
        match the current environment.

    Currently supports domainone.com and domaintwo.com domains. To
    add additional domains, update the `domainRegEx` variable. This script also
    assumes a finite list of environment names (authoring, integration,
    localhost, qa, and sys). To support additional environments, update the
    `envRegEx` variable.
*/
(function(window) {
    window.addEventListener('DOMContentLoaded', () => {
        const domainRegEx = /(domainone\.com)|(domaintwo\.com)/i;
        const envRegEx = /authoring\.|integration\.|localhost\.|qa\.|sys\./i;
        const environment = location.hostname.match(envRegEx);
        const links = document.querySelectorAll('a[href^="http"], a[href^="//"]');

        for (let i = links.length - 1; i > -1; i--) {
            const link = links[i];
            const href = link.getAttribute('href');
            if (domainRegEx.test(href)) {
                // If production, remove any environment segments ...
                if (environment === null) {
                    link.setAttribute('href', href.replace(envRegEx, ''));
                } else {
                    // ... else if downstream environment, ensure correct environment segment.
                    if (envRegEx.test(href)) {
                        link.setAttribute('href', href.replace(envRegEx, `${environment[0]}`));
                    } else {
                        link.setAttribute('href', href.replace(domainRegEx, `${environment[0]}$1`));
                    }
                }
            }
        }
    });
}(window));


texts: Animated progress bar in C++ | How to simplify or alternatives using strings

texts:
i'm a beginner in C++
i decided to learn the Scary C++ Programing Language
i am a slow learner and after 2 Months learning C++ i saw the need to have a Nice and Tidy progress bar for my programs.

Here what i wrote:

#include <iostream>
#include <string>
#include <iomanip>
#include <unistd.h>

// That function controls the inner Bar

void printProgressBar(char  fill = '.',
                      char  highlight = '*',
                      int   barSize = 10,
                      float startingProgress = 0.0f
                     )
{
        for (int pos = 0; pos < (barSize-(startingProgress*10)); ++pos)
        {
        std::cout << "\r[" << std::string(pos, fill) << highlight << std::flush;
        usleep(50000);
        }
}

// That function controls the outer Bar

void progressBarBox(char highlight = '*', float endPoint = 1.0f){
        std::cout << std::string(endPoint*10, highlight);
        std::cout << ']' << std::flush;
}

int main(int argc, char* argv[]) {
        const int  barSize{3};
        const char barFill{'.'};
        const char barHighlight{'*'};

        progressBarBox(barFill, barSize+0.1f);

        float progress {0.0f};
        while (progress < barSize)
        {
                  printProgressBar(barFill, barHighlight, barSize*10, progress);

        progressBarBox(barHighlight, progress);
        progress += 0.1;
        }

        std::cout << "\nDone" << std::endl;

        return 0;
}

The problem is: with python i never cared about best practices, clean of code or code readbility

I Have many questions about my solution

 My Questions:

How would you rate my code, what to improve ?
how to improve his readbility?
this code would be fine to work with or a headache to mantain, how to improve?
is there Better ways ( that are not so complex too ) to achieve the same ? with the star moving and everything.
Is there a best practice i'm not following or missing ?
i hardcoded some values is that bad ?
a friend of mine said that this code will have a bad performance because of my use of string, is that true ?

I know thats a lot of questions and i am grateful for any contribution or help.