texts: Adding all IDs associated with a Fax to one Row

texts:
I found a custom function called UniqueItems() to use and then developed my own RemoveDups() and FaxesToUse() code:

Function UniqueItems(ArrayIn, Optional Count As Variant) As Variant
'   Accepts an array or range as input
'   If Count = True or is missing, the function returns the number of unique elements
'   If Count = False, the function returns a variant array of unique elements
    Dim Unique() As Variant ' array that holds the unique items
    Dim Element As Variant
    Dim i As Integer
    Dim FoundMatch As Boolean
'   If 2nd argument is missing, assign default value
    If IsMissing(Count) Then Count = True
'   Counter for number of unique elements
    NumUnique = 0
'   Loop thru the input array
    For Each Element In ArrayIn
        FoundMatch = False
'       Has item been added yet?
        For i = 1 To NumUnique
            If Element = Unique(i) Then
                FoundMatch = True
                Exit For '(exit loop)
            End If
        Next i
AddItem:
'       If not in list, add the item to unique list
        If Not FoundMatch And Not IsEmpty(Element) Then
            NumUnique = NumUnique + 1
            ReDim Preserve Unique(NumUnique)
            Unique(NumUnique) = Element
        End If
    Next Element
'   Assign a value to the function
    If Count Then UniqueItems = NumUnique Else UniqueItems = Unique
End Function

Here is the sub you need to find your Unique IDs and copy them over to the sheet "Use Me":

Sub FaxesToUse()
    Dim LastRow As Long, CurRow As Long, UniqueTotal As Long, SubTotal As Long

    UniqueTotal = InputBox("How Many Unique OtherIDs is Max?")
    If Not UniqueTotal > 0 Then
        Exit Sub
    End If

    LastRow = Range("A" & Rows.Count).End(xlUp).Row
    SubTotal = 0
    For CurRow = 2 To LastRow
        SubTotal = UniqueItems(Range("A2:A" & CurRow))
        If SubTotal > UniqueTotal Then
            SubTotal = UniqueItems(Range("A2:A" & CurRow - 1))
            Range("A1:B" & CurRow - 1).Copy
            Sheets("Use Me").Cells.Clear
            Sheets("Use Me").Range("A1").PasteSpecial xlPasteValues
            Sheets("Use Me").Activate
            MsgBox "Use Me Sheet rows contain " & SubTotal & " Unique OtherIDs"
            Exit Sub
        End If
        Cells(CurRow, 1).EntireRow.Interior.Color = RGB(255, 255, 0)
    Next CurRow

End Sub

That will get you a page that looks like this:

Now we just need to remove all the duplicate Faxes using this macro:

Sub RemoveDups()

Dim CurRow As Long, LastRow As Long, LastCol As Long, DestLast As Long, DestRng As Range, ws As Worksheet

Set ws = Sheets("Use Me")
LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row

For CurRow = LastRow To 3 Step -1
     Set DestRng = ws.Range("B2:B" & CurRow - 1).Find(ws.Range("B" & CurRow).Value, LookIn:=xlValues, LookAt:=xlWhole, SearchDirection:=xlNext)
     If DestRng Is Nothing Then
         'Do Nothing
     Else
        DestLast = ws.Cells(DestRng.Row, Columns.Count).End(xlToLeft).Column + 1
        ws.Cells(DestRng.Row, DestLast).Value = ws.Cells(CurRow, 1).Value
        ws.Cells(CurRow, 1).EntireRow.Delete xlShiftUp
     End If
     Next CurRow
ws.Columns("B:B").Cut
ws.Columns("A:A").Insert Shift:=xlToRight
Application.CutCopyMode = False

LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row
LastCol = 0
For CurRow = 2 To LastRow
    If ws.Cells(CurRow, Columns.Count).End(xlToLeft).Column > LastCol Then
        LastCol = ws.Cells(CurRow, Columns.Count).End(xlToLeft).Column
    End If
Next CurRow

MsgBox "Use Me Sheet Rows contain " & UniqueItems(ws.Range(Cells(2, 2), Cells(LastRow, LastCol))) & " Unique OtherIDs"

End Sub

It leaves you with this:

I'm interested in cleaning this up and making it more efficient for larger data sets.


texts: Linking to an image asset from a JavaScript file in Symfony 2

texts:
I am calling a JS file from a bundle directory like so:

<script src="{{ asset('bundles/macppages/js/main.js') }}"></script>

which loads the JS file into the base.index.twig

In that JS file I want to add some custom css via jQuery like this:

function loadBkrndImg(){
    var img = new Image();
        img.src = "/bundles/macppages/images/bkrnd.0" + currentBkrndImgNum + ".jpg";
        $('body').css("background-image","url('" + img.src + "')");
}

which works, but to the question:

Is this the correct way to do it using the Symfony 2 framework?  In Symfony 1, there was a function you could call to pull the web dir. With Sym2, the assets are in the bundle directories, so is there a Symfony2 command for this so it is not so explicit?


texts: How to delete last element in java.util.Set efficiently?

texts:
List<Route> listOfRoutes = routeStopsService.getAllRoutes();
Set<String> listOfStopNames = new TreeSet<String>();
for(Route route:listOfRoutes){
    Set<Stop> stops = routeStopsService.getStops(route);
    for(Stop stop:stops)
        listOfStopNames .add(stop.getStopName());
    listOfStopNames .remove( ((TreeSet<String>) listOfSources).last());
}

Here I am getting list of stop names for every route, and I am removing the last stop name from every route.


texts:
I'm new to scala and have been working to understand the syntax so that I can be more efficient.  How does this look in terms of functional syntax and scala idioms?

In particular, I'd like to know if this is a good way of handling futures.  I'm aware of onComplete, onSuccess, etc..., matching but I had trouble getting a return value back out.  map seemed like the right approach here.

object Application extends Controller with securesocial.core.SecureSocial {

  val inboxSlurper = Akka.system.actorOf(Props[InboxSlurper], name = "inboxSlurper")

  def index = SecuredAction.async {
    implicit request =>
      implicit val timeout = Timeout(10 seconds)
      val user: User = request.user.asInstanceOf[User]

      val f = inboxSlurper.ask(
        OauthIdentity(
          user.email.get,
          user.oAuth2Info.get.accessToken))

      f flatMap { reply =>
        val emailFeed = reply.asInstanceOf[Enumerator[Message]]
        val iter = Iteratee.fold[Message, String]("")((result, msg) => result + msg.getSubject())
        emailFeed |>>> iter
      } map { str =>
        Logger.debug(str);
        val subj = "Subject: %s".format(str)
        Ok(views.html.index(subj))
      }

  }

}


texts: Python softmatcher using difflib impracticably slow

texts:
I have a softmatch function (below) that takes a donor list and a new entry and looks to see if the given donor already exists.

The data is not exact, so I have to use a softmatch to determine whether a given record exists (ex: Jon Doe at 123 Sesame St. is the same as John P. Doe at 123 Sesame Street).  I have this implemented with difflib, and it works; it's just slow as Christmas.

The program currently takes about two days to process 10mb of data.  The profiler indicates it's the difflib operations in the softmatch function that is causing the slowness.

Is there a way to optimize my matching function to work better?

def softMatch(self, new, donors):
    #Takes new, a contribution record from a DG report, and attempts to soft match it with a record in donors
    #Returns the position of the matched record or -1 if no match
    #Methodology
        #Name
        #Address
        #Affiliation,Occupation,Employer not analyzed
    #Dependences cleanAddr(str), re(from cleanAddr), difflib

    match = -1

    name = new[0]
    address = self.cleanAddr(new[1] + " " + new[2] + " " + new[3] + " " + new[4] + " " + new[5][:5])

    while address.find("  ") != -1:
        address = address.replace("  "," ")

    diff = 0.6

    for x in range(0, len(donors)):
        ratio = difflib.SequenceMatcher(None, name, donors[x].getBestName()[0]).ratio() * difflib.SequenceMatcher(None, address, donors[x].getBestAddr()).ratio()**2
        if ratio > diff:
            diff = ratio
            match = x

    return match

And the profiler output:

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  3091394   53.737    0.000   66.798    0.000 difflib.py:353(find_longest_match)
   368770   10.030    0.000   80.702    0.000 difflib.py:463(get_matching_blocks)
 59454412    7.683    0.000    7.683    0.000 {method 'get' of 'dict' objects}
   368770    6.906    0.000   10.521    0.000 difflib.py:300(__chain_b)
  5210450    4.009    0.000    4.009    0.000 {built-in method __new__ of type object at 0x1001e14a0}
 16895496    3.056    0.000    3.056    0.000 {method 'append' of 'list' objects}
      756    2.863    0.004  104.674    0.138 june12.py:74(softMatch)
  3091394    1.875    0.000    1.875    0.000 {method 'pop' of 'list' objects}
 10299176    1.850    0.000    1.850    0.000 {method 'setdefault' of 'dict' objects}
  2487807    1.808    0.000    4.634    0.000 difflib.py:661(<genexpr>)
  3091394    1.620    0.000    4.345    0.000 <string>:12(__new__)
   368770    1.461    0.000   88.032    0.000 difflib.py:639(ratio)
  2119037    1.258    0.000    2.826    0.000 <string>:16(_make)
  8127502    1.032    0.000    1.032    0.000 {method '__contains__' of 'set' objects}
   184385    0.919    0.000    1.500    0.000 Donor.py:63(getBestAddr)
   368770    0.859    0.000    5.493    0.000 {built-in method sum}
   368770    0.554    0.000   12.131    0.000 difflib.py:154(__init__)
   368817    0.552    0.000    0.552    0.000 {method 'sort' of 'list' objects}
3965153/3965134    0.538    0.000    0.538    0.000 {built-in method len}
   368770    0.421    0.000   11.577    0.000 difflib.py:218(set_seqs)
   368770    0.403    0.000   10.924    0.000 difflib.py:256(set_seq2)
   337141    0.371    0.000    0.371    0.000 {method 'find' of 'str' objects}
   368770    0.281    0.000    0.281    0.000 difflib.py:41(_calculate_ratio)
   368770    0.232    0.000    0.232    0.000 difflib.py:230(set_seq1)
   159562    0.216    0.000    0.216    0.000 {method 'replace' of 'str' objects}
   184385    0.134    0.000    0.134    0.000 Donor.py:59(getBestName)
   1    0.017    0.017  104.718  104.718 june12.py:56(loadDonors)
    ...

(softmatch is called from loadDonors)


texts: Preorder, inorder, postorder for tree in C++11

texts:
Please review my code for preorder, inorder and postorder of a tree. I am using C++11 (or wanted to use), so let me know if anything is deviating from the C++11 standard.

#include <iostream>
#include <memory>

using std::cout;
using std::endl;
using std::shared_ptr;

struct node
{
    int data;
    shared_ptr<node> left;
    shared_ptr<node> right;
};

shared_ptr<node> newNode (int i)
{
    shared_ptr<node> n (new node);
    n->data = i;
    n->left = nullptr;
    n->right = nullptr;

    return n;
}

void preOrder(shared_ptr<node> n)
{
    if(n == nullptr)
        return;

    cout<<n->data<<" ";

    preOrder((n->left));
    preOrder((n->right));
}

void inOrder(shared_ptr<node> n)
{
    if(n == nullptr)
        return;

    inOrder((n->left));

    cout<<n->data<<" ";

    inOrder((n->right));
}

