texts: Implementation of Scytale cipher (encryption and decryption)

texts:
This is web exercise 3.1.41. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:

The scytale cipher is one of the first cryptographic devices used for
military purposes. (See The Code Book.) It
was used by the Spartans in the fifth century BCE. To scramble the
text, you print out every kth character starting at the beginning,
then every kth character starting at the second character, and so
forth. Write a program implements this encryption scheme.

Here is my program:
public class ScytaleCipher
{
    public static String encrypt(String text, int kth)
    {
        int textLength = text.length();
        String encrypted = "";
        for (int i = 0; i < kth; i++)
        {
            for (int j = 0; i+j < textLength; j += kth)
            {
                encrypted += String.valueOf(text.charAt(i+j));
            }
        }
        return encrypted;
    }
    public static String decrypt(String text, int kth)
    {
        return encrypt(text, kth-1);
    }
    public static void main(String[] args)
    {
        int kth = Integer.parseInt(args[0]);
        String message = "";
        while (!StdIn.isEmpty())
        {
            String word = StdIn.readString();
            message += word;
        }
        // to encrypt
        System.out.println(encrypt(message, kth));
        // to decrypt
        //System.out.println(decrypt(message, kth));
    }
}

StdIn is a simple API written by the authors of the book. I checked my program and it works.
Is there any way that I can improve my program?
Thanks for your attention.


texts:
Being given the following code I wonder how can I make it better, without using variable valid, yet check ALL the cases and if at least one of them matches set the returned value to False

  def validate_ticketer_issue(self, ticketer_issue):
      """
      Validate ticket system issue for common rules
      :param ticketer_issue: (str) ticket system issue key
      :return: (bool) True if issue is successfuly validated
      """
      valid = True
      issues_not_allowed = ('Pool', 'Document', 'Declaration', 'Restriction', 'Pre-Check')
      issues_not_allowed_inprod = ('Analysis', 'Test')

      try:
          issue = self.service.issue(ticketer_issue)
          if len(issue.fields.versions) == 0:  # Affects Version/s
              valid = False
              print('{}: Affects Version/s field is empty'.format(ticketer_issue))

          if issue.fields.issuetype.name in issues_not_allowed:
              valid = False
              print('{}: According to working model commit is not'
                    ' allowed to the ticket system issue types'
                    '{}'.format(issue['key'], issues_not_allowed))

          if issue.fields.issuetype.name in issues_not_allowed_inprod:
              valid = False
              print('{}: According to working model commit'
                    ' to the ticket system {} issue types'
                    ' is not allowed in production code'.format(
                        issues_not_allowed_inprod, issue['key']))

          if issue.fields.issuetype.name == 'Fault':
              if not self.validate_fault_issue_summary(issue):
                  valid = False

      except ticketer.exceptions.TicketerError:
          valid = False
          print('{}: issue does NOT exist in the ticket system!'.format(ticketer_issue))

      if valid:
          print('{}: OK'.format(ticketer_issue))

      return valid


texts:
I've written a very simple linked list based stack implementation and was wondering if this is the standard way to do it in C.

typedef struct Node {
    int value;
    struct Node *prev;
} Node;

Node * push(Node *top, int value) {
    Node *node = (Node *) malloc(sizeof(Node));
    node->value = value;
    node->prev = top;
    return node;
}

Node * pop(Node *top, int *val_addr) {
    *val_addr = top->value;
    Node *new_top = top->prev;
    free(top);
    return new_top;
}

int is_empty(Node *top) {
    return top == NULL;
}

Before deciding to post on code review I decided to check google for stack implementations to see if mine was okay. But most of the decent sources that I checked used an array implementation. I was wondering in what situation is it better to use a dynamic array based stack?


texts: Pushing an array into an object with an undefined/non-existing property

texts:
If I want to "push" an array into my object inside of a property, I must first assure that this property exists - it works the same way for arrays too. However, what is the smoothest way of doing this?
Currently, I am first assigning the property it's first initial value so it gets made: then, since the property exists, I can push data into it.
const result = {};
const data = [{
    name: "John Doe"
},
{
    name: "Doe John"
}];

const key = "helloworld";

if(result.hasOwnProperty(key)) {
  result[key].push(data);
} else {
  Object.assign(result, {
    [key]: data
  });
}

console.log(result);

Which gives me the following object.
{
    helloworld: [
        {
            name: "John Doe"
        },
        {
            name: "Doe John"
        }
    ]
}

What is the smoothest/better way to do this, if there is such a way?


texts: Automating heap dumps from an Android device or emulator

texts:
I've automated the process of extracting and converting a heap dump from an Android device/emulator.

I'd appreciate any feedback and improvements regarding style, bad practices, non-idiomatic code, performance or other issues you may find.

Also, dump_heap() function tries to wait for a daemon to complete and I'm wondering if there are better ways to handle the situation.

#!/bin/bash
#
# Extracts a heap dump from a device/emulator.
# Assumes the appropriate tools (adb, hprof-conv) are included in the path.

SERIAL=""
PACKAGE=""
FILE=""

usage() {
    echo "Usage: -s <serialNumber> -p <package> -f <file>"
    exit 1
}

err() {
    local msg="$1"
    echo "$msg" >&2
    exit 1
}

create_file() {
    local file=$1
    local dir=$(dirname "$file")

    mkdir -p -- "$dir" && touch -- "$file"

    if [ ! -e "$file" ]; then
        err "File $file could not be created."
    fi
}

file_size_on_device() {
    local adbcmd="adb -s $SERIAL"
    local file="$1"
    local adbinfo="$adbcmd shell ls -l $file"

    $adbinfo | awk '{print $4}'
}

dump_heap() {
    local adbcmd="adb -s $SERIAL"
    local pid="$1"
    local file="$2"
    local dir=$(dirname "$file")

    # Remove any existing tmp files we created. Ideally, there should be none.
    local exists=$($adbcmd shell ls "$dir" | grep "$file")
    if [ -n "$exists" ]; then
        $adbcmd shell rm "$file"
    fi

    echo -n "Dumping heap "

    # Dump the heap to a tmp file on a device/emulator
    $adbcmd shell am dumpheap "$pid" "$file"

    # Beacuse the previous cmd runs as a daemon, we have to wait for it to
    # finish. The following checks the tmp file size continuously, stopping
    # when it's not changing anymore.
    sleepinterval=0.5

    s0=-1
    sleep $sleepinterval
    s1=$(file_size_on_device "$file")

    while ((s1 > s0))
    do
        echo -n "."
        sleep $sleepinterval
        let s0=$s1
        let s1=$(file_size_on_device "$file")
    done

    echo " Done"
}

extract_from_device() {
    local adbcmd="adb -s $SERIAL"

    local pid=$($adbcmd shell ps | grep $PACKAGE | awk '{print $2}')
    if [ -z "${pid}" ]; then
        err "PID for $PACKAGE not found. Is your app installed and running?"
    fi

    # Dump heap to tmp file on a device
    local file="/sdcard/hprof___tmp"
    dump_heap "$pid" "$file"

    # Extract
    local tmp="$FILE-nonconv"
    create_file $tmp
    $adbcmd pull -p $file $tmp

    # Convert
    if [ -s "$tmp" ]; then
        create_file $FILE
        hprof-conv $tmp $FILE
    else
        echo "No data to convert."
    fi

    # Finish
    $adbcmd shell rm "$file"
    rm -- $tmp

    echo "Done, converted heap extracted to $FILE"
}

while getopts ":s::p::f:" opt; do
    case $opt in
        s) SERIAL="$OPTARG";;
        p) PACKAGE="$OPTARG";;
        f) FILE="$OPTARG";;
        *) usage;;
    esac
done

if [ -z "${SERIAL}" ] || [ -z "${PACKAGE}" ] || [ -z "${FILE}" ]; then
    usage
else
    version=$(adb -s "$SERIAL" shell getprop ro.build.version.sdk | tr -d '\r')
    if [ "$version" -gt "10" ]; then
        extract_from_device
    else
        err "The target device/emulator must be API 11 or above."
    fi
fi

The above is part of Dumpey, which helps you

run the monkey on multiple devices or emulators and
make converted memory heap dumps before and after it


texts: Pulling information from XML to insert into Word Document inside 3rd party application

texts:
This is code written for use inside a 3rd party application to pull information from an XML and insert into a word document,  I don't know all the mechanics of the fun process of inserting the information into the word document (inside the 3rd party application) so some questions you might have for me are going to be answered with an "I don't know."

I haven't tested the code yet because it is pretty simple and I want to get changes into it before I have to shoot it to production.

Dim oNode
Dim oNodes

Set oNodes = XmlDoc.SelectNodes("/Record/Case/CaseFormsLoad/PartyLoad/Party/PartyPhones/Phone")
If oNodes.Length > 0 Then
    For Each oNode In oNodes
        If oNode.GetAttribute("ConfidentialFlag") = "True" Then
            ReturnData = ReturnData & oNode.Getattribute("PhoneNum") & VbCrLf
        End If
        If ReturnData Is Nothing Then
            ReturnData = ""
        End If
    Next
Else
    ReturnData = ""
End If

and the XML that it is parsing is in the format

<PartyPhones CurrHomeIndex="-1" CurrWorkIndex="-1" CurrCellIndex="0" CurrFaxIndex="-1" Count="2">
    <Phone PhoneID="111111" PartyID="1111111" PhoneNum="111-111-1111" PhoneExt="" PhoneTyKy="CELL" fPhoneNS="0" InvalidPhone="0" UserIDCr="101" TSCreate="3/12/2014 2:30:32 PM" UserIDChg="001" TSChange="05/01/2014 08:57:26" ConfidentialFlag="False"/>
    <Phone PhoneID="111112" PartyID="1111111" PhoneNum="111-111-1112" PhoneExt="" PhoneTyKy="CELL" fPhoneNS="0" InvalidPhone="0" UserIDCr="102" TSCreate="3/19/2014 11:10:55 AM" UserIDChg="001" TSChange="05/01/2014 08:57:26" ConfidentialFlag="True"/>
</PartyPhones>


texts:
I tried hard to come up with a function template computing a sliding average. A sliding average over data \$x_1, x_2, \dots, x_n\$ with window length \$k \leq n\$ is a sequence \$y_1, y_2, \dots, y_{n - k + 1}\$, where
$$y_i = \frac{1}{k}\sum_{j = 0}^{k - 1} x_{i + j}.$$

Here is my attempt:

mymath.h

#ifndef MYMATH_H
#define MYMATH_H

#include <iterator>
#include <sstream>
#include <stdexcept>

