texts: Implementation of Radix Sort algorithm for sorting integers in c++

texts:
I wrote the following code for Radix Sort algorithm for number sorting. Any review is highly appreciated.

  You can also view and run/test the code here Radix Sort

#include<iostream>
using namespace std;

int getNumberAtPosition(int num,int position){
    return (num/position)%10;
}
void radixSort(int array[],int length){
int sizeOfEachBucket = length;
int numberOfBuckets = 10;
int buckets[10][sizeOfEachBucket];
int large = 0;
int maxPasses = 0;
//finding largest number from array
for(int i=0; i<length; i++){
    if(array[i]>large){
        large = array[i];
    }
}

//finding the number of passes
while(large != 0){
     maxPasses++;
     large = large/10;
}
cout<<"Max passes ="<<maxPasses<<endl;
int position = 1;
int bucketIndex = 0;
int newListIndex = 0;
int arrayLengths[10];
for(int i=0; i<maxPasses; i++){
    //cout<<"i ="<<i<<endl;
    for(int k=0; k<=9; k++){
         //cout<<"k ="<<k<<endl;
         bucketIndex = 0;
        for(int j=0; j<length; j++){
            if(k==getNumberAtPosition(array[j],position)){
                buckets[k][bucketIndex] = array[j];
                bucketIndex++;
            }
        }
        arrayLengths[k] = bucketIndex;
    }
    position = position*10;
    int newArrayIndex = 0;
    for(int k=0; k<=9; k++){
         //cout<<"k ="<<k<<endl;
         bucketIndex = 0;
         for(int x=0; x<arrayLengths[k];x++){
            array[newArrayIndex] = buckets[k][x];
            newArrayIndex++;
         }
    }

}
for(int i=0; i<length; i++){
    cout<<array[i]<<"\t";
}
}


texts: Bash script to set up an ad hoc wireless network

texts:
This script creates an adhoc network using hostapd.
I have tested it and seems to work reliably.
I am new to linux networking and not sure if this is a recommended way to create an adhoc network this way.