void postOrder(shared_ptr<node> n)
{
    if(n == nullptr)
        return;

    postOrder((n->left));
    postOrder((n->right));

    cout<<n->data<<" ";

}

int main(int argc, char* argv[])
{
    shared_ptr<node> r = newNode(1);
     (r->left) = newNode(2);
     (r->right) = newNode(3);
    (r->left->left) = newNode(4);
    (r->left->right) = newNode(5);

    preOrder(r);
    cout<<endl;

    inOrder(r);
    cout<<endl;

    postOrder(r);
    cout<<endl;

    return 0;
}


texts:
This is one way to make a boolean in C.

typedef enum {
    false = 1 == 0,
    true = 0 == 0
} bool;

Recently I made some like

typedef enum {
    true = ~(int)0, //true is the opposite of false
    false = (int)0  //the smallest enum is equal to sizeof int
} bool;

int main(void) {
    return false;
}

Can this be improved upon?


texts: Updating register_globals code for importing $_GET and $_POST data

texts:
I'm updating a bunch of PHP code that relies on register_globals and uses request data globally. In the process of fixing/updating I spend a lot of time writing code that looks like:

<?php
$x = isset($_REQUEST['x']) ? $_REQUEST['x'] : $xdefault; // other times loaded from $_GET['x'] or $_POST['x']
$abc = isset($_REQUEST['abc']) ? $_REQUEST['abc'] : $abcdefault;
?>

I've been toying with the idea of using something like:

<?php
function _export(&$source, &$defaults) {
  return array_merge($defaults, array_intersect_key($source, $defaults));
}

// old code essentially uses $_REQUEST, but I could point this at $_POST
// $_GET or a db query in the future

$defaults = array (
  'x'   => $xdefault,
  'abc' => $abcdefault,
);

$options = _export($_GET, $defaults);
extract($options); //export if needed until global code can be fixed
?>

The benefits being:

It's easier (I feel) to read array syntax compared to a list of ternary issets() assignments
The defaults array acts as a whitelist
The defaults array can be used to document the expected or required inputs

Are there any disadvantages or possible improvements to this approach? I would name _export() something different.


texts:
I am creating a watchdog in python to monitor a folder and then create a backup with the new version when a file is modified. I extend the FileSystsemEventHandler class to add 7 extra variables. However not every variable is used on every event so I'm not sure where to initialize the variables and where to put the logic for initializing certain variables based on the event. My current program works however I am new to coding and want to make sure I am using proper coding convention.
import os
import getpass
import re
import glob
import sys
import time
import pathlib
import logging
import shutil
import tkinter as tk
from tkinter import filedialog

from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler, FileSystemEventHandler

SLEEP_TIME = 30

class OnMyWatch:

    def __init__(self, watch_src, watch_dest):
        self.observer = Observer()
        self.watch_src = watch_src
        self.watch_dest = watch_dest

    def run(self):
        event_handler = Handler(watch_src, watch_dest)
        self.observer.schedule(event_handler, watch_src, recursive = True)
        self.observer.start()
        try:
            while True:
                time.sleep(SLEEP_TIME)
        except:
            self.observer.stop()
            print("Observer Stopped")

        self.observer.join()

class Handler(FileSystemEventHandler):
    def __init__(self, watch_src, watch_dest):
        self.watch_src = watch_src
        self.watch_dest = watch_dest

        self.src_dir = ''
        self.src_name = ''
        self.dest_dir = ''
        self.file_extension = ''

    # METHOD DONE
    def on_any_event(self, event):
        if event.event_type == 'moved':
            self.src_dir = os.path.join(self.watch_dest, os.path.relpath(event.src_path, self.watch_src))
            self.dest_dir = os.path.join(self.watch_dest, os.path.relpath(event.dest_path, self.watch_src))

        else:
            if event.is_directory:
                self.src_dir = event.src_path
                self.dest_dir = os.path.join(self.watch_dest, os.path.relpath(event.src_path, self.watch_src))

            else:
                src_path, self.file_extension = os.path.splitext(event.src_path)
                self.src_name = os.path.basename(src_path)
                self.src_dir = os.path.dirname(src_path)
                self.dest_dir = os.path.join(self.watch_dest, os.path.relpath(src_path, self.watch_src))

    def on_created(self, event):
        # CREATED EVENT

    def on_modified(self, event):
        # MODIFIED EVENT

    def on_moved(self, event):
        # MOVED EVENT

    def on_deleted(self, event):
        # DELETED EVENT

if __name__ == "__main__":
    root = tk.Tk()
    root.withdraw()

    watch_src = filedialog.askdirectory()
    watch_dest = filedialog.askdirectory()

    watch = OnMyWatch(watch_src, watch_dest)
    watch.run()


texts: Finding the nearest defibrillator exercise from CodingGames

texts:
For my first attempt at Scala I decided to solve a simple exercise on codingame.com.

Based on a string input containing the user location, the defibrillators count and a list of defibrillators entries (id, name, address, phone number, longitude, latitude), I have to print the closest defibrillator from the user. The distance formula is given in the rules.

An example of input:

3,879483
43,608177
3
1;Maison de la Prevention Sante;6 rue Maguelone 340000 Montpellier;;3,87952263361082;43,6071285339217
2;Hotel de Ville;1 place Georges Freche 34267 Montpellier;;3,89652239197876;43,5987299452849
3;Zoo de Lunaret;50 avenue Agropolis 34090 Mtp;;3,87388031141133;43,6395872778854

import math._
import scala.util._

object Solution extends App {
    val playerLongitude = readLine
    val playerLatitude = readLine
    val defibrilatorCount = readInt

    def sanitizeString(string : String) : String = string.replace(',', '.')
    def stringToDouble(string : String) : Double =  sanitizeString(string).toDouble

    val playerLongitudeValue = stringToDouble(playerLongitude)
    val playerLatitudeValue = stringToDouble(playerLatitude)

    def distanceToPlayer(long : Double, lat : Double) :  Double = {
        val x = (long - playerLongitudeValue) * cos((playerLatitudeValue + lat) / 2)
        val y  = lat - playerLatitudeValue
        sqrt(x * x + y * y) * 6371;
    }

    def distanceToPlayer(stringInput : String) : Double = {
        val tokens = sanitizeString(stringInput).split(";")
        distanceToPlayer(tokens(4).toDouble, tokens(5).toDouble)
    }

    var smallestDistance = Double.MaxValue
    var closestDefibName = ""

    for(i <- 0 until defibrilatorCount) {
        val defib = readLine
        val distance = distanceToPlayer(defib)
        if(distance < smallestDistance) {
            smallestDistance = distance
            closestDefibName = defib.split(";")(1)
        }
    }

    println(closestDefibName)
}


texts:
Input Format

Input starts with an integer n (1 ≤ n ≤ 100) indicating the number of cases. The following n lines each contain a test case of a single even number x (4 ≤ x ≤ 32000).

Output Format

For each test case x, give the number of unique ways that x can be represented as a sum of two primes. Then list the sums (one sum per line) in increasing order of the first addend. The first addend must always be less than or equal to the second to avoid duplicates.

Sample Input

2
26
100

Sample Output

26 has 3 representation(s)
3+23
7+19
13+13

The above problem was originally posted in 2013 ICPC North America Qualifier, I encountered it in HackerRank's Round-I Holiday Cup contest.

My Python 3.x Code

import math
import time
def sieve(n):
    "Return all primes <= n using sieve of erato."
    np1 = n + 1
    s = list(range(np1))
    s[1] = 0
    sqrtn = int(round(n**0.5))
    for i in range(2, sqrtn + 1):
        if s[i]:
            s[i*i: np1: i] = [0] * len(range(i*i, np1, i))
    return filter(None, s)
def primeSum(n):
    p=2
    limit=math.floor(n/2)
    for p in primes:
        q=n-p
        if(p>q):
            break
        if(q in primes):
            out.extend([p,q])
    print (n,"has",round(len(out)/2),"representation(s)")
    for i,j in zip(out[0::2],out[1::2]):
        print (i,"+",j,sep='')

    print ("")

primes = sorted(set(sieve(32000)))
for __ in range(int(input())):
    out = []
    primeSum(int(input()))