template<typename ForwardIterator, typename OutputIterator>
void sliding_average(ForwardIterator begin,
                     ForwardIterator end,
                     OutputIterator output,
                     size_t window_length)
{
    if (window_length == 0)
    {
        std::stringstream ss;
        ss << "Bad window_length: ";
        ss << window_length;
        throw std::runtime_error{ss.str()};
    }

    using T = typename std::iterator_traits<ForwardIterator>::value_type;

    ForwardIterator finger = begin;
    T sum {};
    size_t count = 0;

    while (finger != end and count < window_length)
    {
        sum += *finger++;
        count++;
    }

    if (count < window_length)
    {
        std::stringstream ss;
        ss << "The length of the range (";
        ss << count;
        ss << ") is too short. Must be at least ";
        ss << window_length;
        throw std::runtime_error{ss.str()};
    }

    *output++ = sum / window_length;
    ForwardIterator window_tail = begin;

    while (finger != end)
    {
        sum -= *window_tail++;
        sum += *finger++;
        *output++ = sum / window_length;
    }
}

#endif // MYMATH_H

main.cpp

#include "mymath.h"
#include <iostream>
#include <iterator>

using std::cout;
using std::endl;
using std::begin;
using std::end;

int main(int argc, const char * argv[]) {
    float input[15];

    for (size_t i = 0; i < 15; ++i)
    {
        input[i] = i + 1;
    }

    float output[11];

    sliding_average(begin(input), end(input), begin(output), 5);

    for (auto& a : output)
    {
        cout << a << " ";
    }

    cout << endl;
    return 0;
}

Critique request

I would like to receive comments regarding how to make my implementation more generic, and how to make it more idiomatic. Other comments are welcome as well.


texts:
Still oiling my Forth. Below are few essential algorithms for in-place merge. Please review.

Some introductory comments:

>swap< is not a cute smiley. I am trying to tell that two pointers are going towards each other at each swap.
rdrop drop looks hideously ugly. Any suggestions?
lower-bound and upper-bound must be unified. How can I do that without execute?

: @swap ( a a -- )
    2dup @ >r @ ! r> !
;

: lower-bownd ( lo hi v -- lb )
    >r
    begin 2dup - cell > while
        2dup over - 2/ +
        dup @ r@ < if
            cell+ -rot then
        swap drop
    repeat
    rdrop drop

: upper-bound ( lo hi v -- ub )
    >r
    begin 2dup - cell > while
        2dup over - 2/ +
        dup @ r@ >= if
            cell+ -rot then
        swap drop
    repeat
    rdrop drop

: >swap< ( a0 a1 -- a1++ --a1 )
    cell - 2dup @swap swap cell+ swap
;

:reverse (lo hi -- )
    begin 2dup < while
        >swap<
    repeat
    drop
;

: reverse-until ( lo hi mi -- lo' hi' pp )
    >r
    begin 2dup r@ = swap r@ = or while
        >swap<
    repeat
    r>
    over = if
        over then
        dup else
;

: rotate ( lo mi hi -- pp )
    2dup reverse  rot
    2dup reverse -rot
    swap reverse-until
    >r reverse r>
;


texts: Decimal-to-binary converter for IP addresses

texts:
def dec_to_bin(ip):

    ip_array = ip.split(".")
    ip_array = filter(None, ip_array)

    if len(ip_array) != 4:
        return "Invalid IP Address format"

    else:
        ip_bin = []

        for x in range(len(ip_array)):

            # Formatting example referenced from:
            # http://stackoverflow.com/a/10411108/1170681

            ip_bin.append('{0:08b}'.format(int(ip_array[x])))
            ip_bin.append(".")

        ip_bin.pop()
        return ''.join(ip_bin)

This is a simple parser that will take a IP address in decimal form and convert it into its binary representation.

I'm looking for any tips on coding styles and improving the efficiency of the code.


texts: Limiting WP user's access to the amount of credits they have

texts:
I like this solution but maybe there is another way. My goal with this is to limit user editing to the amount of credits they have. What do you think?

Here is what it does:

Credits are stored as user meta _credits (int).
Users can only edit pages, posts, custom post types if they have credits left.
Show a proper message when the user does not have any credits left.
Admin users should always be allowed to do thing regardless of having credits or not.

The edit post screens is cleared from all editing components and show an error message when the user does not have any credits left.

Here is some sample code I tested with that is working:

update_user_meta(get_current_user_id(), '_credits', '0'); //just for testing
add_action('add_meta_boxes', function() {
    global $wp_meta_boxes, $credits;

    //get current user's credits
    $credits = intval(get_user_meta(get_current_user_id(), '_credits', true));

    if(is_admin()) {
        //keep everything as it is, admin can always access everything
    } else
        if($credits > 0) {
        //show how many credits the user have left
        add_action('admin_notices', function() {
            global $credits;
            echo '

You have ' . $credits . ' credit(s).

';
        });
    } else {
        $post_type = get_current_screen()->id;

        //remove title and editor editing components
        remove_post_type_support($post_type, 'title');
        remove_post_type_support($post_type, 'editor');

        //remove all meta boxes
        foreach($wp_meta_boxes[$post_type] as $context=>$priorities) {
            foreach($priorities as $priority=>$metaboxes) {
                foreach($metaboxes as $metabox=>$metabox_data) {
                    remove_meta_box($metabox, $post_type, $context);
                }
            }
        }

        //show an error message
        add_action('admin_notices', function() {
            echo '

You are out of credit(s). Buy some more credits.

';
        });
    }
});


texts: A pointer vector sorted by its member function

texts:
I'm asking for suggestions on a random accessed vector with allocated elements sorted by its key obtained from its member function.

I use it with Qt tree view where the access, add and deletion of tree items is implemented via its index or row number. And I want all the tree items are automatically sorted under a tree node.

If I use std::set, I need to calculate the index first (such as using distance function) when adding an item under a tree node and need a binary search when deleting and accessing an item.

Sorted pointer vectors can access items quickly but require moving pointers when adding and deleting an item. Compare all the advantages and disadvantages, I think this can give better performance

Am I right?  Does anyone have experience on it or better suggestions?

#pragma once

#include <vector>
#include <memory>
#include <algorithm>

//! A random accessed vector with allocated elements sorted by
//! its key obtained from its member function.
//! - Duplicate elements are not allowed.
template<class T, class K, K (T::*MemFun)() const>
class SortedPtrVector
{
public:
    SortedPtrVector()   {}

    //! Add an element, return its index.
    bool Add(std::unique_ptr<T> element, int& index)
    {
        if (!Find((element.get()->*MemFun)(), index))
        {
            m_vector.insert(m_vector.begin() + index, std::move(element));
            return true;
        }
        return false;
    }

    //! Find the element with a key.
    //! - Return true when found and record its index;
    //! - Return false when not found and record its lower bound.
    bool Find(const K& key, int& index) const
    {
        if (m_vector.empty())
        {
            index = 0;
            return false;
        }
        index = LowerBound(key);
        if (index >= m_vector.size())
            return false;
        if ((m_vector[index].get()->*MemFun)() == key)
            return true;
        return false;
    }

    //! Return an index to the first element which does not compare less than the key.
    int LowerBound(const K& key) const
    {
        int first = 0;
        int count = m_vector.size();
        while (count > 0)
        {
            int i = first;
            int step = count / 2;
            i += step;
            if ((m_vector[i].get()->*MemFun)() < key)
            {
                first = ++i;
                count -= step + 1;
            }
            else
            {
                count = step;
            }
        }
        return first;
    }

    //! Delete an element at an index.
    void DeleteAt(int index)
    {
        m_vector.erase(m_vector.begin() + index);
    }

    //! Delete an element with a key.
    void Delete(const K& key)
    {
        int index;
        if (Find(key, index))
            DeletaAt(index);
    }

    //! Clear.
    void Clear()
    {
        m_vector.clear();
    }

    unsigned Size()                                 {return m_vector.size();}
    const T& operator [](unsigned i) const          {return *m_vector[i];}

private:
    std::vector<std::unique_ptr<T>> m_vector;
};


texts:
I need to write code for the given problem:

I'm provided with a word and I need to find all the possible combination of it that matches with a given list of words in a file.

Here's my code. Can I make it much better?  I'm sure it can be done. Please offer suggestions.

dict = {}
file = open("/usr/share/dict/words", "r")

for word in file:                                        #Iterate through every word in the dictionary
        word = word.strip().lower()                        #Strip newlines and send to lowercase
        sorted_word = ''.join(sorted(word))                #Alphabetically sort the word
        if sorted_word in dict:                                #Check if sorted_word is already a key
                if word not in dict[sorted_word]:        #Make sure word is not already in the list under the key sorted_word
                        dict[sorted_word].append(word)        #Add to list under the key sorted_word
        else:                                                #If not in dictionary
                dict[sorted_word] = [word]                #Create new list with one entry
while(True):                                                #Loop until quit is typed
        jumble = raw_input("Enter a jumble to decode or 'quit': ")        #Get input
        jumble = jumble.lower()                                #Send jumble to lower
        if(jumble == "quit"):                                #Quit if quit is typed
                break
        jumble = ''.join(sorted(jumble))                #Sort jumble alphabetical
        if jumble in dict:                                #If sorted jumble exists in dictionary
                results = dict[jumble]                        #Get list of words that match jumble
                for result in results:                        #Loop through list printing results
                        print result,                        #Trailing , designates that there should be a space between entries
                print ""                                #Print newlines
        else:                                                #Jumble not found in dictionary print message
                print "Results for jumble not found"


texts: Export EXIF data from thousands of images to CSV

texts:
I have written a script that retrieves specific fields of Exif data from thousands of images in a directory (including subdirectories) and saves the info to a csv file:

import os
from PIL import Image
from PIL.ExifTags import TAGS
import csv
from os.path import join

####SET THESE!###
imgpath = 'C:/x/y' #Path to folder of images
csvname = 'EXIF_data.csv' #Name of saved csv
###

def get_exif(fn):
    ret = {}
    i = Image.open(fn)
    info = i._getexif()
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        ret[decoded] = value
    return ret

exif_list = []
path_list = []
filename_list = []
DTO_list = []
MN_list = []

for root, dirs, files in os.walk(imgpath, topdown=True):
   for name in files:
       if name.endswith('.JPG'):
           pat = join(root, name)
           pat.replace(os.sep,"/")
           exif = get_exif(pat)
           path_list.append(pat)
           filename_list.append(name)
           DTO_list.append(exif['DateTimeOriginal'])
           MN_list.append(exif['MakerNote'])

zipped = zip(path_list, filename_list, DTO_list, MN_list)

with open(csvname, "w", newline='') as f:
    writer = csv.writer(f)
    writer.writerow(('Paths','Filenames','DateAndTime','MakerNotes'))
    for row in zipped:
        writer.writerow(row)

However, it is quite slow. I've attempted to optimise the script for performance + readabilty by using list and dictionary comprehensions.

import os
from os import walk #Necessary for recursive mode
from PIL import Image #Opens images and retrieves exif
from PIL.ExifTags import TAGS #Convert exif tags from digits to names
import csv #Write to csv
from os.path import join #Join directory and filename for path

####SET THESE!###
imgpath = 'C:/Users/au309263/Documents/imagesorting_testphotos/Finse/FINSE01' #Path to folder of images. The script searches subdirectories as well
csvname = 'PLC_Speedtest2.csv' #Name of saved csv
###