#!/bin/bash
#set -x
DEVICE=wlan0
CONFIG_FILE=./hostapd.conf
ConfigureDevice()
{
    if ! sudo iwconfig 2>/dev/null | grep $DEVICE >/dev/null;then
        echo $DEVICE not found!
        exit -1
    fi

    #Ensure config file exists
    if [ ! -e $CONFIG_FILE ]
    then
        echo "Can't find hostapd config file"
        exit -1
    fi

    sudo service isc-dhcp-server stop
    sudo pkill hostapd
    sudo ifdown  $DEVICE
    sudo ifconfig $DEVICE up 192.168.1.100 netmask 255.255.255.0
    sudo service isc-dhcp-server start
    sudo hostapd -B $CONFIG_FILE

}
cd ${0%/*}  #make current working directory the directory of the bash script
ConfigureDevice


texts:
I believe I have achieved computation of primality!  That is, the computation of prime numbers.  The code I am about to post will give you every prime there is, in order, starting with 2.  Can we call this a major win guys?

Edit: just to be clear guys, this is a general formula for the computation of primality! (one which we didn't know existed and one which, well, I get the feeling we were about to prove wrong).

What I mean by this, is you can pass a LinkedList of the first 25 million primes, and the NextPrime() method will give you the 25,000,001 prime.  And you can keep on calling NextPrime() to keep going up!  You can start with a list almost as big as a LinkedList will hold (unfortunately, I think that means we are limited to computing up to the first 2 billion primes.  We can get around that with a little custom data structure coding)

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

public class PrimeTester
{
    public virtual bool RelativelyPrime(IEnumerable<long> numbers, bool onlyCheckLast)
    {
        LinkedList<long> orderedLinkedList;
        if (onlyCheckLast)
        {
            orderedLinkedList = new LinkedList<long>(numbers);
            var numberToCheck = orderedLinkedList.Last.Value;
            var squareRoot = (long)Math.Sqrt(numberToCheck);

            return new LinkedList<long>(orderedLinkedList.Where(number => number <= squareRoot))
                .All(number => numberToCheck % number > 0);
        }

        orderedLinkedList = new LinkedList<long>(numbers);
        while (true)
        {
            var lowestNumber = orderedLinkedList.First.Value;
            orderedLinkedList.RemoveFirst();
            if (orderedLinkedList.Count == 0)
            {
                return true;
            }

            if (orderedLinkedList.Any(number => number%lowestNumber == 0))
            {
                return false;
            }
        }
    }
}

onlyCheckLast is true for computing primes (all the previous primes must be stored in an ordered set).  If you want to pass in a full set of any kind of whole number, then you can always pass false to onlyCheckLast.

(Isn't that modulo arithmetic nice?)
Here is the actual prime generator:

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

public class PrimeGenerator
{
    public PrimeGenerator()
    {
        this.tester = new PrimeTester();
        this.currentSet = new LinkedList<long>(new long[] { 2, 3 });
    }

    public PrimeGenerator(LinkedList<long> currentSet)
    {
        this.tester = new PrimeTester();
        this.currentSet = currentSet;
    }

    public LinkedList<long> CurrentSet => this.currentSet;

    public virtual long NextPrime()
    {
        return this.collectPrime();
    }

    public virtual IEnumerable<long> Generate()
    {
        foreach (var prime in this.currentSet)
        {
            yield return prime;
        }

        while (true)
        {
            yield return this.collectPrime();
        }
    }

    private long collectPrime()
    {
        this.currentSet.AddLast(this.currentSet.Last.Value + 2);
        while (!this.tester.RelativelyPrime(this.currentSet, true))
        {
            var node = this.currentSet.Last;
            this.currentSet.RemoveLast();
            this.currentSet.AddLast(node.Value + 2);
        }

        return this.currentSet.Last.Value;
    }

    private readonly LinkedList<long> currentSet;
    private readonly PrimeTester tester;
}

If you guys need help using this code, let me know and I can post my test code.  I have tested the first 150,000 primes against a text file with the first million primes and it passed!


texts:
I need to test my new functionality by sending about 100 requests in one time.

public class MyTest {
    // ...

    @Test
    public void test() throws Exception {
        Runnable[] runners = new Runnable[size];
        Thread[] threads = new Thread[size];

        for(int i=0; i<threads.length; i++) {
            runners[i] = new RequestThread(i);
        }

        for(int i=0; i<threads.length; i++) {
            threads[i] = new Thread(runners[i]);
        }

        for(int i=0; i<threads.length; i++) {
            threads[i].start();
        }

        while (!threadsAreDead(threads)) {}
    }

    private boolean threadsAreDead(Thread[] threads) {
        for(int i=0; i<threads.length; i++) {
            if (threads[i].isAlive()) return false;
        }

        return true;
    }
}

class RequestThread implements Runnable {
    public RequestThread(int id) {
        this.id = id;
    }

    @Override
    public void run() {
        try {
            b2b.execute(request);
        } catch (B2BException e) {
            // ...
        }
    }

}

Have you any idea how to optimize above code to send requests more 'in one time'?


texts: Parsing objects from complex String in Java

texts:
I want to convert string arrays with following structure:

static String[] lines = {
                          "@1      var_decl         name: testStr  parent: @7",
                          "                         srcp: Auto.cpp:6         "
                        };

into Java objects with following structure:

class Token {
   String type;
   String name;
   String source;
   Token parent;
}

So far I'm parsing this in this way:

Token parseLines(String[] lines) {

    String[] firstElements = lines[0].split(" ");
    String[] secondElements = lines[1].split(" ");

    Token newToken = new Token();

    newToken.type = firstElements[6];
    newToken.name = firstElements[16];
    String parentName = firstElements[19];
    newToken.parent = getParent(parent); // find parent by name
    newToken.source = secondElements[26];
    return newToken;
}

As you can see, this is far from elegant. How can I improve this?


texts:
I am not experienced in C++, and wrote this code for implementing a stack data structure using a linked list.

Can you please point out any flaws, errors, stupid mistakes, general improvements etc that can make this code better?

#include <iostream>
using namespace std;

struct Node;

struct Node {
    int data;
    Node* next;
};

class Stack {
public:
    Node* first;
    Node* last;

    Stack() {
        first = 0;
        last = 0;
    }

    ~Stack() {
         while (first != 0) { pop(); }
    }

    Stack& push(int value) {
        Node* temp = new Node;
        temp->data = value;
        temp->next = 0;

        if (first == 0) {
            first = temp;
            last = temp;
        } else {
            last->next = temp;
            last = last->next;
        }

        cout << "Pushed " << value << " on the stack\n";

        temp = 0;
        return *this;
    }

    Stack& pop() {
        if (first == 0) {
            cout << "No nodes to pop.\n";
        } else {
                // only one node left
                if (first == last) {
                cout << "Popped " << first->data << " off the stack\n";
                delete first;
                first = 0;
                last = 0;
                return *this;
            }

            Node* temp = first;
            while (temp->next != last) {
                temp = temp->next;
            }
            cout << "Popped " << last->data << " off the stack\n";
            delete last;
            last = temp;
            last->next = 0;
        }
        return *this;
    }
};

int main() {
    Stack s;
    s.pop();
    s.push(1);
    s.push(2);
    s.pop();
    s.push(3).push(4);
    s.pop().pop();
    return 0;
}


texts: Python3: using generator to process a very large list of integers

texts:
This is from a leetcode question I am working on. The problem is the following:
create an algorithm that works in the the following fashion:
arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]
the output is:
[2,7,14,8]
by applying the following series of operations:
The XOR values for queries are:
[0,1] = 1 xor 3 = 2
[1,2] = 3 xor 4 = 7
[0,3] = 1 xor 3 xor 4 xor 8 = 14
[3,3] = 8
The input is a very large list for arr and an even longer list for queries. The output has to be a list and I have tried this several ways.
first attempt: (building a gigantic list in memory and returning it using append() )
def XORsubqueries(array, queries):
    result = []
    for pair in queries:
        value = array[pair[0]]
        i = pair[0]
        while i < pair[1]:
            if pair[0] == pair[1]:
                result.append(array[pair[i]] ^ array[pair[i]])
                break
            else:
                i += 1
                value ^= array[i]
        result.append(value)
    return result

As you can imagine this takes FOREVER (53 seconds on my i5 dual core).  I then remembered about generator expressions for lazily building values and thought they might come in handy just for this kind of thing.
def XORsubqueries(array, queries):

    result = [0] * len(array)
    def XOR(array, queries):
        for pair in queries:
            value = array[pair[0]]
            i = pair[0]
            while i < pair[1]:
                i += 1
                value ^= array[i]
                yield value
    return list(XOR(array, queries))

If i remove the list off that return statement it figures it out in like 0.0001 seconds ! But I have to return it as a list.  Is there a way I can rewrite my algorithm to do what I am trying to do with this generator or did I paint myself into a corner ?


texts:
Is this a good solution for FizzBuzz? What can I do better?

for num in range(1, 101):
    if num % 3 == 0:
        if num % 5 == 0:
            print("FizzBuzz")
        else:
            print("Fizz")
    elif num % 5 == 0:
        print("Buzz")
    else:
        print(num)


texts: Given a large string, finding the length of the first longest even length sub-string

texts:
I am writing a function where I can take a string as input, and then find the even number of substrings. The final result is the first longest even length string is returned by the function.

For example:

Input -> It is a pleasant day today

Output -> pleasant

For example:

Input -> It is a day today

Output-> It

(Since there are two sub-strings of the same even length, returning the first longest even length string is enough.)

If there are no such even length strings then, the function should return 00.

import sys

def longestEvenWord(sentence):
    list1 = sentence.split()

    for x in list1[:]:
        # just removing all the odd length words from
        # the list. Then the list will contain only
        # even words
        if (len(x) % 2 != 0):
            list1.remove(x)
    #after removing the odd length numbers, we will have only even and find the
    #longest word and return that.
    return max(list1, key=len)

if __name__ == '__main__':
    result = longestEvenWord(" qqqqqqqqq It is a day today qqqqqqqqq")
    print(result)


texts:
I have made a timer class:

The timer should call an async method and wait between two calls.
I want to wake up the timer to skip the wait period.
When I dispose the timer from outside the timer I want to wait until the current call is completed.
I want to stop the timer from inside the timer.

public sealed class CompletionTimer : IDisposable
{
    private readonly CancellationTokenSource disposeToken = new CancellationTokenSource();
    private readonly Task runTask;
    private int requiresAtLeastOne;
    private CancellationTokenSource wakeupToken;

    public CompletionTimer(int delayInMs, Func<CancellationToken, Task> callback, int initialDelay = 0)
    {
        runTask = RunInternal(delayInMs, initialDelay, callback);
    }

    public void Dispose()
    {
        disposeToken.Cancel();

        runTask.Wait();
    }

    public void Wakeup()
    {
        ThrowIfDisposed();

        Interlocked.CompareExchange(ref requiresAtLeastOne, 2, 0);

        wakeupToken?.Cancel();
    }

    private async Task RunInternal(int delay, int initialDelay, Func<CancellationToken, Task> callback)
    {
        if (initialDelay > 0)
        {
            await WaitAsync(initialDelay).ConfigureAwait(false);
        }

        while (requiresAtLeastOne == 2 || !disposeToken.IsCancellationRequested)
        {
            try
            {
                await callback(disposeToken.Token).ConfigureAwait(false);
            }
            catch (OperationCanceledException)
            {
            }
            finally
            {
                requiresAtLeastOne = 1;
            }

            await WaitAsync(delay).ConfigureAwait(false);
        }
    }

    private async Task WaitAsync(int intervall)
    {
        try
        {
            wakeupToken = new CancellationTokenSource();

            using (var cts = CancellationTokenSource.CreateLinkedTokenSource(disposeToken.Token, wakeupToken.Token))
            {
                await Task.Delay(intervall, cts.Token).ConfigureAwait(false);
            }
        }
        catch (OperationCanceledException)
        {
        }
    }
}

The requiresAtLeastOne field is to enforce at least one run when I do something like that (in a test or so):

var timer = new CompletionTimer(10000, ct => ... );
timer.Wakeup();
timer.Dispose();

It almost works perfectly, but one time (of thousand of calls) I had a deadlock in the Dispose method, when I was calling it from within a timer. I am more confused why it does not deadlock all the time.


texts: PHP - check if array includes value and return value if true

texts:
I developed the function array_includes which checks if an array contains a value and returns it. I would like to know if there is already such a function which is more efficient or how I can make the function more efficient.

<?php
$params = "colorgroup-b;test;abc";
$paramsArr = explode(";", $params);

var_dump(array_includes("colorgroup", $paramsArr));  //outputs: colorgroup-b

function array_includes($needle, $arr)
{
    foreach($arr as $param) {
        if (strpos($param, $needle) !== false) {
            return $param;
        }
    }
    return false;
}


texts:
Another code for exercism, It is to convert Vec of u32 from one base to another base. Please help to make it more idiomatic, Also if this type of question is welcomed here or not.

#[derive(Debug, PartialEq)]
pub enum Error {
    InvalidInputBase,
    InvalidOutputBase,
    InvalidDigit(u32),
}

pub fn convert(number: &[u32], from_base: u32, to_base: u32) -> Result<Vec<u32>, Error> {

    if from_base < 2 {
        return Err(Error::InvalidInputBase);
    }

    if to_base <2  {
        return Err(Error::InvalidOutputBase);
    }

    if number.iter().any(|&x| x > 0 && x >= from_base ){
        return Err(Error::InvalidDigit(from_base));
    }

    let  res: u32 = number.iter().rev().enumerate().map(|(index, x)| x*from_base.pow(index as u32)).sum();
    Ok(convert_back(res, to_base))

}

fn convert_back(number: u32, base: u32) -> Vec<u32>{

    let mut res: Vec<u32> = Vec::new();
    let mut inter = number as f64;

    loop {
        inter = inter as f64/base as f64;
        res.push((inter.fract()*base as f64).round() as u32);
        if inter as u32 ==0{
             break
             }

        inter = inter.trunc();
        }

        res.reverse();
        res

}

Some tests

fn decimal_to_binary() {
    let input_base = 10;
    let input_digits = &[4, 2];
    let output_base = 2;
    let output_digits = vec![1, 0, 1, 0, 1, 0];
    assert_eq!(
        ayb::convert(input_digits, input_base, output_base),
        Ok(output_digits)
    );
}

fn trinary_to_hexadecimal() {
    let input_base = 3;
        let input_digits = &[1, 1, 2, 0];
        let output_base = 16;
        let output_digits = vec![2, 10];
    assert_eq!(
       convert(input_digits, input_base, output_base),
        Ok(output_digits)
    );
}

fn hexadecimal_to_trinary() {
    let input_base = 16;
    let input_digits = &[2, 10];
    let output_base = 3;
    let output_digits = vec![1, 1, 2, 0];
    assert_eq!(
        convert(input_digits, input_base, output_base),
        Ok(output_digits)
    );
}

fn invalid_positive_digit() {
    let input_base = 2;
    let input_digits = &[1, 2, 1, 0, 1, 0];
    let output_base = 10;
    assert_eq!(
        convert(input_digits, input_base, output_base),
        Err(Error::InvalidDigit(2))
    );
}

fn output_base_is_zero() {
    let input_base = 10;
    let input_digits = &[7];
    let output_base = 0;
    assert_eq!(
        convert(input_digits, input_base, output_base),
        Err(Error::InvalidOutputBase)
    );
}

```


texts:
What it is doing basically is reading an std::string from a given pointer.

I was told that using a StringBuilder as I am is not the best way to achieve this, so I would like to know how this would be best written.

As additional information, that is a pointer of a std::string and I've made that because I was originally curious if there was a way to read a std::string in C# without having to create a bridge using C++/CLI.

How could I optimize this bit of code for best performance?

public static string ReadStdString(IntPtr address)
{
    var capacity = Marshal.ReadInt32(address + 24);
    var length = Marshal.ReadInt32(address + 20);
    var startStr = address + 4;
    if (capacity > 15)
        startStr = (IntPtr)Marshal.ReadInt32(address + 4);

    var result = new StringBuilder();
    for (var i = 0; i < length; i++)
    {
        result.Append((char)Marshal.ReadByte(startStr, i));
    }
    return result.ToString();
}


texts: Object-oriented URL loading and HTTP client with requests in Python

texts:
I have an API which I want to consume in Python 3.x using the requests module.
Right now, my solution is to create Requests objects for each URL like the LoginRequest, etc. (see below).

I have one request per API URL and need to write the __init__ method for each class depending on the parameters that are requested for the API. I find it tedious and I am not sure that's a good design.

Could you suggest a better design? (e.g. not using OOP, with metaclass, ... ?)

class BaseRequest:
    USER_AGENT = 'My App 1.0'
    headers = {'User-Agent': USER_AGENT}
    url = None
    data = None
    params = None

    def __init__(self, url, data=None, headers=None, params=None):
        self.url = url
        if data:
            data.update(self.data or {})
            self.data = data
        if headers:
            headers.update(self.headers or {})
            self.headers = headers
        if params:
            params.update(self.params or {})
            self.params = params

    def process(self):
        r = requests.post(self.url, data=self.data, headers=self.headers, params=self.params)
        try:
            j = r.json()
        except:
            print(self.url, self.params, self.data)
            print(r.text)
            exit()
        return j

class AuthenticatedRequest(BaseRequest):
    API_KEY = 'blah'
    APP_ID = 'OfficialClient'
    data = {'appkey': API_KEY, 'appid': APP_ID}

class LoginRequest(AuthenticatedRequest):
    url = 'https://my.api.com/login'

    def __init__(self, email, password):
        super().__init__(self.url, data=dict(email=email, password=password, action='login'))

# now let's play with the API !
user = LoginRequest(email, password).process()
GetUserInfoDetailsRequest(...).process()


texts:
Is there a better way to time the functions and print the result and function name dynamically?

package project_euler
object Timers extends App{

  def time[R](f: => R): Unit = {
        val t0 = System.nanoTime()
        val r = f
        val t1 = System.nanoTime()

        val t = (t1-t0)/1000

    println(s"The result is: $r time taken $t ms ")
    // print also the name of the function f**

  }

   /*
    * Problem 1 project Euler
    * If we list all the natural numbers below 10 that are multiples of 3 or 5,
    * we get 3, 5, 6 and 9.
    * The sum of these multiples is 23.
    * Find the sum of all the multiples of 3 or 5 below 1000.
    * */

   //functional implementation
   def func = (0 until 1000).filter(x => x % 3 ==0  || x % 5 ==0).sum

   //imperative implementation
   def imper = {
     var i,sum = 0

     while (i < 1000) {
      if( i % 3 ==0 || i % 5 ==0)
          sum +=i

      i+=1 //increase counter
    }
    sum
  }
   time (func)
   time (imper)
  }


texts:
To teach myself how to do meta-progaming using Prolog, I've been playing around with translating ABNF syntax into DCG syntax. I'm still at the lexing and tokenising stage, but hope to advance to the "yacc" stage soon.

Using Json, since it is defined in ABNF at https://trac.ietf.org/trac/json/browser/abnf/json.abnf?rev=2 (and something I find frustrating in compiler tutorials I've found online is they don't stick to context free grammars after boring students with the basics), I've written the following code which works OK on the simple examples I've tested.

:- use_module(library(dcg/basics)).

