texts: Option functional type implementation and scenarios

texts:
Have you ever being implementing Option<T> functional type? It is discussed here. Basically, it is about using IEnumerable<T> with no or only one element instead of potentially nullable object reference in C#. We can empower LINQ functionality to streamline processing reducing cyclomatic complexity because of no if(null) conditions anymore.

My adoption of the idea looks this way:

public struct Optional<T> : IEnumerable<T>
    where T : class
{
    public static implicit operator Optional<T>(T value)
    {
        return new Optional<T>(value);
    }

    public static implicit operator T(Optional<T> optional)
    {
        return optional.Value;
    }

    Optional(T value)
        : this()
    {
        Value = value;
    }

    public IEnumerator<T> GetEnumerator()
    {
        if (HasValue)
            yield return Value;
    }

    T Value { get; }
    bool HasValue => Value != null;
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    public override string ToString() => Value?.ToString();
}

It is not so bad. We can use it as argument/return type with automatic conversion to/from T when necessary.

Consumption example might look like this:

 var p = new Product("Milk");
 var basket = ShoppingBasket.Empty
        .Place(p)
        .Place(p)
        .Place(null);

It creates basket with single basket entry for two milk boxes if the following is defined:

public static class ShoppingBasket
{
    public static readonly IEnumerable<BasketItem> Empty =
        Enumerable.Empty<BasketItem>();

    public static IEnumerable<BasketItem> Place(
        this IEnumerable<BasketItem> basket,
        Optional<Product> product) =>
            basket
                .SetOrAdd(
                    i => product.Contains(i.Product),
                    i => i.OneMore(),
                    product.Select(p => new BasketItem(p, 1)))
                .ToArray();
}

Where:

public class BasketItem
{
    public BasketItem(Product product, int quantity)
    {
        Product = product;
        Quantity = quantity;
    }

    public Product Product { get; }
    public int Quantity { get; }
    public BasketItem OneMore() =>
        new BasketItem(Product, Quantity + 1);
}

public class Product
{
    public Product(string name)
    {
        Name = name;
    }

    public string Name { get; }
}

I use this general IEnumerable<T> extension:

public static class EnumerableHelper
{
    public static IEnumerable<T> SetOrAdd<T>(
        this IEnumerable<T> source,
        Func<T, bool> predicate,
        Func<T, T> set,
        params T[] add)
    {
        return source
            .SetOrAdd(predicate, set, add as IEnumerable<T>);
    }

    public static IEnumerable<T> SetOrAdd<T>(
        this IEnumerable<T> source,
        Func<T, bool> predicate,
        Func<T, T> set,
        IEnumerable<T> add)
    {
        var empty = Enumerable.Empty<T>();
        foreach (var item in source)
            if (predicate(item))
            {
                yield return set(item);
                add = empty;
            }
            else
                yield return item;

        foreach (var item in add)
            yield return item;
    }
}

Well, it is pretty functional as far as I can see. But the question is: does it make any sense? Cyclomatic complexity is very low in ShoppingBasket class. But the same time we still have three "virtual paths" of execution to test - for "add" and "replace" in the Place() method + we also need to test for null product argument.

The problem is that they are almost invisible. What do you say? Would you personally prefer to maintain such kind of code in C#?


texts: Javascript: Profile Lookup from freecodecamp

texts:
This is my answer in freecodecamp "Basic Javascript: Profile Lookup" (third day trying javascript using Udemy and freecodecamp).

My problem with the code is the huge number of lines on my lookUpProfile function. I would like to minimize the lines of code of my lookUpProfile function, can you suggest me ways to achieve that?

//Setup
var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["Javascript", "Gaming", "Foxes"]
    }
];

function lookUpProfile(firstName, prop){
// Only change code below this line

  var contain = 0;
  if(firstName == "Akira"){
    contain = 0;
    if(contacts[contain].firstName == firstName)
      if(contacts[contain].hasOwnProperty(prop))
        return contacts[contain][prop];
      else
        return "No such property";
    else
      return "No such contact";
  }
  else if(firstName == "Harry"){
    contain = 1;
    if(contacts[contain].firstName == firstName)
      if(contacts[contain].hasOwnProperty(prop))
        return contacts[contain][prop];
      else
        return "No such property";
    else
      return "No such contact";
  }
  else if(firstName == "Sherlock"){
    contain = 2;
    if(contacts[contain].firstName == firstName)
      if(contacts[contain].hasOwnProperty(prop))
        return contacts[contain][prop];
      else
        return "No such property";
    else
      return "No such contact";
  }
  else if(firstName == "Kristian"){
    contain = 3;
    if(contacts[contain].firstName == firstName)
      if(contacts[contain].hasOwnProperty(prop))
        return contacts[contain][prop];
      else
        return "No such property";
    else
      return "No such contact";

  }
  else
    return "No such contact";

// Only change code above this line
}

// Change these values to test your function
lookUpProfile("Akira", "lastName");


texts: Guessing Game: computer generated number between 1 and 100 guessed by user

texts:
The required output is stated just before the main() function. Is there a better way to achieve it? I feel like I am repeating code unnecessarily but am unable to find a better way to get the result. Not squeezing the code too much, like one liners, but reasonably using better logic.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#Time to play a guessing game.

#Enter a number between 1 and 100: 62
#Too high. Try again: 32
#Too low. Try again: 51
#Too low. Try again: 56

#Congratulations! You got it in 4 guesses.

import random

def main():

    return 0

if __name__ == '__main__':
    main()

print("Time to play a guessing game.")

val = random.randint(1, 100)
guess = 0
count = 1

guess = input("\n\t\tEnter a number between 1 and 100: ")
guess = int(guess)

print("")
print("randint is", val)
print("")

if (guess == val):
    print("\nCongratulations! You got it in", count, "guesses.")

while(guess != val):

    if guess > val:
        print("Too high. Try again:", guess)
        guess = input("\n\t\tEnter a number between 1 and 100: ")
        guess = int(guess)
        count = count + 1
        if guess == val:
            print("\nCongratulations! You got it in", count, "guesses.")
            break

    elif guess < val:
        print("Too low. Try again:", guess)
        guess = input("\n\t\tEnter a number between 1 and 100: ")
        guess = int(guess)
        count = count + 1
        if guess == val:
            print("\nCongratulations! You got it in", count, "guesses.")
            break
    else:
        pass

print("")


texts:
I created a class that I plan on using to autoload my project classes (20-30 classes) maximum. I wonder if there is anything, anything at all, that I can improve on this class to improve it any further.

Please let me know your thoughts below.

<?php
/**
 * YodaCMS, content management system.
 *
 * @info         This class autoloads project classes.
 * @author       Someone Someone <example@something.com>
 * @version      0.0.1
 * @package      YodaCMS
 *
 */

class autoLoader {
    private static $loadedLibrarys;

    public function __construct() {
        $loadedLibrarys = array();
    }

    public static function loadLibrarys() {
        newLibrary("testClass", new testClass());
    }

    private function newLibrary($lName, $lValue) {
        if (!$this->tryLoadLibrary($lName, $lValue)) {
            print_r('Error loading library: ' . $lName);
        }
    }

    public function tryLoadLibrary($lName, $lValue) {
        include(ROOT . '/applocation/base/classes/'.$lName.'.class.php');
        $this->loadedLibrarys[$lName] = $lValue;
        return true;
    }
}


texts:
I have written a program to optimize a point cloud in dependency of their distances to each other. The code works very well for smaller number of points. For 1700 points it takes ca. 6 minutes. But I have 300000 points in the point cloud. The code is still running after almost 30 hours.

I am sure there is a pythonic way to optimze the code. But I do not know how can I reduce the calculation time and make the performance better. I have read alot about multithreding, chunk size etc. But I think there is no need for this size of data. I think, I am using the memory in a very bad way. Am I right? Here is the code:

import pickle
import math
import itertools
import gc

def dist(p0, p1):
    return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)

def join_pair(points, r):
    for p, q in itertools.combinations(points, 2):
        if dist(p, q) < r:
            points.remove(q)
            return True
    return False

if __name__ == "__main__":
    filename = 'points.txt'
    filename2 = 'points_modified.txt'
    mynumbers = []
    with open(filename) as f:
        for line in f:
            mynumbers.append([float(n) for n in line.strip().split(' ')])
        mynumbers = sorted(mynumbers, key=lambda tup: (tup[1], tup[0]))
    gc.collect()
    while join_pair(mynumbers, 3.6):
        pass

    with open (filename2,"w")as fp2:
        for j in range(len(mynumbers)):
            fp2.write(' '.join(map(repr, mynumbers[j]))+'\n')

and the input data is like the following:

661234.58 5763766.03 72.63
661254.81 5763765.08 75.04
661244.86 5763764.14 74.99
661234.90 5763763.21 74.94
661225.13 5763762.29 74.89


texts:
I was doing a standard problem of DP (dynamic programming) on SPOJ  Edit Distance using Python.

t = raw_input()

for i in range(int(t)):
   a,b = raw_input(),raw_input()

   r = len(a)
   c = len(b)
   x = [[0]*(c+1) for j in range(r+1)]

   for j in range(c+1):
       x[0][j] = j

   for j in range(r+1):
       x[j][0] = j

   for j in range(1,r+1):
       for k in range(1,c+1):
           if(b[k-1]!=a[j-1]):
              x[j][k] = min(x[j-1][k-1]+1,x[j-1][k]+1,x[j][k-1]+1)
           else:
              x[j][k] = min(x[j-1][k-1],x[j-1][k]+1,x[j][k-1]+1)

   print x[r][c]

The solution I have proposed is giving T.L.E (Time Limit Exceeded) even though I am using D.P. Is there any way to optimize it further in terms of time complexity or with respect to any feature of Python 2.7 such as input and output?


texts:
Purpose

Validate whether the open brackets within a String have matching closed brackets, in the correct order.

The three types of valid brackets are

[ and ]
{ and }
( and )

Examples:

A[B]{C}(D) returns true
A[B{C}(D) returns false

Feedback

Creating a new Map of open brackets to closed brackets seems a bit expensive to do every single time - what's the best way of making a static Map (or some equivalent)?
Is the switch statement the best way to go about evaluating the cases? Is it better to use if statements instead?

Implementation

public class BracketPairsValidator {

  public static final char OPEN_SQUARE_BRACKET = '[';
  public static final char CLOSED_SQUARE_BRACKET = ']';

  public static final char OPEN_CURLY_BRACKET = '{';
  public static final char CLOSED_CURLY_BRACKET = '}';

  public static final char OPEN_PARENTHESIS = '(';
  public static final char CLOSED_PARENTHESIS = ')';

  public static boolean validBracketPairs(final String candidate) {
    final char[] chars = candidate.toCharArray();
    final Stack<Character> bracketStack = new Stack<>();
    final Map<Character, Character> bracketMap = new HashMap<>();
    bracketMap.put(OPEN_SQUARE_BRACKET, CLOSED_SQUARE_BRACKET);
    bracketMap.put(OPEN_CURLY_BRACKET, CLOSED_CURLY_BRACKET);
    bracketMap.put(OPEN_PARENTHESIS, CLOSED_PARENTHESIS);
    for (final char ch : chars) {
      switch (ch) {
        case OPEN_SQUARE_BRACKET:case OPEN_CURLY_BRACKET:case OPEN_PARENTHESIS: {
          bracketStack.add(ch);
          break;
        }

        case CLOSED_SQUARE_BRACKET:case CLOSED_CURLY_BRACKET:case CLOSED_PARENTHESIS: {
          if (bracketStack.isEmpty()) {
            return false;
          }

          if (ch != bracketMap.get(bracketStack.pop())) {
            return false;
          }
          break;
        }

        default: {
          break;
        }
      }
    }

    return bracketStack.isEmpty();
    }
}


texts: Convert a List of graph edges to a Map of neighboring nodes

texts:
What would be best way achieving this? Is it possible to use Immutable map?

import scala.collection.mutable.Map

/* Convert List of Edges to mapping Node -> List of Nodes */
def create_graph(edges: Array[Array[Int]]): Map[Int, List[Int]]  = {
    val graph = Map[Int, List[Int]]();
    for (i <- 0 until edges.length) {
        val a = edges(i)(0)
        val b = edges(i)(1)
        if(graph contains a ) graph(a) = b::graph(a)
        else graph(a) = List(b)
    }
    return graph
}


texts: Finding the maximum inclusive distance between two duplicate numbers in an array

texts:
The prompt that made me put this function together was sourced from CodingBat.

I was curious about cleaner, more correct methods of doing putting this together such as finding a cleaner way to tell if there is or is not a duplicate in the array. I am also trying to be as efficient as possible. I believe this is an \$O(n^2)\$ function. Let me know what I should change.

The code works just fine. I just feel like there is quite a lot I can streamline and I would like to be pointed in the right direction.

 public int maxSpan(int[] nums) {
    int highestSpan = 0;
    int span;
    boolean duplicate = false;
    if (nums.length == 0)
        return highestSpan;
    for (int i = 0; i < nums.length; i++) {
        for (int j = 0; j < nums.length; j++){

            if ((nums[i] == nums[j])&& j != i){ //if duplicate
                duplicate = true;
                //get the absolute value of j - i
                span = j - i + 1; //Add 1 because it needs to count itself
                //if it is larger than the highestSpan then record it
                if (span > highestSpan)
                    highestSpan = span;
            }
        }
    }
    if (duplicate)
        return highestSpan;
    else
        return 1;
}


texts:
I'm working on a problem to select k nearest points for a given point. Any advice for bugs, improvements are appreciated, including general advice to implement find nearest k points.

My major idea is using the select-rank algorithm (similar to quicksort, using a pivot value, and divide-conquer the distance array). I think my algorithm time complexity is \$O(n)\$ -- which is \$O(n)\$ to calculate distances, and \$O(\log n)\$ for select rank part. If my calculation is wrong for the time complexity, appreciate for corrections.

import math
import random
def find_nearest_k(distance, start, end, k):
    pivot_index = random.randint(start, end)
    original_start = start
    original_end = end
    while start <= end:
        while start <= end and distance[start][1] <= distance[pivot_index][1]:
            start += 1
        while start <= end and distance[end][1] > distance[pivot_index][1]:
            end -= 1
        if start <= end:
            distance[start], distance[end] = distance[end], distance[start]
        else:
            break
    if start - original_start == k:
        return distance[:start]
    elif start - original_start > k:
        return find_nearest_k(distance, original_start, start - 1, k)
    else:
        return find_nearest_k(distance, start, original_end, k - (start-original_start))

def calculate_distance(center, points):
    result = []
    index = 0
    for point in points:
        result.append((index, (math.pow(center[0]-point[0],2) + math.pow(center[1]-point[1],2))))
        index += 1

    return result

if __name__ == "__main__":
    center = (0,0)
    points = [(1,2),(8,9),(6,5),(2,1),(10,20),(10,9)]
    distances = calculate_distance(center, points)
    print find_nearest_k(distances, 0, len(distances)-1, 2)


texts: Using generators to print the tree-like structure of a project

texts:
The goal of this code is to print the entity tree of a VHDL project. There are a readme and very minimal tests on the github repo.

I am trying to refactor the code to use generators in order to familiarize myself with yield, and to think in terms of iterators, not raw data structures. Here is my current attempt at doing so:

import re
from sys import argv
from os import walk
from os.path import join as pjoin

EXCLUDES = ["implementation", "testbench"]
BASIC_ID_REGEX = "[a-z][a-z0-9]*(?:_[a-z0-9]+)*"

def _vhdltree(level, filepath, pattern, vhd_files):
    for entity, component in find_entities(filepath, pattern):
        """Codereview: I am not specifically interested in feedbacks for the
        following snippet (except about the recursive design), but if you
        have a particularly elegant
        solution which keeps the "UI" part very minimal, suggestions
        are welcome"""
        path = vhd_files.get(component.lower(), "Not Found")
        print("    "*level + entity + " : " + path)
        if path != "Not Found":#Probably ugly, but lazy
            _vhdltree(level+1, path, pattern, vhd_files)

def find_entities(filepath, pattern):
    with open(filepath) as f:
        for l in f:
            m = pattern.match(l)
            if m:
                yield m.group('entity'), m.group('component').split(".")[-1]

def find_vhd(proot):
    for (dirpath, dirnames, filenames) in walk(proot):
        if not isexcluded(dirpath.lower()):
            for fn in filenames:
                if fn[-4:].lower() == ".vhd":
                    yield fn[:-4].lower(), pjoin(dirpath, fn)

def isexcluded(path):
    for excluder in EXCLUDES:
        if excluder in path:
            return True
    return False

def vhdltree(filepath, proot):
    instantiation_regex = ("\s*(?P<entity>{0})\s*:\s*entity\s*(?P<component>{0}(?:\.{0})*)"  # NOQA
                           .format(BASIC_ID_REGEX))
    p = re.compile(instantiation_regex, re.IGNORECASE)
    vhd_files = dict(find_vhd(proot))
    _vhdltree(0, filepath, p, vhd_files)

if __name__ == "__main__":
    #Codereview: user is trusted, don't care about this part
    vhdltree(argv[1], argv[2])

Any feedback about the use of generators is welcome. Specifically, I wonder if it would be possible to avoid "realizing" the vhd_files generator as a dict while keeping the search in _vhdltree as simple as a get? Are there more pythonic alternatives or more efficient solutions for a structure designed to be one-wa searchable (I know this is probably never where the program spends its time, but I'd like to know for my general culture). I looked in itertools but didn't find an immediate solution.

I am interested in modern, Python3 solutions for my general knowledge. From a practical point of view however, the code is supposed to be 2-compatible.


texts: Sort array of Numbers with some values always first

texts:
The first number will be dynamically selected and remaining array should be sorted ascending

    int[] array = {1,1,0,1,2,2,0,0};
    int  firstNumber = 0;// dynamic can be 0 or 1 or 2
    int numberOfOccurances = 0;

    //Basic sort functionality
    for(int i = 0 ; i< array.length; ++i)
    {
        if(array[i] == firstNumber)
        {
            numberOfOccurances++;
        }
        for(int j = i+1; j<array.length; ++j)
        {
            if(array[j] < array[i])
            {
                int temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
    }
    int[] requiredArray= new int[array.length];
    for(int i = array.length-1 ; i >= 0; i--)
    {
        if(array[i] != firstNumber)
        requiredArray[i] = array[i];

    }
    for(int i =0;i<array.length;i++)
    {
        if(i<numberOfOccurances)
        requiredArray[i]= firstNumber;
    }

    //Print Output
    for (int i = 0; i<requiredArray.length; i++)
    System.out.print(requiredArray[i] + "  ");

Output:

1 1 1 1 0 0 2 2

I was able to get desired output. But not sure if this is the best way to solve in terms of speed.


texts:
I'm creating tool to add new virtualhost on UNIX-box.
One of tasks is to add a new user and database to MariaDB (aka MySQL) server.
In fact - this my first 'real' attempt to use OOP.

Here is class, which I created for it:

class mysqlUserDb:
        warnings.filterwarnings('error')
        def __init__(self):
                self.root = 'root'
                self.host = 'localhost'
                self.rootpw = 'p@ss'

                try:
                        print '\nChecking MySQL connection...'
                        self.db = MySQLdb.connect(self.host, self.root, self.rootpw)
                        self.cursor = self.db.cursor()
                        self.cursor.execute('select version()')
                        print 'Connection OK, proceeding.'
                except MySQLdb.Error as error:
                        print 'Error: %s ' %error + '\nStop.\n'
                        sys.exit()

        def createdb(self, db):
                print '\nCreating database...'
                try:
                        self.cursor.execute('create database if not exists ' + db)
                        self.cursor.execute('show databases like ' + '\'' + db + '\'')
                        dbs = self.cursor.fetchone()
                        print 'Database created: %s' %dbs
                except Warning as warn:
                        print 'Warning: %s ' %warn  + '\nStop.\n'
                        sys.exit()

        def grants(self, user, userpass, db):
                print '\nGrant privilegies... '
                try:
                        self.cursor.execute('grant all on ' + db + '.*' + 'to ' + '\'' + user + '\'' + "@'localhost'" + 'identified by ' + '\'' + userpass + '\'')
                        self.cursor.execute('select user, db from mysql.db where db=' + '\'' + db + '\'')
                        grs = self.cursor.fetchall()
                        print 'Access granted: %r' %grs
                except Warning as warn:
                        print 'Warning: %s ' %warn  + '\nStop.\n'
                        sys.exit()
                except MySQLdb.Error as error:
                        print 'Error: %s ' %error + '\nStop.\n'
                        sys.exit()

        def __del__(self):
                print '\nFinishing operations...'
                self.cursor.close()
                self.db.close()
                print 'Done.\n'

Next, in tool it call like:

import createvhostFunctsClass as fun

mysql = fun.mysqlUserDb()
mysql.createdb('db_2')
mysql.grants('user', 'pass', 'db_2')
del mysql

(it's just example, not included yet in tool).

And its works like:

$ ./myclass.py

Checking MySQL cconnection...
Connection OK, proceeding.

Creating database...
Database created: db_2

Grant privilegies...
Access granted: ('user', 'db_2')

Finishing operations...
Done.

I'm pretty sure, here is lot of stuff, which I missed or did incorrectly (or not the "Python way").

Also, I'm not sure - which way better:

create methods for each action (add database, add user) and just call this methods from script (currently done)
create one method, which will get needed action ('create database lalala') as argument and call this method several times in script


texts: Partitioning and sorting even and odd numbers within an array

texts:
I solved a problem where it was told to sort an array of numbers such that the even numbers are kept first and the odd numbers should follow. Moreover, the even numbers must be sorted in ascending order among them and the odd numbers as well. Only arrays can be used. My code is as follows , which works fine but it seems bit long to me. I wanted to know if there is anything I can do to shorten it and make it more readable.

#include <stdio.h>

int main(void)
{
    int n,i,k,p,j,temp;

    scanf("%d",&n);

    int arr[n],arr_even[n],arr_odd[n];

    k=0,p=0;
    for(i=0;i<n;i++){
        scanf("%d",&arr[i]);
        if(arr[i]%2==0) arr_even[k++]=arr[i];
        else arr_odd[p++]=arr[i];
    }

    for(i=0;i<k;i++){
        for(j=0;j<=i;j++){
            if(arr_even[j]>arr_even[i]){
                temp=arr_even[i],arr_even[i]=arr_even[j],arr_even[j]=temp;
            }
        }
    }

    for(i=0;i<p;i++){
        for(j=0;j<=i;j++){
            if(arr_odd[j]>arr_odd[i]){
                temp=arr_odd[i],arr_odd[i]=arr_odd[j],arr_odd[j]=temp;
            }
        }
    }

    p=0;
    for(i=0;i<n;i++)
    {
        if(k) arr[i]=arr_even[i],k--;
        else arr[i]=arr_odd[p++];
        }

    for(i=0;i<n;i++)
    {
        printf("%d ",arr[i]);
    }

    return 0;
}

Input:

10
0 5 1 2 3 4 6 12 10 9

Output:

0 2 4 6 10 12 1 3 5 9


texts: Read database from IO context and update UI from Main context in Kotlin

texts:
Still a bit new to Kotlin and coroutines, so I want to learn best practices. The following code seems to work as expected in it's original context, though the naming has been tweaked here. The list of widgets is retrieved from the database, and the UI is updated correctly.
My main question is, in updateList is it approprate to use withContext (Dispatchers.Main) to access the UI from a job on the IO context? Feels a bit kludgy at first blush, but it does seem to work as expected.
class WidgetListActivity : AppCompatActivity() {
    private lateinit var db: AppDatabase
    private lateinit var getListJob: Job
    private lateinit var widgetList: List<WidgetRecord>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_widget_list)

        runBlocking  {
            db = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "Widget.db")
                .createFromAsset("database/prepop_db.sqlite").build()
        }
        val recyclerView = findViewById<RecyclerView>(R.id.widget_recycler_view)
        val linearLayoutManager = LinearLayoutManager(this.applicationContext)
        recyclerView.layoutManager = linearLayoutManager

        updateList()
    }

    private fun updateList() {
        getListJob = GlobalScope.launch (Dispatchers.IO) {
            widgetList = db.widgetDao().getAllWidgets()

            // HERE'S THE SECTION IN QUESTION
            withContext(Dispatchers.Main) {
                val recyclerView = findViewById<RecyclerView>(R.id.deck_recycler_view)
                var widgetListAdapter = WidgetListAdapter(widgetList)
                recyclerView.adapter = widgetListAdapter
                widgetListAdapter.notifyDataSetChanged()
            }
        }

    }

    override fun onDestroy() {
        runBlocking {
            getListJob.join()
        }

        // PLEASE NOTE: I know you wouldn't normally destroy the database
        // like this. The whole point of this Activity is simply to test
        // loading and displaying the contents of a prepopulated database.
        this.applicationContext.deleteDatabase("Widgets.db")
        super.onDestroy()
    }
}


texts: Java code to convert between hex & binary strings

texts:
I have two methods in my code which are using the majority of the CPU time that convert between binary and hex strings and the reverse. I use a static lookup map to convert the individual characters but it's still slow given the amount of data I'm working with.

public static String hexToBin(String s)
{
    StringBuilder binaryString = new StringBuilder();

    for(int i = 0; i < s.length(); i++)
    {
        // This string loop can be quite long sometimes > 3000 chars
        binaryString.append(binMap.get(s.charAt(i)));
    }

    return binaryString.toString();
}

public static String binToHex(String s)
{
    if (s.length() % 4 != 0)
    {
        s = Utils.leftPad4(s, (int)(4 * Math.ceil((double) s.length() / 4.0))); // Pad out any single bit values
    }

    StringBuilder hexString = new StringBuilder();
    StringBuilder chars = new StringBuilder();

    for (int i = 0; i < s.length(); i += 4)
    {
        chars.append(s.charAt(i));
        chars.append(s.charAt(i + 1));
        chars.append(s.charAt(i + 2));
        chars.append(s.charAt(i + 3));

        hexString.append(hexMap.get(chars.toString()));

        chars.delete(0, chars.length());
    }

    return hexString.toString();
}

/* The lookup tables */
private static Map<Character, String> binMap = new HashMap<>();
private static Map<String, Character> hexMap = new HashMap<>();

public Types()
{
    binMap.put('0', "0000");    binMap.put('1', "0001");    binMap.put('2', "0010");
    binMap.put('3', "0011");    binMap.put('4', "0100");    binMap.put('5', "0101");
    binMap.put('6', "0110");    binMap.put('7', "0111");    binMap.put('8', "1000");
    binMap.put('9', "1001");    binMap.put('A', "1010");    binMap.put('B', "1011");
    binMap.put('C', "1100");    binMap.put('D', "1101");    binMap.put('E', "1110");
    binMap.put('F', "1111");

    for (Character k : binMap.keySet())
    {
        hexMap.put(binMap.get(k), k);
    }
}


texts:
Coming from Java and Android development and Objective-C still is a bit strange to me, but I just went in head first and started writing code. Before I started getting really far into it, I just want to throw some basic code here for suggestions about correct syntax, etc. I just want to make sure that my variable and function declarations are correct as well as the way I refer to UI elements is the recommended method.

I was told to make a separate ViewController class for each UI I build as below:

@interface CalculatorViewController : UITableViewController

@property (weak, nonatomic) IBOutlet UITextField *fatTextField;
@property (weak, nonatomic) IBOutlet UITextField *carbsTextField;
@property (weak, nonatomic) IBOutlet UITextField *fiberTextField;
@property (weak, nonatomic) IBOutlet UITextField *proteinTextField;
@property (weak, nonatomic) IBOutlet UITextField *servingsTextField;
@property (weak, nonatomic) IBOutlet UITextField *foodnameTextField;
@property (weak, nonatomic) IBOutlet UILabel *pointsLabel;

- (IBAction)calculate:(id)sender;
- (IBAction)reset:(id)sender;
- (IBAction)addtotracker:(id)sender;

- (void)resetCalculator;
- (void)calculatePoints;

Then inside the CalculatorViewController.m file I ended up with the following code snippets:

// UI FUNCTIONS
- (void) resetCalculator {

    // Reset all nutrion fact fields.
    _fatTextField.text = @"";
    _carbsTextField.text = @"";
    _fiberTextField.text = @"";
    _proteinTextField.text = @"";
    _servingsTextField.text = @"";

    // Reset food name & points label
    _foodnameTextField.text = @"";
    _pointsLabel.text = @"Points: 0";

    // Set Fat as firstresponder
    [self.fatTextField becomeFirstResponder];
}

- (void) calculatePoints {
    float fatFloat = [_fatTextField.text floatValue];
    float carbsFloat = [_carbsTextField.text floatValue];
    float fiberFloat = [_fiberTextField.text floatValue];
    float proteinFloat = [_proteinTextField.text floatValue];
    float servingsFloat = [_servingsTextField.text floatValue];

    float points = proteinFloat + carbsFloat + fatFloat - fiberFloat;
    points = points / 100;
    points = roundf(points);
    points = MAX(points, 0);

    _pointsLabel.text = [NSString stringWithFormat:@"Points: %f", points];
}

- (IBAction)calculate:(id)sender {
    NSLog(@"Calculate button pressed!");

    // Close the keyboard
    [self.view endEditing:YES];
}

- (IBAction)reset:(id)sender {
    NSLog(@"Reset button pressed!");

    [self resetCalculator];
}

- (IBAction)addtotracker:(id)sender {
    NSLog(@"Tracker button pressed!");
}


texts: Checks if a job exists, and appends a bid to that job

texts:
I am very new to Node.js and Express and have been doing a "learn as I go" scenario by building a Craigslist-style app where people can bid on jobs.

I am looking to see if this is the best approach for appending a bid to a job.

var _ = require('underscore');
var request = require('request');
var bcrypt = require('bcrypt');

module.exports = function(app, db, jwt, jwtOptions, passport) {
    app.post('/bids', function(req, res) {
        var body = _.pick(
            req.body,
            'value',
            'hourlyOrFixed',
            'status',
            'title',
            'description',
            'JobForBidId'
        );
        body.BidderId = req.user.id;

        db.jobPosting.findOne({
            where: {
                id: body.JobForBidId
            }
        }).then(function(job) {
            if (job) {
                db.bids.create(body).then(function (bid){
                    res.status(200).json({message:'ok'});
                }).catch(function(err){
                    res.status(500).json({
                        status: 'failure',
                        error: err,
                    });
                });
            } else {
                res.status(404).json({
                    message: 'Job not found'
                });
            }
        }).catch(function(err) {
            res.status(500).json({
                status: 'failure',
                error: err,
            });
        });
    });
});


texts:
I have managed to write this piece of code but as I am using it on big data sets it ends up being quite slow. I am pretty sure it would be possible to optimize it but I am very knew to coding and I don't really know where to start.. I think getting rid of the for loop would be one way but honestly I'm lost. A little bit of help would be greatly appreciated !

Basically, the point is to look if one row of the 'data' dataframe match one row of the 'ref' dataframe. And I use np.isclose in order to allow for small differences in the value as I know my 'data' values can be slightly different than the 'ref' values.

Also, because my rows can have a lot of NaN values in them, I first use np.isnan to get the index of where is my last 'real' value in the row and then only do the row comparison with the 'actual' values. I thought it would speed things up but I'm not very sure it did...

match = []
checklist = set()

for read in data.itertuples():

    for ref in ref.itertuples():

        x = np.isnan(read[3:]).argmax(axis=0)

        if x == 2:
            if np.isclose(read[4:6],ref[7:9],atol=5, equal_nan=True).all() == True and np.isnan(ref[6:]).argmax(axis=0) == x:

                if not read[1] in checklist:
                    match.append([read[1], ref[5]])
                    checklist.add(read[1])

        if x > 2:
            read_pos = 3+x-1
            ref_pos = 6+x-1

            if np.isclose(read[4:read_pos],ref[7:ref_pos],atol=5, equal_nan=True).all() == True and np.isnan(ref[6:]).argmax(axis=0) == x:

                if not read[1] in checklist:
                    match.append([read[1], ref[5]])
                    checklist.add(read[1])

    if read[1] not in checklist:
        match.append([read[1], "not found"])
        checklist.add(read[1])

Thanks in advance !

EDIT:

To download samples of data and ref tables: https://we.tl/RF6lxDZBjt

Short example of the dataframes:

ref = pd.DataFrame({'name':['a-1','a-2','b-1'],
                  'start 1':[100,100,100],
                  'end 1':[200,200,500],
                  'start 2':[300,np.NaN,600],
                  'end 2':[400,np.NaN, 700]},
                   columns=['name', 'start 1', 'end 1', 'start 2', 'end 2'],
                   dtype='float64')

    name  start 1   end 1  start 2  end 2
 0  a-1     100.0   200.0    300.0  400.0
 1  a-2     100.0   200.0      NaN    NaN
 2  b-1     100.0   500.0    600.0  700.0

data = pd.DataFrame({'name':['read 1','read 2','read 3','read 4', 'read 5'],
                  'start 1':[100,102,100,103,600],
                  'end 1':[198,504,500,200, 702],
                  'start 2':[np.NaN,600,650,601, np.NaN],
                  'end 2':[np.NaN,699, 700,702, np.NaN]},
                   columns=['name', 'start 1', 'end 1', 'start 2', 'end 2'],
                   dtype='float64')

    read      start 1   end 1  start 2   end 2
 0  read 1      100.0   200.0    300.0   400.0
 1  read 2      100.0   200.0      NaN     NaN
 2  read 3      100.0   500.0    600.0   700.0
 3  read 4      300.0   400.0    600.0   700.0
 4  read 5      600.0   702.0      NaN     NaN


texts:
As part of studying algorithms, I needed to make a function to count occurrences of characters in a string. My solution is below. I'd like some feedback about how I did - could the implementation be cleaner? Are there any conceptual gaps my code suggests?

<?php
function ra_count_chars($str){
    $dict = str_split(strtolower(str_replace(' ', '', $str)));

    foreach($dict as $key=>$value){
        $dict[$value] = 0;
        unset($dict[$key]);
    }

    for($i = 0; $i < strlen($str); $i++){
        $dict[$str[$i]] += 1;
    }

    return $dict;
}

print_r(ra_count_chars('ccaaat'));


texts: Using SQL to reorder items in a list view - is this efficient?

texts:
I'm writing an application for work that requires me to process a list of transactions.  The list is small (5 records at the most) and I'm required to display that data in an android ListView. My client has asked that I include the ability to order the list based on the date (I have added ordering it by the amount spent.)

My code uses SQLite queries to get the transactions, from an in-memory database, in the desired order.

public Cursor getAllTransactions(int orderByType)
{
    String orderBy = " order by ";
    switch (orderByType)
    {
        case ORDER_BY_NEWER:
            orderBy += "date(" + KEY_DATE + ") desc";
            break;
        case ORDER_BY_OLDER:
            orderBy += "date(" + KEY_DATE + ")";
            break;
        case ORDER_BY_MOST:
            orderBy += KEY_AMOUNT;
            break;
        case ORDER_BY_LEAST:
            orderBy += KEY_AMOUNT + " desc";
            break;
        default:
            orderBy = null;
    }

    return getAllTransactions(orderBy);
}

The getAllTransactions(orderBy) line executes the SQL command select * from TABLE_TRANSACTIONS appending the order by constraint should it be non-null.

Is this the proper use of SQL? Would it be more efficient (aka faster) to store this data in a standard container (such as List<Transaction>) and then sort them in the desired order?


texts: Closures with validation rules for domain object properties

texts:
It is nice to be able to set your data in a domain object like so:

$order->setId($id);
$order->setCustomer($customer);
$order->setItems($items);

And then be able to do

if( !$order->validate() ) {
    // Invalid data
}

Which will validate all the set data and tell you if it was valid or not. I have an implementation of this I came up with but it is sort of messy and limited to only certain common validation rules like checking the type, length/range and format of the data.

I have been doing a lot of Javascript lately and I like the idea of the anonymous functions and I just found out you can do them in PHP 5.3+ and you can use the $this keyword from PHP 5.4.

abstract class AbstractEntity {

    private $id = 0;
    private $validations = array();

    public function setId($id) {
        $this->id = $id;

        // A function to validate the Id
        $this->addValidation( function() {
            return ( $this->id > 0 );
        });
    }

    public function getId() {
        return $this->id;
    }

    public function validate() {
        foreach($this->validations as $validation) {
            if( $validation() === false ) {
                return false;
            }
        }

        return true;
    }

    protected function addValidation($function) {
        $this->validations[] = $function;
    }

}

The Order class:

class Order extends AbstractEntity {

    private $customer;
    private $items = array();
    private $status;

    public function setCustomer(Customer $customer) {
        $this->customer = $customer;

        // Make sure the customers account is active
        $this->addValidation( function() {
            return ( $this->customer->isActive() );
        });
        // Do as many complex validations as needed
    }

    public function setStatus($status) {
        $this->status = $status;

        // The status has to be 'Pending' or 'Complete'.
        $this->addValidation( function() {
            return ( ($this->status === 'Pending') || ($this->status === 'Complete') );
        });

}

Doing it this way validations of all different levels of complexity can be done. I was thinking of adding in another parameter to the addValidation() method so you can group validation rules together so they execute in a certain order.

It needs extra functionality like setting error messages but that should not be too hard to implement.

I was also thinking of maybe making the addValidation() method public so you can add validations outside of the class that will execute when the validate() method is called. This could be handy in some scenarios.

Is this a good or bad idea? I would like to see some opinions before I go and change all my code to using this sort of implementation.


texts: Algorithm to say if win or lose using player's rating and randomness

texts:
I wrote a small simulator to understand the Elo rating system. I can create players, matches and tournaments, and I want to be able to predict the match ending depending on the rating of each player and some randomness. At the beginning the ratings are all around the same values (say 600) and it appears to stay between 400 and 1600. This is what I've tried :

p1 and p2 are instances of Player, rating is an integer attribute.

def random_win(self):
    q = float(self.p2.rating)/float(self.p1.rating)
    if q>2:
        self.win_2()
    elif q<0.5:
        self.win_1()
    else:
        d = float(self.p2.rating)-float(self.p1.rating)
        lim = max(self.p1.rating, self.p2.rating)/2
        r = random.randint(-lim, lim)
        if r > d:
            self.win_1()
        else:
            self.win_2()

I'd like to know if there are some "official" ways of doing this, this custom one works quite fine but I think it can be improved or at least simplified. Any ideas ? The best would be to get something closer the World Chess Ratings.

Once the wins and losses calculated and stored into the Player as a list attribute, I calculate the new rating for each player using this algorithm.


texts:
I am currently working on a NodeJS server, and am switching from callbacks to promises.

Here's an example of my code:

 var record = req.body.record;
var schoolId = req.body.schoolId;
var promise = BusController.addBus(record,schoolId);
promise.then(function(){
    return res.json({status:"success", message : "bus successfully created"});
}).catch(function(error){
        if(error){
            console.log(error);
            res.json({status:"error",message:"error while creating bus"});
            return;
        }

The bus controller has the following in it:

addBus : function(record,schoold){
    return new Promise(function(resolve,reject){
        var bus_number = record.bus_number;

        var newBus = new Bus({
            language: language ? language : "",
            bus_number: bus_number  ? bus_number : "",
            bus_driver: bus_driver  ? bus_driver : {},
            bus_details: bus_details ,
            trips: trips ? trips : [],
            school_id: schoold,
            location: location ? location : {}
        });
        newBus.save().then(function(bus){
            var busCreation = {};
            busCreation.name=  "باص رقم"+ ' ' +bus_number;
            busCreation.type= "3";
            busCreation.refid= bus._id;
            busCreation.email= record.email;
            busCreation.phone_number=record.phone_number;
            busCreation.school_id = schoold;
            console.log(busCreation);
            var promise = UserController.addUser(busCreation);
            promise.then(function(){
                resolve();
            })
        }).catch(function(error){
            if (error) {
                reject(error);
            }
        });
    });
}

This my current logic. Is this a good practice? Or should I switch to async library?


texts: Simple tkinter GUI that uses a popup menu class

texts:
I'm new to OOP and not sure if I'm importing and using my class correctly.

I'm writing a simple app called MyTestApp that uses a tkinter GUI.
I have a textbox widget and I created a popup menu that is bound to that widget.

But my code started to look a little messy so I decided to move all the popup related methods and variables to its own class. And also decided to write it that I can reuse my popup class for other projects in the future that will require a popup menu.

I instantiate my popup class like this: self.popup = p(parent)

Then I assign the self.popup.textbox_text instance variable in the popup class to the self.data_textbox instance variable in my MyTestApp class like so:

self.popup.textbox_text = self.data_textbox

Everything works correctly, but I'm not sure if this is the correct way of doing it. I initially was thinking that I should pass self.data_textbox as a parameter when instantiating the class but was having a hard time to get it too work like that.

Any tips or advice I can get will be greatly appreciated. I would prefer to do things the correct way from the start.

main.py:

import tkinter as tk
from tkinter import Tk, ttk, Frame, FALSE, Text, Button, \
    Scrollbar, Entry, END, INSERT
from popup import Popup as p

class MyTestApp(Frame):

    def __init__(self, parent, *args, **kwargs):
        Frame.__init__(self, parent, *args, **kwargs)
        self.root = parent
        self.root.title('MY Test App')
        self.grid(column=0, row=0, sticky='nsew', padx=12, pady=5)

        self.data_textbox = Text(self, borderwidth=2, relief='sunken')
        self.data_textbox.config(height=30, width=80)
        self.data_textbox.grid(row=1, column=0, sticky="new")
        self.exit_btn = ttk.Button(self, text='Exit', command=self.on_exit)
        self.exit_btn.grid(row=2, column=0, sticky='W', pady=15)

        ## Not sure if im doing the below part correct
        ## Instantiate my popup class
        self.popup = p(parent)
        ## Assign self.popup.textbox_text to self.data_textbox
        self.popup.textbox_text = self.data_textbox
        # Add imported popup menu and bind to textbox widget
        self.data_textbox.bind("<Button-3>", self.popup.text_popup)

    # Exit the program. Linked to the Exit Button
    def on_exit(self):
        self.root.destroy()

def main():
    root = Tk()
    MyTestApp(root)
    root.mainloop()

if __name__ == '__main__':
    main()

popup.py:

import tkinter as tk
from tkinter import Frame, Entry, END, INSERT

class Popup(Frame):
    def __init__(self, parent, *args, **kwargs):
        Frame.__init__(self, parent, *args, **kwargs)

        ### Not sure if this below part is correct
        ### Must it rather be set from the init parameter?
        self.textbox_text = ''

        self.text_widget = tk.Menu(self, tearoff=0, relief='sunken')
        self.text_widget.add_command(label="Copy", command=self.text_copy)
        self.text_widget.add_separator()
        self.text_widget.add_command(label="Paste", command=self.text_paste)
        self.text_widget.add_separator()
        self.text_widget.add_command(label="Clear", command=self.text_clear)

    def text_popup(self, event):
        self.text_widget.post(event.x_root, event.y_root)

    def text_copy(self, event=None):
        self.clipboard_clear()
        text = self.textbox_text.get("sel.first", "sel.last")
        self.clipboard_append(text)

    def text_paste(self):
        self.textbox_text.insert(INSERT, self.clipboard_get())

    def text_clear(self):
        self.textbox_text.delete(1.0, END)


texts:
What do you think of my Algorithm?

I start to eliminate the nearest valid parentheses

and if string.length == 0 so it's valid

/**
 * @param {string} s
 * @return {boolean}
 */
var isValid = function(s) {
    while (s.length != 0 && s.includes("[]") || s.includes("()") || s.includes("{}")) {
        s = s.replace("[]", "");
        s = s.replace("()", "");
        s = s.replace("{}", "");
    }
    return s.length < 1
};

console.log(isValid("({((}{}))})"));
console.log(isValid("({(())})"));


texts:
Edit - here is my modified code: http://jsfiddle.net/#&togetherjs=GzytydCsRh

Can someone take a look and give me some feedback? It seems a bit long still but that is the first time I used functions.

I am reading a bunch of CSV files and using glob to concatenate them all together into separate dataframes. I eventually join them together and basically create a single large file which I use to connect to a dashboard. I am not too familiar with Python but I used Pandas and sklearn often.

As you can see, I am basically just reading the last 60 (or more) days worth of data (last 60 files) and creating a dataframe for each. This works, but I am wondering if there is a more Pythonic/better way? I watched a video on pydata (about not being restricted by PEP 8 and making sure your code is Pythonic) which was interesting.

(FYI - the reason I need to read 60 days worth of files is because customers can fill out a survey from a call which happened a long time ago. The customer fills out a survey today about a call that happened in July. I need to know about that call (how long it lasted, what the topic was, etc).

import pandas as pd
import numpy as np
from pandas import *
import datetime as dt
import os
from glob import glob
os.chdir(r'C:\\Users\Documents\FTP\\')
loc = r'C:\\Users\Documents\\'
rosterloc = r'\\mand\\'
splitsname = r'Splits.csv'
fcrname = r'global_disp_'
npsname = r'survey_'
ahtname = r'callbycall_'
rostername = 'Daily_Roster.csv'
vasname = r'vas_report_'
ext ='.csv'
startdate = dt.date.today() - Timedelta('60 day')
enddate = dt.date.today()
daterange = Timestamp(enddate) - Timestamp(startdate)
daterange = (daterange / np.timedelta64(1, 'D')).astype(int)

data = []
frames = []
calls = []
bracket = []
try:
    for date_range in (Timestamp(startdate) + dt.timedelta(n) for n in range(daterange)):
        aht = pd.read_csv(ahtname+date_range.strftime('%Y_%m_%d')+ext)
        calls.append(aht)
except IOError:
        print('File does not exist:', ahtname+date_range.strftime('%Y_%m_%d')+ext)
aht = pd.concat(calls)
print('AHT Done')
try:
    for date_range in (Timestamp(startdate) + dt.timedelta(n) for n in range(daterange)):
        fcr = pd.read_csv(fcrname+date_range.strftime('%m_%d_%Y')+ext, parse_dates = ['call_time'])
        data.append(fcr)
except IOError:
        print('File does not exist:', fcrname+date_range.strftime('%m_%d_%Y')+ext)
fcr = pd.concat(data)
print('FCR Done')
try:
    for date_range in (Timestamp(enddate) - dt.timedelta(n) for n in range(3)):
        nps = pd.read_csv(npsname+date_range.strftime('%m_%d_%Y')+ext, parse_dates = ['call_date','date_completed'])
        frames.append(nps)
except IOError:
        print('File does not exist:', npsname+date_range.strftime('%m_%d_%Y')+ext)
nps = pd.concat(frames)
print('NPS Done')
try:
    for date_range in (Timestamp(startdate) + dt.timedelta(n) for n in range(daterange)):
        vas = pd.read_csv(vasname+date_range.strftime('%m_%d_%Y')+ext, parse_dates = ['Call_date'])
        bracket.append(vas)
except IOError:
        print('File does not exist:', vasname+date_range.strftime('%m_%d_%Y')+ext)
vas = pd.concat(bracket)
print('VAS Done')
roster = pd.read_csv(loc+rostername)
print('Roster Done')
splits = pd.read_csv(loc+splitsname)
print('Splits Done')


texts:
I have two threads. One runs a simulation and one runs a UI.

In the UI, it is possible to trigger a "tick" of the simulation. There are a few constraints:

Ticks run on the simulation thread
Each tick takes a bit of time to complete.
When the user asks for n ticks, n ticks should be completed, even if they are requested during the execution of a tick.

To manage the triggering of ticks between threads, I have created a Pulse class. Here it is:

public final class Pulse {

    private final Object Lock = new Object();

    private volatile int count;

    public Pulse() {

        super();

        count = 0;
    }

    public void pulse() {

        synchronized (Lock) {

            count++;

            Lock.notifyAll();
        }
    }

    public void waitForPulse() throws InterruptedException {

        synchronized (Lock) {

            while (count == 0) {

                Lock.wait();
            }

            count--;
        }
    }
}

A single Pulse instance is shared between the UI and simulation threads.

In the UI thread I would have something like:

void onTickRequested() {

    simulationPulse.pulse();
}

And in the simulation thread I have something like:

while (isRunningSimulation) {

    myPulse.waitForPulse();

    tick();
}

Will my code work as expected? Is it thread-safe?


texts: Validating a model and focus to the element if validation fails

texts:
I am using Backbone Marionette - I would like to set the user name and password if that passes the model validation method.

I am highly confused with that.  Please show me a handy approach or correct me if I'm doing this wrong.

define(["backbone"], function(Backbone){
    var LoginModel = Backbone.Model.extend({
        defaults:{
                userName:'',
                password:''
        },
        validate:function(attr, options){
            if (!attr.userName) {
                return 'I need your userName';
              }
              if (!attr.password) {
                return 'I need your password';
              }
        },
        initialize:function(){
            this.on("invalid", function(model, error){
                console.log(model, error); // error consoles 2 times (4 times for both)
            });
        }
    });

    return LoginModel;
});

View.js:

define([
    'jQuery','underscore',
    'backbone','marionette',
    'text!./templates/loginView.html'],
    function($,_,Backbone,Marionette,template){
        "use strict";

        var LoginView = Backbone.Marionette.ItemView.extend({

            className:'col-xs-12 col-md-4 col-md-offset-4',

            template:_.template(template),

            events:{
                "submit form" : "loginSubmit"
            },

            loginSubmit:function(e){
                e.preventDefault();
                var data = Backbone.Syphon.serialize(e.target),

                validUser = this.model.set('userName',data.userName, {validate: true}),
                validPass = this.model.set('password', data.password,{validate: true});

                if(!validUser){
                    $(e.target).find('#userName').select();
                } else{
                    $(e.target).find('#userName').next(':input').select();
                }

                if(!validPass){
                    $(e.target).find('#userName').select();
                }

            }

        });

        return LoginView;
    }
);

This works, but I am looking for the best approach.


texts: Tips to refactor code : very repetitive code

texts:
I have this very simple problem : my code is too repetitive. It works, but it could be much cleaner. I don't know exactly where to start.

I'd like to learn to work better, and I'd really like someone to help me with it.

Here's the 2 bits of my code that are very repetitive (everything I've done myself) :

$(document).ready(function () {

  // Setup your Lazy Line element.
  // see README file for more settings
  $('#drawing1').lazylinepainter({
      'svgData': dr1,
      'strokeWidth': 1.2,
      'strokeColor': '#65615a',
      'onComplete': function () {

      }
    })

  $('#drawing2').lazylinepainter({
      'svgData': dr2,
      'strokeWidth': 1.2,
      'strokeColor': '#65615a',
      'onComplete': function () {

      }
    })

  $('#drawing3').lazylinepainter({
      'svgData': dr3,
      'strokeWidth': 1.2,
      'strokeColor': '#65615a',
      'onComplete': function () {

      }
    })

  $('#drawing4').lazylinepainter({
      'svgData': dr4,
      'strokeWidth': 1.2,
      'strokeColor': '#65615a',
      'onComplete': function () {

      }
    })

  $('#drawing5').lazylinepainter({
      'svgData': dr5,
      'strokeWidth': 1.2,
      'strokeColor': '#65615a',
      'onComplete': function () {

      }
    })

  // Paint your Lazy Line, that easy!

})

})(jQuery);

Second part of the code:

var eventsFiredDr1 = 0;

var drawing1 = function () {
  if(eventsFiredDr1 == 0) {

    $('#drawing1').lazylinepainter('paint');

    eventsFiredDr1++; // <-- now equals 1, won't fire again until reload
  }
}

var eventsFiredDr2 = 0;

var drawing2 = function () {
  if(eventsFiredDr2 == 0) {

    $('#drawing2').lazylinepainter('paint');

    eventsFiredDr2++; // <-- now equals 1, won't fire again until reload
  }
}

var eventsFiredDr3 = 0;

var drawing3 = function () {
  if(eventsFiredDr3 == 0) {

    $('#drawing3').lazylinepainter('paint');

    eventsFiredDr3++; // <-- now equals 1, won't fire again until reload
  }
}

var eventsFiredDr4 = 0;

var drawing4 = function () {
  if(eventsFiredDr4 == 0) {

    $('#drawing4').lazylinepainter('paint');

    eventsFiredDr4++; // <-- now equals 1, won't fire again until reload

  }
}

var drawing5 = function () {
  if(eventsFiredDr5 == 0) {

    $('#drawing5').lazylinepainter('paint');

    eventsFiredDr5++; // <-- now equals 1, won't fire again until reload

  }
}

$(window).resize(function () {
  if($(window).width() < 820) {

    $("svg").hide()
    $(".fallback").show()
    $("#drawing2").css("height", "auto")
  }
});

if($(window).width() > 820) {

  $(".fallback").hide()

  $(window).scrollStopped(function () {
    if($("#drawing1").is(":within-viewport")) {
      drawing1()
    }

    if($("#drawing2").is(":within-viewport")) {
      drawing2()
    }

    if($("#drawing3").is(":within-viewport")) {
      drawing3()
    }

    if($("#drawing4").is(":within-viewport")) {
      drawing4()
    }

    if($("#drawing5").is(":within-viewport")) {
      drawing5()
    }

  });

( I know I should put DOM elements in variables, but I planned on doing it when I would refactor the code. )

My first guess would be creating an array but.. No idea how to use it in my code. (I'm a big beginner)


texts: Removing stop words from a Spark Dataframe

texts:
I am trying to apply a function to two Spark Dataframes (in Zeppelin):

def RemoveStopwords (dfin : dataframe) : Dataframe = {
    val stopwords =

    sc.textFile("/media/ed/Seagate/data/stopwords.txt")

    val tokenizer = new Tokenizer().setInputCol("text").setOutputCol("words")
    val wordsData = tokenizer.transform(dfin)

    // remove stop words
    val remover = new StopWordsRemover().setInputCol("words").setOutputCol("NoStop")
    val dfNoStop= remover.transform(wordsData)

}

and I call it:

Array(dfHive, dfHive1).map(RemoveStopwords)

Is this the right way of doing things? Should I be passing in the stopwords.txt file rather than looking it up twice? Also, is it OK to have : Dataframe (some functions I have seen are declared name : type not just : type)?


texts: What value the rear and front counter of an Array implementation of Queue start with? -1 or 0 or 1?

texts:
Is there anything wrong with this implementation of Queue with array?

I have started front = rear = -1.

Some references tend to start front = 0 like this:enter link description here

I think if front starts with 0, the source code becomes cumbersome.

#include <stdio.h>
#include<ctype.h>
#define SIZE 5

int queue[SIZE] = {0};
int front = -1;
int rear = -1;

void PrintQueue()
{
    int i=0;

    if(!IsEmpty())
    {
        for(i=front+1 ; i<=rear ; i++)
        {
            printf("%d, ", queue[i]);
        }
        printf("\n");
    }
    else
    {
        printf("Queue is empty.\n");
    }
}

int IsEmpty()
{
    if(front==rear)
    {
        front = rear = -1;
        return 1;
    }
    else
    {
        return 0;
    }
}

void Enque(int value)
{
    if(rear<SIZE-1)
    {
        ++rear;
        queue[rear] = value;
    }
    else
    {
        printf("Queue overflow!\n");
    }
}

int Dequeue()
{
    int ret = 0;
    if(!IsEmpty())
    {
        ++front;
        ret = queue[front];
    }
    else
    {
        printf("Queue underflow!\n");
        ret = -99;
    }

    return ret;
}

main()
{
    int value = 0;
    int menu = 0;

    while(1)
    {
        printf("Menu\n");
        printf("--------\n");
        printf("1. Enque\n");
        printf("2. Deque\n");
        printf("3. IsEmpty\n");
        printf("4. Print\n");
        printf("5. Clrscr\n");
        printf("6. Exit\n");
        scanf(" %d", &menu);

        switch(menu)
        {
        case 1:
            printf("Enter an element : ");
            scanf(" %d", &value);
            Enque(value);
            break;

        case 2:
            printf("Dequed, %d.\n", Dequeue());
            break;

        case 3:
            if(IsEmpty())printf("Queue is empty.\n");
            else printf("Que has some values.\n");
            break;

        case 4:
            PrintQueue();
            break;

        case 5:
            system("cls");
            break;

        case 6:
            exit(0);
            break;
        }
    }
}


texts: Dynamically creating elements with an object constructor

texts:
Just experimenting with various Javascript techniques and was wondering if the code below is valid and if there are any disadvantages to using this technique to create html tags from JS object constructors? I know the usual technique is to add the html directly in the body and loop through an array to populate the elements.

So the two main questions;

Is the code valid and are there any main reasons not to use this technique?
Can the function call be integrated either into the constructor function (and called when a new object is created) or called from the new object parameter? (It somehow feels wrong to place on a separate line after every new object creator.

(function(){

function Photo(name, src){
this.name = name;
this.src = src;
    this.create = function(){
        var container = document.getElementById('thumbs_container');
        var img = document.createElement('img');
        img.src = this.src;
        img.alt = this.name;
        img.className = 'thumb';
        img.style.width = '200px';
        container.appendChild(img);
    }
}

var photo1 = new Photo('RED SQUARE', 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/25/Red.svg/2000px-Red.svg.png');

photo1.create();

var photo2 = new Photo('BLUE SQUARE', 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/000080_Navy_Blue_Square.svg/600px-000080_Navy_Blue_Square.svg.png');

photo2.create();

var photo3 = new Photo('YELLOW SQUARE', 'https://upload.wikimedia.org/wikipedia/commons/f/f2/Yellow_Square.JPG');

photo3.create();

})();


texts: Simple repository for a small/medium sized ASP.NET MVC site

texts:
I am about to start a small/medium sized project. I am by no means a software architect. But I tend to question every move I make at times, since I want to do things correct.

I found a way to implement a simple repository, and I wanted to know if this is a "correct" way of doing it. I came to this solution, since I know what is going on, and not taking in something to complex before I have the knowledge.

Unit of work

Where I make sure I to keep all my repositories under the same dbcontext. In my UOW I can access all repos when calling it from the controller.

public class UnitOfWork : IDisposable
{
    private ContactRepository _contactRepo;
    private ApplicationDbContext _entities;

    public UnitOfWork(ApplicationDbContext entities)
    {
        _entities = entities;
    }

    public ContactRepository ContactRepo
    {
        get
        {
            if (_contactRepo == null)
            {
                _contactRepo = new ContactRepository(_entities);
            }
            return _contactRepo;
        }
    }

    public void Save()
    {
        _entities.SaveChanges();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                _entities.Dispose();
            }
        }
        this.disposed = true;
    }

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

ContactRepository

This is a short example of a repository, where it receives the dbcontext and uses it to grab whatever data I want.

   public class ContactRepository
   {
    private ApplicationDbContext _entities;

    public ContactRepository(ApplicationDbContext entities)
    {
        _entities = entities;
    }

    public IEnumerable<Contact> GetAll()
    {
        return _entities.Contacts;
    }
}

Controller

Short example of controller

public class ContactController : Controller
{

    UnitOfWork uow = new UnitOfWork(new ApplicationDbContext());

    public ActionResult Index()
    {
        var contacts = uow.ContactRepo.GetAll();
        return View(contacts);
    }

    protected override void Dispose(bool disposing)
    {
        uow.Dispose();
        base.Dispose(disposing);
    }
}

In this way I will have access to all my repositories under the same dbcontext which I was aiming for.

I know things can be done smarter/different. With for example a extendable generic repo. But in this case I am aiming for something simple and understandable. But still don't want to make a huge mistake, if there is a major flaw.

Do you see any major flaws with this way of handling data through entity framework?


texts:
This script is meant to look for an id in the data attribute in each containment div, then send an Ajax call to get the amount of retweets, calculate the karma based on those retweets and then display that number in a div.

This code looks like spaghetti. How do I improve this to make each function more independent?  There is some abstraction function that I can't figure out.

My other question is, how can I use a jQuery deferred object to create a promise and update the div once I get a response?

function get_retweet(id) {
    var url = 'https://api.twitter.com/1/statuses/show/' + id + '.json',
        karma;

    $.ajax({
        url: url,
        type: 'GET',
        dataType:'jsonp',
        crossDomain: true,
        success: function(data) {
            display_karma(data.retweet_count);
        },
        error: function() {alert('fail');}
    }));
}

function calc_karma(tweets) {
    return tweets *10 +10;
}

function display_karma(retweets) {
    var id, karma,
        el =$('.tweetContainer');
    //id = $(el).data(el, tweet_id);
    id = '248988915661410304';
    karma = calc_karma(retweets);
    el.find('.tcPoints').text(karma);
}

function start_get_karma() {
    var id;

    $('.tweetContainer').each(function(index,el) {
        //id = $(el).data(el, tweet_id);
        id = '248988915661410304';
        get_retweet(id);
    });
}


texts: Is using java enums to store filepaths good practice

texts:
I'm working on an android application, but this is basically plain 'ole java.

The aim is to do the right thing and not repeat myself.

public enum Datafile {
    ACTIVITIES() {
        @Override public String filepath() {
            return "activities.yaml";
        }
    },
    OPEN_LOOPS() {
        @Override public String filepath() {
            return "open_loops.yaml";
        }
    };

    public abstract String filepath();
}

Later on, when I want to edit the file I try this

File file = getDataFile(Datafile.OPEN_LOOPS);

Which calls this...

private File getDataFile(Datafile datafile) {
    File file = null;

    String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    file = new File(baseDir + "/" + datafile.filepath());

    return file;
}

Points for a better name for the enum and good advice regarding who responsibility for the getFileData method (currently all this code is in an Activity) really lies (a new class).


texts:
Information about my code:

I am following this MIT OCW algorithms course. The first lecture described insertion sort and merge sort. I implemented insertion sort in C.

The algorithm is structured as a function called from the main function. The array to be sorted is allocated dynamically in the main function but can also be statically allocated.

What I am looking for:

I am looking whether the code can be optimized without changing the algorithm (insertion sort), whether it follows the best-practices of programming in C and does it have proper readability factor?

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

void insertion_sort(int arr[], int length)
{
    /*
    Sorts into non-decreasing order
    To change the sorting to non-increasing order just change
    the comparison in while loop
    */
    register int j, k;
    int temp;

    for(j = 1; j < length; j++)
    {
        temp = arr[j];
        k = j - 1;
        while (k >= 0 && arr[k] > temp)
        {
            arr[k + 1] = arr[k];
            k--;
        }
        arr[k + 1] = temp;
    }
}

int main()
{
    int length;
    register int i;
    int *arr;

    //Finds the length of array and dynamically creates array of that length
    scanf("%d", &length);
    if ( (arr =  (int *)malloc(sizeof(int) * length)) == NULL)
    {
        printf("Not enough memory");
        return 1;
    }

    //Reads the array
    for(i = 0; i < length; i++)
        scanf("%d", &arr[i]);

    //Calls the sorting algorithm
    insertion_sort(arr, length);

    //Prints the sorted array
    for(i = 0; i < length; i++)
        printf("%d ", arr[i]);

    //Frees the memory allocated and returns
    free(arr);
    return 0;
}


texts: How to deal with elimination of duplicate logic vs. cost of complexity increase?

texts:
I just wrote some code that is very representative of a recurring theme (in my coding world lately): repeated logic leads to an instinct to eliminate duplication which results in something that is more complex the tradeoff seems wrong to me (the examples of the negative side aren't worth posting - but this is probably the 20th console utility I've written in the past 12 months).

I'm curious if I'm missing some techniques or if this is really just on of those "experience tells you when to do what" type of issues.

Here's the code... I'm tempted to leave it as is, even though there will be about 20 of those if-blocks when I'm done.

static void Main(string[] sargs)
{
    try
    {
        var urls = new DirectTrackRestUrls();
        var restCall = new DirectTrackRestCall();
        var logger = new ConsoleLogger();
        Args args = (Args)Enum.Parse(typeof(Args), string.Join(",", sargs));
        if (args.HasFlag(Args.Campaigns))
        {
            var getter = new ResourceGetter(logger, urls.ListAdvertisers, restCall);
            restCall.UriVariables.Add("access_id", 1);
            getter.GotResource += new ResourceGetter.GotResourceEventHandler(getter_GotResource);
            getter.GetResources();
            SaveResources();
        }
        if (args.HasFlag(Args.Advertisers))
        {
            var getter = new ResourceGetter(logger, urls.ListAdvertisers, restCall);
            restCall.UriVariables.Add("access_id", 1);
            getter.GotResource += new ResourceGetter.GotResourceEventHandler(getter_GotResource);
            getter.GetResources();
            SaveResources();
        }
        if (args.HasFlag(Args.CampaignGroups))
        {
            var getter = new ResourceGetter(logger, urls.ListCampaignGroups, restCall);
            getter.GotResource += new ResourceGetter.GotResourceEventHandler(getter_GotResource);
            getter.GetResources();
            SaveResources();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.InnerException);
        Console.WriteLine(e.StackTrace);
    }


texts: Recursive method to print a descending then ascending integer sequence

texts:
From a programming assignment:

  Write a method writeSequence that accepts an integer n as a
  parameter and prints a symmetric sequence of n numbers with
  descending integers ending in 1 followed by ascending integers
  beginning with 1, as in the table below:

Call                        Output

writeSequence(1);             1
writeSequence(2);            1 1
writeSequence(3);           2 1 2
writeSequence(4);          2 1 1 2
writeSequence(5);         3 2 1 2 3
writeSequence(6);        3 2 1 1 2 3
writeSequence(7);       4 3 2 1 2 3 4
writeSequence(8);      4 3 2 1 1 2 3 4
writeSequence(9);     5 4 3 2 1 2 3 4 5
writeSequence(10);   5 4 3 2 1 1 2 3 4 5

  Notice that for odd numbers the sequence has a single 1 in the middle
  while for even values it has two 1s in the middle.

  Your method should throw an IllegalArgumentException if passed a
  value less than 1. A client using this method would have to call
  println to complete the line of output.

I wrote code that is pretty ugly, but produces the correct output. I've put this up to see if anyone had a more efficient recursive algorithm and to put the example up. There are not many hits about more complex recursive methods in Java when searching.

public static void writeSequence(int n) {

    if( n < 1 )
        throw new IllegalArgumentException();

    if( n == 1 ) {
        System.out.print("1");

    } else if( n == 2 ) {
        System.out.print("1 1");

    } else if( n % 2 == 0 ){
        System.out.print((n / 2) + " ");
        writeSequence(n - 2);
        System.out.print(" " + (n / 2));

    } else if( n % 2 == 1 ) {
        System.out.print(((n + 1) / 2) + " ");
        writeSequence((n - 2));
        System.out.print(" " + ((n + 1) / 2));
    }
}


texts: Implement a range behaviour in Python using iterators

texts:
I've been assigned the following Python homework:

Implement myrange that acts like range using iterators. Define a function myrangeand  define a class MyRange.

We've just seen iterators, so I think I'm asked to use them. I am not required to write a sophisticated code, but only something that allows the range-for loop syntax.
Professor said that, roughly, an iterator is an object for which the dunder method __next__ is provided. I've seen there are similar questions here. However, none of them is defining the __next__ method in a class.

So, here's what I did: first I implemented MyRange class and then my range. After that, I did two tests.
Question: It works, but I'd like to be sure from you if I solved correctly the question, I mean, if this is what I was supposed to do :-) As I said, I've just seen what is an iterator.
class MyRange():

    def __init__(self,data):
        self.data = data
        self.check()
        self.index = -1

    def check(self):
        assert len(self.data)>0, "Not enough data"

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == len(self.data)-1:
            raise StopIteration
        self.index= self.index+1
        return self.data[self.index]

def my_range(*args):
    return MyRange((args))

print("Tests using MyRange class \n")

for i in MyRange((1,2,3,4)):
    print(i)

print("Tests with range for loop \n")
for i in my_range(1,2,3,4,5,"Hello"):
    print(i)

r = MyRange((1,2,3,4,"Last Value"))
print(next(r))
print(next(r))
print(next(r))
print(next(r))
print(next(r))
print(next(r))

I'll show here the output, which seems the correct one:
1
2
3
4
Tests with range for loop

1
2
3
4
5
Hello
1
2
3
4
Last Value
Traceback (most recent call last):
  File "Untitled3.py", line 45, in <module>
    print(next(r)) #<-- Raises StopIteration
  File "Untitled3.py", line 16, in __next__
    raise StopIteration
StopIteration


texts: Avoiding code duplication in mapping layer between dataRecord and

texts:
The following code is for mapping a dataRecord to a class. I don't like this solution since it requires to duplicate the logic of mapping for each field in every method which access to the same table.

What do you think about? What about using automapper?

public IEnumerable<Model.Accounts.User> GetUsers(int IDUser)
{
    using (var sqlClient = CreateSqlManagerInstance("ListUser", CommandType.StoredProcedure))
    {
        sqlClient.AddParameterWithValue("IDUser", IDUser);
        return sqlClient.ExecuteResultSet().Select(
           dataRecord => new GModel.Accounts.User
           {
               IDUser = dataRecord.GetInt("IdUtente"),
               FirstName = dataRecord.GetString("Nome"),
               LastName = dataRecord.GetString("Cognome"),
               //[...]
           }).ToArray();
    }
}


texts:
I want to make sure I'm understanding loops. Below are the two files I used to test what I've learned. Is there anything that I'm not using that would help simplify my code?

//Program.cs
using System;

namespace _99_Bottles
{
    class Program
    {
        static void Main(string[] args)
        {
            Bar b = new Bar();
            Console.WriteLine(b.SingASong(SingingMethod.DoWhile));

            Console.WriteLine(b.SingASong(SingingMethod.ForLoop));

            Console.WriteLine(b.SingASong(SingingMethod.WhileLoop));

            Console.WriteLine(b.SingASong(SingingMethod.ForEach));
        }
    }
}

//Bar.cs
using System.Text;

namespace _99_Bottles
{
    public enum SingingMethod
    {
        ForLoop,
        WhileLoop,
        DoWhile,
        ForEach
    }
    class Bar
    {
        private StringBuilder _chorus = new StringBuilder();
        private int _bottleCount;

        public string SingASong(SingingMethod singingMethod, int numberOfBottles = 99)
        {
            _bottleCount = numberOfBottles;
            switch (singingMethod)
            {
                case SingingMethod.DoWhile:
                    return DoWhileLoop();
                case SingingMethod.ForLoop:
                    return ForLoop();
                case SingingMethod.WhileLoop:
                    return WhileLoop();
                case SingingMethod.ForEach:
                    return ForEach();
                default:
                    return "Nothing valid";
            }
        }

        private string ForLoop()
        {
            _chorus.AppendLine("ForLoop");
            for (int i = _bottleCount; i >= 1; i--)
            {
                _chorus.AppendLine(SingTheLine(i));
            }
            return _chorus.ToString();
        }

        private string WhileLoop()
        {
            _chorus.AppendLine("WhileLoop");
            int i = _bottleCount;
            while (i > 0)
            {
                _chorus.AppendLine(SingTheLine(i));
                i--;
            }
            return _chorus.ToString();
        }

        private string DoWhileLoop()
        {
            int i = _bottleCount;
            do
            {
                _chorus.AppendLine(SingTheLine(i));
                i--;
            } while (i > 0) ;

            return _chorus.ToString();
        }

        private string SingTheLine(int drinksLeft)
        {
            StringBuilder sb = new StringBuilder();
            string plurality = ((drinksLeft != 1) ? "s" : string.Empty);
            string pluralityMinusOne = ((drinksLeft + 1 != 1) ? "s" : string.Empty);
            sb.AppendLine(string.Format(string.Format("{0} bottle{1} of beer on the wall, {0} bottle{1} of beer.", drinksLeft, plurality)));
            sb.AppendLine(string.Format("Take one down and pass it around, {0} bottle{1} of beer on the wall.",((drinksLeft-1 > 1) ? (drinksLeft-1).ToString() : "no"), pluralityMinusOne));

            return sb.ToString();
        }

        private string ForEach()
        {
            const string ymca = "YMCA";

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("It's fun to stay at the:");
            foreach (char letter in ymca)
            {
                sb.AppendLine(letter.ToString());
            }

            return sb.ToString();
        }
    }
}


texts: Fetching data from a website using "POST" request

texts:
I've written some code in vba for the purpose of making twofold "POST" requests to get to the destination page and  harvest name and address from there. There are two types of structures within which the desired results lie. One type of structure holds name and address in a single "th" storage and the other holds name in one "td" and address in another "td". So, to handle this I had to use error handler to get the most out of it. By using xmlhttp I could not get any result so I used WinHttpRequest in my script to get the result by enabling redirection. My script is running errorlessly at this moment. However, any suggestion to improve my code specially by handling error more efficiently will be highly appreciated.

Here is the full working code:

Sub reverse_scraping()

    Dim http As New WinHttp.WinHttpRequest, html As New HTMLDocument
    Dim posts As Object, post As Object
    Dim ArgStr As String, ArgStr_ano As String, cNo As String, cName As String

    For Each cel In Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).Row)

        If cel.Value <> "" Then
            cNo = cel.Value
            cName = Replace(cel.Offset(0, 1).Value, " ", "+")
        End If

        ArgStr = "search=addr"
        ArgStr_ano = "TaxYear=2017&stnum=" & cNo & "&stname=" & cName

        With http
            .Option(6) = True
            .Open "POST", "https://public.hcad.org/records/QuickSearch.asp", False
            .setRequestHeader "Content-type", "application/x-www-form-urlencoded"
            .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36"
            .setRequestHeader "Referer", "https://public.hcad.org/records/quicksearch.asp"
            .send ArgStr
        End With

        With http
            .Option(6) = True
            .Open "POST", "https://public.hcad.org/records/QuickRecord.asp", False
            .setRequestHeader "Content-type", "application/x-www-form-urlencoded"
            .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36"
            .setRequestHeader "Referer", "https://public.hcad.org/records/quicksearch.asp"
            .send ArgStr_ano
            html.body.innerHTML = .responseText
        End With

        On Error Resume Next
        Set posts = html.getElementsByClassName("data")(2).getElementsByTagName("th")
        Set post = html.getElementsByClassName("bgcolor_1")(0).getElementsByTagName("tr")(1).getElementsByTagName("td")

        If posts.Length Or post.Length Then
            cel.Offset(0, 2) = posts(0).innerText
            cel.Offset(0, 2) = post(1).innerText
            cel.Offset(0, 3) = post(2).innerText
        End If

    Next cel
End Sub

Here are the two links to show how to reach the destination page (in first link it is needed to click on the "search by address" button to get the search option):

1 https://www.dropbox.com/s/e9on9zwqzmcboze/1Untitled.jpg?dl=0

2 https://www.dropbox.com/s/0lchpde8uq63jps/pics.jpg?dl=0

search to be made using the below documents placing those in column "A" and "B" respectively and results will be placed in column "c" to the corresponding cells.

Street No   Street Name
6330        LAUTREC DR
5522        DARLING ST
7411        SANDLE ST
10234       LUCORE ST


texts:
Following on from my last question, I've been continuing to look at what information is available from the SE Data Explorer, I thought it would be interesting to know who else had favorited a question.  Which led me to this query:

DECLARE @FavoriteType TINYINT = 5;

SELECT
       Votes.UserId AS [User Link],
       Votes.PostId AS [Post Link]
FROM Votes
JOIN Posts
  On Votes.PostId = Posts.Id
WHERE Votes.PostId = ##QuestionID##
AND Votes.VoteTypeId = @FavoriteType
ORDER BY Votes.CreationDate DESC

Whilst this is vaguely interesting, it's not really all that useful.  However, I thought what might be useful is to know what other questions those users might have favorited.  If enough of them favorite another question then since we already have something in common, it's probably an interesting question.  With that in mind, I came up with this query:

DECLARE @FavoriteType TINYINT = 5;

SELECT
  TOP 100
  Posts.Id AS [Post Link],
  Posts.Score AS [Score],
  Count(1) AS [Favorited By]
FROM Votes [Favorited Post]
JOIN Votes [Other Favorites]
  On [Favorited Post].UserId = [Other Favorites].UserId
JOIN Posts
  On [Other Favorites].PostId = Posts.Id
WHERE [Favorited Post].PostId = ##PostID##
AND [Favorited Post].VoteTypeId = @FavoriteType
AND [Other Favorites].VoteTypeId = @FavoriteType
GROUP BY
  Posts.Id, Posts.Score
Order by
  [Favorited By] desc

I've encountered various DBA's that were adamant about using COUNT(1) or COUNT(*), so I'm not really sure what the current flavour of the month is.  Happy for feedback on either of the queries.


texts:
I am new to erlang (2 days to be honest) and I would highly appreciate some peer review. I am doing these exercises and was a bit stuck at this point:

  2) Write a function which starts N processes in a ring, and sends a
  message M times around all the processes in the ring. After the
  messages have been sent the processes should terminate gracefully.

With some help from SO, I came up with a working solution, but I am not sure about its quality in any aspect: Language comprehension, Coding style, Efficiency, etc.

I will be grateful for any comment you have.

-module (concur).
-export ( [pingCircle/3, pingCircle/2] ).

pingCircle (Names, Message, TTL) ->
    Processes = lists:map (fun (Name) -> spawn (?MODULE, pingCircle, [Name, nobody] ) end, Names),
    ProcessPairs = lists:zip (Processes, rot1 (Processes) ),
    lists:map (fun ( {Process, Recipient} ) -> Process ! {setRecipient, Recipient} end, ProcessPairs),
    Circle = lists:map (fun ( {Process, _} ) -> Process end, ProcessPairs),
    hd (Circle) ! {Message, TTL - 1, lists:last (Circle) }.

rot1 ( [] ) -> [];
rot1 ( [Head | Tail] ) -> Tail ++ [Head].

pingCircle (Name, Recipient) ->
    receive
        {setRecipient, NewRecipient} ->
            pingCircle (Name, NewRecipient);
        {Message, 0, Originator} ->
            io:format ("~s received ~p with TTL 0 and dying.~n", [Name, Message] ),
            if
                Originator == self () -> io:format ("All dead.~n");
                true -> Recipient ! {Message, 0, Originator}
            end;
        {Message, TTL, Originator} ->
            io:format ("~s received ~p with TTL ~p.~n", [Name, Message, TTL] ),
            if
                Originator == self () -> Recipient ! {Message, TTL - 1, Originator};
                true -> Recipient ! {Message, TTL, Originator}
            end,
            pingCircle (Name, Recipient)
    end.


texts: My Sal's Shipping challenge on Codecademy

texts:
This is my attempt on the Python 3 Sal's Shipping challenge on Codecademy (Challenge Link (instructions in the link)).

I'd really appreciate anyone to take the time to review my code. I'm a very new to programming and I really wanna improve my coding, so all feedback is apreciated.

def groundCost(weight):
  if weight > 10:
    cost = weight * 4.75
  elif weight > 6:
    cost = weight * 4
  elif weight > 2:
    cost = weight * 3
  else:
    cost = weight * 1.5
  cost += 20
  return cost

def droneCost(weight):
  if weight > 10:
    cost = weight * 14.25
  elif weight > 6:
    cost = weight * 12
  elif weight > 2:
    cost = weight * 9
  else:
    cost = weight * 4.5
  return cost

def costCalc(weight):
  g = groundCost(weight)
  p = 125
  d = droneCost(weight)
  gS = "Ground Shipping"
  pS = "Premium Ground Shipping"
  dS = "Drone Shipping"
  if d == g or d == p or g == p:
    if d == g and d == p:
      print("All shipping methods cost $125 according to your items weight")
      return
    if d == g:
      same1 = dS
      same2 = gS
      cost = d
    if d == p:
      same1 = dS
      same2 = pS
      cost = d
    if g == p:
      same1 = gS
      same2 = pS
      cost = g
    print("Youre cheapest shipping method is "+same1+" and "+same2+" as they both cost $"+str(cost))
    return
  elif (g < d) and g < p:
    cheapMeth = gS
    cost = g
  elif (p < d) and p < g:
    cheapMeth = pS
    cost = p
  elif (d < g) and d < p:
    cheapMeth = dS
    cost = d
  print("Youre cheapest shipping method is "+cheapMeth+" costing $"+str(cost))
  return
weight = int(input())
costCalc(weight)


texts:
I want to refresh my web page every time a file is uploaded to the folder.

I have a web service written in flask having the following handler

@app.route('/getlatest/')
def getlatest():
    import os
    import glob
    newset = max(glob.iglob('static/*'),key=os.path.getctime)
    Return newest;

This gives me the name of the latest file in the folder.

I have an Ajax call in my JS (client side) to constantly get data from above function.

function GetLatest()
            {
                $.ajax({
                    url: "http://localhost:5000/getlatest",
                    success: function(result)
                    {
                        if(previousName != result){
                            previousName = result;
                            $("#image").attr("src","/"+previousName);
                        }
                    }
                });
            }

function calling server every second.

(function myLoop (i) {
    setTimeout(function () {
    GetLatest();
    if (--i) myLoop(i);
       }, 1000)
})(100);

This Works fine (well almost). My Question is: Is there any better way to do it (there must be)?

I'm open to technology choices what every they may be (node, angualr etc).


texts:
In my everyday work I'm trying to move away from traditional iterating over collections to a more Java 8 streams-like behavior. I'm currently working on a project where I have a collection defined as:

Map<String, <Int, String>> lineBufferMap;

that I would like to iterate through and produce a List<Record>.

My current implementation goes something like this:

Set<Record> l = lineBufferMap
    .entrySet().stream()
    .flatMap(outer -> e.getValue()
            .entrySet().stream()
            .map(inner -> createRecord(outer.getKey(), inner.getKey(), inner.getValue())))
    .filter(Objects::nonNull)
    .collect(Collectors.toSet());

createRecord method:

private Record create(String filename, Long lineNumber, String line) {
    Record record = null;
    try {
        record = new Record(
                offsetKey(key),
                offsetValue(lineNumber),
                topic,
                keySchema,
                keyStructBuilder.withContent(line).buildStruct(),
                valueSchema,
                valueStructBuilder.withContent(line).buildStruct());
    }catch (ParseException e){
        log.error("Malformed line",e);
    }
    return record;
}

I'm not happy with .filter(Object::nonNull) and haven't come up with a better idea yet.

To add to this problem, the createStruct methods can produce an unchecked parse-exception which in the current solution aborts the whole iteration.

I would prefer it to not break the whole iteration but just to skip the current faulty line and continue with the rest.

This could be considered overcomplicating things as someone suggested but I'm mostly doing it for educational purposes.


texts: NAddOdd - Topcoder - Single Round Match 714 Round 1 - Division I, Level Two

texts:
I am interested in DP problems from the past couple of days and am trying to solve various problems on topcoder. To be very frank could not even solve a single one till now. I went through https://community.topcoder.com/stat?c=problem_statement&pm=14408 question and thought to try this. I could come up with a recursive solution easily but now I am struggling for a DP solution. The following is the best I came up with:

package testpackage;

import java.util.HashMap;
import java.util.Map;

public class NAddOdd {

    public static Map<Long, Long> map = new HashMap<Long, Long>();

    public static void main(String[] args) throws Exception{
        System.out.println(solve(1, 1000, 3));
    }

    public static long solve(long L, long R, int K) throws InterruptedException{
        long answer=0l;
        for(long l = R;l>=L;l--){
            answer+=solveInter(l,K);
        }
        return answer;
    }
    public static long solveInter(long h, long K) throws InterruptedException{
        if(map.get(h) != null){
            return map.get(h);
        }
        if(K>=h){
            if(map.get(h) == null)
                map.put(h, 0l);
            return 0l;}
        if(h%2 == 0){
            if(map.get(h) == null)
                map.put(h, 1+solveInter(h/2, K));
            return map.get(h);
        }
        else{
            h = h+K;
            if(map.get(h) == null)
                map.put(h, 1+ solveInter(h, K));
            return map.get(h);
        }

    }

}

But this takes time on bigger values. Also I know memory would fails on large long values. Any clues to perfect this one?

Thanks.


texts:
Regarding the use of the file system as a database to simply hold JSON files.

Any input on this matter from people who know will be appreciated...

class JDB{

    public $path;

    function JDB( $path = __DIR__.'/jdb/' ){
        $this->path = $path;
        if( !file_exists($this->path) ) mkdir($this->path);
    }

    function p($t){
        return $this->path.$t.'.json';
    }

    function get($t){
        return json_decode(file_get_contents( $this->p($t) ));
    }

    function set($t,$c){
        return file_put_contents( $this->p($t), json_encode($c,JSON_PRETTY_PRINT) );
    }

    function create( $t, $d = [] ){
        $s = file_put_contents( $this->p($t), json_encode($d) );
        return $s;
    }

    function destroy(){
        $files = glob($this->path.'*'); // get all file names present in folder
        foreach($files as $file){ // iterate files
        if(is_file($file))
            unlink($file); // delete the file
        }
    }

    function delete( $t ){
        $s = unlink( $this->p($t) );
        return $s;
    }

    function insert( $t, $d = null ){
        if($d) $d['__uid'] = $t.'_'.$this->uid();
        $c = $this->get($t);
        array_push($c,$d);
        $s = $this->set($t,$c);
        if($s) return $d['__uid'];
    }

    function update($t,$conditions,$u){
        $c = $this->get($t);
        $this->search($c,$conditions,function($object) use (&$c,$u){
            foreach ($u as $key => $value) {
                $object->$key = $value;
            }
        });
        $this->set($t,$c);
    }

    function remove($t,$conditions){
        $c = $this->get($t);
        $this->search($c,$conditions,function($object,$key) use (&$c){
            unset($c[$key]);
        });
        $this->set($t,$c);
    }

    function search( $c, $conditions = [], $fn ){
        $l = count($conditions);
        foreach ($c as $key => $object) {
            $f = 0;
            foreach ($conditions as $k => $v) {
                if( property_exists($object,$k) && ($object->$k == $v) ){
                    $f++;
                    if( $f==$l ) $fn($object,$key);
                }else break;
            }
        }
    }

    function select( $t, $conditions = [] ){
        $c = $this->get($t);
        $r = [];
        $this->search($c,$conditions,function($object) use (&$r){
            array_push($r,$object);
        });
        if (count($r) == 0) return false;
        if (count($r) == 1) return $r[0];
        return $r;
    }

    function count($t){
        $c = $this->get($t);
        return count($c);
    }

    function uid($length = 20) {
        $c = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $cl = strlen($c);
        $uid = '';
        for ($i = 0; $i < $length; $i++) {
            $uid .= $c[rand(0, $cl - 1)];
        }
        return $uid;
    }

}

/*

$db = new JDB();

$db->create('users');
$db->create('pages');

$user_uid = $db->insert('users',[
    'name' => 'a',
    'password' => 'hello world',
    'pages'  => []
]);

$user_uid = $db->insert('users',[
    'name' => 'b',
    'password' => 'hello world',
    'pages'  => []
]);

_log($user_uid,'1');

$page_uid = $db->insert('pages',[
    'name' => 'page 1',
    'content' => 'hello world',
    'users'  => [$user_uid]
]);

_log($page_uid);

$user = $db->select('users',['name'  => 'a']);
$page = $db->select('pages',['users'  => [$user_uid]]);

$db->update('users',['name'  => 'b'],['pages' => [$page->__uid]]);
$db->remove('users',['name'  => 'a']);

_log($user);
_log($page);

*/