def get_exif(fn): #Defining a function that opens an image, retrieves the exif data, corrects the exif tags from digits to names and puts the data into a dictionary
    i = Image.open(fn)
    info = i._getexif()
    ret = {TAGS.get(tag, tag): value for tag, value in info.items()}
    return ret

Paths = [join(root, f).replace(os.sep,"/") for root, dirs, files in walk(imgpath, topdown=True) for f in files if f.endswith('.JPG' or '.jpg')] #Creates list of paths for images
Filenames = [f for root, dirs, files in walk(imgpath, topdown=True) for f in files if f.endswith('.JPG' or '.jpg')] #Creates list of filenames for images
ExifData = list(map(get_exif, Paths)) #Runs the get_exif function on each of the images specified in the Paths list. List converts the map-object to a list.
MakerNotes = [i['MakerNote'] for i in ExifData] #Creates list of MakerNotes from exif data for images
DateAndTime = [i['DateTimeOriginal'] for i in ExifData] #Creates list of Date and Time from exif data for images

zipped = zip(Paths, Filenames, DateAndTime, MakerNotes) #Combines the four lists to be written into a csv.

with open(csvname, "w", newline='') as f: #Writes a csv-file with the exif data
    writer = csv.writer(f)
    writer.writerow(('Paths','Filenames','DateAndTime','MakerNotes'))
    for row in zipped:
        writer.writerow(row)

However, this has not changed the performance.

I've timed regions of the code and found that specifically opening each image and getting the Exif data from each image in the get_exif function is what takes time.
To make the script faster, I am wondering:

Is it possible to optimise on the performance of the function?
Is it possible to retrieve Exif data without opening the image?
Is list(map(fn,x)) the fastest way of applying the function?


texts: Inserting filename, reading data, inserting regex, and testing if each line matches

texts:
This program first displays a menu which shows some options that the user can select. Each option will the respective functions which do some things.

The user can insert a filename, read data from it, enter a regex pattern, test if each line of the file matches the given regex pattern.

Please provide feedback on how I can improve my program.

import re

filename = None
readData = None
regex    = None

def test_data():
    '''Checks if each line of data matches the regex'''

    global readData
    global regex

    if regex == None:
        print('Empty regex')
        print('')
        return None

    try:
        pattern = re.compile(regex)
    except:
        print('Invalid regex')
        print('')
        return None
    i = 1
    if readData == None:
        print('Read data is empty')
        print('')
        return None

    for line in readData:
        if pattern.match(line.strip()):
            print(' Line ', i, ':"', line,'"', ' matches current regex', sep='')
        else:
            print(' Line ', i, ':"', line,'"', ' does not match current regex', sep='')
        i += 1
    print('')

def change_regex():
    '''Sets the regex variable'''

    global regex
    print('Current regex is ', end='')
    if regex != None:
        print('"', regex, '"', sep='')
    else:
        print('empty')

    regex = input('Enter new regex: ')
    print('')

def read_file():
    '''Reads data from file if possible'''

    global filename
    global readData
    try:
        file = open(filename, "r")
        readData = file.readlines()
        print('Data read successfully!')
        file.close()
    except TypeError:
        print('filename is empty!')
    except FileNotFoundError:
        print('File not found!')

    print('')

def change_filename():
    '''Sets the filename variable'''

    global filename
    print('Current filename is ', end='')
    if filename != None:
        print('"', filename, '"', sep='')
    else:
        print('empty')

    filename = input('Enter new filename (with extension): ')
    print('')

def show_menu():
    '''Shows the menu'''

    print('Enter 1 to change filename')
    print('Enter 2 to read file')
    print('Enter 3 to change regex')
    print('Enter 4 to test if read data matches given regex')
    print('Enter 5 to exit')

def main():
    while True:
        show_menu()
        try:
            option = int(input('Option: '))
        except:
            print('Invalid input')
            print('Please enter a valid option')
            print('')
            continue
        if option == 1:
            change_filename()
        elif option == 2:
            read_file()
        elif option == 3:
            change_regex()
        elif option == 4:
            test_data()
        elif option == 5:
            break
        else:
            print('Invalid input')
            print('Please enter a valid option')
            print('')

if __name__ == "__main__":
    main()


texts: Get the character and its count which has highest occurrence

texts:
I have this C# method which get the character and its count which has highest occurrence
    public KeyValuePair<char, int> CountCharMax_Dictionary_LINQ(string s)
    {
        char[] chars = s.ToCharArray();

        var result = chars.GroupBy(x => x)
            .OrderByDescending(x => x.Count())
            .ToDictionary(x => x.Key, x => x.Count())
            .FirstOrDefault();

        return result;
    }

It works but is there any better or efficient way to get the same result? Is there any difference if I return it as Tuple vs KeyValuePair?
Test data:

Input: 122. Expected Output: 2,1
Input: 122111. Expected Output: 1,4


texts: Program that tells if a date is valid in C

texts:
I'm reading a book about C programming, at the end of each chapter it has some training exercise and one of them was to make a program that tells if a date is valid or not, the code below is what I did and I would like to know if it can be improved?

#include <stdio.h>

int main(){
int dd,mm,yy;

printf("write a date(day/month/year):");
scanf("%d/%d/%d",&dd,&mm,&yy);

int bissextile=(yy%4==0)?1:0;

if (dd>31 || dd<1 || mm>12 || mm<1)
    printf("Invalid date.\n");
    else
        if((mm==2 && dd<30 && bissextile) || (mm==2 && dd<29 && bissextile==0))
            printf("valid date.\n");
            else
                if((mm==4 || mm==6 || mm==9 || mm==11)&& dd<31)
                    printf("valid date.\n");
                    else
                        if(dd<31 && mm!=2)
                            printf("valid date.\n");
                            else
                                printf("Invalid date.\n");
}


texts:
I decided to make a solution in Haskell to a problem that I found on another post here at CodeReview (link: The Beauty and the Strings)
I would like suggestions on how to improve letterFreqs.  I have tried searching for mutable arrays that could help with performance.  But is it worth it?  The array that is modified often is only 26 elements long.  Haskell is new to me, so I find syntax of libraries such as Data.Vector, Data.Array.MArray, and Data.IO.Array difficult to grasp easily.