% value = false / null / true / object / array / number / string
value(l("false"))           --> blanks, [102, 97, 108, 115, 101], blanks.
value(l("null"))            --> blanks, [110, 117, 108, 108], blanks.
value(l("true"))            --> blanks, [116, 114, 117, 101], blanks.
% object = "{" [ member *( "," member ) ] "}"
value(o(Object))            --> blanks, [123], blanks, members(Object), blanks, [125], blanks.
% array = "[" [ value *( "," value ) ] "]"
value(a(Array))             --> blanks, [91], blanks, values(Array), blanks, [93], blanks.
% number = [ "-" ] int [ frac ] [ exp ]
value(n(Number))            --> number(Number).
% string = '"' *char '"'
value(s(String))            --> blanks, [34], chars(Codes), { string_codes(String, Codes) }. % needs a different pattern to handle escaping
% a string has several chars terminated by an unescaped double quote
chars([92,34|Codes])        --> [92,34], chars(Codes). % skip \"
chars([Code|Codes])         --> [Code], chars(Codes), { Code \= 34 }.
chars([])                   --> [34].
% member = string ":" value   abreviated to memb to avoid collision with prolog's builtin clause member
memb(m(s(String), Value))   --> blanks, value(s(String)), blanks, [58], blanks, value(Value), blanks.
% an object can have several comma separated members
members([Member|Members])   --> blanks, memb(Member), blanks, [44], blanks, members(Members).
members([Member])           --> blanks, memb(Member), blanks.
members([])                 --> [].
% an array can have several comma separated values
values([Value|Values])      --> blanks, value(Value), blanks, [44], blanks, values(Values).
values([Value])             --> blanks, value(Value), blanks.
values([])                  --> [].

tokenize(Filename, Tokens) :-
  phrase_from_file(value(Tokens), Filename), !.

I'd appreciate some tips on how to improve this from the gurus in this group.


texts:
I've created the following string manipulation function for randomizing my passed string in Lua:

require "string"
require "math"

math.randomseed( os.time() )

function string.random( self )
    local tTemporary, tNew = {}, {}
    if not self or self:len() < 5 then
        return nil
    end
    self:gsub( "%a", function( cChar )
            table.insert( tTemporary, cChar )
        end
    )
    for i = 1, #tTemporary, 1 do
        local iRandom = math.random(1, #tTemporary)
        tNew[i] = tTemporary[iRandom]
        table.remove( tTemporary, iRandom )
    end
    return table.concat(tNew, "   ")
end

Can this be optimized/more-randomised?


texts:
I'm learning C++, so I wrote a stack with the help of templates. I'm wondering if there is anything I can improve or if I did something vastly wrong.

Stack.h

#pragma once
#include <ostream>

template <class Type>
struct Node {
    Node(Type data, Node<Type>* next)
        : data(data), next(next) {}
    Node* next;
    Type data;
};

template <class Type>
class Stack
{
public:

    Stack() : length(0), topNode(NULL) {
    }

    ~Stack() {
        while (!isEmpty()) {
            pop();
        }
    }

    void push(Type data) {
        Node<Type>* newNode = new Node<Type>(data, topNode);
        topNode = newNode;
        ++length;
    }

    Type pop() {
        if (!isEmpty()) {
            Node<Type>* popped = topNode;
            Type poppedData = popped->data;
            topNode = popped->next;
            --length;
            delete popped;
            return poppedData;
        }

        throw new std::exception("Stack underflow!");
    }

    bool isEmpty() {
        return length == 0;
    }

    void print() const {
        Node<Type>* tempTop = topNode;
        while (tempTop != NULL) {
            std::cout << tempTop->data << endl;
            tempTop = tempTop->next;
        }
    }

    int count() const {
        return length;
    }

private:
    Node<Type>*         topNode;
    int                 length;

};

Main.cpp

#include <iostream>
#include "Stack.h"

using namespace std;

int main() {
    Stack<int> myStack;

    // Push some values
    myStack.push(2);
    myStack.push(4);
    myStack.push(8);
    myStack.push(16);
    myStack.push(32);

    // We pop the 32
    myStack.pop();

    // Display count after the pop
    int lastPopped = myStack.pop();
    cout << "Popped value: " << lastPopped << ", Count: " << myStack.count() << endl;

    // Print whole stack
    cout << endl << "Stack print: " << endl;
    myStack.print();

    // Exit program when the 'any' key is pressed.
    system("PAUSE");
    return 0;
}


texts: Helper function to find rotation of Caesar Cipher

texts:
Just finished an assignment in Python where one part was to write a function to find the correct rotation in a encryption similar to a Caesar Cipher..

As mentioned it's already finished and works as intended. The course is an introduction to Python, but I do have experience with other languages since previously.

I was hoping someone could have a look at my findRot to see where I possibly could have done anything that isn't 'Python-esque' or what potential bottlenecks might occur.

def findRot(word1, word2, iterator):
    letterFreq = [("A", 65), ("E", 69), ("I", 73), ("O", 79), ("T", 84), ("U", 85)]
    rot = ord(word1) - letterFreq[iterator][1]
    letters = [chr(ord(letter) - rot) if (ord(letter) - rot >= 65) else chr(90 - (65 -(ord(word2[2]) - rot + 1))) for letter in word2]
    with open('words.txt', 'r') as words:
        lines = words.readlines()
        lines = list(map(lambda s: s.upper().strip(), lines))
        if ''.join(letters) in lines:
            print(''.join(letters) + ", " + str(True))
            return rot
        else:
            findRot(word1, word2, iterator + 1)

The assignment specified the usage of letter frequency, so I just took some of the more common letters found in English and put them in a list of tuples for readability purposes.

In the professor's use-case the first word would be 'R' and the second would be 'Uxen'. So in this case the rotation would supply the 'I' and 'Love'.

Again, this function just runs a primary check to find the rotation to apply to the rest of the 'encrypted' text. So a validation of the decrypted text will take place later.

EDIT:

Example usage:

>>> findRot('R', 'UXEN', 0)
9

Because it takes 9 rotations to get to the clear text I and Love.


texts: Map unique raw words to a list of code words

texts:
Problem

Write a function that replaces the words in raw with the words in code_words such that the first occurrence of each word in raw is assigned the first unassigned word in code_words. If the code_words list is too short, raise an error. code_words may contain duplicates, in which case the function should ignore/skip them.

Examples:

encoder(["a"], ["1", "2", "3", "4"]) → ["1"]
encoder(["a", "b"], ["1", "2", "3", "4"]) → ["1", "2"]
encoder(["a", "b", "a"], ["1", "1", "2", "3", "4"]) → ["1", "2", "1"]

Solution

def encoder(raw, code_words):
    cw = iter(code_words)
    code_by_raw = {} # map of raw item to code item
    result = []
    seen = set() # for ignoring duplicate code_words
    for r in raw:
        if r not in code_by_raw:
            for code in cw: # cw is iter(code_words), "persistent pointer"
                if code not in seen:
                    seen.add(code)
                    break
            else: # nobreak; ran out of code_words
                raise ValueError("not enough code_words")
            code_by_raw[r] = code
        result.append(code_by_raw[r])
    return result

Questions

My main concern is the use of cw as a "persistent pointer". Specifically, might people be confused when they see for code in cw?

What should be the typical best practices in this case?

Might it be better if I used the following instead?

try:
    code = next(cw)
    while code in seen:
        code = next(cw)
except StopIteration:
    raise ValueError("not enough code_words")
else:
    seen.add(code)


texts: Performance in Hackerrank challenge "Sherlock and Queries"

texts:
I translated the solution by the author to his challenge from C++ to Python.
It seems to be correct, but I get timeouts for the test cases 6, 9 and 12.

Here is the full challenge description:

  Watson gives to Sherlock an array: \$A_1, A_2, ..., A_N\$. He also gives to
  Sherlock two other arrays: \$B_1, B_2, ..., B_M\$ and \$C_1, C_2, ..., C_M\$.

  Then Watson asks Sherlock to perform the following program:

for i = 1 to M do
    for j = 1 to N do
        if j % B[i] == 0 then
            A[j] = A[j] * C[i]
        endif
    end do
end do

  Can you help Sherlock and tell him the resulting array A? You should
  print all the array elements modulo \$(10^9 + 7)\$.

  Input Format

  The first line contains two integer numbers \$N\$ and \$M\$. The next line
  contains \$N\$ integers, the elements of array A. The next two lines
  contains \$M\$ integers each, the elements of array B and C.

  Output Format

  Print \$N\$ integers, the elements of array A after performing the program
  modulo \$(10^9 + 7)\$.

  Constraints

  \$1 ≤ N, M ≤ 10^5\$
   \$1 ≤ B[i] ≤ N\$
   \$1 ≤ A[i], C[i] ≤ 10^5\$

  Sample Input

4 3
1 2 3 4
1 2 3
13 29 71

  Sample Output

13 754 2769 1508

And here is my code:

import fileinput
import collections

lines = [[int(x) for x in line.split()] for line in fileinput.input()]
[n, m], a, b, c = lines

def one():
    return 1

factors = collections.defaultdict(one)
for i in range(0, m):
    factors[b[i]] *= c[i] % 1000000007

for i, factor in factors.iteritems():
    for j in range(1, n/i + 1):
        idx = j*i-1
        a[idx] *= factor
        a[idx] %= 1000000007;

print ' '.join(map(str, a))

Any idea on how I could increase the performance of my solution?


texts:
I've implemented a "remember me" automatic login if no session has been set, but a remember me cookie is on their computer. I'm concerned about security and I'm not the best. I'm relatively new to OOP (just started a learning a week ago).

$database = new db;

if (isset($_SESSION['info'])){
  $token = $_SESSION['info']['token'];
  $loggedIn = 1;
} else {
  $loggedIn = 0;
  if (isset($_COOKIE["rememberMe"])){
    $rememberId = $_COOKIE["rememberMe"][0];
    $rememberKey = $_COOKIE["rememberMe"][1];
    if ($database->rememberMe($rememberId,$rememberKey) === "verified") {
      $loggedIn = 1;
    }
  }
}

$loggedIn is for use in JavaScript.

rememberMe function in the db class:

  public function rememberMe ($userId,$rememberKey) {

    $conn = $this->connect();
    $stmt = $conn->prepare(
    "SELECT COUNT(*) as count
     FROM sessions
     WHERE remember_key = :remember_key AND user_id = :user_id"
    );
    $stmt->bindParam(":remember_key",$rememberKey);
    $stmt->bindParam(":user_id",$userId);
    $stmt->execute();
    $remember = $stmt->fetchAll();
    $rememberVerify = $remember[0]["count"];

    if ($rememberVerify > 0) {

      $stmt = $conn->prepare(
      "SELECT id,username,display_name,avatar FROM users WHERE id = :user_id"
      );
      $stmt->bindParam(":user_id",$userId,PDO::PARAM_INT);
      $stmt->execute();
      $userInfo = $stmt->fetchAll();

      $dbId = $userInfo[0]["id"];
      $dbUsername = $userInfo[0]["username"];
      $dbDisplayName = $userInfo[0]["display_name"];
      $dbAvatar = $userInfo[0]["avatar"];
      $token = hash('sha256',openssl_random_pseudo_bytes(50));

      $_SESSION['info'] = [
        'id'=>$dbId,
        'username'=>$dbUsername,
        'display_name'=>$dbDisplayName,
        'avatar'=>$dbAvatar,
        'token'=>$token
      ];
      return "verified";
    }
  }

When the user signs in with "remember me" checked:

  if ($_POST['remember'] === "true"){
    $rememberKey = hash('sha256',openssl_random_pseudo_bytes(50));
    $stmt = $db->prepare("INSERT INTO sessions (user_id,remember_key) VALUES (:user_id,:remember_key)");
    $stmt->bindParam(":user_id",$dbId);
    $stmt->bindParam(":remember_key",$rememberKey);
    $stmt->execute();
    setcookie ('rememberMe[0]', $dbId, time() + (86400 * 365), "/");
    setcookie ('rememberMe[1]', $rememberKey, time() + (86400 * 365), "/");
  }


texts:
I have a form, which uses AJAX to send POST data to the following controller method:

public function action_sendmail() {
        $jsonHelper=Loader::helper('json');
        $answer = (int) $_POST['security'];
        if($answer <= 0)
            $answer = 1;

        if($answer == 4){

            $name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
            $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
            $message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

            $name = strip_tags($name);
            $email = strip_tags($email);
            $message = strip_tags($message);

            $name = str_replace(array("\r", "\n", "%0a", "%0d"), '', stripslashes($name));
            $email = str_replace(array("\r", "\n", "%0a", "%0d"), '', stripslashes($email));
            $message = str_replace(array("\r", "\n", "%0a", "%0d"), '', stripslashes($message));

            if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
                echo $jsonHelper->encode(t("Wrong email address."));
                die;
            }
            if(preg_match("/^[+]?[0-9]*$/", $_POST['phone'])) {
                $phone = strip_tags($_POST['phone']);
            }
            else {
                echo $jsonHelper->encode(t("Wrong phone number format."));
                die;
            }

            $message = t('Phone number').": ".$phone."\n\n".$message;

            $mail = Loader::helper('mail');
            $mail->setBody($message);
            $mail->from($email, $name);
            $mail->to("test@example.com");
            $mail->to($email);
            $mail->setSubject(t('Example subject'));

            $sent = true;

            $mail->sendMail();

            if($sent) {
                echo $jsonHelper->encode("sent");
                die;
            }
            else {
                echo $jsonHelper->encode(t("Could not send mail. Please try again."));
                die;
            }

        }
        else{
            echo $jsonHelper->encode(t("Wrong security answer!"));
            die;
        }
    }