This code almost took over 5 seconds for larger values of n but ran less than second in most cases. Is it because of time taken to output all those representations for larger values (because 32000 has over 300 representations.

Can this be optimized? and also review my general coding (I'm new to python).


texts:
We have hundreds of employees and for tracking each employees' data, and I am using this code:

<?php
$sqldelivery9 = "SELECT COUNT(*) as count FROM orders WHERE employeename = 'nawaz' AND DATE(reattemptdate) = DATE(NOW() - INTERVAL 2 DAY)";
$resultdeliverys9 = $db_handle->runSelectQuery($sqldelivery9);
$numrowsresultdelivery9 =$resultdeliverys9[0]['count'];
echo $numrowsresultdelivery9;

Also, I am tracking the last 7 days of records of each employee, so it's going to be 100*7= 700 SQL queries. Is this acceptable? Will it going to affect performance? Is there any better way to do it with minimal SQL queries?


texts:
I am receiving and Expression (String) as follows:

String expression = "+name;-age;-city";

I parse this expression by splitting it using ";" and interpreting the +/- signs and create a List<OrderRule>. To wrap this I created the following:

public class OrderExpression {

  public HashSet<OrderRule> Rules { get; set; }

  public static Boolean TryParse(String expression, out OrderExpression orderExpression) {
    // Parse expression into a List<OrderRule>
    if (_parser.ExpressionIsValid(expression)) {
       orderExpression = new OrderExpression { Rules = _parser.Parse(expression) }
       return true;
    else
       return false;
  }
}

So I would use it as follows:

String expression = "+name;-age;-city";
OrderExpression orderExpression;
OrderExpression.TryParse(expression, out orderExpression);

Does this make sense? I am not sure if this architecture and naming is the way to go.

I am being picky about this because I will use it as a standard for an API to convert an order expression into a List.


texts:
This is my first by-self written code. Looking for advice on what not to or to do so I could deal with any bad habits now. It's a guessing game and works perfectly fine. I just wanted to know if more experienced programmers would see any huge mistakes in the coding style.

Basically it generates a number and then asks for the user input. If the two match you win. I tried playing around with arrays, multiple classes and methods and I was curious if there is anything wrong here.

Class: GuessGame

package base;

import java.util.Scanner;

public class GuessGame {

    public static Scanner scanKeyboard = new Scanner(System.in);

    public static void main(String[] args) {

        Handler gameHandler = new Handler();

        System.out.println("Start guessing! You have " + gameHandler.guessLeft + " guesses left.");
        System.out.println(gameHandler.goal);

        while(!gameHandler.gameOver){
            if (gameHandler.guessLeft == 0) {
                gameHandler.gameOver = true;
                gameHandler.gameOver();
            } else if(gameHandler.isGuessRight()){
                gameHandler.gameWin();
                gameHandler.gameOver = true;
            } else{

                gameHandler.guessCount++;
                System.out.println("Give me your " + gameHandler.guessCount + ". guess!");
                gameHandler.guesses[gameHandler.guessCount] = scanKeyboard.nextInt();
                gameHandler.guessLeft--;
                }
            }

        scanKeyboard.close();

        }

Class: Handler

package base;

import java.util.Random;

public class Handler {

    public int guessLeft = 5;
    public int guessCount = 0;
    public int[] guesses = new int[guessLeft + 1];

    public boolean gameOver = false;

    public Random rand = new Random();
    public int goal = rand.nextInt(100);

    public Handler(){
    }

    public String PrintGuesses(){
        String str = " ";
        for(int i = 1; i < guessCount; i++){
            str += guesses[i] + " ";
        }
        return str;
    }

    public void gameOver(){
        System.out.println("You suck!");
        System.out.println("The answer was: " + goal);
        System.out.println("Your miserable guesses were:" + PrintGuesses()+ guesses[guessCount]);

    }

    public void gameWin(){
        System.out.println("You won!");
        System.out.println("You guessed it on your " + guessCount + ". guess. With the guess " + guesses[guessCount] + ".");
        System.out.println("Your glorious guesses were:" + PrintGuesses() + guesses[guessCount]);
    }

    public boolean isGuessRight(){
        if (guessCount != 0){
            if (guesses[guessCount] == goal){
                return true;
            } else if(guesses[guessCount] < goal){
                System.out.println("Too low.");
            } else if(guesses[guessCount] > goal){
            System.out.println("Too high.");
            }
        }
        return false;

    }


texts: Displaying each number of an integer in a sequence

texts:
One of the books I'm currently reading to learn C# asked me to write a method that takes an integer between 1 and 99999 and displays each number in that integer in a sequence, separating each digit by 2 spaces.

For example: the int 87564 would be written to the console as 8 7 5 6 4.

This is simple enough to do using the input as a string, converting it to a char array, or looping over the string with a foreach and printing out a formatted string for each character.

For fun though and mostly to challenge myself, I like to work out the problems as they are intended for someone just learning the concepts for the first time. The chapter was about methods and briefly introduced recursion. It's clearly the author's intent that you solve this using division and modulus operations to pick off each digit and then write them out.

So there really were limited options in terms of solving this with the material you have learned to this point in the book. You could pick off each digit and store it as it's own variable, then later write them out in order since you know the range of integers.

I decided to make the method more useful by really allowing any non-negative integer and my approach involved recursion. I'm not really experienced using recursion so I'd like to get some feedback on my implementation to see what I could have done better.

public class Program
{
    static void Main()
    {
        // Get User Input From Console
        // Validate and parse as int input
        DisplayDigits(input);
    }

    static void DisplayDigits(int value)
    {
        if (value < 10)
        {
            Console.Write("{0}  ", value);
            return;
        }
        DisplayDigits(value / 10);
        Console.Write("{0}  ", value % 10);
    }
}

Obviously, this is not meant to be production level code, I'm solving the problem in the textbook and then throwing the code away.
It appears to be working for all non-negative numbers I've tried. I even wrote an overload that takes a ulong and passed it UInt64.MaxValue and it printed everything fine. I can't help but feel like maybe it could be better in some way. Any criticism, suggestions, links to more reading material would be appreciated.


texts: Producing a nested data set from flat data

texts:
I have this example data :

 var objects = [
                {
                    title: "Parent Area",
                    code: "P",
                    areas: "B,C",
                    child: [],
                    selected: 0,
                    remove: 0
                },
                {
                    title: "Child area one",
                    code: "B",
                    areas: "C",
                    child: [],
                    selected: 0,
                    remove: 0
                },
                {
                    title: "Child area two",
                    code: "C",
                    areas: undefined,
                    child: [],
                    selected: 0,
                    remove: 0
                }
            ];

I want to create this data set :

sortedSet = [
                {
                    title: "Parent Area",
                    code: "P",
                    areas: "B,C",
                    child: [
                        {
                            title: "Child area one",
                            code: "B",
                            areas: "C",
                            child: [
                                {
                                    title: "Child area two",
                                    code: "C",
                                    areas: undefined,
                                    child: [],
                                    selected: 0,
                                    remove: 0
                                }
                            ],
                            selected: 0,
                            remove: 0
                        },
                        {
                            title: "Child area two",
                            code: "C",
                            areas: undefined,
                            child: [],
                            selected: 0,
                            remove: 0
                        }

                    ],
                    selected: 0,
                    remove: 0
                }
            ];

Iv written the following code:

 /**
             * for each area get it's children
             */
            angular.forEach(objects, function (obj) {

                if (obj.areas) {

                    var subChildren = obj.areas.split(",");

                    /**
                     * assign the current child as child of the parent area
                     */
                    angular.forEach(subChildren, function (currentChild) {

                        angular.forEach(objects, function (currentObj) {

                            if (currentObj.code == currentChild) {

                                /**
                                 * mark this for removal from main array
                                 * @type {number}
                                 */
                                currentObj.remove = 1;
                                obj.child.push(currentObj);
                            }
                        })

                    })

                }

            })

            var sortedSet = [];
            /***
             * clean out main areas array
             */
            angular.forEach(objects, function (obj, index) {

                if (!obj.remove) {
                    /**
                     * copy the correct values to a secondary array
                     */
                    sortedSet.push(objects[index]);
                }
            })

My code works as required but I really wish I didn't need to do so many loops.

Any suggestion re-factors to optimise this code?


texts: Recursive Binary Tree Inorder Traversal in Python

texts:
This is a very simple problem to see if my understanding of basic Python is correct
Problem:
Given a binary tree, return the inorder traversal of its nodes' values.
Example:

Input: [1,null,2,3]
Output: [1,3,2]

Solution:
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        self.inorder = []
        self.inorderHelper(root, self.inorder)
        return self.inorder

    def inorderHelper(self, node, inorder):
        if (node is None):
            return
        else:
            self.inorderHelper(node.left, inorder)
            inorder.append(node.val)
            self.inorderHelper(node.right, inorder)


texts:
I wrote a framework and I want to hear the thoughts of other on the design patterns it uses. Every method contains three design patterns - adapters(strategy), intercepting filters, and observers.

A normal class/method in a class looks like this:

class Run extends PVStaticObject{

    public static function goForARun($miles) {

        $return ='I ran '.$miles. ' miles today';

        return $return;
    }
}

With the design patterns the class/method looks like this:

class Run extends PVStaticObject{

    public static function goForARun($miles) {

        if (self::_hasAdapter(get_class(), __FUNCTION__))
            return self::_callAdapter(get_class(), __FUNCTION__, $miles);

        $miles = self::_applyFilter(get_class(), __FUNCTION__, $miles, array('event' => 'args'));

        $return ='I ran '.$miles. ' miles today';

        self::_notify(get_class() . '::' . __FUNCTION__, $miles, $return);
        $return = self::_applyFilter(get_class(), __FUNCTION__, $return, array('event' => 'return'));

        return $return;
    }
}

A brieft explanation, the adapter will completely change the method by calling another method in its place. Its a way of changing the functionality of a class without modifying the core functionality.

Filters modify variables in a method by passing them out to another class's method or anonymous function where they are modified and return. Normal execution of the method continues.

Observers do not have a return and are purely call another class or anonymous function. They are for event drivin programming.

Examples of adding adapters, filters and observers are below.

Run::addObserver('Run::goForARun', 'run_observer', function($miles, $return){
    echo PVHtml::div('Running '. $miles. ' has caused you to lose 2 pounds', array('style' => 'margin-top:10px;'));
}, array('type' => 'closure'));

Run::addAdapter('Run','goForARun', function($miles){
    echo PVHtml::p('Because of the weather, you were not able to run '.$miles. ' today');
}, array('type' => 'closure'));

Run::addFilter('Run', 'goForARun', 'run_filter', function($data, $options) {

    $data = PVHtml::strong($data);
    $data = PVHtml::p($data);

    return $data;

}, array('type'=> 'closure', 'event' => 'return'));

So what is thoughts and feedback on the design patterns? They are meant to faciliate aspect oriented and event driven design. They also to replace design patterns like dependency injection easily.

PS: More examples of AOP here.


texts:
I started implementing algorithms to learn them in order to get better at programming. Here is a merge sort one and criticisms / optimizations are welcome.

import unittest
import random

def mergeSort(list):
    """Sorts a mutable list.

    Args:
      list: An unordered list

    Returns:
      The sorted list.
    """
    if len(list) > 1:
        middle = len(list) // 2
        left_sorted = mergeSort(list[:middle])
        right_sorted = mergeSort(list[middle:])
        i,j,k = 0, 0, 0
        merged_list = []
        while (k < len(list) and len(left_sorted) != i and len(right_sorted) != j):
            if left_sorted[i] < right_sorted[j]:
                merged_list.append(left_sorted[i])
                i+=1
            else:
                merged_list.append(right_sorted[j])
                j+=1
            k+=1
        # Handle remaining items in the list.
        if len(left_sorted) == i:
            merged_list += right_sorted[j:]
        elif len(right_sorted) == j:
            merged_list += left_sorted[i:]
        return merged_list
    else:
        return list

class test_mergeSort(unittest.TestCase):
    def test_mergeSort(self):
        random_list = [random.randrange(0, 1000) for _ in range(500)]
        self.assertEqual(mergeSort(random_list), sorted(random_list))

if __name__ == '__main__':
    unittest.main()


texts: Simple python COM server to expose scipy integration to VBA

texts:
I want to create a COM server to expose scipy to VBA code, as performing integration is kinda difficult and I don't know of any good VBA/COM libraries for this. My objectives are:

As portable as possible
Fast
Maintainable

Here's the python:
# Requires C:\Users\...\anaconda3\Library\bin on the PATH
from scipy import integrate
from win32com.client import Dispatch
from typing import Callable
import comtypes

class ScipyWrapper:
    # pythoncom.CreateGuid()
    _reg_clsid_ = "{A621AB64-9378-4B54-A7D3-20711C0B72DB}"
    _reg_desc_ = "Python Scipy COM Server"
    _reg_progid_ = "PythonCOM.ScipyWrapper"
    _reg_clsctx_ = comtypes.CLSCTX_LOCAL_SERVER # don't want inproc because conda not supported on 64 bit
                                                # see https://stackoverflow.com/q/67462529/6609896

    _public_methods_ = ["quad",]
    # _public_attrs_ = []
    # _readonly_attrs_ = []

    def quad(self, vbFunc, a: float, b: float) -> float:
        vb_dispatch = Dispatch(vbFunc)
        func: Callable[[float], float] = vb_dispatch.Evaluate  # Callable[..., float]?
        return integrate.quad(func, a, b)[0]  # only return val, not uncertainty

if __name__ == "__main__":
    import win32com.server.register

    win32com.server.register.UseCommandLine(ScipyWrapper)

Called from VBA (twinBasic) like:
Module Main
    Public Sub doStuff()
        Dim integrator as Object = CreateObject("PythonCOM.ScipyWrapper")
        Dim func as IOneDimensionalFunction = New XSquared 'this is what we'll integrate
        Debug.Print integrator.quad(func, 0., 1.) 'integrate x^2 from 0->1, returns 0.333333...
    End Sub
End Module

'@Description("Interface for a f(x) -> y function, with optional parameters")
Class IOneDimensionalFunction
    Public Function Evaluate(ByVal x As Double, ParamArray parameters() as Variant) As Double
    End Function
End Class

Class XSquared
    Implements IOneDimensionalFunction
    Private Function IOneDimensionalFunction_Evaluate(ByVal x As Double, ParamArray parameters() as Variant) As Double
        Return x^2
    End Function
End Class

Questions:

Not sure how to Type the python, vbFunc is a PyIDispatch instance but not sure what that means for typing/mypy.
I'd like to use strong typing to protect my python, right now it's duck typed and I could easily pass an Interface without the Evaluate method, or anything else for that matter.
No idea how to handle python errors and turn them into COM errors.
Is this ref-count safe?

OFC any other tips on general style, use of comments and naming etc. are welcome :)


texts: Determining winning line in TicTacToe game

texts:
I am trying to write code to determine a win in tic-tac-toe game. In this question, I am not focusing on the whole game, I am only interested in the question of how to determine that the game ended with the victory of one of the players. So I made a synthetic example to test different approaches.
My guess is that a winning line on the board can only appear after the current player has made his move. Therefore, it makes no sense to check all the lines on the board. I only consider those that include the last move made. I assume that the board can be of any size (but only square) and the winning line has the same size. Thus, it is one of the rows, or one of the columns, or one of the two diagonals.
After several attempts, I ended up with the code below:
import java.util.List;
import java.util.function.Predicate;

enum Cell {
    X,
    O,
    B // blank cell
}

public class Board {

    private final int size = 3;
    private final Cell[][] board;

    public Board(Cell[][] board) {
        this.board = board;
    }

    private boolean isLineCompleted(Predicate<Integer> predicate) {
        boolean result = true;
        int i = 0;
        while (result && i < size) {
            result = predicate.test(i);
            i++;
        }
        return result;
    }

    public boolean hasWinningLine(int row, int col) {
        if (board[row][col] == Cell.B) return false;

        Cell base = board[row][col];
        List<Predicate<Integer>> checks = List.of(
                i -> board[row][i] == base, //columns
                i -> board[i][col] == base, //rows
                i -> board[i][i] == base,   //top-down diagonal
                i -> board[size - i - 1][i] == base //down-top diagonal
        );

        boolean lineCompleted = false;
        for (var check : checks) {
            if (!lineCompleted) {
                lineCompleted = isLineCompleted(check);
            }
        }

        return lineCompleted;
    }
}

And I wrote some tests that use this code something like this:
Cell[][] xWins = {
    {Cell.X, Cell.O, Cell.X},
    {Cell.O, Cell.X, Cell.O},
    {Cell.X, Cell.B, Cell.B}};

board = new Board(xWins);
AssertTrue(board.hasWinningLine(0, 2));

I have several questions:

How easy is this code to read and understand? How can you improve it in this sense?

I try not to make unnecessary checks. The algorithm should return false as soon as it finds an unsuitable cell. Should I handle the loop like this

for (var check : checks) {
            if (!lineCompleted) {
                lineCompleted = isLineCompleted(check);
            } else break; // That's better?
        }

Is it possible to rewrite this loop using a stream API?

When checking each line, this code can compare the cell to itself. How can i avoid this without complicating the code? Should I even think about it?

I am new to programming and would appreciate any advice that would help me code better.
EDITED:
The predicate checking loop can be rewritten as
return checks.stream()
    .map(this::isLineCompleted)
    .filter(b -> b == true)
    .findFirst()
    .orElse(false);

What are the disadvantages of this approach?


texts:
I am a beginner with only about 2 months under my belt. I'm learning Python 3 using the Automate the Boring Stuff with Python manual. In the chapter on reading and writing files one of the exercises is to make a program that would fill in a mad lib that was read from a file. It works, but it's not very elegant. Can anyone offer me advice on how to better do this task or a better direction to go?

# madLibs.py

import re, os

# define regex
verbRegex = re.compile(r'verb', re.I)
nounRegex = re.compile(r'noun', re.I)
adjectiveRegex = re.compile(r'adjective', re.I)

# change directory
os.chdir('C:\\MyPythonScripts')

# read contents of madLib.txt and store it in variable madLib
madLibFileObject = open('madLib.txt')
madLib = madLibFileObject.read()

y = 0
newMadLib = []

for word in madLib.split():
    newMadLib.append(word)
    if verbRegex.search(word) != None:
        x = input('Enter VERB:  ')
        newMadLib[y] = x
    elif nounRegex.search(word) != None:
        x = input('Enter NOUN:  ')
        newMadLib[y] = x
    elif adjectiveRegex.search(word) != None:
        x = input('Enter ADJECTIVE:  ')
        newMadLib[y] = x
    y += 1

newMadLib = (' ').join(newMadLib)

print(madLib)
print (newMadLib)


texts: Using JS/JQuery to serve ads from a self-hosted advertisements solution

texts:
I'm working on a custom (self-hosted) ads solution that allows the users to create ad units (by uploading the banner image and target URL) and get the ad display code. A JSON response is returned (by the endpoint) for the requested ad. As of now, here is what I do to get and display the ad on the page where ad code is added:

JSON output at the endpoint:

{
    "success": true,
    "ad_url": "https:\/\/adlandingpage.com",
    "ad_banner": "http:\/\/localhost\/ads\/complete\/uploads\/banners\/add-banner.gif"
}

Content of rw-ads.js:

var getAds = function(ad_id, callback) {
  url = 'http://localhost/ads/complete/index.php/ads/adjson/'+ad_id+'/';
  var xhr = new XMLHttpRequest();
  xhr.open('get', url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if(status == 200) {
      callback(null, xhr.response);
    } else {
      callback(status);
    }
  };
  xhr.send();
};

Ad code to be added to a page:

I need suggestions from experts. Am I doing this correctly or this can be improved? Thank you in advance for your help.


texts: Calling a MySQL procedure with an arbitrary parameter on a GoDaddy website

texts:
I'm deploying a PHP project, and I always try to use prepared statements, but unfortunately, GoDaddy does not have the mod mysqlnd which I use it for the function mysqli_stmt_get_result($stmt), so I had to start using mysqli_query in order to use the classic.

Example:

while($row = mysqli_fetch_array($query,MYSQLI_ASSOC)){
   echo $row['Name'];
}

I've been using mysqli_query, but I'm not expert in security, so could you please evaluate or give me some tips?

<?php
   include '../session.php';
   include '../connection.php';
   $link = mysqli_real_escape_string($connection,$_GET['file']);
   $query = mysqli_query($connection,'CALL mostrarConvocatoriaLink("'.$link.'")');
   if(!$query){
     echo mysqli_error($connection);
   }
   else{
     $row = mysqli_fetch_array($query,MYSQLI_BOTH);
     extract($row);
   }
   mysqli_close($connection);
?>

This is used to get an entry on my database using a procedure (which is only a Select statement) but, we're using a random generated string to create the links, instead of using the ID of the page. This is for using a kind of a WordPress that we're creating for the project. In my project all the inserts are with prepared statements and using Post, but in this case, I create a <a href="template.php?file=[the random string]">. I wanna know if I'm screwing things up.


texts:
I need two icons:

If the email is verified, show an icon without a hyperlink and set an "activated" CSS class for green style and checked.
If the email is not verified, the icon is linked to the verify page, and the default is a gray color style.

Which of these solutions is better and standard?

Solution #1:

<a href="<?php echo ($modelStatic->isVerifiedEmail) ? 'javascript:void(0)' :
    Yii::app()->createUrl('/user/reActivate'); ?>"
   class="item<?php if($modelStatic->isVerifiedEmail) echo ' activated'; ?>">

        <?php echo Yii::t('app', 'Verify Email'); ?>

Solution #2:

if($modelStatic->isVerifiedEmail) : ?>

            <?php echo Yii::t('app', 'Verify Email'); ?>

<?php else: ?>
    <a href="<?php echo Yii::app()->createUrl('/user/reActivate'); ?>"
       class="item">

            <?php echo Yii::t('app', 'Verify Email'); ?>

<?php endif; ?>

Solution #3:

<?php if($modelStatic->isVerifiedEmail) : ?>

<?php else: ?>
    <a href="<?php echo Yii::app()->createUrl('/user/reActivate'); ?>" class="item">
<?php endif; ?>

            <?php echo Yii::t('app', 'Verify Email'); ?>

<?php if($modelStatic->isVerifiedEmail) : ?>

<?php else: ?>

<?php endif; ?>


texts:
I was wondering if there is a better, more elegant way to write the following JavaScript code block:

var searchString = 'ma';
var names = ['Mark Kennel', 'Hellen Smith', 'Jane Mary Annet', 'Peter'];

var filteredNames = names.filter(name => {
  var words = name.toLowerCase().split(' ');
  for(var i = 0; i < words.length; i++) {
    if (words[i].indexOf(searchString.toLowerCase()) === 0 )
      return true;
  }
}

This runs in a function that filters an autocomplete input results. The filtering rule is:

  Show the names that have a word which begins with the searchString

The above code (with searchString = 'ma') should return an array with two names: 'Mark Kennel' and 'Jane Mary Annet'.


texts:
A few days ago I posted a little program that would check for vowels within a given word. I have rewritten this program, it can only find vowels in the English language still but, it will now tell you each vowel that is contained in your word, along with a count of how many vowels there are total, it's still not very exciting but I would like some more feedback on what I've done, anything will help:

using System;
using System.Linq;

namespace CheckForVowels
{
    class Vowels
    {
        static string say(string input)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(input);
            return input;
        }
        static string prompt(string input)
        {
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.Write($"{input}: ");
            return input;
        }
        static void Main(string[] args)
        {
            say("We will be checking your input to see if it contains vowels or not");
            prompt("Enter a word");

            var count = 0;
            var vowels = Console.ReadLine()
                .Where(c => "aeiouAEIOU".Contains(c))
                .Distinct();

            foreach (var vowel in vowels)
            {
                count += 1;
                say($"Your word contains vowel: {vowel}.");
            }

            say($"You have a total of {count} vowels in your word.");

                if (!vowels.Any())
                say($"Your word contains no vowels.");

        }

    }
}


texts: Three versions of a counting-up timer in JavaScript

texts:
I made 3 versions of a counting-up timer in JavaScript:

Version #1

All units of time (seconds, minutes, hours, and days) are updated every second, whether they change or not.

Pro: Shorter code.

Con: Worse performance than version #2.

const timeIntervals = [
    ["day", 86400],
    ["hour", 3600],
    ["minute", 60],
    ["second", 1]
];
var counter = 1;
var tick = () => {
    var gucci = counter;
    for (unit of timeIntervals) {
        $("#" + unit[0]).html(Math.floor(gucci / unit[1]));
        gucci %= unit[1];
    }
    counter++;
};
var timer = window.setInterval(tick, 1000);

Version #2

Each unit of time (seconds, minutes, hours, and days) is updated only at fixed intervals when they change.

Pro: Better performance than version #1.

Con: Longer code.

const timeIntervals = [
    ["day", 86400],
    ["hour", 3600],
    ["minute", 60],
    ["second", 1]
];
var counter = 1;
var tick = () => {
    let zero = false;
    for (unit of timeIntervals) {
        let element = $("#" + unit[0]);
        if (zero) {
            element.html("0");
        }
        else if (counter % unit[1] === 0) {
            element.html(
                parseInt(element.html()) + 1
            );
            zero = true;
        }
    }
    counter++;
};
var timer = window.setInterval(tick, 1000);

Version #3

Each unit of time (seconds, minutes, hours, and days) is incremented up by 1 when the counter before it reaches its maximum limit.

Pro: Doesn't require a counter variable.

Con #1: It will break if the user clicks "Inspect Element" and messes with the HTML.

Con #2: Long code.

const timeIntervals = [
    ["second", 60],
    ["minute", 60],
    ["hour", 24],
    ["day", Infinity]
];
var tick = () => {
    $("#second").html(
        parseInt($("#second").html()) + 1
    );
    for (let i = 0; i < timeIntervals.length; i++) {
        let currentElement = $("#" + timeIntervals[i][0]);
        if (parseInt(currentElement.html()) >= timeIntervals[i][1]) {
            currentElement.html("0");
            let nextElement = $("#" + timeIntervals[i + 1][0]);
            nextElement.html(parseInt(nextElement.html()) + 1);
        }
    }
};
var timer = window.setInterval(tick, 1000);

Which of these 3 codes has the best performance, readability, and structure? Do any of them have security vulnerabilities?


texts: Function and method debugging decorator - Part 2

texts:
This is a follow-up to this question.

I've refactored my previous debugging decorator, and added a couple new features, and changed a few things. Here's a complete list of things that have changed:

There is only one decorator, Debug, and it now supports functions, and class methods.
Each debug message is prefixed with [debug] to help distinguish it from normal output.
The output now tells you what it's outputting, rather than just outputting unreadable data.
The decorator will now output local variables names, along with argument and keyword argument names as well.

I'm wondering the following:

Is there a way to get the values of local variables in the function, or is that just not possible?
Is there a shorter way to get the names of local variables than function.__code__.co_varnames?
Is it a good idea to create an empty string, and then add to, and re-assign it to build an output string?
Is this Python 3, and Python 2.7 compatible?
How's my documentation?
Is this code "pythonic"?

debug.py

from pprint import pformat
from inspect import getargspec

class Debug(object):
    """Decorator for debugging functions.

    This decorator is used to debug a function, or
    a class method. If this is applied to a normal
    function, it will print out the arguments of

    Keyword arguments:
    debug -- Whether or not you want to output debug info. Generally, a global DEBUG variable is passed in here.
    """
    def __init__(self, debug=True):
        self.debug = debug

    def __format_debug_string(self, function, *args, **kwargs):
        """Return a formatted debug string.

        This is a small private helper function that will
        return a string value with certain debug information.

        Keyword arguments:
        function -- The function to debug.
        *args    -- The normal arguments of the function.
        **kwargs -- The keyword arguments of the function.
        """
        debug_string = ""
        debug_string += "[debug] {}\n".format(pformat(function))
        debug_string += "[debug] Passed args: {}\n".format(pformat(args))
        debug_string += "[debug] Passed kwargs: {}\n".format(pformat(kwargs))
        debug_string += "[debug] Locals: {}".format(pformat(function.__code__.co_varnames))
        return debug_string

    def __call__(self, function):
        def wrapper(*args, **kwargs):
            if self.debug:
                if getargspec(function).args[0] != "self":
                    print(self.__format_debug_string(function, *args, **kwargs))
                else:
                    print(self.__format_debug_string(function, *args, **kwargs))
                    print("[debug] Parent attributes: {}".format(pformat(args[0].__dict__)))

            return function(*args, **kwargs)
        return wrapper

Here are a few small, albeit unreadable tests, but it's good enough to get the point across:

from debug import Debug

@Debug(debug=True)
def a(a, b):
    d = 10
    return a * b

print(a(10, 10))

class B(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    @Debug(debug=True)
    def e(self, c):
        return self.a * self.b * c

c = B(10, 10)
print(c.e(10))

Here's the output of these tests:

[debug] <function a at 0x1bf9d38>
[debug] Passed args: (10, 10)
[debug] Passed kwargs: {}
[debug] Locals: ('a', 'b', 'd')
100
[debug] <function B.e at 0x1944ce8>
[debug] Passed args: (<B object at 0x1bfc838>, 10)
[debug] Passed kwargs: {}
[debug] Locals: ('self', 'c')
[debug] Parent attributes: {'a': 10, 'b': 10}
1000


texts: Speeding up script for processing three huge files

texts:
I have three huge files I need to process in order to rearrange the data contained within.

The first file is a list of English example sentences (468,785 lines long).
A typical line from this file looks like this:

120033#eng#Creativity is an important aspect for the development of human.

The second file is a list which tells me the ID of the equivalent sentences (7,243,419 lines) in the third file. A typical line from the second file looks like this:

1#77

This tells me that the English sentence with ID "1" in the first file matches a translation with ID "77" in the third file.

The third file contains a list of the translated sentences (2,945,676 lines). A typical line from this file looks like this:

1#cmn#我們試試看！

Here is the script I am using to get each line from file one, find which sentences it links to in file 2 and then get the matching sentence from file 3:

with open("eng_lines.txt") as f:
    eng_lines = f.readlines()
with open("all_lines.txt") as f:
    all_lines = f.readlines()
with open("all_links.txt") as f:
    all_links = f.readlines()
for ln,line in enumerate(eng_lines):
    print ln,len(eng_lines)
    with open("matches.txt", "a") as matches:
        matches.write(line+"\n")
        hash = line.index("#")
        sentence_idA = line[:hash]
        for line2 in all_links:
            hash = line2.index("#")
            link_a = line2[:hash]
            link_b = line2[hash+1:].strip()
            if (link_a==sentence_idA):
                for line3 in all_lines:
                    hash = line3.index("#")
                    sentence_idB = line3[:hash]
                    if (sentence_idB==link_b):
                        matches.write(line3+"\n")

This process is going to take a LONG time (about a year given that each iteration is currently taking about a minute to process on my i7 PC).


texts: How to eliminate repetitive serializers and API Viewsets in Django Rest Framework

texts:
I built an backend using Django and the django-rest-framework and realized that a lot of the code snippets (mainly classes) are similar. Is there any better way? I tried to wrap them into a very generic class, but didn't succeed yet. This is what I mean by "similar serializers":
...
class DeviceSerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = Device

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = User
...

Then there are the viewsets:
...
class DeviceAPI(mixins.ListModelMixin, viewsets.GenericViewSet):
    model = Device
    serializer_class = DeviceSerializer
    queryset = Device.objects.all()

class UserAPI(mixins.ListModelMixin, viewsets.GenericViewSet):
    model = User
    serializer_class = UserSerializer
    queryset = User.objects.all()
...

This goes on for about 150 lines of code as I have a lot of models. I tried wrapping them into one generic serializer and one viewset, but the Swagger generator didn't register all the serializer classes then.


texts:
I would like to receive feedback on my coding interview for the following problem:

  Bracket Match

  A string of brackets is considered correctly matched if every opening
  bracket in the string can be paired up with a later closing bracket,
  and vice versa. For instance, “(())()” is correctly matched, whereas
  “)(“ and “((” aren’t. For instance, “((” could become correctly
  matched by adding two closing brackets at the end, so you’d return 2.

  Given a string that consists of brackets, write a function
  bracketMatch that takes a bracket string as an input and returns the
  minimum number of brackets you’d need to add to the input in order to
  make it correctly matched.

  Explain the correctness of your code, and analyze its time and space
  complexities.

    Examples:

    input:  text = “(()” output: 1

    input:  text = “(())” output: 0

    input:  text = “())(” output: 2 Constraints:

    [time limit] 5000ms

    [input] string text

    1 ≤ text.length ≤ 5000 [output] integer

def bracket_match(text):
    diffCounter = 0
    answer = 0
    length = len(text)

    for i in range(length):
        if text[i] == '(':
            diffCounter += 1
        elif text[i] == ')':
            diffCounter -= 1
        if diffCounter < 0:
            diffCounter += 1
            answer +=1

    return answer + diffCounter

text1=")))("
print(bracket_match(text1))


texts: Use reflection to check for class methods with a custom attribute

texts:
This code is within a ViewModelBase class.  I have a custom attribute defined that is meant to trigger methods when a property is changed.  The following runs as the ViewModel is being constructed.  The idea is to catalog the methods that should be triggered upon a property changed event based on the property name.

It works but I was wondering if there was a way to more efficiently identify methods with the custom attribute, since there are a lot of methods to loop through and generally only one or two methods that have the sought-after attribute.

ExecuteOnPropertyChangedMap = new Dictionary<string, List<MethodInfo>>();

foreach (var method in this.GetType().GetMethods(
    BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy))
{
    var execAttributes = method.GetCustomAttributes(typeof(ExecuteOnPropertyChangedAttribute), true);
    foreach (ExecuteOnPropertyChangedAttribute execAttribute in execAttributes)
    {
        if (execAttribute == null) continue;

        foreach (string propertyName in execAttribute.PropertyNames)
        {
            if (!ExecuteOnPropertyChangedMap.ContainsKey(propertyName))
                ExecuteOnPropertyChangedMap.Add(propertyName, new List<MethodInfo>());

            ExecuteOnPropertyChangedMap[propertyName].Add(method);
        }
    }
}


texts:
Here is the code:

pub fn insertion_sort<T>(vec: &mut Vec<T>) where T: Ord + Copy {
    fn insert<U>(vec: &mut Vec<U>, pos: usize, value: U) where U: Ord + Copy {
        assert!(pos > 0);
        let mut pos: usize = pos - 1;
        loop {
            let value_at_pos = vec[pos];
            if value_at_pos <= value {
                break;
            }
            vec[pos + 1] = value_at_pos;
            if pos == 0 {
                vec[pos] = value;
                return ();
            }
            pos -= 1;
        }
        vec[pos + 1] = value;
    }
    for i in 1..vec.len() {
        let value = vec[i];
        insert(vec, i, value);
    }
}

#[test]
fn test_insertion_sort() {
    let mut vec = vec![9, 8, 7, 11, 10];
    insertion_sort(&mut vec);
    let vec_res: Vec<_> = (7..12).collect();
    assert_eq!(vec, vec_res);
}

It's slightly more complex than in textbooks due to the fact negative integers are not allowed for indexing in Rust, not a huge problem though.


texts: Print a "shebang" line, or prepend it to a file

texts:
This is a sort-of-useless "utility" I wrote to learn my way around shell programming better.

My concerns are:

Is the code readable? Could it be more efficient, or just simpler? The logic ends up being a little complicated and I have a lot of nested if statements. Should I use 4 tabs instead of 2?
Is the interface itself (the flags, arguments, etc) intuitive? Is the documentation clear?
How easily this could be ported to Bash? As far as I remember, the only Zsh-specific feature I use here is zparseopts, but I've been casually using Zsh for a while and I could have forgotten some of the inconsistencies between shells.

# shebang [-iv] [-t interpreter] [-I extension] [-J [extension]] [filename]
#
# If no filename is given, print a shebang. If a filename is given, append a shebang to the file and print its contents. If a filename is given and the -I or -J options are specified, append a shebang to the file in place.
#
# OPTIONS
#   -i
#     Interactive mode; ask for confirmation first.
#   -I
#     Modify "filename" in place (as in `sed -i`) using specified extension. Extension is mandatory.
#   -J
#     Same as -I, but extension is mandatory only if the string "gsed" cannot be found in the output of `which sed`. Overridden by -I.
#   -t
#     Specify an interpreter, e.g. `shebang -t zsh` produces "#!/usr/bin/env zsh"
#   -v
#     Print (to stderr) the interpreter being used.

shebang () {
  local interpreter
  local inplace
  local inplace2
  local verbose
  local interactive
  local input_shebang
  local shebang
  local continue
  local sed_command
  local gsed_avail
  zparseopts -D t:=interpreter I:=inplace J::=inplace2 v=verbose -i=interactive
  (( $? )) && return 1

  if [[ -n $1 ]]; then
    input_shebang=$(sed -n '1 { /^#!/ p; }' "$1")
    if (( $? )); then
      echo "Unable to read $1." >&2
      return 1
    fi
    if [[ -n "$input_shebang" ]]; then
      echo "$1 already has a shebang." >&2
      return 1
    fi
  fi

  if [[ (-z "$interpreter") && (-z "$1") ]]; then
    echo "The -t option is mandatory if no argument is supplied." >&2
    return 1
  fi

  if [[ (-z "$interpreter") && (-n "$1") ]]; then
    interpreter=$(filename=$(basename "$1"); [[ "$filename" = *.* ]] && echo "${filename##*.}" || echo '')  # grab extension
    interpreter=${interpreter:#(* *|* | *)}  # "extensions" with whitespace probably aren't legit
    interpreter=${interpreter:-sh}  # assume sh if no extension and no -t option
  else
    interpreter="$interpreter[2]"
  fi

  shebang="#!/usr/bin/env $interpreter"

  if [[ -n $verbose ]]; then
    echo "Using interpreter '$interpreter'" >&2
  fi

  if [[ -n $interactive ]]; then
    read -q "continue?Shebang will be '$shebang'. Ok? y/n: "
    [[ $continue == n ]] && return 1
  fi

  if [[ -z "$1" ]]; then
    echo $shebang
  else
    gsed_avail=$(command which -s gsed && echo 1)
    echo $gsed_avail

    if [[ -n $gsed_avail ]]; then
      sed_command="1 i\\$shebang\n"
      if [[ -n $inplace ]]; then
        gsed "${inplace/-I/-i}" "$sed_command" "$1"
      elif [[ -n $inplace2 ]]; then
        gsed "${inplace2/-J/-i}" "$sed_command" "$1"
      else
        gsed "$sed_command" "$1"
      fi
    else
      sed_command='1 i\
REPLACEME\n'  # need to use single quotes to preserve the line break
      sed_command=${sed_command/REPLACEME/$shebang}  # work around the single quotes
      if [[ -n $inplace ]]; then
        sed "${inplace/-I/-i}" "$sed_command" "$1"
      elif [[ (-n $inplace2) && (-z ${inplace2#-J}) ]]; then
        echo "'-J' was given without an argument, but 'gsed' is unavailable. Specify an explicit extension or use -I."
      elif [[ -n ${inplace2#-J} ]]; then
        sed "${inplace2/-J/-i}" "$sed_command" "$1"
      else
        sed "$sed_command" "$1"
      fi
    fi
  fi
}


texts: Modular exponentiation optimisation in Java

texts:
As part of an assignment in Cryptography I've been asked to write code that involves calculating modular exponentiation. The BigInteger modPow is not allowed in this case, we have to implement it ourselves.

I have the assignment working, but I think my modular exponentiation function is not the greatest in terms of run time. It's based on the right-to-left binary method.
 Here is it :

The algorithm calculates (a^b) mod c.

private static BigInteger modulo(BigInteger a, BigInteger b, BigInteger c) {

    BigInteger x = BigInteger.ONE;
    final BigInteger TWO = new BigInteger("2", 16);

    while(b.compareTo(BigInteger.ZERO) > 0) {

        BigInteger compareVal = b.mod(TWO);
        if(compareVal.compareTo(BigInteger.ONE) ==0) {
            x = (x.multiply(a)).mod(c);
        }

        a = (a.multiply(a)).mod(c);
        b = b.divide(TWO);
    }
    return x.mod(c);

}

However, that solution uses 2 comparisons, 2 multiplications and a division within the loop. Can anyone point me in the direction of something more efficient? I'm not looking for a specific answer here, maybe just some ideas. Googling modular exponentation doesn't yield much that's useful in this case, and when I time this algorithm it's performance is very poor.

Any direction or feedback would be hugely appreciated.


texts: Can I use a header tag in footer inside section?

texts:
I want to know if I can use a header tag in footer inside section.  I also want to know if this follows SEO.

For example, I made four section boxes in footer:

Box 1

Box 2

Box 3


texts:
I just figured out how to do a building menu with a progression feature in c++ console application.

What this code does:

It simply offers you a choice to build a building and then prints
the progression like: 1% - 9% erasing and printing one number at a time (Which is the kind of the core feature that I struggled a lot with).

then prints "Building done".

I would like to have some thoughts and comments on how to:

Make this code simpler in any way .
Did someone else make the same feature and how did you implement it?
General thoughts on the code
How would you structure it?

std::string building;

std::cout << "-CONSTRUCTION MENU-" << std::endl << std::endl;

std::cout << "1. Barrack" << std::endl << std::endl;

std::cout << "Build: ";

std::cin >> building;

if (building == "1" || building == "Barrack" || building == "barrack")
{
    std::string sentence[10] = { "1%", "2%","3%", "4%", "5%", "6%", "7%", "8%", "9%" };

    for (int index = 0; sentence[index] != sentence[9]; index++)
    {
        std::cout << sentence[index] << std::flush;
        std::cout << "\b\b";
        Sleep(150);

        if (index == 8)
        {
            system("cls");
            std::cout << "Building done" << std::endl;
            system("pause");
            break;
        }
    }
}


texts: Display all Prime Factors from user input

texts:
The following program is written in python. Is there a more efficient way to write this program? Suggestions and criticism are welcome. You can also comment about my variable naming practices and code readability.

# int ----> list
# returns factor list of a num
def factor(num):
    factors = []
    for i in range(num):
        if not (i == 0 or i == 1):
            if num % i == 0:
                factors.append(i)
    return factors

# int ----> bool
# returns true if num is prime
def prime(num):
    for i in range(num):
        if not(i == 0 or i == 1):
            if num % i == 0:
                return False
    return True

# main
# prints the factors of a number which are prime
def primeFactorization():
    num = int(input("Enter the number: "))
    factors = factor(num)
    prime_factors = []

    for item in factors:
        if prime(item):
            prime_factors.append(item)
    print(prime_factors)

primeFactorization()


texts: Initializing super class's variable from sub class

texts:
I have written down codes something like below:

abstract class ZmqSubscriber {
   protected String zmqPort, zmqIp, zmpTopic;
   public void start() {
      init();
      // connect to zeroMQ with initialized zmq port, ip, topic and receive data
   }
   abstract protected void init();
}

abstract class Collector extends ZmqSubscriber {
   @Override
   protected void init() {
      super.zmqIp = this.zmqIp;
      super.zmqPort = this.zmqPort;
      super.zmqTopic = this.zmqTopic;
   }
   public void otherMethod() { //blablabla }
}

class Syncronizer extends ZmqSubscriber() {
   //blablabla
}

class SensorCollector extends Collector {
   private String zmqPort, zmqIp, zmpTopic;
   @Override
   protected void init() {
      //this.zmqIp, this.zmpPort, this.zmqTopic will be already initialized at this moment using Spring framework's xml config file. In this way we can change ip and port at any time
      super.zmqIp = this.zmqIp;
      super.zmqPort = this.zmqPort;
      super.zmqTopic = this.zmqTopic;
      super.init();
   }
   // getters & setters for zmq port, ip, topic
}
class BeconCollector extends Collector {
   // blablabla like SensorCollector
}

I definitely need three-level extends and this code is running well.
But I think the way of initializing super class's (ZmqSubscriber) instance variable (zmqPort, zmqIp, zmqTopic) in sub class (SensorCollector) is not elegant, I can't say exactly why I think the part is not elegant, but I'm just "Feeling" it's not right when I looking at the code, maybe it is because of the duplicated code in init() method...

Could anyone suggest more elegant architecture?


texts: Check column values are in different sets

texts:
I have a data frame called data with lots of columns, and Country is one of them.

I created a new logical column called train, which is true when the row belongs to the train set and false otherwise.  The data frame is already sampled.

Now I want to be sure that there are no countries in both train and test sets with this code:

nrow( data[ data[ data$train, ]$Country %in% data[! data$train, ]$Country, ] ) == 0

which evaluates to true, so I guess I sampled correctly.  But that line makes my eyes bleed.


texts: Refactoring a collection of if statements that contain 2 arguments.

texts:
At the moment I have seven if statements that resemble the following code:

if(hit.collider.gameObject.tag == "Colour1" && start_time > look_at_time)
        {
            new_colour1.ChangeObjectMaterialColour(hit.collider.gameObject.renderer.material.color);

            var colums = GameObject.FindGameObjectsWithTag("column");
            foreach( GameObject c in colums)
                c.GetComponent<MeshRenderer>().materials[1].color = new_colour1.orignalMaterial;
        }

        else if(hit.collider.gameObject.tag == "Colour2" && start_time > look_at_time)
        {

            new_colour2.ChangeObjectMaterialColour(hit.collider.gameObject.renderer.material.color);
            var colums = GameObject.FindGameObjectsWithTag("column");
            foreach( GameObject c in colums)
                c.GetComponent<MeshRenderer>().materials[1].color = new_colour2.orignalMaterial;
        }

Each statement is roughly 6 lines of code and takes up a lot of space and can be a little tricky to read. What I'm wanting to do is find a way to re factor this so that my code is little less clunky and doesn't take up too much space.

I had thought about changing my collection of if statements into a switch statement but I discovered that switch statements can't handle two arguments like I have above. If there any other way I can re factor my code but keep the same functionality or am I stuck with my collection of if statements?


texts: Get list of unique parents from childrens list

texts:
Parent has list of Children. I only have access to the list of children. I need to get list of unique parents from the List of Children. Is there a better/faster/more efficient way of doing it than this?

var temp = new HashSet<Parent>(
                        (from child in program.Children
                        select child.Parent).ToList());


texts:
I want to write a very simple std::string like compile-time const char* string.

I need to work with strings in the compiletime, just like with strings, I implemented basic functions.

class cstring final {
const char* str_;
std::size_t size_;

public:
constexpr cstring(const char* str, std::size_t size, std::size_t prefix = 0, std::size_t suffix = 0) noexcept
    : str_{str + prefix},
        size_{size - prefix - suffix} {}

template <std::size_t N>
constexpr cstring(const char (&str)[N]) noexcept : cstring{str, N - 1, 0, 0} {}

constexpr cstring() noexcept : cstring{nullptr, 0, 0, 0} {}

cstring(const std::string& str) noexcept : cstring{str.data(), str.size(), 0, 0} {}

constexpr cstring(const cstring&) = default;

cstring& operator=(const cstring&) = default;

constexpr std::size_t size() const noexcept { return size_; }

constexpr std::size_t length() const noexcept { return size_; }

constexpr std::size_t max_size() const noexcept {
    return (std::numeric_limits<std::size_t>::max)();
}

constexpr bool empty() const noexcept { return size_ == 0; }

constexpr const char* begin() const noexcept { return str_; }

constexpr const char* end() const noexcept { return str_ + size_; }

constexpr const char* cbegin() const noexcept { return begin(); }

constexpr const char* cend() const noexcept { return end(); }

constexpr const char& operator[](std::size_t i) const { return str_[i]; }

constexpr const char& at(std::size_t i) const {
    return (i < size_) ? str_[i]
                    : (throw std::out_of_range{"cstring::at"}, str_[0]);
}

constexpr const char& front() const { return str_[0]; }

constexpr const char& back() const { return str_[size_ - 1]; }

constexpr const char* data() const noexcept { return str_; }

constexpr cstring remove_prefix(std::size_t n) const {
    return {str_ + n, size_ - n};
}

constexpr cstring add_prefix(std::size_t n) const {
    return {str_ - n, size_ + n};
}

constexpr cstring remove_suffix(std::size_t n) const {
    return {str_, size_ - n};
}

constexpr cstring add_suffix(std::size_t n) const {
    return {str_, size_ + n};
}

constexpr cstring substr(std::size_t pos, std::size_t n) const {
    return {str_ + pos, n};
}

constexpr int compare(cstring other) const {
    return (size_ == other.size_) ? detail::StrCompare(str_, other.str_, size_)
                                : ((size_ > other.size_) ? 1 : -1);
}

friend constexpr bool operator==(cstring lhs, cstring rhs) {
    return lhs.compare(rhs) == 0;
}

friend constexpr bool operator!=(cstring lhs, cstring rhs) {
    return !(lhs == rhs);
}

std::string append(cstring s) const {
    return std::string{str_, size_}.append(s.str_, s.size_);
}

friend std::string operator+(cstring lhs, cstring rhs) {
    return std::string{lhs.str_, lhs.size_} + std::string{rhs.str_, rhs.size_};
}

friend std::ostream& operator<<(std::ostream& os, cstring str) {
    os.write(str.str_, str.size_);
    return os;
}

operator std::string() const { return std::string{str_, size_}; }
};

Note that I use C++11 in my project so I can't use std::string_view.


texts:
I am trying to compare Entries by their frequencies using Comparator. I wanna know if this piece of code would work for this case?

    // Creates entries
private class Entry {
    private String word;
    private long count;

    public Entry(String w, long c) {
        word = w;
        count = c;
    }

    public String getWord() { return word; }
    public long getCount() { return count; }

    public Entry(String entry) {
        String parts[] = entry.split("\t");
        word = parts[1].trim();
        count = new Long(parts[0].trim());
    }

    public String toString() {
        return "(" + word + "," + count + ")";
    }

}

    // compare Entry objects by their frequencies
private static Comparator<Entry> countComparator() {
    return new Comparator<Entry>() {
        public int compare(Entry e1, Entry e2) {
            if(e1.getCount() > e2.getCount()) {
                return 1;
            }
            else if(e1.getCount() < e2.getCount()) {
                return -1;
            }
            else {
                return 0;
            }
        }
    };
}


texts:
I'm a freshman in Python world, I used to program in C.

I wrote a function/method that returns the power of a number:

def pow(x, y):

    powered = x

    if y == 0:
        return 1

    while y > 1:
        powered *= x

        y -= 1

    return powered

Mine is a logic question (correctly): if I set y = 0 then it returns \$1\$, but on the last line of the code I wrote return powered then = x.

Does return work like as break?


texts:
Implement a queue using a linked list.

I'm looking for a code review, optimizations and best practices.

public class QueueAsLinkedList<T> {

    private Node<T> front;
    private Node<T> rear;
    private int size;

    public QueueAsLinkedList() {}

    private static class Node<T> {
        T item;
        Node<T> next;

        Node (T item, Node<T> next) {
            this.item = item;
            this.next = next;
        }
    }

    public void add(T item) {
        Node<T> node = new Node<T>(item, null);
        if (rear == null) {
            rear = node;
            front = node;
        } else {
            rear.next = node;
        }

        rear = node;
        size++;
    }

    public T remove() {
        if (front == null) {
            throw new NoSuchElementException();
        }
        T item = front.item;
        front = front.next;
        if (front == null) {
            rear = null;
        }
        size--;
        return item;
    }

    public T peek() {
        if (front == null) {
            throw new NoSuchElementException();
        }
        return front.item;
    }

    public int getCount() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public static void main(String[] args) {
        QueueAsLinkedList<Integer> ll = new QueueAsLinkedList<Integer>();
        ll.add(1);   ll.add(2); ll.add(3);
        while (!ll.isEmpty()) {
            System.out.println(ll.remove());
        }
    }
}


texts:
I was hoping that some more experienced programmers could help me make my implementation of Dijkstra's algorithm more efficient.

So far, I think that the most susceptible part is how I am looping through everything in X and everything in graph[v].

My graph is formatted as:

g = {0:{1:2}, 1:{0:2, 2:6}, 2:{1:6}}

This is my full code, where n is the number of vertices and m is the number of edges, formatted like this:

n m
v1 v2 weight
...

from sys import stdin
n, m = stdin.readline().split()
n, m = int(n), int(m)
graph = {i:{} for i in range(n)}
V = [i for i in range(n)]

# paths to themselves have zero length
for i in range(m):
    a, b, t = stdin.readline().split()
    a, b, t = int(a), int(b), int(t)
    graph[a][b] = t
    graph[b][a] = t

def Dijkstra(graph, start):
# places we've found shortest path for
X = [start]
# list of shortest path length to vertices
A = [0]*len(graph)

    while X != V:
        #Dijkstra's greedy criterion
        U = float('inf')
        W = float('inf')
        uw = float('inf')
        for v in X:
            for w in graph[v]:
                if A[v] + graph[v][w] < uw and w not in X:
                    uw = A[v] + graph[v][w]
                    U = v
                    W = w
        X.append(W)
        try:
            A[W] = uw
        except:
            return A

A = Dijkstra(graph, 0)
B = Dijkstra(graph, n-1)
C = [A[i] + B[i] for i in range(n)]
print(max(C))


texts: Validating region/state/province codes for different countries

texts:
I have a large table in which I store region/state/province codes (two letters) from different countries. I use these  region codes further downstream for multiple process. One of the steps I do is a cleanup of regions to ensure it is a valid region/state/province code. I have a lookup table consisting of a country vs region code to validate each column.

6 columns are validated separately. Is there a way to do this better?

UPDATE  table_region
SET     a_region = NULL
WHERE   a_region IS NOT NULL
        AND country IS NOT NULL
        AND dbo.IsValidRegion(country,a_region) = 0;

UPDATE  table_region
SET     b_region = NULL
WHERE   b_region IS NOT NULL
        AND country IS NOT NULL
        AND dbo.IsValidRegion(country,b_region) = 0;

UPDATE  table_region
SET     c_region = NULL
WHERE   c_region IS NOT NULL
        AND country IS NOT NULL
        AND dbo.IsValidRegion(country, c_region) = 0;

UPDATE  table_region
SET     d_region = NULL
WHERE   d_region IS NOT NULL
        AND country IS NOT NULL
        AND dbo.IsValidRegion(country,d_region) = 0;

UPDATE  table_region
SET     e_region = NULL
WHERE   e_region IS NOT NULL
        AND country IS NOT NULL
        AND dbo.IsValidRegion(country, e_region) = 0;

UPDATE  table_region
SET     f_region = NULL
WHERE   f_region IS NOT NULL
        AND country IS NOT NULL
        AND dbo.IsValidRegion(country, f_region) = 0;

The function is like this:

ALTER Function [dbo].[IsValidRegion](@country VARCHAR(20), @value

VARCHAR(20))
Returns INT
AS
BEGIN
    DECLARE @res INT
    BEGIN
        IF EXISTS (SELECT 1 FROM mapping.region WHERE country = @country AND region_code = @value)
            SELECT @res = 1
        ELSE
            SELECT @res = 0
    END
    RETURN @res
END


texts: Expanding powers of expressions of the form ax+b

texts:
I solved the following problem:

  Write a function expand that takes in an expression with a single, one character variable, and expands it. The expression is in the form (ax+b)^n where a and b are integers which may be positive or negative, x is any one-character long variable, and n is a natural number. If a = 1, no coefficient will be placed in front of the variable. If a = -1, a "-" will be placed in front of the variable.
  The expanded form should be returned as a string in the form ax^b+cx^d+ex^f... where a, c, and e are the coefficients of the term, x is the original one character variable that was passed in the original expression and b, d, and f, are the powers that x is being raised to in each term and are in decreasing order. If the coefficient of a term is zero, the term should not be included. If the coefficient of a term is one, the coefficient should not be included. If the coefficient of a term is -1, only the "-" should be included. If the power of the term is 0, only the coefficient should be included. If the power of the term is 1, the caret and power should be excluded.

Examples:

expand("(p-1)^3");      // returns "p^3-3p^2+3p-1"
expand("(2f+4)^6");     // returns "64f^6+768f^5+3840f^4+10240f^3+15360f^2+12288f+4096"
expand("(-2a-4)^0");    // returns "1"
expand("(-12t+43)^2");  // returns "144t^2-1032t+1849"
expand("(r+0)^203");    // returns "r^203"
expand("(-x-1)^2");     // returns "x^2+2x+1"

My solution passed all tests but I would like to know how it can be improved.

function expand(str) {
    const fac = n => n < 2 ? 1 : n * fac(n - 1);
    let result = '', [_, a, x, b, n] = str.match(/\((-?\d*)([a-z])([-+]\d+)\)\^(\d+)/);

    a = a ? a == '-' ? -1 : parseInt(a) : 1;
    b = parseInt(b); n = parseInt(n);

    for (let i = n; i >= 0; i--) {
        let k = n - i;
        let c = !b && k > 0
            ? 0
            : a**i * b**k * (k == 0
                ? 1
                : fac(n) / (fac(k) * fac(n - k)));

        if (Math.abs(c) == 1 && i > 0) c = c > 0 ? '+' : '-';
        else c = c > 0 ? `+${c}` : c;
        if (c) result += c;

        if (i > 0 && c) result += x;
        if (i > 1 && c) result += `^${i}`;
    }

    return result[0] == '+' ? result.substr(1) : result;
}

I got this problem from a coding challenges site. https://www.codewars.com/kata/binomial-expansion All the context that i had to solve it came from the description of the task.

I did not try to obfuscate the code. As Roland Illig stated, most of the single-letter variables come from the task. Variables a, x, b, n come from the parts of the input expression of the form (ax+b)^n. Variable k comes from a math formula n!/(k!(n-k)!) for the binomial coefficient. Variable c is the coefficient of the term being formed, and its mentioned in ax^b+cx^d+ex^f. So names come from problem's domain.

I mostly just do coding challenges for fun, and I like to golf things a bit. I concede the code lacks readability though.

My main concern is that small numbers like 203 have large factorials and produce overflow. One of the test cases is expand("(r+0)^203");    // returns "r^203". I did not wanted to treat this case separately. Hence I used conditions !b && k > 0 and k == 0 to avoid calculating factorials for "large" n when b == 0. I would like to change this with a better approach for calculating the binomial coefficients. Sadly I don't know enough math.

If someone solves this problem differently I would love to see their code.

I don't have too much experience writing questions in stackexchange and English is not my native language. Tried to format the text to the best of my ability. Thanks all for your patience.


texts: Removing duplication in horizontal and vertical checks

texts:
// Check horizontals
for (int y = 0; y < sGridHeight; y++)
{
    Shape* groupShape = nullptr;
    int groupSize = 0;
    for (int x = 0; x < sGridWidth; x++)
    {
        GridItem* gridItem = GetItem(x, y);
        Shape* shape = gridItem->GetShape();
        if (shape == groupShape)
        {
            groupSize++;
            if (groupSize == m_MatchSize)
            {
                g_Audio->PlaySound(m_GemDestroyedSound.c_str());
                m_Score += shape->GetScore();
                for (int tx = x - m_MatchSize + 1; tx <= x; tx++)
                {
                    RANDOMIZE(GetItem(tx, y))
                }
                return;
            }
        }
        else
        {
            groupSize = 1;
            groupShape = shape;
        }
    }
}

// Check verticals
for (int x = 0; x < sGridWidth; x++)
{
    Shape* groupShape = nullptr;
    int groupSize = 0;
    for (int y = 0; y < sGridHeight; y++)
    {
        GridItem* gridItem = GetItem(x, y);
        Shape* shape = gridItem->GetShape();
        if (shape == groupShape)
        {
            groupSize++;
            if (groupSize == m_MatchSize)
            {
                g_Audio->PlaySound(m_GemDestroyedSound.c_str());
                m_Score += shape->GetScore();
                for (int ty = y - m_MatchSize + 1; ty <= y; ty++)
                {
                    RANDOMIZE(GetItem(x, ty))
                }
                return;
            }
        }
        else
        {
            groupSize = 1;
            groupShape = shape;
        }
    }
}

Is there an easy way to clean this up? It seems like a lot of code duplication.

I have no qualms about using #defines, and I cannot use C++11.


texts: Function to spell numbers below 1,000,000,000

texts:
I wrote simple code to spell the number below 1,000,000,000. It works perfectly as per my intention. However, I do think my code is a little bit messy since I only able to imagine of using decision statements in my function/method.

I'm still learning in writing Python function/method code. I will be glad if anyone here can review my code and comment on how to improve it.

def main():
    value = int(input("\nPlease enter a positive integer < 1000000000 : "))
    if value < 100:
        print(processDigit(value))
    elif value > 100:
        print(intName(value))

# turns a number into its English name
def intName(number):
    part = number
    nameMillion = ""
    nameThousand = ""
    nameHundred = ""

    if part >= 1000000:
        divide = part // 1000000
        part = part % 1000000
        divide1 = divide // 100
        part1 = divide % 100
        nameMillion = digitName(divide1) + " hundred" + processDigit(part1) + " million "

    if part >= 1000:
        divide = part // 1000
        part = part % 1000
        divide1 = divide // 100
        part1 = divide % 100
        nameThousand = digitName(divide1) + " hundred" + processDigit(part1) + " thousand "

    if part >= 100:
        divide = part // 100
        part = part % 100
        nameHundred = digitName(divide) + " hundred" + processDigit(part)

        return nameMillion + nameThousand + nameHundred

# process the three digit number
def processDigit(number):
    part = number
    name = ""

    if part >= 20:
        name = name + " " + tensName(part)
        part = part % 10

    elif part >= 10:
        name = name + " " + teenName(part)
        part = 0

    if part > 0:
        name = name + " " + digitName(part)

    return name

# turns a digit into its English name
def digitName(digit):
    if digit == 1: return "one"
    if digit == 2: return "two"
    if digit == 3: return "three"
    if digit == 4: return "four"
    if digit == 5: return "five"
    if digit == 6: return "six"
    if digit == 7: return "seven"
    if digit == 8: return "eight"
    if digit == 9: return "nine"
    return ""

# turns a number between 10 and 19 into its English name
def teenName(number):
    if number == 10: return "ten"
    if number == 11: return "eleven"
    if number == 12: return "twelve"
    if number == 13: return "thirteen"
    if number == 14: return "fourteen"
    if number == 15: return "fifteen"
    if number == 16: return "sixteen"
    if number == 17: return "seventeen"
    if number == 18: return "eighteen"
    if number == 19: return "nineteen"
    return ""

# gives the name of tens part of a number between 20 and 99
def tensName(number):
    if number >= 90: return "ninety"
    if number >= 80: return "eighty"
    if number >= 70: return "seventy"
    if number >= 60: return "sixty"
    if number >= 50: return "fifty"
    if number >= 40: return "fourty"
    if number >= 30: return "thirty"
    if number >= 20: return "twenty"
    return ""

# start the program
main()


texts: Does using SharedPreferences drain resources?

texts:
I have created class that uses SharedPreferences to store and retrieve application settings. Is it good idea to access SharedPreferences each time I need parameters? Will it drain system resources?

class MqttSettings
{

    public static final String ADDRRESS ="address";
    public static final String PORT ="port";
    public static final String USERNAME ="username";
    public static final String PASSWORD ="password";
    public static final String CLIENTID ="clientid";

    public  SharedPreferences preferences;

    public  void setAddress(String value) {
        preferences.edit().putString(ADDRRESS, value ).commit();
    }
    public  void setPort(int value) {
        preferences.edit().putInt(PORT, value ).commit();
    }
    public  void setUsername(String value) {
        preferences.edit().putString(USERNAME, value ).commit();
    }
    public  void setPassword(String value) {
        preferences.edit().putString(PASSWORD, value ).commit();
    }

    public  void setClientId(String value) {
        preferences.edit().putString(CLIENTID, value ).commit();
    }

    public  String getAddress() {
        return preferences.getString(ADDRRESS,"192.168.1.8");
    }
    public  int getPort() {
        return preferences.getInt(PORT,8883);
    }
    public  String getUsername() {
        Log.d(Utils.LOGTAG,"getting username");
        String r = null;
        try {
            r= preferences.getString(USERNAME,"");
            Log.d(Utils.LOGTAG,"getting username preferences");
        } catch (Exception e) {
            Log.d(Utils.LOGTAG,"got exception "+e.getMessage());
            e.printStackTrace();
        }
        Log.d(Utils.LOGTAG,"getting username return");
        return r;
    }
    public  String getPassword() {
        Log.d(Utils.LOGTAG,"getting password");
        return preferences.getString(PASSWORD,"");
    }
    public  String getClientId() {
        return preferences.getString(CLIENTID,"");
    }

    public  String getUri()
    {
        String  uri ="tcp://";
        uri=uri+getAddress()+":"+getPort();
        Log.d(Utils.LOGTAG,uri);
        return uri;

    }

    public MqttSettings(SharedPreferences preferences)
    {
        this.preferences = preferences;
    }

}


texts:
I am learning to write a multi-threaded linked list class implementation with basic functionality such as push to front or back, pop_back and read. I came up with this implementation:

#include <iostream>
#include <thread>
#include <mutex>
std::mutex m;
template<class T>
class Node{
    public:
    T data;
    Node* next;
    Node(T data):data(data),next(NULL){}
};
template<class T>
class List{
  Node<T> *head;
  public:
  List():head(NULL){}
  List(const List<T>&)=default;               //default copy constructor
  List& operator =(const List<T>&)=default;   //default assignment
  List(List<T>&&)=default;                    //default move constructor
  List& operator =(List<T>&&)=default;        //default move assignment
  void push_front(T val){                    //push data to front
    std::lock_guard<std::mutex> lock(m);
    Node<T>* temp=new Node<T>(val);
      if(head==NULL)
        head=temp;
      else{

          temp->next=head;
          head=temp;
      }
  }
  void pop_back(){                      //pop from back
      std::lock_guard<std::mutex> lock(m);
      Node<T>* cur=head;
      while(cur->next->next)
      cur = cur->next;
      Node<T>* temp=cur->next;
      delete(temp);
      cur->next=NULL;
  }
  T front(){                 //return front of Linkedlist
      if(head!=NULL)
      return head->data;
      return -1;
  }
  void push_back(T val){                    //push at back
      std::lock_guard<std::mutex> lock(m);
      Node<T>* temp=new Node<T>(val);
      if(head==NULL)
        head=temp;
      else{
          Node<T>* cur=head;
          while(cur->next)
          cur = cur->next;
          cur->next=temp;
      }
  }
  int size(){               //return size
      int size=0;
      Node<T>* cur=head;
      while(cur){
        size++;
        cur=cur->next;
      }
      return size;
  }
  void display(){            //read from linked list
      std::lock_guard<std::mutex> lock(m);
      Node<T>* cur=head;
      while(cur){
          std::cout<<cur->data<<" ";
          cur = cur->next;
      }
      std::cout<<"\n";
  }
  ~List(){
    Node<T>* current = head;
    Node<T>* next;
    while (current != NULL) {
        next = current->next;
        delete current;
        current = next;
    }
  }
};

But, I am not very sure if I covered it right. Please share some opinions on how to make it perfect.
Also, I am targeting C++11, so please throw some pointers/suggestions in that area also.

In particular, I am looking for is answers to these questions:

Is this a correct approach for acquiring mutex in push() and display(), in a multi-threaded environment?
How can I prioritize the read/delete/write operations. For example, suppose 1 thread is displaying the data and another thread comes which wants to pop_back from the data. How do I make the changes so that my 2nd thread gets the priority while 1st thread was using my node.
I have not much worked with C++11 — I just started it few months ago — so I would like to know what more I should have in my class.
In case there are any possible bugs in this code, please let me know that too.


texts: Conway's Game of Life in Python, saving to an image

texts:
I have attempted to make conways game of life in Python, and then save the output into a picture.

Is there any way to make this more efficient?
Is there anything wrong with the logic? (Most of the pictures don't look quite correct)
Other?

import PIL.Image, random

WIDTH = 1366
HEIGHT = 768
ROUNDS = 10

DEAD = (0, 0, 0)
ALIVE = (0, 64, 255)

print("Creating image")
img = PIL.Image.new("RGB", (WIDTH, HEIGHT))
data = img.load()

print("Creating grid")
grid = []
for y in range(HEIGHT):
    grid.append([])
    for x in range(WIDTH):
        grid[y].append(random.randint(0, 1))

for i in range(ROUNDS):
    print("Starting round", i + 1, "of", ROUNDS)
    for y in range(HEIGHT):
        for x in range(WIDTH):
            n = 0
            for y2 in range(-1, 2):
                for x2 in range(- 1, 2):
                    if x2 != 0 and y2 != 0 and grid[(y + y2) % HEIGHT][(x + x2) % WIDTH] == 1:
                        n += 1
            if n < 2:
                grid[y][x] = 0
            elif n > 3:
                grid[y][x] = 0
            elif grid[y][x] == 1 and n > 1 and n < 4:
                grid[y][x] = 1
            elif grid[y][x] == 0 and n == 3:
                grid[y][x] = 1

print("Rendering image")
for y in range(HEIGHT):
    for x in range(WIDTH):
        if grid[y][x] == 1:
            data[x, y] = ALIVE
        else:
            data[x, y] = DEAD

print("Saving image")
img.save("gofl.png")


texts:
I want you to pick my code apart and give me some feedback on how I could make it better or simpler. Although, agree that generics should be used, instead of integers, let's punt on generics as a review for now.

public class CreateBinarySearchTree {

    private TreeNode root;

    public CreateBinarySearchTree() {
    }

    /**
     * Will create a BST imperative on order of elements in the array
     */
    public CreateBinarySearchTree(int[] a) {
        this();
        for (int i : a) {
            add(i);
        }
    }

    private static class TreeNode {
        TreeNode left;
        int item;
        TreeNode right;

        TreeNode(TreeNode left, int item, TreeNode right) {
            this.left = left;
            this.right = right;
            this.item = item;
        }
    }

    public void add(int item) {
        if (root == null) {
            root = new TreeNode(null, item, null);
            return;
        }

        TreeNode node = root;
        while (true) {
            if (item < node.item) {
                if (node.left == null) {
                    node.left = new TreeNode(null, item, null);
                    break;
                }
                node = node.left;
            } else {
                if (node.right == null) {
                    node.right = new TreeNode(null, item, null);
                    break;
                }
                node = node.right;
            }
        }
    }
}