{-# OPTIONS_GHC -F -pgmF htfpp #-}
module Main where
import Test.Framework
import Data.Char (isLower, isUpper, ord)
import Data.List (zipWith, sort)

letterFreqs :: String -> [Int]
letterFreqs str =
    freqs' str (replicate 26 0)
    where freqs' [] fs = fs
          freqs' (ch:tail) fs
            | isLower ch = let index = (ord ch - ord 'a')
                               (front, back) = splitAt index fs
                               newval = 1 + fs !! index
                           in freqs' tail (front ++ newval : drop 1 back)
            | isUpper ch = let index = (ord ch - ord 'A')
                               (front, back) = splitAt index fs
                               newval = 1 + fs !! index
                           in freqs' tail (front ++ newval : drop 1 back)
            | otherwise = freqs' tail fs

computeMaxBeauty :: String -> Int
computeMaxBeauty = sum . zipWith (*) [1..26] . sort . letterFreqs

test_ABbCcc = assertEqual 152 $ computeMaxBeauty "ABbCcc"

test_This_is_from_Facebook_Hacker_Cup_2013_ =
    assertEqual 551 $ computeMaxBeauty "This is from Facebook Hacker Cup 2013."

test_Ignore_punctuation__please___ =
    assertEqual 491 $ computeMaxBeauty "Ignore punctuation, please :)"

test_Sometimes_test_cases_are_hard_to_make_up_ =
    assertEqual 729 $ computeMaxBeauty "Sometimes, test cases are hard to make up."

test_CodeReview_is_love__CodeReview_is_life_ =
    assertEqual 724 $ computeMaxBeauty "CodeReview is love. CodeReview is life."

main :: IO ()
main = htfMain htf_thisModulesTests


texts: Finding collisions of the first few bits of a SHA-1 hash

texts:
My objective is to find a hash collision of my modified hash function. Assuming my modified hash only outputs the first 36 bits of SHA-1. As we know, SHA-1 is a 160-bit hash value, hence, we only need to output 9 characters out of 40 characters for comparison.

How i begin my program is by hashing a string (I have a SHA-1 algorithm running and i will name it as sha1. I have also ensured that the output of the SHA-1 algorithm is correct.)

Firstly, i would hardcode 2 string and extract out 9 characters out of 40 characters since i require only the first 36 bits of SHA-1. The function below basically return a true if a collision is found and false if a collision is not found

public static boolean findCollision(int x1, int x2) {

    String message1 = "I tried " + x1 + " iteration to find a collision";
    String message2 = "I tried " + x2 + " iteration to find a collision";

    //hashing my string and extracting 9 characters
    String message_hash1 = sha1(message1);
    String message_hash2 = sha1(message2);

    String modified_hash1 = message_hash1.substring(0, 9);
    String modified_hash2 = message_hash2.substring(0, 9);

    if (modified_hash1.equals(modified_hash2))
        return true;
    else
        return false;
}

Lastly, i will have a main function that will random Integers up to MAX_VALUE in a infinite loop and will break out if and only if a hash is found.

public static void main(String[] args) {

    Random random = new Random();
    int x1 = 0;
    int x2 = 0;
    int counter = 0;

    while (true) {

        while(true){

            x1 = random.nextInt(Integer.MAX_VALUE);
            x2 = random.nextInt(Integer.MAX_VALUE);

            if (x1 != x2)
                break;
        }

        if (findCollision(x1, x2) == true) {
            break;
        }
        counter++;
    }

    System.out.println("\nNumber of trials: " + counter);
}

If i tried taking only the first 24 bits of SHA-1, i could easily find a collision. However, i'm unable to find a collision for 36 bits instead despite running it for hours. Hence, I'm wondering what is other alternative way for me to find a collision with just 36 bits of SHA-1.


texts:
Here are a few questions on my mind:

What improvements to the above code can you think of?
I want to say new UnionFind(x) where x is a Set[T] (I emphatically don't want to say new UnionFind(x.toList). Is Traversable[T] (and .toList inside the UnionFind) the right choice for that?
Note that the union method requires an equality test on T. Would it be sensible to take an explicit or implicit equality test as an additional argument?  What are the best arguments against?  (Other than "it's more code of perhaps limited benefit"—which is a relevant consideration, but I'm not asking to improve that area of my thinking.)
Is the placement of the import statement reasonable?

In favor of it: it makes minimal the scope of a rename-import
In favor of beginning of class or beginning of file: the substance is header-ish, so it should be in a place where people expect to find header-ish things. In favor particularly of beginning of class is that it both header-ish and local.
Are there trade-offs other than findability/discoverability vs. breakage prevention that I'm making (unknowingly)?

class UnionFind[T](nodes: Traversable[T]) {
    private type Node[T] = Either[T, Int]

    private val parent: MutableMap[T, Node[T]] = {
        import scala.collection.mutable.{Map => MutableMap}
        MutableMap((for (n <- nodes.toList) yield (n -> Right(1))): _*)
    }

    private def root(a: T): (T, Int) = parent(a) match {
        case Right(n) => (a, n)
        case Left(parent_of_a) => {
            val (root_over_a, n) = root(parent_of_a)
            parent(a) = Left(root_over_a)
            (root_over_a, n)
        }
    }

    def find(a: T): T = root(a)._1

    def size(a: T): Int = root(a)._2

    def union(a: T, b: T) {
        val (root_a, size_a) = root(a)
        val (root_b, size_b) = root(b)
        if (root_a != root_b) {
            val size_union = size_a + size_b
            if (size_a <= size_b) {
                parent(root_a) = Left(root_b)
                parent(root_b) = Right(size_union)
            } else {
                parent(root_b) = Left(root_a)
                parent(root_a) = Right(size_union)
            }
        }
    }
}


texts:
I have a method in C# which communicates with REST API.It has a several small task like splitting of a string ,checking a commandText is valid or not,POST and GET JSON payload to/from REST API.

  public  string PostToAPI([FromBody]string value)
        {
            string input = value;
            //splitting of string into substrings
               var str = input.Split(new[] { ' ' }, 2);
                var payload = new testModel
               {
                   Command = str[0],
                   CommandText = str[1]
               };
            //list of commands
              List<string> cmdText = new List<string>(){"/calc", "/test" };
            //check CommandText is valid or not
              if(cmdText.Contains(payload.CommandText))
              {
               //return valid
              }

            // Serialize our concrete class into a JSON String
            var stringPayload = JsonConvert.SerializeObject(payload);
             try
             {
                 // Wrap our JSON inside a StringContent which then can be used by the HttpClient class
                 var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

                  using (var httpClient = new HttpClient())

                 {
                     HttpResponseMessage message = httpClient.PostAsync("https://testapi.com", httpContent).Result;
                     if (message.IsSuccessStatusCode)
                     {
                         string result = message.Content.ReadAsStringAsync().Result;
                         return result;
                     }
                     else
                     return message.StatusCode+"kindly contact to administrator";

                 }
             }
             catch (Exception ex)
             {
                 return ex.InnerException.ToString();
             }

            }

splitting of a string splits the string into two substrings.

checking a commandtext, checks commandtext is valid or not.

they all are in one method.From architecture/design point of view is this right or should i split the task into different module or in different classes to add more flexibility, readability,As there may be a situation where i just need to add commands string and don't want to touch the other task.

How to organize such c# tasks into different modules/class to make them more flexible, readable?
Thanks!


texts:
I have a config.ini that contains my database credentials. I retrieve them with a parser class like this:

public function getField($section, $field) {
    return $this->iniArray[$section][$field];
}

In my DbConnect class I do this, which seems silly:

public function __construct() {
    $ini = new Configuration('configs/config.ini');
    $this->host = $ini->getField('Database', 'host');
    $this->user = $ini->getField('Database', 'user');
    $this->pass = $ini->getField('Database', 'password');
    $this->dbname = $ini->getField('Database', 'name');

I'm sure there is a better way to set these values, but I'm not sure how.


texts: Algorithm to find all legal moves in Reversi game

texts:
Reversi Game:
The image from the Reversi game:

I have my algorithm to find all legal moves in Reversi game.
Here's the code with comments:
"""
-1    => no disc
0/1   => player's disc
"""

for row_idx, row in enumerate(board):
    for column_idx, column in enumerate(board):
        if board[row_idx][column_idx] == -1:
            """
            Loop through square with chosen `-1` in middle
            5   5   5
            5  -1   5
            5   5   5
            """
            for i in range(-1, 2, 1):
                for j in range(-1, 2, 1):
                    """
                    Check if loop is not beyond borders
                    """
                    if row_idx + i < 0 or row_idx + 1 > (len(board) - 1) or column_idx + j < 0 or column_idx + j > (len(board) - 1):
                        continue

                    """
                    If there is a opponent disc, go straight in this direction (that way)
                    """
                    if board[row_idx + i][column_idx + j] == self.opponent_color:
                        i2, j2 = i, j
                        for _ in range(8):
                            """
                            Check if loop is not beyond borders
                            """
                            if row_idx + i + i2 < 0 or row_idx + i + i2 > (len(board) - 1) or column_idx + j + j2 < 0 or column_idx + j + j2 > (len(board) - 1):
                                continue

                            """
                            Break if the `no disc` is on `that way`
                            """
                            if board[row_idx + i + i2][column_idx + j + j2] == -1:
                                break

                            """
                            The legal move has been found, then break.
                            """
                            if board[row_idx + i + i2][column_idx + j + j2] == self.my_color:
                                legal_moves.append((row_idx, column_idx))
                                break

                            i2 += i
                            j2 += j

Is there any better way to do it? I am not sure about those nested for loops.
Thanks for any help or any hint!


texts:
Given the following task:

  Exercise 1.38.  In 1737, the Swiss
  mathematician Leonhard Euler published
  a memoir De Fractionibus Continuis,
  which included a continued fraction
  expansion for e - 2, where e is the
  base of the natural logarithms. In
  this fraction, the Ni are all 1, and
  the Di are successively 1, 2, 1, 1, 4,
  1, 1, 6, 1, 1, 8, .... Write a program
  that uses your cont-frac procedure
  from exercise 1.37 to approximate e,
  based on Euler's expansion.

I wrote this solution:

(define (i-cont-frac n d k)
  (define (iterate result i)
    (define (next n) (- n 1))
    (if (= i 0) result
        (iterate (/ (n i)
                    (+ (d i)
                    result)) (next i))))
  (iterate 0 k))

(define (divisible? a b) (= (remainder a b) 0))
(define (compute-e k)
  (define (n i) 1)
  (define (d i) (cond ((= i 1) 1)
                      ((= i 2) 2)
                      ((divisible? (- i 1) 3)
                       (* (/ (- i 1) 3.0) 2.0))
                      (else 1.0)))
  (+ 2 (cont-frac n d k)))

What do you think?


texts:
One of my first ever Jython scripts lets me get comma-separated values out of an RDBMS:

from java.lang import System
from java.sql import DriverManager, ResultSet
import csv
import cStringIO as StringIO
import sys
def doIt():
    if System.getProperty("jdbc.drivers") is None or System.getProperty("jdbc2csv.query") is None:
        try:
            System.setProperty("jdbc2csv.url", sys.argv[1])
            System.setProperty("jdbc2csv.query", sys.argv[2])
        except IndexError:
            print 'Usage: java -cp jython.jar:jdbc.jar -Djdbc.drivers=<jdbc.driver.class> -Djdbc2csv.query=<query> -Djdbc2csv.url-<jdbc.url> org.python.util.jython ' + sys.argv[0]
            exit()
    output = StringIO.StringIO()
    conn = DriverManager.getConnection(System.getProperty("jdbc2csv.url"))
    res = conn.createStatement().executeQuery(System.getProperty("jdbc2csv.query"))
    meta = res.getMetaData()
    header = ['row #']

    for i in range(0, meta.getColumnCount()):
        header.append(meta.getColumnName(i+1))

    writer = csv.writer(output, quotechar = '"', quoting = csv.QUOTE_ALL, escapechar = '\\', delimiter = ',')
    writer.writerow(header)
    i = 0

    while not res.isLast():
        res.next()
        i = i + 1
        row = [i]

        for column in range(1, meta.getColumnCount()+1):
            row.append(res.getString(column))
        writer.writerow(row)

    conn.close()
    print output.getvalue()

if __name__ == '__main__':
    doIt()

One thing I can immediately see as a potential issue is utilising the optparse module to handle options in addition to JVM properties instead of sys.argv. But, I await others ripping it apart.


texts: Repeatedly partitioning an array equally as far as possible

texts:
I solved HackerRank Nikita and the Game.  The implementation is correct as program passes all test cases.

  Nikita just came up with a new array game. The rules are as follows:

  Initially, there is an array, A, containing N integers (1 ≤ N ≤ 109), with 0 ≤ Ai ≤ 109.
  In each move, Nikita must partition the array into 2 non-empty parts
  such that the sum of the elements in the left partition is equal to
  the sum of the elements in the right partition. If Nikita can make
  such a move, she gets 1 point; otherwise, the game ends.
  After each successful move, Nikita discards either the left partition
  or the right partition and continues playing by using the remaining
  partition as array A.

  Nikita loves this game and wants your help getting the best score
  possible. Given A, can you find and print the maximum number of points
  she can score?

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

public class NikitaAndTheGame
{

public static void main(String[] args)
{
    Scanner sc=new Scanner(System.in);
    int cases=sc.nextInt();
    for(int i=0;i<cases;i++)
    {
        int size=sc.nextInt();
        int[] array=new int[size];

        for(int j=0;j<size;j++)
        {
            array[j]=sc.nextInt();
        }

    System.out.println(splitPossible(array,0,size-1));

    }
}
public static int splitPossible(int[] array,int start,int end)
//a recursive fuction that returns 1 if equal sum split possible otherwise returns 0
{
    int size=end-start+1;
    int sum=0;
    int count=0;
    if(sumOfArray(array,0,array.length-1)==0&&start==0&&end==array.length-1) //handles the case when all elements of array are 0.

   {
       return array.length-1;
   }
    if(size==0)
    {
        return 0;
    }
    for(int i=0;i<size;i++)
    {
        if(sumOfArray(array,start,start+i)!=sumOfArray(array,start+i+1,end))
        {
            continue;
        }
        else
        {
            count+=1;
            return count+Math.max(splitPossible(array,start,start+i),splitPossible(array,start+i+1,end));
        }
    }

    return count;
}
public static int sumOfArray(int[] array,int start,int end)
//returns sum of array from start to end.
{
    int sum=0;
    for(int j=start;j<=end;j++)
    {
        sum+=array[j];
    }
    return sum;
}
}

I am new to recursion, so any input in designing of recursive method/assigning or simplifying variables/simpler coding styles during recursion are welcomed.


texts: Retrieving all the email addresses on a web page

texts:
I recently discovered the file_get_contents function and wanted to put it to some use, alongside preg_match_all, off the information in this Stack Overflow thread.

<?php
    //use a site with lots of email address on.
    $string = file_get_contents("https://stackoverflow.com/questions/3901070/in-php-how-do-i-extract-multiple-e-mail-addresses-from-a-block-of-text-and-put");

    //initialise an empty array.
    $matches = array();

    //regular expression that matches most email addresses, courtesy of @Eric-Karl.
    $pattern = '/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/';

    //perform global regular expression match, ie search the entire web page for a particular thing, and store it in the previously initialised array.
    preg_match_all($pattern, $string, $matches);

    //output array of values; remove duplicate email addresses, but maintain incremental key count.
    var_dump(array_values(array_unique($matches[0])));

    //store above in array for upcoming bit.
    $neaterArray = array_values(array_unique($matches[0]));

    //count the amount of variables in the array.
    $count = count($neaterArray);

    //implode array values to string.
    $emailsAsString = implode(", ", $neaterArray);

    //present the string, prepended with the count.
    echo "<h3>$count email addresses in total:</h3> $emailsAsString";

?>

I trust my comments are enough to justify the choices I made. I used the stackoverflow thread I mentioned as a test case, because it had many test/fake emails, but all in an appropriate format for the regex.

Here's the output for this case:

array (size=19)
  0 => string 'apple-touch-icon@2.png' (length=22)
  1 => string 'example@slu.edu' (length=15)
  2 => string 'a+b@google.com.sg' (length=17)
  3 => string 'test1+2@gmail.com' (length=17)
  4 => string 'test-2@yahoo.co.jp' (length=18)
  5 => string 'test@test.com' (length=13)
  6 => string 'test@test.co.uk' (length=15)
  7 => string 'test@google.com.sg' (length=18)
  8 => string 'email@domain.info' (length=17)
  9 => string 'email@domain.inf' (length=16)
  10 => string 'first.lastname@domain.be' (length=24)
  11 => string 'lastname@domain.be' (length=18)
  12 => string 'HIDDENFORLOGICALREASONS@cameranh.rs.gov.br' (length=42)
  13 => string 'HIDDENFORLOGICALREASONS@cameranh.rs.go' (length=38)
  14 => string 'myemail@office21.company.com' (length=28)
  15 => string 'mymail@yahoo.com' (length=16)
  16 => string 'my-e.mail@yahoo.com' (length=19)
  17 => string 'joe@mysite.com' (length=14)
  18 => string 'name@example.com.sv' (length=19)
19 email addresses in total:

apple-touch-icon@2.png, example@slu.edu, a+b@google.com.sg, test1+2@gmail.com, test-2@yahoo.co.jp, test@test.com, test@test.co.uk, test@google.com.sg, email@domain.info, email@domain.inf, first.lastname@domain.be, lastname@domain.be, HIDDENFORLOGICALREASONS@cameranh.rs.gov.br, HIDDENFORLOGICALREASONS@cameranh.rs.go, myemail@office21.company.com, mymail@yahoo.com, my-e.mail@yahoo.com, joe@mysite.com, name@example.com.sv

I realise the string at the end isn't particularly necessary, I just wanted to make use of implode.

Some questions:

Is this a good way to go about solving the problem? Are there parts that could be optimised with more suitable functions?
Is initialising the array imperative for this program? I tried it without the original declaration (in the preg_match_all line) and it still functioned.
Is there a part/are there parts of the code that comes across as poorly written?


texts: Add protocols inside the same file as controller

texts:
I have a question about something maybe not so much important, but every time when I have to decide, I feel it can write in another way.
Imagine I am developing and system about authentication and then I have to receive a pin after sending my phone number.
So I am writing some UseCase and, in this case, I have an interactor and a Worker as protocol.
Let's show the code
import Foundation

protocol SendPinWorker {
    func run(onResult: ((Result<Bool, Error>)->Void)?)
}

protocol SendPinUseCaseInteractor {
    func error(e: SendPINUseCaseError)
    func sent()
    func processing()
}

enum SendPINUseCaseError {
    case invalidPhone
    case couldNotSend
}

class SendPINUseCase {

    private let worker: SendPinWorker
    private let output: SendPinUseCaseInteractor
    init(worker: SendPinWorker, output: SendPinUseCaseInteractor) {
        self.worker = worker
        self.output = output
    }

    func execute(phone: String) {
        guard !phone.isEmpty else {
            self.output.error(e: .invalidPhone)
            return
        }

        self.output.processing()

        self.worker.run { [weak self] result in

            guard let self = self else {
                return
            }

            guard let sent = try? result.get(), sent else {
                self.output.error(e: .couldNotSend)
                return
            }

            self.output.sent()
        }
    }
}

Should I put these protocols and enums in another file or should I still with these structures in the same file?


texts:
I have written a small JavaScript function which performs an AJAX request every x seconds.

I was hoping some of you could give it a look over and give me any pointers on redundant code or bad practices.

The idea of the function is to:

Allow for polling to be initiated
Once initiated, poll once every x seconds and perform an AJAX request.
Stop polling once disablePolling() is executed.
Be able to be reused anywhere.

requester.js

function Request() {

this.poll = false;

this.activatePoll = function () {
    this.poll = true;
    this.runPoll();
};

this.disablePoll = function () {
    this.poll = false;
};

this.runPoll = function () {
    var self = this;
    var poll = setTimeout(function () {
        $.ajax({
            url: './request.php',
            success: function (response) {
                console.log(response);
            },
            dataType: "json",
            complete: function () {
                if (self.poll == false) {
                    clearTimeout(poll);
                } else {
                    self.runPoll();
                }
            }
        })
    }, 1000);
};
}

Usage:

  index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Requester</title>

Requester

    <input type="button" onclick="$request.test();" value="test">
    <input type="button" onclick="$request.activatePoll();" value="poll">
    <input type="button" onclick="$request.disablePoll();" value="turn off poll">

  request.php

<?php
echo json_encode($time());
?>

It should also be mentioned that theAajax request will need to also POST some parameters.


texts: Optimize mass import of XML to SQLServer in Ruby

texts:
I have the following Ruby code that's designed to update item, price and stock data for items in a MSSQL database. It's running on a Ruby 1.8.6/Rails 1.2.3 installation, in its own controller (for now)

What I'm looking for is ways to optimize performance.

Right now each item takes about 0,2 seconds (200ms) to process. Edit: There may be 10,000+ items in the XML file, and 10,000,000+ items in the "Items" and "Price" SQL tables.

I've been told that

composing my own SQL queries directly instead of using the models will be faster, since I'm doing quite a few lookups, how much performance would that lend me?
and selecting many rows at once, doing processing, and inserting at once should be faster, instead of doing it one by one. (How would this be done in practice?)

  # counters for statistics
  count = 0
  skips = 0

  # load + parse XML
  file = File.read(XML_PATH)
  doc = REXML::Document.new file

  # loop through products in XML file
  doc.elements.each('products') { |product|
    itemid = product.attributes['id'].to_i
    itemprice = product.elements['price'].text.to_i

    item = Item.find_by_id(itemid)
    if item.nil?
      skips += 1
      next
    end

    # update prices
    price = Price.find(:first, :conditions => { :item_id => itemid })
    # create new price if price not found
    if price.nil?
      price = Price.new
      price.item_id = itemid
    end
    price.price = product.elements['price'].text.to_i
    price.save

    # find + update item stock data
    product.elements.each('stocks/location') { |location|
      item_stock_location_id = location.attributes['location_code']
      item_stock_location = ItemStockLocationCount.find(:first,
                                                    :conditions => {
                                                        :item_stock_location_id => item_stock_location_id,
                                                        :item_id => itemid.to_s
                                                    })

      if item_stock_location.nil?
        item_stock_location = ItemStockLocationCount.new
        item_stock_location.item_stock_location_id = item_stock_location_id
        item_stock_location.item_id = itemid
      end
      item_stock_location.stock_qty = location.elements['stock'].text.to_i
      item_stock_location.save
    }

    # update onsite_stock + offsite_stock
    item_stock_count_on_site = 0
    item_stock_count_off_site = 0
    item_stock_loc_qtys = ItemStockLocationQuantity.find_all({ :item_id => itemid.to_s })
    item_stock_loc_qtys.each { |stock_loc_qty|
      item_stock_count_on_site += stock_loc_qty.stock_qty
      item_stock_count_off_site += stock_loc_qty.stock_qty unless stock_loc_qty.item_stock_location_id == 1
    }
    item.onsite_stock = item_stock_count_on_site
    item.offsite_stock = item_stock_count_off_site

    # update price lock
    item.price_lock = product.elements['price_locked']
    if item.price_lock == 1
      item.vat_price = product.elements['price']
      item.price = (itemprice - ((itemprice * 25)/ (100 + 25)))
    end

    item.save

    count += 1
    # progress bar
    if count%100 == 0
      printf '.'
    end
  }

  puts 'Item Count: ' + count.to_s
  puts 'Items skipped: ' + skips.to_s


texts: Counter GUI in Swing, updating the count in the background

texts:
I made a simple counter GUI for practice. The user presses a button to start the counter. The button click executes a SwingWorker task that updates a JLabel with the count. The update occurs in the doInBackground method.

Is this a bad idea? Even for something as simple as this, I should still update the component from a method that runs on the event dispatch thread, such as process?

If so, why would it be a bad practice for something as simple as this?

Main.java:

package counter;

import javax.swing.SwingUtilities;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                CounterView view = new CounterView();
                view.activate();
            }
        });
    }
}