The script sanitizes different attributes (name, email and the message) and sends an email to a specified address and the one from the HTML form.
My question: Is the form secure?


texts: Django model for an inventory management system

texts:
The usecase of my app I am trying to build is about Inventory Management System for a single company. I have
attached a layout depicting what table or model should look like. I have designed the model the following way

class Office(models.Model):
    title = models.CharField(max_length=200, blank=True, null=True)
    sub_title = models.CharField(max_length=200, blank=True, null=True)
    name = models.CharField(max_length=200, blank=False, null=False)
    address = models.CharField(max_length=200, blank=True, null=True)
    phone = models.CharField(max_length=200, blank=True, null=True)
    email = models.EmailField(max_length=100, blank=True, null=True)

    class Meta:
        verbose_name = 'Office Setup'
        verbose_name_plural = 'Office Setup'

    def __str__(self):
        return self.name

class Department(models.Model):
    office = models.ForeignKey(Office, blank=False, null=False)
    name = models.CharField(max_length=200, blank=False, null=False)

    class Meta:
        verbose_name = 'Department'
        verbose_name_plural = 'Department'

    def __str__(self):
        return self.name

class DocumentNumbering(models.Model):
    office = models.ForeignKey(Office, blank=False, null=False)
    document = models.CharField(max_length=200, blank=False, null=False)
    start_number = models.PositiveIntegerField(
        default=0, blank=False, null=False)
    length = models.PositiveIntegerField(default=0, blank=False, null=False)

    class Meta:
        verbose_name = 'Document Numbering'
        verbose_name_plural = 'Document Numbering'

    def __str__(self):
        return self.document

class ItemUnit(models.Model):
    office = models.ForeignKey(Office, blank=False, null=False)
    name = models.CharField(max_length=200, blank=False, null=False)
    code = models.CharField(max_length=100, blank=True, null=True, unique=True)

    class Meta:
        verbose_name = 'Item Unit'
        verbose_name_plural = 'Items Unit'

    def __str__(self):
        return self.name

I just want to make ensure if this is the right way to do or not. Can anyone guide me on the relation part, please?
I am not confident enough to tell if this is the way to model an app.

A lots of office = models.ForeignKey(Office, blank=False, null=False) in each table confused me.


texts:
I am wondering if there is a better way to set up a filterable table on a web page using Python/Django/JavaScript or potentially a different stack.

The current setup is as follows.

1) The Python backend pulls datetime.date and datetime.time objects from the database.

2) These are converted into string via the backend as I want full control over how they are displayed (and on the web page they become string anyway, as far as I can tell).

3) The strings are passed to the view and displayed in an HTML <table>.

4) The filtering is done via a JavaScript function. The JavaScript converts the strings back to datetime objects to be able filter on them.

Issue 1: Is there a way to avoid the back and forth converting between datetime and string?

Below is my JavaScript function. The below only works for datetime.time. I'll have to write something similar for datetime.date.

Issue 2: I would like the code to stay DRY, so any ideas on how to make the function be able to handle both datetime.date and datetime.time objects would also be very welcome.

function filter(id, column_id) {
    var table, tr, filter_time;
    table = document.getElementById("myTable");
    tr = table.getElementsByTagName("tr");
    filter_time = document.getElementById(id).value;

    filter_time = filter_time.split(':');
    filter_time = new Date(0, 0, 0, filter_time[0], filter_time[1]);

    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[column_id];
        if (td) {
            td = td.innerHTML.split(':');
            var time_to_filter = new Date(0, 0, 0, td[0], td[1]);
            if (time_to_filter < filter_time) {
                tr[i].style.display = "none";;
            } else {
                tr[i].style.display = "";
            }
        }
    }
}


texts:
This is some code that fetches a result from a database.  It connects, makes a query, processes the query, then has to close the DB (under all possible code paths) and return the result.

It seems like the code for closing the database under all circumstances is a bit messy.  I'm wondering if there's a cleaner way to do this?

function getBlocked(data) {
    let openDb;

    close() {
        if (openDb) {
            openDb.close().catch(err => {
                console.log("Error closing db: ", err);
            })
        }
    }

    return MongoClient.connect(url).then(db => {
        openDb = db;
        const blQ = {blocked_user:data.tag_search_mail};
        return db.collection("block_list").find(blQ,{"_id":0}).toArray();
    }).then(results => {
        let blocked = results.map(item => item.blocker);
        close();
        return blocked;     // make this the resolved value of the promise
    }).catch(err => {
        close();
        throw err;          // rethrow to keep the promise rejected
    })
}

Usage:

getBlocked(data).then(blocked => {
    // use blocked array here
}).catch(err => {
    // handle error here
});