ProgressBar.java:

package counter;

import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingWorker;
import javax.swing.SwingConstants;
import java.awt.event.*;

public class CounterView {
    private JFrame frame;
    private JPanel gui;
    private JButton button;
    private JLabel count;

    public CounterView() {
        customizeFrame();
        createMainPanel();
        createCountText();
        createButton();
        addComponentsToFrame();
    }

    private void customizeFrame() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void createMainPanel() {
        gui = new JPanel();
        gui.setLayout(new BorderLayout());
    }

    private void createCountText() {
        count = new JLabel("0");
        count.setHorizontalAlignment(SwingConstants.CENTER);
    }

    private void createButton()  {
        button = new JButton("Start counter");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Create the worker
                SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

                    @Override
                    protected Void doInBackground() throws Exception {
                        for (int i = 0; i <= 50; i++) {
                            Thread.sleep(100);
                            System.out.println(i);
                            text.setText(Integer.toString(i));
                        }

                        return null;
                    }
                };

                // Start the worker
                worker.execute();
            }
        });
    }

    private void addComponentsToFrame() {
        gui.add(count, BorderLayout.CENTER);
        gui.add(button, BorderLayout.SOUTH);
        frame.add(gui);
        frame.pack();
    }

    public void activate() {
        frame.setVisible(true);
    }
}


texts: COMpatible+ Google+ Integrations+ Scoping+

texts:
So I have part of a library which deals with scopes in Google+ integration, and I'm curious on the overall view of it.

Yes, things are stringly typed in one of the methods, that is because this has to be COMpatible, which does not support enum's.

I have (purposefully) omitted XML documentation, as most people think I go overboard and I'd rather not bloat.

public bool COM_GetLoginStatus(ref GoogleIdentity identity, WebBrowserSettings settings, bool force, string scopes = "")
{
    GooglePermissionScopes googlePermissionScopes = GooglePermissionScopes.None;

    scopes = scopes.ToLower();

    if (scopes == "")
    {
        scopes = "all";
    }

    foreach (string scope in scopes.Split(','))
    {
        switch (scope)
        {
            case "openid":
                googlePermissionScopes |= GooglePermissionScopes.OpenID;
                break;
            case "email":
                googlePermissionScopes |= GooglePermissionScopes.Email;
                break;
            case "plus.login":
            case "pluslogin":
                googlePermissionScopes |= GooglePermissionScopes.PlusLogin;
                break;
            case "all":
                googlePermissionScopes |= GooglePermissionScopes.All;
                break;
        }
    }

    return GetLoginStatus(ref identity, settings, force, googlePermissionScopes) == LoginStatus.Success;
}