FYI, it is intentional to return the result without waiting for the DB to close (thus why it's not inserted in the promise chain) and to only log the error, not fail the main operation if closing the db fails.


texts:
This filter is basically gradient detection (the variable gradImg) like an edge detection (Sobel or Prewitt filters) and also the direction of that gradient whether vertical or horizontal (dirImg).

I'm trying to optimize it to run faster and I found that this part of the code slow. Would you have any suggestions please?  Here's the code you can copy to http://quick-bench.com/.

#include <math.h>
static void Old_Version(benchmark::State& state) {
  // Code inside this loop is measured repeatedly
  int rows = 1000, cols = 1000;
  unsigned char *smoothImg = new unsigned char[cols*rows];
  short *gradImg = new short[cols*rows];
  unsigned char* dirImg = new unsigned char[cols*rows];
  for (auto _ : state) {
    for (int i = 1; i<rows - 1; i++) {
           for (int j = 1; j<cols - 1; j++) {
               int com1 = smoothImg[(i + 1)*cols + j + 1] - smoothImg[(i - 1)*cols + j - 1];
               int com2 = smoothImg[(i - 1)*cols + j + 1] - smoothImg[(i + 1)*cols + j - 1];

               int gx=abs(com1+com2+(smoothImg[i*cols + j + 1] - smoothImg[i*cols + j - 1]));
               int gy=abs(com1-com2+(smoothImg[(i + 1)*cols + j] - smoothImg[(i - 1)*cols + j]));

               int sum = (int)sqrt((double)gx*gx + gy*gy);

               int index = i*cols + j;

               gradImg[index] = sum;
               if (sum >= 20) {
                   if (gx >= gy) dirImg[index] = 1;//1 vertical
                   else      dirImg[index] = 2;//2 Horizontal
               }
           }
       }
  }
}
// Register the function as a benchmark
BENCHMARK(Old_Version);

My compilation command, using GCC (Ubuntu 8.1.0-5ubuntu1~16.04) 8.1.0:

g++ -std=c++1z -fomit-frame-pointer -O4 -ffast-math -mmmx -msse -msse2 -msse3 -DNDEBUG -Wall improve_code.cpp -o improve_code -fopenmp


texts: Insert str into larger str in the most pythonic way

texts:
I want to insert a small str into a larger one in the most pythonic way.

Maybe I missed a useful str method or function ? The function that insert the small str into the larger one is insert_tag.

I have tried something with reduce but it didn't work and it was too complex.

Code:

from random import choice, randrange
from typing import List

def insert_tag(text: str, offsets: List[int], tags: List[str]) -> str:
    text: str = text
    for offset, tag in zip(offsets, tags):
        # text = f'{text[:offset]}{tag}{text[offset:]}'  # solution 1
        text = text[:offset] + tag + text[offset:]  # solution 2
    return text

if __name__ == '__main__':
    tag_nbr = 30
    # Text example
    base_text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do ' \
                'eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut ' \
                'enim ad minim veniam, quis nostrud exercitation ullamco laboris ' \
                'nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor ' \
                'in reprehenderit in voluptate velit esse cillum dolore eu fugiat ' \
                'nulla pariatur. Excepteur sint occaecat cupidatat non proident, ' \
                'sunt in culpa qui officia deserunt mollit anim id est laborum.' \
        .replace(',', '').replace('.', '')
    # Random list of tag only for testing purpose
    tag_li: List[str] = [f'<{choice(base_text.split())}>' for _ in range(tag_nbr)]
    # Ordered list of random offset only for testing purpose
    offset_li: List[int] = [randrange(len(base_text)) for _ in range(tag_nbr)]
    offset_li.sort(reverse=True)
    # Debug
    print(tag_li, offset_li, sep='\n')

    # Review
    new_text: str = insert_tag(base_text, offset_li, tag_li)
    # End Review

    # Debug
    print(new_text)

Output:

"Lorem ips<consectetur>u<Lorem>m dolo<Lorem>r sit amet consecte<Lorem>tur <nostrud>adipiscing eli<aute>t sed d<anim>o eiusmod tempo<voluptate>r <exercitation>incid<anim>i<non>dunt ut l<quis>abor<do>e et dol<reprehenderit>ore magna aliqua Ut enim ad minim veniam quis nostrud exercitatio<est>n ullamco laboris nisi ut aliquip ex<nulla> ea <consectetur>commodo consequat Duis aute irure dolor in repreh<deserunt>enderit in voluptate vel<sint>it esse cillum dolore eu f<qui>ugiat nulla pariatur <magna>Excepteur sin<ex>t occaecat cup<labore>i<ut>datat non proident sun<est>t<in> in cul<fugiat>pa qui officia<enim> deserunt mollit anim i<in><anim>d est laborum"

PS: The rest of the code is not my primary concern, but if it can be improved, tell me, thanks.


texts:
Do you think this works well? I.e, do I need to close the database connection at the end? The goal is to be able to upsert and delete many records in one shoot.

Here is is an example HTTP POST request with JSON body to use it:

{"db" : "Memorise", "upsert" : [["Diagram", {"_id" : "abcd", "key1" : "value1"}]], "delete" : [["Diagram", {"_id" : "abc"}]]}

var http = require('http');
var MongoClient = require('mongodb').MongoClient;

var myServer = http.createServer(function(request, response)
{

    var data = '';

    request.on('data', function (chunk){
        data += chunk;
    });

    request.on('end',function(){

        var obj = JSON.parse(data);
        var databaseName = obj['db']

        MongoClient.connect("mongodb://localhost:27017/" + databaseName, function(err, db) {

            if(!err) {

                var recordsToUpsert = obj['upsert']
                for (var i = 0; i < recordsToUpsert.length; i++) {
                var recordToUpsertAndCollection = recordsToUpsert[i]

                    var collectionName = recordToUpsertAndCollection[0];
                    var recordToUpsert = recordToUpsertAndCollection[1];

                    var collection = db.collection(collectionName);
                    collection.save(recordToUpsert,{w:1}, {});
                };

                var conditionsToRemoveAndCollection = obj['delete']
                for (var i = 0; i < conditionsToRemoveAndCollection.length; i++) {
                var conditionToRemoveAndCollection = conditionsToRemoveAndCollection[i]

                    var collectionName = conditionToRemoveAndCollection[0];
                    var conditionToRemove = conditionToRemoveAndCollection[1];

                    var collection = db.collection(collectionName);
                    collection.remove(conditionToRemove,{w:1}, {});
                };

                response.writeHead(200)
                response.end()
            }
        });
    });
});
myServer.listen(3000)


texts: Kattis Challenge - Recount - count who has the most votes in a list of names

texts:
I am attempting to solve the Kattis problem Recount.

  The recent schoolboard elections were hotly contested: a proposal to swap school start times for elementary and high school students, a controversial new dress code proposal that bans athletic clothes in school, and a proposal to raise real-estate taxes to pay for a new football practice facility, and the list goes on and on. It is now hours after the polls have closed and a winner has yet to emerge!

  In their desperation, the election officials turn to you and ask you to write a program to count the vote!

  Input

  The input consists of a single test case, which is a list of votes cast. Each line in the input contains the name of a candidate for whom a vote was cast. A name may consist of multiple words, separated by spaces. Words contain letters or hyphens, but no other punctuation characters. There will be at least 2 votes on the list. The list of votes ends with a single line containing the characters ***. This line should not be counted. There can be up to 100,000 valid votes.

  Output

  If a candidate obtained a simple or absolute majority of all votes cast (that is, more than any other candidate), output the name of this candidate! If no candidate obtained a simple majority, output: “Runoff!” (don’t forget to include the exclamation mark!)

  Sample Input 1

Penny Franklin
Marti Graham
Connie Froggatt
Joseph Ivers
Connie Froggatt
Penny Franklin
Connie Froggatt
Bruce Stanger
Connie Froggatt
Barbara Skinner
Barbara Skinner
***

  Sample Output 1

Connie Froggatt

  Sample Input 2

Penny Franklin
Connie Froggatt
Barbara Skinner
Connie Froggatt
Jose Antonio Gomez-Iglesias
Connie Froggatt
Bruce Stanger
Barbara Skinner
Barbara Skinner
***

  Sample Output 2

Runoff!

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;

struct voter
{
    string name;
    int numvotes;
    bool operator==(const string   &) const;
    bool operator<(const voter   &) const;
    bool operator>(const voter   &) const;

};
bool voter::operator==(const string &f) const
{
    return name == f;
}

bool voter::operator<(const voter &f) const
{
    return (numvotes < f.numvotes);
}
bool voter::operator>(const voter &f) const
{
    return (numvotes > f.numvotes);
}

bool myfunction(voter i, voter j) { return (i<j); }

int main() {
    vector<voter> voters;
    string name;

    while (getline(cin, name))
    {
        if (name == "***")
        {
            break;
        }
        _Vector_iterator<_Vector_val<_Simple_types<voter>>> it = find(voters.begin(), voters.end(), name);
        if (it != voters.end()) {
            it->numvotes += 1;
        }
        else
        {
            voter a;
            a.name = name;
            a.numvotes = 1;
            voters.push_back(a);
        }
    }
    sort(voters.begin(), voters.end(), greater<voter>());

    if (voters[0].numvotes == voters[1].numvotes)
    {
        cout << "Runoff!" << endl;
    }
    else
    {
        _Vector_iterator<_Vector_val<_Simple_types<voter>>>  tt = max_element(voters.begin(), voters.end());
        cout << tt->name << endl;
    }
    return 0;
}

My program will pass all of the tests except the very last one where it "times out". Any input I can get on this will be greatly appreciated. This code does compile and run in VS and here: http://cpp.sh/8l3b

To get this to run on cpp.sh I did have to change the _Vector_iterator<_Vector_val<_Simple_types<voter>>> on lines 43 and 63 to auto. I don't quite understand why, so I would also be very appreciative if you could explain what I should use as a type to be portable.


texts: Find the largest sum of the GCD and LCM of two numbers in a range

texts:
The program is supposed to get one number n as input, and output the max value of gcd + lcm of two numbers that range from 1 to n.

For example, if n == 3, the answer is 7 because gcd(3,2) == 1 and lcm(3,2) == 6.

The issue is that the code works really slowly and the double loop makes it so numbers above basically 1000 take forever to run. How do I make it run faster?

#include <iostream>

using namespace std;

int main()
{
    int n;

    cin >> n;

    int highest_value = 0,equation;
    int gcd,smaller;

    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= n; j++)
        {
            if(i > j){smaller=j;}
            else{smaller=i;}

            for(int y = 1; y <= smaller; y++)
            {
                if(i%y==0 && j%y==0) gcd = y;
            }
            equation = gcd+((i*j)/gcd);
                if(equation > highest_value) highest_value = equation;
        }
    }
    cout << highest_value;

    return 0;
}


texts: Entity Framework 7 In Memory Database - Unit Testing using xUnit

texts:
I'm using EF7 with In-Memory database and xUnit for repository testing. I'd like to know if it's a good practice initializing the database in this manner for reuse it in every test method, specifically through the Initialize() method:

private Context _context;
private BrandsRepository _repository;
private void Initialize()
{
    var db = new DbContextOptionsBuilder();
    db.UseInMemoryDatabase();
    _context = new Context(db.Options);
    _repository = new BrandsRepository(_context);

    _context.Database.EnsureDeleted();
    _context.Database.EnsureCreated();
}

[Fact]
public void Retrieve_Brands()
{
    // Arrange
    Initialize();
    var brands = new List<Brand>()
    {
        new Brand() { Name = "First" },
        new Brand() { Name = "Second" },
        new Brand() { Name = "Third" }
    };
    _context.Brands.AddRange(brands);
    _context.SaveChanges();

    // Act
    var retrievedBrands = _repository.GetAll();

    // Assert
    Assert.Equal(retrievedBrands, brands);
}

[Fact]
public void Add_a_Brand()
{
    // Arrange
    Initialize();
    var brand = new Brand() { Name = "First" };

    // Act
    _repository.Add(brand);

    // Assert
    Assert.Equal(_context.Brands.First(), brand );
}


texts:
I have just started playing around with L4 and would like to get some feedback on how I implemented a multi-page form

Here are my routes:

Route::model('appointment', 'Appointment');
Route::get('appointment/book_new/{appointment}', array('as' => 'booking-form', 'uses' => 'AppointmentBookingController@index') );
Route::post('appointment/book_new/verify/{appointment}', 'AppointmentBookingController@verify');
Route::post('appointment/book_new/success/{appointment}', 'AppointmentBookingController@success');

Here is my controller:

class AppointmentBookingController extends BaseController {

    public function index(Appointment $appt)
    {
        return View::make('appointment/bookings/book',  array('appt' => $appt));
    }

    public function verify(Appointment $appt){
        $fields = array('name', 'email', 'description');

        // Declare the rules for the form validation
        $rules = array(
            'name'        => 'required',
            'email'       => 'required|email',
            'description' => 'required',
        );

        // Create a new validator instance from our validation rules
        $validator = Validator::make(Input::all(), $rules);

        // If validation fails, we'll exit the operation now.
        if ($validator->fails())
        {
            foreach($fields as $v)
            {
                Session::flash($v, Input::get($v));
            }
            return View::make('appointment/bookings/book',  array('appt' => $appt, 'errors' => $validator->messages()));
        } else {
            Session::put('booking-form-index', Input::all());
            return View::make('/appointment/bookings/verify',  array('appt' => $appt));
        }
    }

    public function success(Appointment $appt){
        // validate, if valid save the booking.
            // don't do anything for now
            var_dump ( Session::get('booking-form-index') );
            exit();

            // display the success page
            // return View::make('/appointment/bookings/success',  array('appt' => $appt));
}

Here are my views ( book.blade.php )

{{ Form::open(array('url' => '/appointment/book_new/verify/'. $appt->id )) }}

{{ Form::token() }}

    {{ Form::text('name', Session::get('name'), array('placeholder' => 'Name')) }}
    {{ $errors->first('name') }}

    {{ Form::text('email', Session::get('email'), array('placeholder' => 'email@email.com')) }}
    {{ $errors->first('email') }}

    {{  Form::textarea ('description') }}
    {{ $errors->first('description') }}

{{ Form::submit('Click Me!') }}

{{ Form::close() }}

verify.blade.php

{{ Form::open(array('url' => 'appointment/book_new/success/' . $appt->id )) }}

{{  Form::text('validate') }}

{{ Form::submit('Click Me!') }}

{{ Form::close() }}

success.blade.php

Success


texts:
I need help cleaning up this piece of code.

if is_complete == true
  #If there are time stamps get between time stamps
  if start_date && end_date
    tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NOT NULL and DATE(completed_date) between ? and ?", contact_id, start_date, end_date])
  else
    tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NOT NULL", contact_id])
  end
else
  #If there are time stamps get between time stamps
  if start_date && end_date
    tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NULL and DATE(completed_date) between ? and ?", contact_id, start_date, end_date])
  else
    tasks = Task.find(:all, :include => [:task_observer, :job, :contact], :conditions => ["contact_id = ? and completed_date IS NULL", contact_id])
  end
end


texts:
Purpose
A garland word is a word

formed by chopping off the last few letters and “wrapping around” to the start.
For example: You can chop off the the trailing “on” from “onion” and still form the word by wrapping around to the starting “on”. In other words, you can write the letters “o”, “n”, “i” in a circle, in that order, and form the word “onion”.
I say that a garland word is of degree n if you can do the above with the last n letters of the word.

Build an implementation that returns the garland degree of a String. (Note, this was a dailyprogrammer subreddit question)
Strategy

Check if String is size 0 (return garland degree of 0) or size 1 (return garland degree of 1).
Start with the first character in the String. Iterate through the characters in the String from the second character onwards. Do we see a matching character? If not, return size 0.
Move on to the first + second characters in the String. Iterate through the characters in the String from the 3rd character onwards for a matching substring - if we can't see one, return size 1.
Repeat.
Note that the upper limit of the garland degree should be the the floor of the length of the String divided by 2. (Right? Or am I missing something?)

Implementation
public class GarlandDegreeIdentifierImpl implements GarlandDegreeIdentifier {
    @Override
    public int identifyGarlandDegree(final String candidate) {
        switch (candidate.length()) {
            case 0: {
                return 0;
            }

            case 1: {
                return 1;
            }

            default: {
                final char[] chars = candidate.toCharArray();
                for (int subStringIndex = 1; subStringIndex <= chars.length - subStringIndex; subStringIndex++) {
                    final char[] startingChars = Arrays.copyOfRange(chars, 0, subStringIndex);
                    final char[] remainingChars = Arrays.copyOfRange(chars, subStringIndex, chars.length);
                    if (subsetIndexIdentifier(remainingChars, startingChars) == -1) {
                        return subStringIndex - 1;
                    }
                }

                return Math.floorDiv(chars.length, 2);
            }
        }
    }