The next method is responsible for building an endpoint to contact the API at.

public string GetLoginUrl(GooglePermissionScopes googlePermissionScopes = GooglePermissionScopes.None, bool force = false, string state = "")
{
    string endpoint = "https://accounts.google.com/o/oauth2/auth?";

    if (googlePermissionScopes != GooglePermissionScopes.None)
    {
        endpoint += "scope=";

        if ((googlePermissionScopes & GooglePermissionScopes.OpenID) == GooglePermissionScopes.OpenID)
        {
            endpoint += "openid";
        }

        if ((googlePermissionScopes & GooglePermissionScopes.Email) == GooglePermissionScopes.Email)
        {
            if (endpoint.Length > 6)
            {
                endpoint += "%20";
            }

            endpoint += "email";
        }

        if ((googlePermissionScopes & GooglePermissionScopes.PlusLogin) == GooglePermissionScopes.PlusLogin)
        {
            if (endpoint.Length > 6)
            {
                endpoint += "%20";
            }

            endpoint += "https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fplus.login";
        }
    }

    if (state != "")
    {
        endpoint = endpoint + "&state=" + state;
    }

    endpoint = endpoint + "&redirect_uri=" + CallbackUrl + "&response_type=code" + "&client_id=" + ClientId + "&access_type=offline";

    if (force)
    {
        endpoint += "&approval_prompt=force";
    }

    return endpoint;
}

I'm not sure if I should be using a StringBuilder here or not, since it's not a looped string concatenation.


texts:
The first function, sqlPull(), connects to a local MySQL database and pulls the last 20 rows from the database every 5 seconds.  The data coming in is a list of tuples, where MAC, RSSI and TimeStamp are the 3 elements in each tuple.  The data is entering the database at a variable rate, where sometimes I'll have tons of entries in a minute and sometimes I will have very few.  The data that is coming in consists of a MAC address, an RSSI and a TimeStamp for every time a user's device pings our hardware.  So, we will have unique MAC addresses that will have changing RSSIs and TimeStamps over a period of time.

Since I never know how many database entries will be added within the 5 seconds that the first function runs on, the second function, dupCatch() is used to detect and eliminate duplicates.

The third function, post(), just sends a POST request to Google Analytics with the data stripped of duplicates.

Here is how I would like to optimize my code:

My next step in this process is to calculate the length of time between a users first and last entries in the database.  We can assume that the max time between a user's entry and exit is 2 hours (in this time, the users would probably have 10-15 pings with different RSSIs and timestamps).  I have been trying to think of the best way to do this with the current code, but everything I am thinking of seems so unwieldy.  In my mind, sqlPull() and/or dupCatch() could be rewritten/optimized to better serve my purposes for a function to calculate length of time between entry and exit.

How would you pull data that is coming in at a variable and unpredictable rate?

import mysql.connector
import datetime
import requests
import time

run = True

def sqlPull():
    connection = mysql.connector.connect(user='XXXXX', password='XXXXX', host='XXXXX', database='XXXXX')
    cursor = connection.cursor()
    cursor.execute("SELECT TimeStamp, MAC, RSSI FROM wifiscan ORDER BY TimeStamp DESC LIMIT 20;")
    data = cursor.fetchall()
    connection.close()
    time.sleep(5)
    return data

seen = set()
def dupCatch():
    data = sqlPull()
    new_data = []
    for (TimeStamp, MAC, RSSI) in data:
        if (TimeStamp, MAC, RSSI) not in seen:
            seen.add((TimeStamp, MAC, RSSI))
            new_data.append((TimeStamp, MAC, RSSI))
    print new_data
    return new_data

def post():
    new_data = dupCatch()
    for ((TimeStamp, MAC, RSSI)) in new_data:
        payload = {'v':'1','tid':'XXXXXX','cid': '1','t':'event', 'ec': MAC, 'ea': 'InStore', 'el': RSSI}
        requests.post("http://www.google-analytics.com/collect", data = payload)

while run is True:
    post()


texts: How to find contradiction in order of items in multiple sequences

texts:
Suppose you have several sequences:

  A: 1  2  3  4  5
  B: 2  4  5
  C: 2  1  3  4  5
  D: 3  2

Here, some pairs of list contradicts each other, because they don't expose the same order for their similar elements: (A,C) (A,D) (C, D)

What is an algorithm or a linq statements to find such pairs? Or just to say if my sequences have such a contradiction or not! I store these sequences in a list of lists of strings

 List<List<String>> Sequences;

This is my code for the problem:

    private bool HasContradiction(List<List<String>> Sequences)
    {
        Cont = new List<Tuple<string, string>>();
        bool f = false;
        foreach (List<String> item1 in Sequences)
        {

            foreach (string elem1 in item1)
            {
                foreach (string elem2 in item1)
                {
                    int o1 = GetIndexOrder(item1, elem1, elem2);
                    foreach (List<String> item2 in Sequences)
                    {
                        int o2 = GetIndexOrder(item2, elem1, elem2);
                        if (o2 != 0 && o2 != o1)
                        {
                            Cont.Add(new Tuple<string, string>(String.Join(" ", item1), String.Join(" ", item2)));
                            f = true;
                        }
                    }
                }
            }
        }
        return f;
    }
    // this list stores contradicted pairs
    List<Tuple<string, string>> Cont = new List<Tuple<string, string>>();
    private int GetIndexOrder(List<string> item, string elem1, string elem2)
    {
        int i = item.FindIndex(x => x == elem1);
        int j = item.FindIndex(x => x == elem2);
        if (i < 0 || j < 0)
        {
            return 0;
        }
        if (i <= j)
        {
            return 1;
        }

        return 2;

    }

To test it:

    List<List<String>> seqs = new List<List<String>>{
    new List<String>{
        "1", "2", "3", "4", "5"
    },
    new List<String>{
         "2", "4", "5"
    },
    new List<String>{
        "2", "1","3","4","5"
    },
    new List<String>{
        "3", "2"
    },

};

        HasContradiction(seqs);
        foreach (var item in Cont.Distinct())
        {
            string tt = item.Item1 + "   AND  " + item.Item2;

            listView2.Items.Add(tt);
        }

Result:


texts:
This accepts values from a user that needs to show up in a intervals of some number. In this case, we will say intervals of 5.

Is there a better way to do this?

public static int RoundTo(this int value, int roundTo)
{
    var midPoint = roundTo / 2.0;
    var remainder = value % roundTo;
    var result = remainder < midPoint
        ? (value - remainder) //round down
        : (value + (roundTo - remainder)); //round up
    return result;
}

Example

Console.WriteLine(7.RoundTo(5)); //5
Console.WriteLine(8.RoundTo(5)); //10


texts:
Task (1.20)

  Write a program detab that replaces tabs in the input with the proper number
  of blanks to space to the next tab stop.

Also, the condition is is not to use pointers and structs etc because they will be considered in next chapters.

I'm new in C, and want to know what in my solution is bad idea and what can be done other way (but without pointers):

#include <stdio.h>
#define TABLINE 4

int count(char stri[]);

void main() {

    printf ("\nTabline is %d\n", TABLINE);

    int i = 0;
    int h;
    char stri[100];
    char c;

    while ((c = getchar()) != '\n' && c != EOF) {
        if (c == '\t')
            for (h=0; h<TABLINE; ++h) {
                stri[i] = ' ';
                ++i;
        } else {
            stri[i] = c;
            ++i;
        }
    }

    printf ("%d\n", count(stri));

    for (i=0; i< count(stri); ++i)
        printf ("%c", stri[i]);
}

int count(char stri[]) {

    int l;

    for (l=0; stri[l]; ++l)
        ;

    return l;
}

And its work:

$ ./detab

Tabline is 4
befortan        aftertab
20
befortan    aftertab


texts:
I have a function that compares two doubles to N decimal places.

#include <cmath>
#include <iostream>

using namespace std;

enum class RelType : int { Less, Equal, Greater };

RelType _compare(double v1, double v2, int multiplier)
{
    if (std::round(v1 * multiplier) == std::round(v2 * multiplier))
        return RelType::Equal;
    if (v1 < v2)
        return RelType::Less;
    return RelType::Greater;
}

template<int N> RelType compare(double, double) { static_assert(false, "Not implemented."); }
template<> RelType compare<5>(double v1, double v2) { return _compare(v1, v2, 100000); }

int main(int argc, char* argv[])
{
    double v1 = 1.0;                        // 1.0000000000000000
    double v2 = (1.0 / 13.67) * 13.67;      // 0.99999999999999989

    cout << std::boolalpha;
    cout << (v1 == v2) << endl;                               // false (not what we expected)
    cout << (compare<5>(v1, v2)==RelType::Equal) << endl;     // true (correct behaviour)
    cout << (v1 > v2) << endl;                                // true (not what we expected)
    cout << (compare<5>(v1, v2)==RelType::Greater) << endl;   // false (correct behaviour)

    return 0;
}

My main two questions are about the efficiency and correctness of the _compare helper function. Are there any pitfalls to consider that might not be obvious at first glance?


texts: Tic Tac Toe using Cartesian coordinate system

texts:
I am trying to learn the Cartesian Coordinate System, starting with a basic tic tac toe grid for simplicity, then perhaps moving to chess. I was able to make the following code to start out:

board = []

def new_board():
    for row in range(4):
        board.append([])
        for column in range(4):
            board[row].append('_')

def print_board():
    print(board)
    print('  %s | %s | %s' % (board[1][1], board[1][2], board[1][3]))
    print('----+---+----')
    print('  %s | %s | %s' % (board[2][1], board[2][2], board[2][3]))
    print('----+---+----')
    print('  %s | %s | %s' % (board[3][1], board[3][2], board[3][3]))

new_board()
print(board)
print_board()

When the list 'board' is printed, it gives the following:

[['_', '_', '_', '_'], ['_', '_', '_', '_'], ['_', '_', '_', '_'], ['_', '_', '_', '_']]
[['_', '_', '_', '_'], ['_', '_', '_', '_'], ['_', '_', '_', '_'], ['_', '_', '_', '_']]

Which is fine, but my issue is that in order for my commands to match the board (e.g. board[1][2] targeting the 1st row and the 2nd column of the board), I have to have a 'dummy entry' for [0], for both the sublists and the entries in the sublists.

Is there a way to do this without the dummy entries and still have my board list references match the actual board spaces?


texts: Compare File with ignore some line/last line

texts:
We have two log files in which one is generated from a process. We compare one file(golden file) to another file to check if file correct or not. It should have same value. We generally use diff utility to compare two files. I have got enhancement to add machine information into process generated File. So I want to compare upto previous line and ignore  new changes.
Could Anyone provide me any utility which I can use in python.

Golden File

CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -rise -data
CMD gen -vdd 0.99 -vss 0 -sinps 0.06 -slew 0.1 -temp -40 -rise -clock
CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -fall -data
CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -fall -data
CMD gen -vdd 0.99 -vss 0 -sinps 0.06 -slew 0.1 -temp -40 -rise -clock
CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -rise -data
Temp1   Temp2   Temp3   Temp4   Temp5   Temp6
-31.00     -19.00      -3.00       -8.00      43.00      61.00