    @Override
    public int subsetIndexIdentifier(final char[] chars, final char[] candidateChars) {
        for (int index = 0; index <= chars.length - candidateChars.length; index++) {
            int counter = 0;
            for (int candidateCharIndex = 0; candidateCharIndex < candidateChars.length; candidateCharIndex++) {
                if (chars[index + candidateCharIndex] != candidateChars[candidateCharIndex]) {
                    counter++;
                }
            }

            if (0 == counter) {
                return index;
            }
        }

        return -1;
    }
}


texts:
I am creating a playbook that takes a variable ver at runtime and then runs tasks based on that variable. If that ver is defined, it takes the version number and installs a version according to that. If the ver is not defined, it defaults to a default version.

My playbook for now looks like:

- name: Download Maven from remote repository.
  unarchive:
    src: "{{ baseurl }}/{{ versions[ver] }}"
    dest: /usr/local/
    remote_src: yes
  become: yes
  when: ver is defined

- name: Rename maven folder.
  command: mv /usr/local/apache-maven-{{ver}} /usr/local/maven-{{ver}}
  become: yes
  when: ver is defined

- name: Create symbolic link to maven folder.
  file:
    src: "/usr/local/maven-{{ver}}"
    dest: "/usr/local/maven"
    state: link
  become: yes
  when: ver is defined

- name: Download Default Maven from remote repository.
  unarchive:
    src: "{{ baseurl }}/{{ versions[default_version] }}"
    dest: /usr/local/
    remote_src: yes
    list_files: yes
  become: yes
  when: ver is not defined

- name: Rename maven folder.
  command: mv /usr/local/apache-maven-{{default_version}} /usr/local/maven-{{default_version}}
  become: yes
  when: ver is not defined

- name: Create symbolic link to maven folder.
  file:
    src: "/usr/local/maven-{{default_version}}"
    dest: "/usr/local/maven"
    state: link
  become: yes
  when: ver is not defined

As you can see, based on whether a variable is defined or not, I have to write whole new tasks for it.

The above works but I think it's not optimized as I'm writing too much code to get this to work. One idea that I have is to create have main.yaml invoke another task file when ver is defined and a separate task file when ver is not defined.

Is there another way to optimize this? I have many other tasks that deal with version number.


texts: Compress and decompress a string from a file

texts:
I need to compress some text, I'm wondering if my program could be made more efficient. The only things I could think of would be the 'import re' and turning the filename input and read part as a function.

import re
from ast import literal_eval

################## Compression #####################
def comp():
    while True:
        try:
            fileName=input('Please input text file name in current directory: ')+'.txt'
            a=open(fileName)
            break
        except:
            print('No Such text file in current directory name: '+fileName)

    content = a.read()
    a.close()

    p = re.compile(r'[\w]+|[\W]')
    split = p.findall(content)

    b = []
    wordList = []

    for word in split:
        try:
            r = wordList.index(word) + 1
        except ValueError:
            wordList.append(word)
            r = len(wordList)
        b.append(r)

    f=open('compressed.txt', 'w')
    f=open('compressed.txt', 'r+')
    f.write(str(wordList)+'\n'+str(b))
    f.close()

####################################################

################## De-Compression ##################

def decomp():
    while True:
        try:
            fileName=input('Please input text file name in current directory: ')+'.txt'
            a=open(fileName)
            break
        except:
            print('No Such text file in current directory name: '+fileName)

    words = literal_eval(a.readline().rstrip('\n'))
    pos = literal_eval(a.readline())

    temp = []

    for index in pos:
        temp.append(words[index-1])
    sentence = ''.join(temp)
    print(sentence)
####################################################


texts: Test Scores and Summary Statistics from a file

texts:
This program takes a file from a user, "example.txt". The file contains only positive integers, and the first interger in the file is stating how many intergers come after that integer (Ex. 3, 45, 98, 102) It is safe to assume everything in the users file is properly formatted and they put .txt at the end. The program is pretty simple for the most part, it was mainly to practice Array's, but I'm curious if I can cut this down a bit, or if I over-complicated anything. This code works by the way.

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

public class TestScoresAndSummaryStatistics
{
public static void main(String[] args) throws IOException
{

int i = 0;
Scanner keyboard = new Scanner(System.in);

System.out.println("Enter the name of the file");
String fileName = keyboard.nextLine();
File inputFile = new File(fileName);
Scanner data = new Scanner(inputFile);

//declaring that whatever the first number in the document is is how many indices the document has
int scores[] = new int[data.nextInt()];

while (data.hasNext())
{
  scores[i] = data.nextInt();
  i++;
}

Arrays.sort(scores);

//Highest and Lowest score
System.out.println("Lowest score: " + scores[0]);
System.out.println("Highest score: " + scores[(scores.length - 1)]);

//Calculating Mean
double gradesTotal = 0;
for (i=0; i<scores.length; i++)
{
  gradesTotal = gradesTotal + scores[i];
}
double mean = gradesTotal/scores.length;
System.out.println("Mean score: " + mean);

//Calculating Standard Deviation
double variance = 0;
for (i=0; i<scores.length; i++)
{
  variance = variance + (Math.pow((scores[i] - mean), 2));
}
variance = variance / scores.length;
double standardDeviation = Math.sqrt(variance);
System.out.println("Standard Deviation: " + standardDeviation);

//Finding Median score
double median;
if (scores.length % 2 == 0)
  median = ((scores[(scores.length/2) - 1]) + scores[(scores.length/2)]) / 2;
else
  median = scores[(scores.length/2)];
System.out.println("Median score: " + median);

//Finding how many number of A's, B's, etc
int gradeA = 0;
int gradeB = 0;
int gradeC = 0;
int gradeD = 0;
int gradeF = 0;

for (i=0; i<scores.length; i++)
{
  if (scores[i] >= 90)
  {
    gradeA++;
  }
  else if (scores[i] <= 89 && scores[i] >=80)
  {
    gradeB++;
  }
  else if (scores[i] <= 79 && scores[i] >=70)
  {
    gradeC++;
  }
  else if (scores[i] <= 69 && scores[i] >=60)
  {
    gradeD++;
  }
  else
  {
    gradeF++;
  }
}

System.out.println("You have recieved " + gradeA + " A's, " + gradeB + " B's, " + gradeC + " C's, " + gradeD +
                   " D's, and " + gradeF + " F's");

}
}


texts: Set a default if key not in a dictionary, *or* value is None

texts:
Let's say I have a key 'messages' that is usually a list, but might be None, or might not be present. So these are all valid inputs:

{
   'date': 'tuesday',
   'messages': None,
}

{
   'date': 'tuesday',
   'messages': ['a', 'b'],
}

{
   'date': 'tuesday',
}

If I want to retrieve 'messages' from the input, and iterate over them, I need to do something like this:

messages = d.get('messages', []) # Check for key existence
if messages is None:             # Check if key is there, but None
    messages = []
for message in messages:
    do_something()

That seems a little verbose for Python - is there a simpler way to write that?


texts:
I'm pretty new to Python and I made a password generator. I would like you to check it out and give me tips on how I could do it better.

import random

def small():  # Prints a generated string of 6 chars

    list = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "L", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
    "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "a", "b", "c", "d", "e", "f",
    "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
    "v", "w", "x", "y", "z")

    generatepassword = random.choice(list) + random.choice(list) + random.choice(list) + random.choice(list) +\
               random.choice(list) + random.choice(list)

    print(generatepassword)
    print("The passwords consists of: " + str(len(generatepassword))+" Characters")
    print("\n")

def med():  # Prints a generated string of 10 chars

   list2 = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "L", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
     "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "a", "b", "c", "d", "e", "f",
     "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
     "v", "w", "x", "y", "z")

   generatepassword = random.choice(list2) + random.choice(list2) + random.choice(list2) + random.choice(list2) +\
               random.choice(list2) + random.choice(list2) + random.choice(list2) + random.choice(list2) +\
               random.choice(list2) + random.choice(list2)

   print(generatepassword)
   print("The passwords consists of: " + str(len(generatepassword))+" Characters")
   print("\n")

def big():  # Prints a generated string of 32 chars

    list3 = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "L", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
     "V", "W", "X", "Y", "Z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "a", "b", "c", "d", "e", "f",
     "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
     "v", "w", "x", "y", "z")

    generatepassword = random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3) +\
               random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3) +\
               random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3) +\
               random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3) +\
               random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3) +\
               random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3) +\
               random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3) +\
               random.choice(list3) + random.choice(list3) + random.choice(list3) + random.choice(list3)

    print(generatepassword)
    print("The passwords consists of: " + str(len(generatepassword))+" Characters")
    print("\n")

def generate():  # This askes how long the password should be

    print("How big do you want your password? choices >> [6], [10], [32]")
    choice = input("please input the lenght >> ")

    while choice != '6' and choice != '10' and choice != '32':
         choice = input("please choose: [6], [10] or [32] >> ")

        if choice == '6':
          break

        elif choice == '10':
          break

        elif choice == '32':
          break

   if choice == '6':
       small()

   if choice == '10':
       med()

   if choice == '32':
       big()

again = 'yes'
while again == 'yes' or again == 'y':

  # From here on the user can choose to generate another password
  # If the person typed yes or y then it will run the def function generate
  # And it will restart
  # If the user types anythin else then yes or y then the program quits

  generate()
  print("\n")
  print("Do you want to generate another password? [yes] or [no] >> ")
  again = input()


texts: Mapping square objects to specific cells in a TableLayoutPanel in WindowsForms game

texts:
I have solved this problem but I am looking for a better way to do it, in fewer lines of code.

The problem was from this previous question on Stack Overflow.