Process File

CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -rise -data
CMD gen -vdd 0.99 -vss 0 -sinps 0.06 -slew 0.1 -temp -40 -rise -clock
CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -fall -data
CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -fall -data
CMD gen -vdd 0.99 -vss 0 -sinps 0.06 -slew 0.1 -temp -40 -rise -clock
CMD gen -vdd 0.99 -vss 0 -sinps 0.02 -slew 0.1 -temp -40 -rise -data
Temp1   Temp2   Temp3   Temp4   Temp5   Temp6
-31.00     -19.00      -3.00       -8.00      43.00      61.00
 Adding machine name( ignore machine name)

I have write code in following.Can we better way for improve code

data = None
with open("Golden_File",'r+') as f:
    data = f.readlines()
del data[-1]

data_1 = None
with open("cp.log",'r+') as f:
    data_1 = f.readlines()
del data_1[-1]
print cmp(data, data_1)

[Question]: Does cmp function works fine in list also. I have used first time and not sure how internally works.


texts:
After a somewhat lengthily discussion in the chat room, I have set up an IoC container with Unity to store my settings in.

This is my static IoC class:

public static class IoCContainer
{
    public static IUnityContainer Container = new UnityContainer();
}

In App.xaml.cs:

IoCContainer.Container.RegisterType<ApplicationSettingProvider<Theme>, ApplicationThemeProvider>(new ContainerControlledLifetimeManager());
IoCContainer.Container.RegisterType<ApplicationSettingProvider<FontSize>, ApplicationFontSizeProvider>(new ContainerControlledLifetimeManager());
IoCContainer.Container.RegisterType<ApplicationSettingProvider<AppVersion>, ApplicationStartupVersionProvider>(new ContainerControlledLifetimeManager());

Wherever I want to access my settings:

private ApplicationSettingProvider<Theme> _ThemeProvider = IoCContainer.Container.Resolve<ApplicationSettingProvider<Theme>>();
private ApplicationSettingProvider<FontSize> _FontSizeProvider = IoCContainer.Container.Resolve<ApplicationSettingProvider<FontSize>>();
private ApplicationSettingProvider<AppVersion> _StartupVersionProvider = IoCContainer.Container.Resolve<ApplicationSettingProvider<AppVersion>>();

And, an example setting, just to make everything complete:

public class ApplicationThemeProvider : ApplicationSettingProvider<Theme>
{
    public ApplicationThemeProvider()
    {
        ApplicationData.Current.DataChanged += (a, o) =>
        {
            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                OnSettingChanged((Theme)ApplicationData.Current.RoamingSettings.Values["Theme"]);
            });
        };
    }

    public override Theme GetCurrentSetting()
    {
        object value;
        if (ApplicationData.Current.RoamingSettings.Values.TryGetValue("Theme", out value))
        {
            int themeValue = (int)value;
            return (themeValue >= 0 && themeValue <= 2) ? (Theme)themeValue : Theme.Default;
        }
        return Theme.Default;
    }

    public override void SetCurrentSetting(Theme theme)
    {
        ApplicationData.Current.RoamingSettings.Values["Theme"] = (int)theme;
        ApplicationData.Current.SignalDataChanged();
    }
}

Which is based on:

public class SettingChangedEventArgs<T> : EventArgs
{
    public T NewSetting { get; private set; }

    public SettingChangedEventArgs(T newSetting)
    {
        NewSetting = newSetting;
    }
}

public abstract class ApplicationSettingProvider<T>
{
    public abstract T GetCurrentSetting();
    public abstract void SetCurrentSetting(T setting);

    public event EventHandler<SettingChangedEventArgs<T>> SettingChanged;
    public void OnSettingChanged(T newSetting)
    {
        var handler = SettingChanged;
        if (handler != null)
        {
            handler(this, new SettingChangedEventArgs<T>(newSetting));
        }
    }
}

This review is primarily to make sure I am using Unity right.  Please tell me everything that can be improved.


texts: Fetching specific foreign exchange rates from fixer using curl and jsconcpp in C++

texts:
I am trying to create my own algorithmic trading system using C++. I have searched the web for a nice tutorial for such systems and I didnt find any. Then I started to learn about curl and jsoncpp libraries and even documentation of those libraries are not made for a novice programmer like me. I mostly reused most of the codes for creating this scrapper especially WriteCallback function which I directly copy pasted from another c++ code without understanding it. I am sharing this whole code because some one else dosent need to reinvent the wheel and can use this code as a template.Any way this code is working properly (Ubuntu 14.04, CodeBlocks IDE, API: fixer.io) and any kind of suggestion or feedback is welcomed.

#include <string.h>
#include <iostream>
#include <stdio.h>
#include <jsoncpp/json/json.h>
#include <curl/curl.h>

//writing call back function for storing fetched values in memory
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

int main(void)
{
  std::string readBuffer;

 //global initiliation of curl before calling a function
 curl_global_init( CURL_GLOBAL_ALL );

 //creating session handle
 CURL * myHandle;

 // We’ll store the result of CURL’s webpage retrieval, for simple error checking.
 CURLcode result;

 // notice the lack of major error-checking, for brevity
 myHandle = curl_easy_init ( ) ;

 //after creating handle we ill start transfering webpage

 //curl_easy_setopt is used to tell libcurl how to behave.
 //By setting the appropriate options, the application can change libcurl's behavior.

 //CURLOPT_URL provide the URL to use in the request. Pass in a pointer to the URL to work with.
 //sample json output >> {"base":"EUR","date":"2016-07-22","rates":{"GBP":0.84108,"USD":1.1014}}
 curl_easy_setopt(myHandle, CURLOPT_URL, "http://api.fixer.io/latest?symbols=USD,GBP");

   /* send all data to this function  */
  curl_easy_setopt(myHandle, CURLOPT_WRITEFUNCTION, WriteCallback);

   /* we pass our 'chunk' struct to the callback function */
  curl_easy_setopt(myHandle, CURLOPT_WRITEDATA, &readBuffer);

 //perform a blocking file transfer
 result = curl_easy_perform( myHandle );

 /* check for errors */
  if(result != CURLE_OK) {
    fprintf(stderr, "curl_easy_perform() failed: %s\n",
            curl_easy_strerror(result));
  }
  else {
    /*
     * Now, our chunk.memory points to a memory block that is chunk.size
     * bytes big and contains the remote file.
     *
     * Do something nice with it!
     */

    //std::cout << readBuffer << std::endl;

    //json parsing
Json::Value root;   // will contains the root value after parsing.
Json::Reader reader;
bool parsingSuccessful = reader.parse( readBuffer, root );
if(not parsingSuccessful)
 {
   // Report failures and their locations
   // in the document.
   std::cout<<"Failed to parse JSON"<<std::endl
       <<reader.getFormatedErrorMessages()
       <<std::endl;
   return 1;
 }else{
 std::cout<<"\nSucess parsing json\n"<<std::endl;
 std::cout << root<< std::endl;
 std::cout <<"Base = "<< root["base"].asString() << std::endl;
 std::cout <<"Date = "<< root["date"].asString() << std::endl;
 std::cout <<"Rate GBP ="<< root["rates"]["GBP"].asFloat() << std::endl;
 std::cout <<"Rate USD ="<< root["rates"]["USD"].asFloat() << std::endl;

 }

  }

 //End a libcurl easy handle.This function must be the last function to call for an easy session
 curl_easy_cleanup( myHandle );

 return 0;
}


texts: Improving readability of non-recursive depth first search function in Lisp

texts:
As a free-time activity in order to learn some Lisp I had to implement depth first directed graph search. Due to large graph size (800K nodes, 5M arcs) recursion-based approach I could devise didn't work.

Below is my stack-based implementation that I would like to improve in terms of readability if nothing else. Any comments on style, use of Lisp idioms, code smell are welcome.

(defun depth-first-search (adjacency-array visit-function &optional (init-function nil init-function-supplied-p))
  (let* ((num-nodes (array-dimension adjacency-array 0))
         (init most-negative-fixnum)
         (nodes-seen (make-array num-nodes :element-type 'fixnum :initial-element init))
         (results (make-array num-nodes :element-type 'fixnum :initial-element init)))
    (labels ((visited-p (node) (not (eql init (aref results (1- node)))))
             (seen-p (node) (not (eql init (aref nodes-seen (1- node)))))
             (mark-seen (node) (setf (aref nodes-seen (1- node)) 1))
             (mark-visited (node)  (setf (aref results (1- node)) (funcall visit-function)))
             (visit (node)
               (unless (visited-p node)
                 (when init-function-supplied-p (funcall init-function node))
                 (mark-seen node)
                 (loop with stack = (list node)
                       until (null stack)
                       for head = (first stack)
                       for tails = (aref adjacency-array (1- head))
                       for fresh-tails = (unless (visited-p head)
                                           (loop for tail in tails
                                                 unless (or (visited-p tail)
                                                            (seen-p tail))
                                                 collect tail))
                       do (if fresh-tails
                            (progn
                              (mapcar #'mark-seen fresh-tails)
                              (setq stack (append fresh-tails stack)))
                            (progn
                              (pop stack)
                              (unless (visited-p head) (mark-visited head))))))))
      (loop for node from 1 to num-nodes
            unless (or (null node)
                     (visited-p node))
            do (visit node)
            finally (return results)))))

Some details:

adjacency-array for a graph 1->2;1->3;3->1 would be #((2 3) nil (1)).
visit-function returns a "visited" value for a node.
init-function makes necessary actions when new subgraph search starts.


texts: Best way to relate methods with properties

texts:
I have a class with some properties that I need to reflect over. One of the things I need, is a instance of a complex type returned for each of my properties, which means I can't just instantiate it directly in the attribute.

Now, I have so far two ways to do this. Either I can write method-names, in strings, in each attribute pointing to the method to call to get the instance, or I can use Duck Typing and add a "magic" method, that will contain information about the instance needed for each attribute.

Okay, let me show some code and then I need some feedback on which way is preferable or suggestions for other ways I haven't thought of.

public class SomeClass
{
   [Parameter("OnePropertyWidgetProvider")]
   public string OneProperty { get; set; }

   [Parameter("AnotherPropertyWidgetProvider")]
   public string AnotherProperty { get; set; }

   private Widget OnePropertyWidgetProvider() {}
   private Widget AnotherPropertyWidgetProvider() {}
}

Or

public class SomeClass
{
   public string OneProperty { get; set; }
   public string AnotherProperty { get; set; }

   private ParameterWidgets GetWidgets()
   {
      return new ParameterWidgets()
        {
            { () => this.OneProperty, new Widget() },
            { () => this.AnotherProperty, new Widget() },
        };
   }
}

The class itself a unit-of-work that can be configured through a GUI. The Widget-instance is needed to configure the editor the user should see to fill out the given property.

My concern with the first way is lack of type-safety, there is no way to check at compile-tile if the functions actually exists. It's always kinda verbose, and with many properties in one class, you end up with many methods returning Widgets.

The other way might introduce ways of coding that many programmers are not familiar with; lambdas and such. The syntax is cool, there is type safety, etc., but I'm afraid of it being "too clever".


texts:
Edit: A follow up post can be found here.

So I've started a c++ project, coming from Java / C# there are many obvious differences.

Below is an example of a class I've been working on:

.h

#pragma once

#include <vector>

#include <GL/glew.h>
#include <glm/glm.hpp>

class GLDebug {
private:

    struct Line {
        glm::vec3 p0, p1;
    };

private:

    std::vector<Line> m_lines;

public:

    GLDebug();
    ~GLDebug();

public:
    void drawLine(const glm::vec3& p0, const glm::vec3& p1);

    void onRender(const glm::mat4& projMatrix, const glm::mat4& viewMatrix);
};

.cpp

#include "GLDebug.h"

#include <glm/gtc/type_ptr.hpp>

GLDebug::GLDebug() { }

GLDebug::~GLDebug() { }

void GLDebug::drawLine(const glm::vec3& p0, const glm::vec3& p1) {
    m_lines.push_back({ p0, p1 });
}

void GLDebug::onRender(const glm::mat4& projMatrix, const glm::mat4& viewMatrix) {
    glMatrixMode(GL_PROJECTION);
    glLoadMatrixf(glm::value_ptr(projMatrix));

    glMatrixMode(GL_MODELVIEW);
    glLoadMatrixf(glm::value_ptr(viewMatrix));

    glBegin(GL_LINES);

    for (auto& line : m_lines) {
        glVertex3fv(glm::value_ptr(line.p0));
        glVertex3fv(glm::value_ptr(line.p1));
    }

    glEnd();

    m_lines.clear();
}

I've written this basic OpenGL debug utility class based on one I wrote in Java previously. Now it seems fine from what I can tell, but with my limited C++ knowledge I'm wondering if anything I'm doing is redundant / unnecessary and/or performance impacting.

One other thing, I know I can use compiler directives such as
#ifdef _DEBUG etc. If I wanted this class to only exist if compiling in debug mode, Obviously I can't wrap the whole class in the ifdef as that would break other code that is calling functions in the GLDebug class. So I was thinking of wrapping the functions internals instead. Is that a bad approach, I could use them everywhere else as well but that seems kinda bloated and less manageable.


texts: Fading in while scrolling - is this an elegant solution?

texts:
I have posted such question at StackOverflow but the single answer I got there was to ask here.
My task is to get elements fading in while the user is scrolling. Here is my link - http://layot.prestatrend.com/ I have made it with the help of such jQuery code I've gathered from two sources:

<script type="text/javascript">
 $(document).ready( function() {

 tiles = $('.ajax_block_product').fadeTo(0,0);

 $(window).scroll(function(d,h) {
    tiles.each(function(i) {
        a = $(this).offset().top + $(this).height();
        b = $(window).scrollTop() + $(window).height();
        if (a < b) $(this).fadeTo(500,1);
    });
 });

 function inWindow(s){
  var scrollTop = $(window).scrollTop();
  var windowHeight = $(window).height();
  var currentEls = $(s);
  var result = [];
  currentEls.each(function(){
    var el = $(this);
    var offset = el.offset();
    if(scrollTop <= offset.top && (el.height() + offset.top) < (scrollTop + windowHeight))
      result.push(this);
  });
  return $(result);
}

inWindow('.ajax_block_product').fadeTo(0,1);

});
</script>

Is this an elegant solution or is there a way to make the code shorter and more elegant?


texts: Rot and polyalphabetic ciphers in Python 2.7

texts:
I'm writing a "crypto library" and gradually adding algortihms. Now it's just ancient cryptography, but I'm going to expand the library.
It doesn't depend on any external libraries.

class Crypto():
    def __init__(self, rotInt=3, letters=list("abcdefghijklmnopqrstuvwxyz")):
        self.letters = letters
        self.length = len(self.letters)
        self.rotInt = rotInt
    def rot(self, string, rotInt, letters, length): # To decrypt, use a negative number
        result = []
        for letter in string:
            if letter == " ": # Skip spaces
                result.append(" ")
            else:
                letterIndex = letters.index(letter)
                resultIndex = letterIndex + rotInt
                resultIndex = resultIndex % length-1
                result.append(letters[resultIndex])
        return "".join(result) # Return result as a string
    def getRotArr(self, string, negative=False): # Negative is for decryption
        result = []
        for char in string:
            if negative:
                result.append(0-(self.letters.index(char)+1))
            else:
                result.append(self.letters.index(char)+1)
        return result
    def polyalphabetic(self, string, rotArr, letters, length):
        result = []
        rotArrIndex = 0
        for letter in string:
            if letter == " ": # Skip spaces
                result.append(" ")
            else: # Spaces would mess up rotArrIndex
                if rotArrIndex > len(rotArr)-1: # Repeat when end of rotArr is reached
                    rotArrIndex = 0
                rotInt = rotArr[rotArrIndex]
                letterIndex = letters.index(letter)
                resultIndex = letterIndex + rotInt
                resultIndex = resultIndex % length
                result.append(letters[resultIndex])
                rotArrIndex += 1
        return "".join(result) # Return result as a string


texts:
I have a some filters that chains around 30 Expression<Func<T, bool>> using linq to entities. Currently this is how I am managing them

        ...
        //project filter
        Expression<Func<Project, bool>> projectFilter = FilterEnabled();
        projectFilter = projectFilter.And(GetProjectByOrganization())
             .And(GetProjectByProductLine())
             .And(GetProjectByProjectType())
        ...

        //subproject filter
        Expression<Func<SubProject, bool>> subProjectFilter = FilterEnabled();
        subProjectFilter = subProjectFilter .And(...)
        ...

        //activity filter
        Expression<Func<Activity, bool>> activityFilter = FilterEnabled();
        activityFilter = activityFilter .And(...)
        ...

The problem is .And(Expression<Func<T, bool>>) extension method goes on for another 30 lines or so. How can I manage this another way instead of having to add .And 30+ times for each filter critera. Each filter method looks something like this.

public Expression<Func<Project, bool>> GetProjectByProjectId()
{
    return prj => FilterCriteria.ProjectId == null || prj.ProjectID == FilterCriteria.ProjectId.Value;
}

This is also my predicate builder class where I created the .And()

 public static class PredicateBuilder
    {

        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> a, Expression<Func<T, bool>> b)
        {
            ParameterExpression p = a.Parameters[0];

            SubstExpressionVisitor visitor = new SubstExpressionVisitor();
            visitor.subst[b.Parameters[0]] = p;

            Expression body = Expression.And(a.Body, visitor.Visit(b.Body));
            return Expression.Lambda<Func<T, bool>>(body, p);
        }

        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> a, Expression<Func<T, bool>> b)
        {
            ParameterExpression p = a.Parameters[0];

            SubstExpressionVisitor visitor = new SubstExpressionVisitor();
            visitor.subst[b.Parameters[0]] = p;

            Expression body = Expression.Or(a.Body, visitor.Visit(b.Body));
            return Expression.Lambda<Func<T, bool>>(body, p);
        }
    }

    internal class SubstExpressionVisitor : System.Linq.Expressions.ExpressionVisitor
    {
        public Dictionary<Expression, Expression> subst = new Dictionary<Expression, Expression>();

        protected override Expression VisitParameter(ParameterExpression node)
        {
            Expression newValue;
            if (subst.TryGetValue(node, out newValue))
            {
                return newValue;
            }
            return node;
        }
    }


texts:
I am pretty new to Clojure & am loving it so far. After going through a few resources, I decided to make a hangman game.

I'm wondering how idiomatic is my code & where can I improve it stylistically & reduce complexity. It is divided into two files. Both of them are shown below.

src/core.clj

(ns hangman.core
  (:gen-class)
  (:require [clojure.string :as string])
  (:use hangman.play))

(defn exit-screen []
  (println "Exit?\n->(Y)eah\n->(N)ope")
  (case (string/upper-case (read-line))
    "Y" :null-screen
    "N" :menu-screen
    :exit-screen))

(defn play-screen []
  (println "Mode:\n->(1)p\n->(2)p")
  (case (read-line)
    "1" (play-turn (get-cipher :1p) #{} #{})
    "2" (play-turn (get-cipher :2p) #{} #{})
    (println "Enter a valid mode."))
  :menu-screen)

(defn menu-screen []
  (println "Menu:\n->(P)lay\n->(E)xit")
  (case (string/upper-case (read-line))
    "P" :play-screen
    "E" :exit-screen
    :menu-screen))

(defn run-screen [screen]
  (case screen
    :menu-screen (recur (menu-screen))
    :play-screen (recur (play-screen))
    :exit-screen (recur (exit-screen))
    (println "Exiting...")))

(defn -main [& args]
  (run-screen :menu-screen))

src/play.clj

(ns hangman.play
  (:require [clojure.string :as str]))

(defn game-over? [cipher right wrong]
  (or
    (> (count wrong) 5)
    (= (count (set cipher)) (count right))))

(defn get-move [right wrong]
  (let [move (str/upper-case (read-line))]
    (if (or (contains? right move) (contains? wrong move))
      (do
        (println "Already Tried.")
        (recur right wrong))
      move)))

(defn show-ui [cipher right wrong]
  (println (case (count wrong)
             0 " O \n/|\\\n/ \\"
             1 " O \n/|\\\n  \\"
             2 " O \n/|\\\n    "
             3 " O \n |\\\n    "
             4 " O \n | \n     "
             5 " O \n   \n     "
             6 " X \n   \n     "))
  (println (str "Right: " right))
  (println (str "Wrong: " wrong))
  (doseq [letter cipher]
    (if (contains? right letter)
      (print letter)
      (print " _")))
  (println ""))

(defn play-turn [cipher right wrong]
  (show-ui cipher right wrong)
  (let [move (get-move right wrong)]
    (let [[right wrong]
          (if (.contains cipher move)
            [(conj right move) wrong]
            [right (conj wrong move)])]
      (if-not (game-over? cipher right wrong)
        (recur cipher right wrong)
        (println "Game Over!")))))

(defmulti get-cipher (fn [mode] mode))

(defmethod get-cipher :1p [mode]
  (let [ciphers (str/split (str/trim-newline (slurp "resources/ciphers.txt")) #", ")]
    (str/split (str/upper-case (rand-nth ciphers)) #"")))

(defmethod get-cipher :2p [mode]
  (println "Enter a cipher")
  (str/split (str/upper-case (read-line)) #""))

There is a file called cipher.txt in my resources folder. It contains various ", " separated words that can be used for the game.

resources/cipher.txt

apple, ball, cat, dog, elephant, fish, hangman

I feel that my play.clj file is needlessly complicated & is the main source of inelegance.

Playing the game: To select an option, press whatever character is in (). For eg: To select the (P)lay option, press p or P.

PS: Do you know any resource where I can learn good style in Clojure. Preferably something to do with games?