My solution:

   /// <summary>
        /// For a given square number, tells you the corresponding row and column numbers.
        /// Pre:  none.
        /// Post: returns the row and column numbers, via "out" parameters.
        /// </summary>
        /// <param name="squareNumber">The input square number.</param>
        /// <param name="rowNumber">The output row number.</param>
        /// <param name="columnNumber">The output column number.</param>
        private static void MapSquareNumToScreenRowAndColumn(int squareNumber, out int rowNumber, out int columnNumber){

        // ######################## Add more code to this method and replace the next two lines by something more sensible.  ###############################
        rowNumber = 0; // Use 0 to make the compiler happy for now.
        columnNumber = 0; // Use 0 to make the compiler happy for now.

        columnNumber = squareNumber % 6;
        rowNumber = squareNumber/6;

        //switch statement for assigning column values to odd rows
        int remainder = squareNumber%6;
        switch (remainder){
            case 0:
                columnNumber = 5;
                break;
            case 1:
                columnNumber = 4;
                break;
            case 2:
                columnNumber = 3;
                break;
            case 3:
                columnNumber = 2;
                break;
            case 4:
                columnNumber = 1;
                break;
            case 5:
                columnNumber = 0;
                break;

        }

        if (squareNumber >=0 && squareNumber <= 5){
            rowNumber = 6;
            columnNumber = squareNumber%6;

        }

        if (squareNumber >=6 && squareNumber <= 11){
            rowNumber = 5;
        }

        if (squareNumber >=12 && squareNumber <= 17){
            rowNumber = 4;
            columnNumber = squareNumber%6;
        }
        if (squareNumber >=18 && squareNumber <= 23){
            rowNumber = 3;

        }
        if (squareNumber >= 24 && squareNumber <= 29){
            rowNumber = 2;
            columnNumber = squareNumber%6;

        }
        if (squareNumber >= 30 && squareNumber <= 35){
            rowNumber = 1;

        }
        if (squareNumber >= 36 && squareNumber <= 41){
            rowNumber = 0;
            columnNumber = squareNumber % 6;
        }

    }//end MapSquareNumToScreenRowAndColumn

I'm fairly new to programming, so I just wanted a second opinion on it. Is there a way for me to get the same outcome, but with less code?


texts:
My teacher often tells me that I don't take full advantage of Python capabilities, I would like to know if my implementation of Quicksort is good enough and how could I improve it, aside from doing it in-place

def quickSort(l):
    if len(l) > 1:
        l,iPiv = partition(l)
        return quickSort(l[:iPiv]) + [l[iPiv]] + quickSort(l[iPiv+1:])
    else:
        return l

def partition(l):
    i = 1
    iPiv = 0
    for j in range(1,len(l)):
        if l[j] <= l[iPiv]:
            l[i],l[j] = l[j],l[i]
            i += 1
    l[i-1],l[iPiv] = l[iPiv],l[i-1]
    return l,i-1


texts:
I have been trying to improve my knowledge with Python and I think the code is pretty forward. However I do dislike abit the coding style I have done where I use too much try except in a content there it might not needed to be at first place.
My goal is basically to have a ready payload before scraping as you will see at the top of the code. Those should be always declared before scraping. What im trying to do basically is to try to scrape those different data. If we don't find the data, then it should skip or set the value to [], None or False (Depending on what we are trying to do).
I have read abit regarding getattr and isinstance functions but im not sure if there might be a better way than using lots of Try except as a cover if it doesn't find the element on the webpage.
I would appreciate all kind of helps!
import requests
from bs4 import BeautifulSoup

payload = {
    "name": "Untitled",
    "view": None,
    "image": None,
    "hyperlinks": []
}

site_url = "https://stackoverflow.com/questions/743806/how-to-split-a-string-into-a-list"

response = requests.get(site_url)

bs4 = BeautifulSoup(response.text, "html.parser")

try:
    payload['name'] = "{} {}".format(
        bs4.find('meta', {'property': 'og:site_name'})["content"],
        bs4.find('meta', {'name': 'twitter:domain'})["content"]
    )
except Exception:  # noqa
    pass

try:
    payload['view'] = "{} in total".format(
        bs4.find('div', {'class': 'grid--cell ws-nowrap mb8'}).text.strip().replace("\r\n", "").replace(" ", ""))
except Exception:
    pass

try:
    payload['image'] = bs4.find('meta', {'itemprop': 'image primaryImageOfPage'})["content"]
except Exception:
    pass

try:
    payload['hyperlinks'] = [hyperlinks['href'] for hyperlinks in bs4.find_all('a', {'class': 'question-hyperlink'})]

except Exception:  # noqa
    pass

print(payload)


texts: Selecting random class from weighted class probability distribution

texts:
I have a solution that I've scratched out, but it's a tad messy:

First, let's say we have a random number from a uniform distribution we'll be using to select a random class from a class probability distribution:

r = 0.525325235325

And a list of classes, along with a corresponding list of values representing a class probability distribution for the four classes:

classes = ["w", "x", "y", "z"]

distribution = [0.1, 0.2, 0.3, 0.4]

Now, to get the cumulative probabilities:

b = [sum(distribution[0:x + 1]) for x in range(len(distribution))]
>>> b
[0.1, 0.30000000000000004, 0.6000000000000001, 1.0]

So far so good. Now, select a class by the weighted probability:

c = [y for y in b if y > r][0]
>>> c
0.6000000000000001

And to get the selected class:

selected = classes[b.index(c)]
>>> selected
'y'

Putting it all together:

r = 0.525325235325
classes = ["w", "x", "y", "z"]
distribution = [0.1, 0.2, 0.3, 0.4]

b = [sum(distribution[0:x + 1]) for x in range(len(distribution))]
selected = classes[b.index([y for y in b if y > r][0])]

This works well enough. The thing is, it will be called each time the class probability distribution is updated along with a complex code base – so efficiency matters.

Are there any ways I can make this code more efficient in terms of speed and/or memory usage (eliminating b without the expense of additional processing would be nice) in Python? Alternatively, is there an established algorithm for this problem that I've overlooked?


texts: Trie Tree match string containing ? and *

texts:
Using Python 2.7 and here is my code which implement trie match for a whole word, and also support if the whole word contains ? (match any one character) or * (any zero or more characters).

My question is wondering if any improvement I can make (in terms of performance) and also if any code functional bugs, please feel free to point out.

from collections import defaultdict

class TrieNode:
    def __init__(self):
        self.children = defaultdict(TrieNode)
        self.isEnd = False

    def insert(self, source):
        if not source:
            return
        node = self
        for s in source:
            node = node.children[s]
        node.isEnd = True

    def search(self, source):
        if not source:
            return self.isEnd == True
        if source[0] == '?':
            for (ch,node) in self.children.items():
                if node.search(source[1:]) == True:
                    return True
            return False
        elif source[0] == '*':
            for (ch, node) in self.children.items():
                if ((node.search(source[1:]) == True) or
                    (node.search(source) == True)):
                    return True
            return False
        else:
            if source[0] in self.children:
                node = self.children[source[0]]
                return node.search(source[1:])
            else:
                return False
if __name__ == "__main__":
    root = TrieNode()
    root.insert('abc')
    root.insert('acd')
    root.insert('bcd')
    print root.search('acd') # True
    print root.search('acdd') # False
    print root.search('aaa') # False
    print root.search('a?d') # True
    print root.search('a*d') # True
    print root.search('ad*') # False
    print root.search('*c*') # True
    print root.search('*c?') # True
    print root.search('*a?') # False


texts: Updating multiple membership plan expiration dates at once

texts:
I have model action in RequestAdmin like this:

def offer_plan(modeladmin, request, queryset):
    class MembershipForm(forms.Form):
        plan = forms.ModelChoiceField(queryset=Plan.objects.all(), required=True,empty_label=None)
        _selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
        expires = forms.DateField(initial="click to select date")

    selected = request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
    links = {}
    if request.POST.get('submit'):
        form = MembershipForm(request.POST)
        if form.is_valid():
            plan = form.cleaned_data['plan']
            expires = form.cleaned_data['expires']
            for _id in selected:
                Request.objects.filter(id=_id).update(offered_membership_plan=plan,expires=expires)
                links[Request.objects.filter(id=_id).get().email] = 'www.xyz.com/plan/' + str(int(_id))
            return render_to_response("success.html", {'links': links,
                }, context_instance=RequestContext(request))

    else:
        form = MembershipForm(initial={'_selected_action': selected})
    return render_to_response("offer.html", {'form': form,
        'selected_action': selected,}, context_instance=RequestContext(request))

How can I improve the above code (I think it's always better not to run database calls in for loops) by removing database calls in loops?


texts:
I have implemented the K-Nearest Neighbor algorithm with Euclidean distance in R. It works fine but takes tremendously huge time than the library function (get.knn). Please point out the possibility of improvement.

knn<-function(list,k){
  n=nrow(list)
  if (n<=k) stop("k can not be more than n-1")
  neigh<- matrix(0,nrow=n,ncol=k)
  for(i in 1:n){
    dist<-matrix(0,ncol=2,nrow=n)
    for (j in 1:n){
      dist[j,1]<-j
      dist[j,2]<-sum((list[i,]-list[j,])^2)
      #dist[j,2]<-dtw(list[i,],list[j,])$distance
    }
    sorted<-dist[order(dist[,2]),]
    neigh[i,]<-sorted[2:(k+1),1]
  }
  return(neigh)
}


texts: Random missile generator and air defense system

texts:
My task in C#:

Random missile generator generating 2 types of missiles each second: ThermoNuclearBomb and FacetBomb

Missiles have properties Serial Number, Type

Air Defense System, that is identifying the 2 types of missiles and neutralizes each of them with a different gun (AntiThermoGun and AntiFacetGun)

Air Defense system has a method AcceptMissile that accepts a Missile as a parameter
Every Gun has a method Neutralize that accepts an appropriate Missile as a parameter and neutralizes only such types of missiles.
The Air Defense system must decide which missile will be neutralized with which gun.

I've got two interfaces:

public interface IMissile
    {
         int SerialNumber { get; set; }
         string Type { get; set; }

    }

public interface IGun
    {
         string Name { get; set; }
         void Neutrilize(IMissile missile);
    }

Of course FacetBomb and ThermoNuclearBomb class implement this interface IMissile:

public class FacetBomb : IMissile
    {
        public int SerialNumber { get; set; }
        private string type;
        public string Type { get; set; }
    }

    public class ThermoNuclearBomb:IMissile
    {
        public int SerialNumber { get; set; }
        public string Type { get ; set ;  }

    }

Here are my two classes AntiThermoGun and AntiFacetGun that implement IGun:

public class AntiThermoGun  : IGun
    {
        private string name;
        public string Name
        {   get {return name;}
            set { name = "AntiThermoGun"; }
        }
        public  void Neutrilize(ThermoNuclear gun)
        {
            Console.WriteLine(this.Name + "neutrilizes" + gun.Type);

        }
    }

   public class AntiFacetGun : IGun
    {
        private string name;
        public string Name
        {
            get { return name; }
            set { name = "AntiFacetGun"; }
        }
        public void Neutrilize(FacetBomb missile)
        {
            Console.WriteLine(this.Name + "neutrilizes" + missile.Type);
        }
    }

Here is my AirDefence class which accepts a missile and decides which missile will be neutralized with which gun:

public class AirDefenceSystem
    {

        public void InterceptMissile(IMissile missile)
        {
            IGun igun = null;

            switch (missile.Type)
            {
                case "ThermoNuclear":

                    igun = new AntiThermoGun();
                    break;

                case "FacetBomb":
                    igun = new AntiFacetGun();
                    break;
            }
            igun.Neutrilize(missile);
        }
    }

In my program.cs:

 static void Main(string[] args)
        {
            FacetBomb facetBomb = new FacetBomb { SerialNumber = 100, Type = "FacetBomb" };
            FacetBomb facetBomb2 = new FacetBomb { SerialNumber = 200, Type = "FacetBomb" };
            ThermoNuclear thermoBomb = new ThermoNuclear { SerialNumber = 500, Type = "ThermoNuclear" };

            IMissile[] objects = new IMissile[] { facetBomb, facetBomb2, thermoBomb };
            AirDefenceSystem system = new AirDefenceSystem();
            foreach (var item in objects)
            {
                system.InterceptMissile(item);

            }

        }


texts: Compressing a vector into a specific range

texts:
I want to solve the following task --- I am given a vector of integers. I want to 'compress' this list, where the elements will be replaced with numbers 0 through n - 1, where n is the number of unique elements in the vector, such that the relative ordering among the elements is preserved, i.e., if previously vector[index1] < vector[index2], then that is still true after the compression. In other words, each element is replaced with its ranking among the source vector.
For example, given the vector {1, 3, 10, 6, 3, 12}, the elements will be replaced with 0 through 4 since there are 5 unique value. To preserve ordering, it will be transformed into {0, 1, 3, 2, 1, 4}.
Right now, to complete this, I use the following algorithm:
#include <iostream>
#include <map>
#include <set>
#include <vector>

using namespace std;

int compress_vector(vector<int>& vec) {
  // function compresses the vector passed in by reference
  // and returns the total number of unique elements
  map<int, int> m;
  set<int>      s;
  for (auto i : vec) s.insert(i);
  int counter = 0;
  for (auto i : s) {
    m[i] = counter;
    counter++;
  }
  for (auto& i : vec) i = m[i];
  return s.size();
}

int main() {
  vector<int> vec = { 1, 3, 10, 6, 3, 12 };  //

  int size = compress_vector(vec);

  // Should output "0 1 3 2 1 4", then a newline, then a "5"
  for (auto i : vec) cout << i << " ";
  cout << endl;
  cout << size;

  return 0;
}

However, I feel this function is quite messy --- it uses maps, sets, and counters. While this is functional, is there a faster or cleaner way to do this?
Thanks


texts: Dynamic Fibonacci algorithm in x86 (MASM)

texts:
My task was to implement this algorithm that uses memoization to calculate fibonnaci numbers:

int fib(int n)
{
  int f[n+2];   // 1 extra to handle case, n = 0
  int i;

  /* 0th and 1st number of the series are 0 and 1*/
  f[0] = 0;
  f[1] = 1;

  for (i = 2; i <= n; i++)
  {
      f[i] = f[i-1] + f[i-2];
  }
  return f[n];
}

This proved to be more challenging because it involves local variables. What's more, it's a local array with a variable initial size.

;*******************************************************************************
; This program calculates fibonacci numbers with a dynamic programming
; algorithm.
;
; Author: William

                .386
                .model  flat, stdcall
                .stack  4096

ExitProcess     PROTO,  dwExitCode:DWORD

.code

;-------------------------------------------------------------------------------
; FibAsm( int n )
;
; Calculates fibonacci numbers using memoizaiton
;
; Entry: n      @ ebp + 8                       ; DWORD unsigned int up to 47
;
; Local: f[]                                    ; array to store fibs
;
; Exit: the fib number is returned in eax
;-------------------------------------------------------------------------------
FibAsm:
                ; set up stack frame
                push    ebp
                mov     ebp, esp
                push    ebx
                push    ecx
                push    esi
                push    edi

                mov     ebx, [ebp + 8]          ; n stored in ebx

                ; new f[] of size n + 2
                lea     edi, [ebx + 2]          ; save size of array in edi
                shl     edi, 2                  ; mul by 4, size of DWORD int
                sub     esp, edi                ; allocate space for f[]
                                                ; pointer to f[] in esp !

                ; f[0] = 0 and f[1] = 1
                mov     DWORD PTR[esp], 0
                mov     DWORD PTR[esp + 1 * 4], 1

                ; for (i = 2; i <=n; i++)
                mov     ecx, 2                  ;loop count i set to 2
L1:             cmp     ecx, ebx
                jg      endL1

                ; f[i] = f[i - 1] + f[i - 2]
                lea     eax, [ecx - 1]
                mov     esi, DWORD PTR[esp + eax * 4]
                dec     eax
                add     esi, DWORD PTR[esp + eax * 4]
                mov     [esp + ecx * 4], esi

                inc     ecx                     ;inc i
                jmp     L1
endL1:
                ; return f[n]
                mov     eax, DWORD PTR[esp + ebx * 4]

                ;clean up stack, restore regs
                add     esp, edi                ; add array size to esp
                pop     edi
                pop     esi
                pop     ecx
                pop     ebx
                pop     ebp
                ret     4

main:
                push    47
                call    FibAsm
                INVOKE  ExitProcess, 0

                END             main

What I ended up doing after a long time playing with the stack frame was to calculate the size first and save that in a register in order to clean up the stack later. Also I used the esp register as the start of the array instead of an offset from ebp. That seems counter intuitive, but it was simpler than calculating some distance from ebp (which would have to account for all the registers than were pushed to the stack after ebp).

Anyway, I'm wondering how this is normally done and looking for any other criticism as well.


texts: Concurrent dependant routines in a gui application

texts:
The idea is that, in my application I have 5 routines named long_process_1, long_process_2, long_process_3, long_process_4, long_process_5. These are each long calculations that would hang the GUI and can only be called in that order. When each result is ready, user input is required about the result. So we call ask_user_1, ask_user_2, ask_user_3, ask_user_4, ask_user_5 which must obviously run in the main GUI thread. Thus the whole thing cannot be run in a separate thread in its entirety. Here's how I did it:
void MainWindow::on_button_click() // starts with a button click
{
    QEventLoop eventLoop;
    QFutureWatcher<int> watch;

    // Watcher intercepts eventLoop when the computation is finished
    connect(&watch, &decltype(watch)::finished, &eventLoop, &decltype(eventLoop)::quit);

    auto const res1 = QtConcurrent::run(long_process_1);
    watch.setFuture(res1);
    eventLoop.exec(); // Handles GUI during computation
    auto const user_in1 = ask_user_1(res1);

    auto const res2 = QtConcurrent::run(long_process_2, user_in1);
    watch.setFuture(res2);
    eventLoop.exec();
    auto const user_in2 = ask_user_2(res2);

    auto const res3 = QtConcurrent::run(long_process_3, user_in2);
    watch.setFuture(res3);
    eventLoop.exec();
    auto const user_in3 = ask_user_3(res3);

    auto const res4 = QtConcurrent::run(long_process_4, user_in3);
    watch.setFuture(res4);
    eventLoop.exec();
    auto const user_in4 = ask_user_4(res4);

    auto res5 = QtConcurrent::run(long_process_5, user_in4);
    watch.setFuture(res5);
    eventLoop.exec();
    (void)ask_user_5(res5); // result is not used
}

This works alright. I find this a lot simpler than running the whole thing through "on-finished" signal-slots. It also simplifies ownership of local variables/function results as they are all in a single function. The long routines are clearly decoupled from the function calling them. It seems a bit odd overall though. I got the idea from very old Qt docs. All comments are welcome.


texts:
I've written some XSLT where I want to assign values to some variables.

Depending on whether or not a condition is met, I want the variable to be populated with a computed value and I want it to have a default value otherwise.

I've written the following code that appears to work, but I think that there may be a better way.

<xsl:variable name='HasValue' select='count($Catalog/lookup) &gt; 0' />
<xsl:variable name='Product' >
    <xsl:choose><xsl:when test='$HasValue'>
      <xsl:value-of select='$Catalog/lookup/Product' />
    </xsl:when><xsl:otherwise>UNK</xsl:otherwise></xsl:choose>
</xsl:variable>
<xsl:variable name='Area' >
    <xsl:choose><xsl:when test='$HasValue'>
      <xsl:value-of select='$Catalog/lookup/Area' />
    </xsl:when><xsl:otherwise>UNK</xsl:otherwise></xsl:choose>
</xsl:variable>

Yes, my XSLT processor uses XSLT 2.0


texts: Converting multiple excel files in multiple folders into CSV

texts:
The whole project is quite large, involving parsing the CSV-files, validating them, exporting them to a database and such, but my code in question involves subset of the project: converting multiple excel files. The converter method can be seen below:

import glob
from openpyxl import load_workbook
import csv
import codecs
from zipfile import BadZipFile

def convert_excel(data, meta, meta_additional, sheet_number):
    convert_xlsx_to_csv(data, sheet_number)
    convert_xlsx_to_csv(meta, sheet_number)
    convert_xlsx_to_csv(meta_additional, sheet_number)

def convert_xlsx_to_csv(directory, sheet_number):
    excel_files = glob.glob(directory + '*.xlsx')
    for excel_file in excel_files:
        try:
            workbook = load_workbook(excel_file)
            sheets = workbook.get_sheet_names()
            sheet = sheets[sheet_number]
            out = excel_file.replace('.xlsx', '.csv')
            write_as_csv(out, workbook, sheet)
        # this exception will only occur if the excel file is corrupted.
        except BadZipFile:
            print("error in file: " + excel_file + " -- ignoring file")

def write_as_csv(output, workbook, sheet):
    # utf-8 is used, because the parsing parts rely on that and the database
    # itself is encoded as utf-8
    with codecs.open(output, 'w', 'utf-8') as converted_file:
        wr = csv.writer(converted_file, delimiter='\t')
        for row in workbook[sheet].rows:
            wr.writerow([cell.value for cell in row])

if __name__ == '__main__':
    convert_excel('testdir1/', 'testdir2/', 'testdir3/', 0)

And here is how it's called from another module (the 'main'-module):

import convert_excel
convert_excel.convert_excel(**params)

where sheet number and directories are read from a config file that looks like this:

[parseparams]
data=path/to/dir/
meta=path/to/meta/
meta_additional=path/to/meta_additional/
sheet_number=0

and the config is parsed like this:

from configparser import ConfigParser

def config(filename='config/cfg.ini', section):
    """
    parses the directory information
    :param filename: path to the config file
    :param section: which portion of the config will be parsed;
    'parseparams', for parsing, 'dbase' for database config.
    :return: returns config information as a dictionary
    """
    parser = ConfigParser()
    parser.read(filename)
    params = {}

    if parser.has_section(section):
        parameters = parser.items(section)
        for param in parameters:
            params[param[0]] = param[1]
    else:
        raise Exception("no config was found!")
    return params

I decided to make calling the module a one-liner (and thus add one method, convert_excel() to the converter module), to keep the main module as short and readable as possible.