texts: Most frequent word in an array of strings - Java

texts:
Input word array is
{ "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer","science", "zoom", "yup", "fire", "in", "be", "data", "a", "portal","geeks" };

Problem is to find most frequent word in array.
I want to find solution that can support on adding more element.

I have tried this code :-

package com.techiekunal.examples.datastructure;

import java.util.Iterator;
import java.util.PriorityQueue;

/**
 * MyWord objects will have word and its frequency
 *
 * @author Kunal.Saxena
 *
 */
class MyWord implements Comparable<MyWord>{

    // word from array
    private String word;

    // word's frequency
    private int count;

    public MyWord(int count, String word) {
        this.count = count;
        this.word = word;
    }

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    // Objects are equals if words are same
    @Override
    public boolean equals(Object obj) {
        if(obj == null)
            return false;
        if(this.getClass() != obj.getClass())
            return false;

        MyWord myWord = (MyWord) obj;
        return this.word.equals(myWord.word);
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    // Printing word and count against it
    @Override
    public String toString() {
        return this.word + " : " + this.count;
    }

    // comparison for descending order of count
    @Override
    public int compareTo(MyWord o) {
        if(this.count > o.count) {
            return -1;
        }
        if(this.count < o.count) {
            return 1;
        }
        return 0;
    }

}

public class MostFrequentUsedWords {

    // Input array
    private static String[] arr = { "geeks", "for", "geeks", "a", "portal", "to", "learn", "can", "be", "computer",
            "science", "zoom", "yup", "fire", "in", "be", "data", "a", "portal","geeks" };

    // Queue will work as max heap to store words
    private static PriorityQueue<MyWord> queue = new PriorityQueue<>();

    // Creating PriorityQueue from given input array
    private static void createQueue() {

        for (String word : arr) {
            // check if word already exists
            if (queue.contains(new MyWord(1, word))) {

                MyWord oldWord = null;
                // iterate to find word : we need latest frequency of that word
                Iterator<MyWord> itr = queue.iterator();
                while (itr.hasNext()) {

                    MyWord next = itr.next();
                    if (next.getWord().equals(word)) {
                        oldWord = next;
                    }
                }
                // create new word by incrementing frequency, remove old word from queue, adding new word to queue
                MyWord newWord = new MyWord(oldWord.getCount() + 1, oldWord.getWord());
                queue.remove(oldWord);
                queue.add(newWord);

            } else {
                // if word is not in queue : add it with frequency 1
                MyWord newWord = new MyWord(1, word);
                queue.add(newWord);
            }
        }

    }

    public static void main(String[] args) {

        // Create priority queue
        createQueue();

        // Print Queue
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
    }

}

My output is :-

geeks : 3
a : 2
portal : 2
be : 2
yup : 1
zoom : 1
science : 1
computer : 1
in : 1
can : 1
learn : 1
to : 1
data : 1
fire : 1
for : 1

I implemented this using priority queue and it is working fine. it is like creating max heap. But its complexity is n^2. Need help if this can be solve in less complex way.


texts:
How can I improve this method that adds data to three tables in the database?

The tables are:

UserTable
UserInfoTable
ContactTable

UserInfoTable and ContactTable have a one-to-many relationship, with ContactTable having UserInfoID as a foreign key.

public static boolean addUser(User user) {
Connection connection = getConnection();
try {
PreparedStatement insertUser = connection.prepareStatement(Insert_User);
insertUser.setString(1, user.getUsername());
insertUser.setString(2, user.getPassword());
insertUser.setString(3, user.getUserType());
insertUser.executeUpdate();
PreparedStatement insertUserInfo = connection.prepareStatement(Insert_UserInfo);
insertUserInfo.setString(1, user.getFirstName());
insertUserInfo.setString(2, user.getMiddleName());
insertUserInfo.setString(3, user.getLastName());
insertUserInfo.setString(4, user.getGender());
insertUserInfo.setString(5, user.getBirthdate());
insertUserInfo.executeUpdate();
//I need to get the UserInfoID to insert to ContactTable. I really hate to do this but I can't think of any way to insert the foreign key.
PreparedStatement getUserInfoID = connection.prepareStatement(GET_USER_INFO_ID);
getUserInfoID.setString(1, user.getFirstName());
getUserInfoID.setString(2, user.getMiddleName());
getUserInfoID.setString(3, user.getLastName());
getUserInfoID.setString(4, user.getGender());
getUserInfoID.setString(5, user.getBirthdate());
ResultSet rs = getUserInfoID.executeQuery();
PreparedStatement insertContact = connection.prepareStatement(Insert_Contact);
while (rs.next()) {
insertContact.setInt(1, rs.getInt(1));
insertContact.setString(2, user.getEmailAddress());
insertContact.setString(3, user.getAddress());
insertContact.setString(4, user.getContactNumber());
insertContact.executeUpdate();
}
} catch (SQLException sqle) {
sqle.printStackTrace();
return false;
}
return true;
}

I originally want to set the connections's autocommit to false so the connection will rollback if an insert statement fails, but since I need to get the UserInfo ResultSet to get the UserInfoID, I can't do it anymore. How can I do this better?


texts:
Following this reference, below is the list abstraction implementation using array,

/* list.h */

/*
   List is an ordered collection(sequence) of homogeneous type elements(unique or duplicate).
   By definition, List is not suppose to have collection of heterogeneous type elements.
   All elements in a List are related.
   List is mutable
   Each element has a position.
   If an element is deleted, then still the remaining elements sit in new order.

   Array implementation of List

*/

#include<stddef.h>
#include<stdlib.h>
#include<string.h>

#define INITIAL_LIST_SIZE 50

#define NEW_LIST 0
#define DOUBLE_THE_LIST 1
#define HALF_THE_LIST 2

typedef struct List{
  int *array;
  int lastItemPosition;
  int size;
}List;

extern List *arrayList;

void insertItem(int newItem, int location);
List* createList(List *, int);

/* arrayImpl.c */
#include"list.h"

List *createList(List *list, int flag){

  List *lptr = (List *)malloc(sizeof(List));

  if(flag == NEW_LIST){
    lptr->array = malloc(INITIAL_LIST_SIZE*sizeof(int));
    lptr->array = memset(lptr->array, -1, INITIAL_LIST_SIZE*sizeof(int));
    lptr->lastItemPosition = -1;
    lptr->size = INITIAL_LIST_SIZE;
  }else if(flag == DOUBLE_THE_LIST){
    lptr->array = malloc(2*(list->size)*sizeof(int));
    lptr->array = memcpy(lptr->array, list->array, list->size*sizeof(int));
    lptr->lastItemPosition = list->lastItemPosition;;
    lptr->size = 2*(list->size);
  }else if(flag == HALF_THE_LIST){
    lptr->array = malloc(((list->size)/2)*sizeof(int));
    lptr->array = memcpy(lptr->array, list->array, (list->size/2)*sizeof(int));
    lptr->lastItemPosition = list->lastItemPosition;;
    lptr->size = (list->size)/2;
  }
  return lptr;

}

void insertItem(int newItem, int index){

  /* House keeping */
  if(arrayList->lastItemPosition + 1 == arrayList->size){
    arrayList = createList(arrayList, DOUBLE_THE_LIST);
  }

  /* Insert the element */
  arrayList->array[index] = newItem;
  if(index > arrayList->lastItemPosition){
     arrayList->lastItemPosition = index;
  }

  return;
}

void deleteItem(int index){

  arrayList->array[index] = -1;
  if(index == arrayList->lastItemPosition){
    arrayList->lastItemPosition--;
  }

  /* House keeping */
  if(arrayList->size > INITIAL_LIST_SIZE){
    if(arrayList->lastItemPosition == ((arrayList->size)/2)){
      arrayList = createList(arrayList, HALF_THE_LIST);
      arrayList = createList(arrayList, HALF_THE_LIST);
    }
  }
}

/* main .c */
#include"list.h"

List *arrayList = NULL;

int main(void){
  arrayList = createList((List *)NULL, NEW_LIST);

}

Is  Listfollowing abstraction and encapsulation?

Note: Encapsulation is about maintaining in-variants of ADT, after performing operations on ADT. Abstraction is a barrier between representation and usage.


texts: Project Euler problem 11, finding adjacent numbers with the greatest sum

texts:
The full description of the problem to solve can be found here. The code I have written works fine but seems extremely verbose for what it's doing, I'm not sure if list comprehensions are meant to be used in the way that I have (maybe some kind of other construct would be more suitable?). Would be great for there to be a way to make the numberPairs function to be more DRY.

Also get the sense that I don't use function composition enough . and instead use $ for most nested function calls. Is this bad practice? How could I rewrite some of the functions in this using composition?

I am fairly new to Haskell so am unaware of any typical coding practices.

gridOfNumbers evaluates to a string containing the grid numbers from the problem with each number in a row separated by spaces and each row separated by newlines. Didn't seem worth including here (although I may be mistaken).

-- | In the `gridOfNumbers` find the 4 adjacent numbers in the given
-- | direction that have the greatest sum.
problem_11 :: Direction -> Int
problem_11 dir =
    maximum $ map (\(x1,x2,x3,x4) -> product $ x1:x2:x3:x4:[]) $ numberPairs dir

data Direction = UpDown | SideWays | LeftStartDiagonal | RightStartDiagonal

numberPairs :: Direction -> [(Int,Int,Int,Int)]
numberPairs UpDown =
    [(x1,x2,x3,x4) |
     currentRow <- [0..16],
     currentCol <- [0..19],
     let x1 = (listifyGrid !! currentRow) !! currentCol,
     let x2 = (listifyGrid !! (currentRow + 1)) !! currentCol,
     let x3 = (listifyGrid !! (currentRow + 2)) !! currentCol,
     let x4 = (listifyGrid !! (currentRow + 3)) !! currentCol]
numberPairs SideWays =
    [(x1,x2,x3,x4) |
     currentRow <- [0..19],
     currentCol <- [0..16],
     let x1 = (listifyGrid !! currentRow) !! currentCol,
     let x2 = (listifyGrid !! currentRow) !! (currentCol + 1),
     let x3 = (listifyGrid !! currentRow) !! (currentCol + 2),
     let x4 = (listifyGrid !! currentRow) !! (currentCol + 3)]
numberPairs LeftStartDiagonal =
    [(x1,x2,x3,x4) |
     currentRow <- [0..16],
     currentCol <- [0..16],
     let x1 = (listifyGrid !! currentRow) !! currentCol,
     let x2 = (listifyGrid !! (currentRow + 1)) !! (currentCol + 1),
     let x3 = (listifyGrid !! (currentRow + 2)) !! (currentCol + 2),
     let x4 = (listifyGrid !! (currentRow + 3)) !! (currentCol + 3)]
numberPairs RightStartDiagonal =
    [(x1,x2,x3,x4) |
     currentRow <- [0..16],
     currentCol <- [3..19],
     let x1 = (listifyGrid !! currentRow) !! currentCol,
     let x2 = (listifyGrid !! (currentRow + 1)) !! (currentCol - 1),
     let x3 = (listifyGrid !! (currentRow + 2)) !! (currentCol - 2),
     let x4 = (listifyGrid !! (currentRow + 3)) !! (currentCol - 3)]

listifyGrid :: [[Int]]
listifyGrid = map (map read) doubleListOfStrings
    where doubleListOfStrings = map (S.split " ") $ lines gridOfNumbers


texts: Console-based game in Java to demonstrate Solid principles and abstractions

texts:
I've written a console-based demo while learning about the Solid principles. Along the way, I've become exceedingly paranoid about whether I'm writing good code or not.

Here is the code I have so far:

public class Entity {  //Base template for all game entities...

private String name;

public Entity(String name)
{
    this.name = name;
    displayEntityName();
}

public String getName()
{
    return name;
}

public void setName(String newName)
{
    name = newName;
}

private void displayEntityName()
{
    System.out.println(name + " entity created...");
}

public class Player extends Entity {

private String[] inventory; //Player will have an inventory.
private int itemsInInventory;
private static final Random RAND = new Random();

public Player(String name) {
    super(name);
    inventory = new String[25]; //Default inventory size.
}

public void attack(Enemy enemy) //Player can attack all enemy types.
{
    System.out.println(super.getName() + " attacked the enemy...");
}

public void findLegendaryWeapon()
{
    inventory[0] = WeaponConstants.LEGENDARY_WEAPONS
    [RAND.nextInt(WeaponConstants.LEGENDARY_WEAPONS.length)];
    itemsInInventory++;
}

public void equiptWeapon()
{
    System.out.println(super.getName() + " equipted a weapon...");
}

public void searchChest()
{
    System.out.println(super.getName() + " searched the chest and found nothing...");
}

}

public enum WeaponConstants{ //Legendary weapon constants.

BOW_OF_THE_MAJOR_ARCHER(), BLOOD_LETTER,
DAWNFANG, FROZEN_TOUCH;

public static final String[] LEGENDARY_WEAPONS = {DAWNFANG.name(),
        BLOOD_LETTER.name(), FROZEN_TOUCH.name(), BOW_OF_THE_MAJOR_ARCHER.name()};

}

public interface Enemy { //Enemy interface...
    void attack(Player player);
}

public class Ghoul extends Entity implements Enemy { //An example of a standard enemy class.

    public Ghoul(String name) {
        super(name);
    }

    @Override
    public void attack(Player player) {
        System.out.println(super.getName() + " attacked " + player.getName());
    }
}

As mentioned above, I mainly want to know if I'm violating any of the Solid principles. My main concern is with my player class. I have quite a few methods in the class that do different types of things but they are all related to the player. Is this in any way violating the SRP principle?

Also, I wanted to know if my abstractions are correct and well-designed. Does this represent good coding style when used to develop more serious apps? I only have one year of experience, so I'm trying to solidify good practices early on. All input would be appreciated.


texts:
I hava a collection of schedules - EventSchedules. I want to select from this collection today, tomorrow and after tomorrow schedules. The day start from 06:00 and end 6:00 of next day.

Examples:

For today the query return events start in range: 30 July 2012 06:00 - 31 July 2012 06:00
For tomorrow the range is: 31 July 2012 06:00 - 01 August 2012 06:00

Any advice for refactoring this code?

private void FillSchedulesByFilter()
{
    var filterTimeStart = DateTime.Today.AddHours(6);
    var filterTimeEnd = filterTimeStart.AddDays(1);

    TodayGroupedSchedules = EventScheduleList.Where(s => s.RecurrenceStart >= filterTimeStart &&
                              s.RecurrenceStart < filterTimeEnd).
                              GroupBy(p => p.BasePlace);

    filterTimeStart = filterTimeStart.AddDays(1);
    filterTimeEnd = filterTimeEnd.AddDays(1);

    TomorrowGroupedSchedules = EventScheduleList.Where(s => s.RecurrenceStart >= filterTimeStart &&
                               s.RecurrenceStart < filterTimeEnd).
                               GroupBy(p => p.BasePlace);

    filterTimeStart = filterTimeStart.AddDays(1);
    filterTimeEnd = filterTimeEnd.AddDays(1);

    AfterTomorrowGroupedSchedules = EventScheduleList.Where(s => s.RecurrenceStart >= filterTimeStart &&
                               s.RecurrenceStart < filterTimeEnd).
                               GroupBy(p => p.BasePlace);

}


texts: Display related records, if they exist, in Rails view

texts:
Is this much logic in view is justified to check for the presence of record?

# device model
class Device < ApplicationRecord
  validates :abbr, uniqueness: { case_sensitive: false }, presence: true
  validates :name, presence: true

  def abbr=(value)
    self[:abbr] = value.to_s.strip
  end
end

Here is the code for DeviceVendor that also saves abbr column of Device to uniquely identify the device:

# model code
class DeviceVendor < ApplicationRecord
  validates :vendor, uniqueness: {scope: :device}
end

# controller code
def index
  @device_vendors = DeviceVendor.order(:device, :vendor)
end

# view code
<% @device_vendors.each do |device_vendor| %>
  <% device = Device.where(abbr: device_vendor.device).first %>
  <% vendor = Vendor.where(abbr: device_vendor.vendor).first %>

    <%= device.name if device %>
    <%= vendor.name if vendor %>
    <%= link_to 'Show', device_vendor %>
    <%= link_to 'Edit', edit_device_vendor_path(device_vendor) %>

<% end %>

What is the rails way to do this?


texts:
Given a list of tuples of the form, (a, b, c), is there a more direct or optimized for calculating the average of all the c's with PySpark? Below is what I have, but I feel like there is a more direct/optimized approach?

Classic movie recommendation example, where each tuple is (userID, movieID, rating). How do we get the average of all of the ratings in a direct/optimized fashion?

ds_movie = sc.parallelize([(1,1,2.25), (1,2,3.0), (2,1,4.5)])
total = (ds_movie
         .map(lambda (userid, movieid, rating): rating)
         .reduce(lambda x, y: x + y))
num = ds_movie.count()
average = total / num
# in this example, average = 3.25


texts: Graph implementation to be used for finding Cycles, Paths, closest path between two nodes, etc

texts:
I am restudying graph theories and I want to write a Graph class that would allow me to implement those methods. Is there a better way of implementing a general Graph class?

Main function:

int main() {

    using namespace GraphUtils;

    Graph<char> graph;

    Node<char> a('a');
    Node<char> b('b');
    Node<char> c('c');
    Node<char> d('d');
    Node<char> e('e');
    Node<char> f('f');

    graph.AddNode(a).AddNode(b).AddNode(c).AddNode(d).AddNode(e).AddNode(f);

    a.AddChild(f).AddChild(d);
    b.AddChild(c).AddChild(a);
    c.AddChild(d);
    e.AddChild(f);
    f.AddChild(b);

    graph.Print();

    if( !PathExist(graph, a, b)) {
        cout << "ERR: a -> b exists" << endl;
    }

    if( !PathExist(graph, a, c)) {
        cout << "ERR: a -> c exists" << endl;
    }

    if( PathExist(graph, a, e)) {
        cout << "ERR: a -> c doesn't exist" << endl;
    }

    if( PathExist(graph, c, e)) {
        cout << "ERR: c -> e doesn't exist" << endl;
    }
    if( !PathExist(graph, e, c)) {
        cout << "ERR: e -> c exists" << endl;
    }
}

Class implementation, which is heavily pointer-oriented:

#include <iostream>
#include <map>
#include <vector>
#include <queue>

using std::map;
using std::vector;
using std::cout;
using std::endl;
using std::queue;

namespace GraphUtils {

template <typename T>
struct Node {
    T data;
    vector<Node*> children;

    Node() {}
    Node(T input): data(input) {}

    Node& AddChild(Node& input) {
        children.push_back(&input);
        return *this;
    }

};

template <typename T>
bool operator<(Node<T>& lhs, Node<T>& rhs) {
    return (lhs.data < rhs.data);
}

template <typename T>
bool operator==(Node<T>& lhs, Node<T>& rhs) {
    return !(lhs.data < rhs.data || lhs.data > rhs.data);
}

template<typename T>
struct Graph {
    vector<const Node<T>* > nodes;

    Graph& AddNode(const Node<T>& input) {
        nodes.push_back(&input);
        return *this;
    }

    void Print() {

        for(typename vector<const Node<T>* >::const_iterator iter = nodes.begin();
                iter != nodes.end();
                iter++)
        {
            cout << (*iter)->data << ":";

            for(typename vector<Node<T>* >::const_iterator child = (*iter)->children.begin();
                    child != (*iter)->children.end();
                    child++)
            {
                cout << (*child)->data << ", ";

            }

            cout << endl;
        }
    }
};

// using BFS to determine if path exists
template<typename T>
bool PathExist(Graph<T>& graph, Node<T>& a, Node<T>& b) {

    map<const Node<T>* , bool> t_visited;
    queue<Node<T>* > t_queue;

    for(typename vector<const Node<T>* >::const_iterator iter = graph.nodes.begin();
            iter != graph.nodes.end(); iter++)
    {
        t_visited[*iter] = false;
    }

    t_queue.push(&a);

    Node<T>* t_node;
    while(!t_queue.empty()) {

        // get the top object
        t_node = t_queue.front();
        t_queue.pop();

        // set visited
        t_visited[t_node] = true;

        // node doesn't have the == operator
        if(*t_node == b) return true;

        // for each ot it's children
        for(typename vector<Node<T>* >::iterator iter = t_node->children.begin();
                iter !=  t_node->children.end(); iter++)
        {
            // if item has not been visited
            if(!t_visited[(*iter)]) {
                t_queue.push((*iter));
            }
        }
    }

    return false;
}

};


texts:
I'm working on a personal project to get better with C#, and as part of that I have a zip file with 20 or so images saved inside. I want to load those images out of the zip file and display them in my WPF app. I have it working, but I don't know if what I have is the best way to go about this. The goal is to load the images to be used as fast as possible, so I tried using threads, which work, but again I'm not sure if this is the proper way to utilize them for this, or if threads are even the best way to achieve the quickest time for the task.

I would appreciate any feedback anyone could give to help me improve this code and write better code in the future.

In the code below, I have the two functions I use to open and get the images. the variable ChapterLocation is a string that stores the file location of the .zip file, and Pages is a List. Page is a custom struct that just holds a BitmapImage and a String that gives that image a name that I can display.

private void BitmapLoad(ZipArchiveEntry z)
{
    using (var stream = z.Open())
    {
        using (var mstream = new MemoryStream())
        {
            stream.CopyTo(mstream);
            mstream.Position = 0;

            var bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.CacheOption = BitmapCacheOption.OnLoad;
            bitmap.StreamSource = mstream;

            bitmap.EndInit();
            bitmap.Freeze();

            Pages.Add(new Page(bitmap, z.Name));
        }
    }
}

private void LoadChapterOptimized()
{
    var zipFile = ZipFile.OpenRead(ChapterLocation);
    foreach (ZipArchiveEntry z in zipFile.Entries)
    {
        Thread t = new Thread(() => BitmapLoad(z));
        t.Start();
        t.Join();
        Debug.WriteLine(z.Name);
    }
    Pages.Sort();
    zipFile.Dispose();
}


texts: Breadth First Search using adjacency list

texts:
I want to improve this code using STL. Let me know if I should add any other function in this code.

#include <iostream>
#include <vector>
#include <queue>
#include <list>
#include <limits>

class Graph
{
  int vertex_count;
  enum Color {WHITE, GRAY, BLACK};

  enum { INFINITY = std::numeric_limits<int>::max() };

  struct Vertex
  {
     int id;
     int distance;
     Color color;

     Vertex(int _id) : id(_id),
                       color(Color::WHITE),
                       distance(INFINITY)
                       {}
  };

public:

  std::vector<Vertex> vertices;
  std::vector< std::list<int> > adjList;

  Graph(int);
  void addEdge(int, int);
  void breadthFirstSearch(int);
};

Graph::Graph(int v)
{
   vertex_count = v;
   adjList.resize(vertex_count);
   for (int i = 0; i < vertex_count; i++)
   {
       vertices.push_back( Vertex(i) );
   }
}

void Graph::addEdge(int src, int dest)
{
  //undirected graph
   adjList[src].push_back(dest);
   adjList[dest].push_back(src);
}

void Graph::breadthFirstSearch(int s)
{
   vertices[s].color = GRAY;
   vertices[s].distance = 0;
   std::queue<Vertex> q;
   q.push(vertices[s]);
   while (!q.empty())
   {
      auto u = q.front();
      q.pop();
      for (auto v = adjList[u.id].begin(); v != adjList[u.id].end(); v++)
      {
         if (vertices[*v].color == WHITE)
         {
            vertices[*v].color = GRAY;
            vertices[*v].distance = u.distance + 1;
            q.push(vertices[*v]);
         }
      }
      u.color = BLACK;
      std::cout << vertices[u.id].id << " at level " << vertices[u.id].distance <<'\n';
   }
}

int main()
{
   Graph grp(5);
   grp.addEdge(0, 1);
   grp.addEdge(0, 4);
   grp.addEdge(1, 3);
   grp.addEdge(1, 4);
   grp.addEdge(1, 2);
   grp.addEdge(2, 3);
   grp.addEdge(3, 4);
   grp.breadthFirstSearch(2);
}


texts: Building multiple parts of formula strings from different inputs in R

texts:
I have been building a function that creates more advanced formula snippets using simple formula code. For example, a user may write:
$$Given\ dependent\ variable\ Y,\ and\ indepdentent\ variables\ X\  and \ U$$
$$Argument\ 1:\ Y_t = \alpha_t +  X_t,\ where\ X_t\ \to\  X_t + \sum_{i = -k}^k \Delta X_{t-i}$$
$$Argument\ 2: \ =U_t ,\ where\ U_t \to\ +\sum_{I = 1}^k U_{t-i} $$

in R: y ~ 1 + x becomes y ~ 1 + x + L(diff(x),-k:k) and

in R: ~ u becomes L(u,1:k)

I have built the following but am curious for feedback as (1) the code itself feels lengthy and (2) it is not super intuitive for a user to start Argument 2 with a ~.

buildFormula(Arg1 = y ~ x, data = dat)
#[1] "y ~ 1 + x + L(diff(x),-k:k)"

buildFormula(Arg1 = y ~ x + u + z, data = dat)
#[1] "y ~ 1 + x + u + z + L(diff(x),-k:k) + L(diff(u),-k:k) + L(diff(z),-k:k)"

buildFormula(Arg1 = y ~ x, data = dat, Arg2 = ~ u)
#[1] "y ~ 1 + x + L(diff(x),-k:k) + L(u,1:k)"

buildFormula(Arg1 = y ~ x, data = dat, Arg2 = ~ u + z)
#[1] "y ~ 1 + x + L(diff(x),-k:k) + L(u,1:k) + L(z,1:k)"

buildFormula(Arg1 = y ~ x, data = dat, Arg2 = ~u)
#[1] "y ~ 1 + x + L(diff(x),-k:k) + L(u,1:k)"

buildFormula(Arg1 = y ~ x, data = dat, Arg2 = u + z)
#Error in ... :
#  object 'u' not found

buildFormula(Arg1 = y ~ x, data = dat, Arg2 = u + z)
#Error in ... :
#  object 'u' not found

(3) I would also be appreciative if someone would recommend how to catch this error and warn the user to add a ~ in Arg2.

Function Code

# generate data
dat <- cbind(y = rnorm(30), x = rnorm(30), u = rnorm(30), z = rnorm(30))
# function
buildFormula <- function(Arg1, data, Arg2 = NULL){
  ff <- Arg1
  all_names <- dimnames(attr(terms(ff), "factors"))
  y_names <- all_names[[1]][!(all_names[[1]] %in% all_names[[2]])]
  x_names <- all_names[[2]][all_names[[2]] %in% colnames(data)]
  ff_LHS <- y_names
  # building the right hand side ( ~ X1 + X2 + L(diff(X1),-k:k) + L(diff(X2),-k:k) )
  ff_RHS <- paste(c(ifelse(attr(terms(ff), "intercept") == 1, "1", "-1"), # intercept
                    x_names, # independent variables
                    paste0("L(diff(", x_names, "),-k:k)")), # sum of lagged differences of independent variables
                  collapse = " + ")
  # if extra was indicated, add it on but treat it differently (~ + L(X3, 1:k) )
  ff_RHS <- ifelse(is.null(Arg2), ff_RHS, paste0(ff_RHS, " + ",
                                                   paste0("L(", unlist(strsplit(as.character(Arg2)[-1], " \\+ ")),
                                                          ",1:k)",
                                                          collapse = " + ")))
  ff_k <- paste(ff_LHS, "~", ff_RHS)
  ff_k
}


texts:
I am building one of those contact forms that are conversational. I have code that works but I don't think it is optimal (at the bottom). The form looks like:

The code is live on this codepen

The problem I was solving was that the placeholder text on one of them is very large and would either break into two lines or if I gave it a fixed width, it would break the layout of smaller mobile phones. Yes, I understand the the very simple solution would be to propose a change to the copy for any instance, but going on the fact that it cannot be done, how would I solve swapping the text based on the device width.

My proposed solution was to reduce the text on mobile. Since there they are more flexible with the mobile product, I can make these changes, but the desktop needs to comply with the PSD.

HTML

<input type="text" id="org" name="" placeholder="ORGANIZATION OR COMPANY NAME">

CSS

#org{
  display: block;
  width: 96%;
  margin: 0 auto;
}
@media only screen and (min-width: 768px) {
  #org{
    display: inline-block;
    width: 360px;
  }
}

It needs to be at least 360px to match the PSD for desktop.

One other option that I have is if I have entirely different inputs, would that work? like

<input type="text" id="org" class="orgm" name="" placeholder="ORG/COMPANY">
<input type="text" id="org" class="orgd" name="" placeholder="ORGANIZATION OR COMPANY NAME">

.orgm { //mobile
    display: block;
}
.orgd {
    display: none;
}
@media only screen and (min-width: 768px) {
  .orgm{
      display: none;
      width: 96%;
      margin: 0 auto;
  }
  .orgd {
      display: inline-block;
      width: 360px;
      margin: 0;
  }
}


texts:
Just looking for some feedback on a hangman script.  It works perfectly fine; I'm just trying to master the Python language, and the best place way to get better is to ask the true masters!

import random

UNKNOWN_CHARACTER = "*"
GUESS_LIMIT = 7

words = []

def load_words():
    global words
    with open("dictionary.txt") as file:
        words = file.readlines()
    stripped = []
    for word in words:
        stripped.append(word.strip())
    words = stripped

def play():
    word = random.choice(words)
    solved = False
    constructed = ""
    guessed = []
    guess = ""
    for i in range(0, len(word)):
        constructed += UNKNOWN_CHARACTER
    while not solved and len(guessed) < GUESS_LIMIT:
        print("\n" + str(GUESS_LIMIT - len(guessed)) + " errors left...")
        print(constructed)
        valid_guess = False
        while not valid_guess:
            guess = input("Guess a letter: ").lower()
            if len(guess) == 1:
                if guess not in guessed and guess not in constructed:
                    valid_guess = True
                else:
                    print("You've already guessed that letter!")
            else:
                print("Please guess a single letter.")
        if guess in word:
            new_constructed = ""
            for i in range(0, len(word)):
                if word[i] == guess:
                    new_constructed += guess
                else:
                    new_constructed += constructed[i]
            constructed = new_constructed
        else:
            guessed.append(guess)
        solved = constructed == word
    print("\n" + word)

def main():
    load_words()
    keep_playing = True
    while keep_playing:
        play()
        keep_going = input("Continue playing? (y/n): ").lower()
        if keep_going not in ["yes", "y"]:
            keep_playing = False

if __name__ == "__main__":
    main()

Excerpt of dictionary.txt:

logorrheic
logos
logotype
logotypes
logotypies
logotypy
logroll
logrolled
logroller
logrollers
logrolling
logrollings
logrolls
logs
logway
logways
logwood
logwoods
logy
loin
loincloth
loincloths
loins
loiter
loitered
loiterer
loiterers
loitering
loiters
loll
lollapalooza
lollapaloozas
lolled
loller
lollers


texts: Dynamically creating login screen on Android devices

texts:
This has been an experience. I'm well above "hello world" java is not a language I use often when programming and I don't program too much. I find myself a lot on Google.... basically just about for every task. Which has brought me here. Before I continue on I would like a critique of my work so I don't have to change a great deal if things are off.

The goal is to create a dynamically created login screen, adding the appropriate buttons for the social networks the user has installed on their device. (As I type that I question the reasoning for that... except as an excruciating coding exercise, lol.) Regardless I believe I would find a critique useful and beneficial as I'm sure I'll encounter more situations where the lessons can be applied.

A few things have stuck out at me:

Excessive exception handling
JSON not as easy in Java as PHP
Best approach for global constants

For constants I did the following, and made them all arrays just to make life easier later:

public final class Globals {
    // .. More constants
    public static final class SocialMedia {
        public static final String[] Facebook = {
                    "com.facebook.orca",
                    "com.facebook.katana",
                    "com.example.facebook",
                    "com.facebook.android"
            };
        public static final String[] Twitter = {"com.twitter.android"};
    }
    // .. More constants
}

My onCreate method for the Login activity seems overly cluttered with needless exception handling (at least IDK what to do... and in some instances the "problem" is legal). It has me questioning whether or not JSON is the best way to store the app state across activities. That and accessing nested JSONObjects seems to be a bit more work than PHP (i.e. PHP: if($myJSON["SocialNetworkInstalled"]["Facebook"] == false) )

Lastly, to iterate over constants that could be a growing list, I chose reflection. Not really sure if my approach to global constants and accessing them is the best.

onCreate() Beginning:

public class LoginActivity extends AppCompatActivity implements
    View.OnClickListener {

private JSONObject mAppState;
//... More members and methods

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    JSONObject json = new JSONObject();
    int orientation;
    mAppState = ((MyApp) getApplicationContext()).state;

    if(!mAppState.has(Labels.SocialNetworkInstalled)) {
        String nameNetwork;
        boolean bInstalled;

        PackageManager pm = getPackageManager();

        for (Field field : Globals.SocialMedia.class.getDeclaredFields()) {
            if(!field.getType().isAssignableFrom(String[].class)) continue;

            bInstalled = false;
            nameNetwork = field.getName();

            try {
                for (String apkname : (String[]) field.get(null)) {
                    try {
                        pm.getPackageInfo(apkname, 0);
                        bInstalled = true;
                    } catch (PackageManager.NameNotFoundException e) {}
                }
                json.put(nameNetwork, bInstalled);
            }
            catch (IllegalAccessException e) {/*Legal: field.get(null) for statics*/}
            catch (JSONException e) {}
        }

        try {
            mAppState.put(Labels.SocialNetworkInstalled, json);
        } catch (JSONException e) {}
    }

    try {
        json = mAppState.getJSONObject(Labels.SocialNetworkInstalled);
        Iterator<String> i = json.keys();
        String app;
        while(i.hasNext()) {
            app = i.next();
            if(json.getBoolean(app))
                Log.d("L2SN","FOUND " + app);
            else
                Log.d("L2SN","NOT FOUND " + app);
        }
    } catch (JSONException e) {}
    //.....

Seems quite a bit of code for creating and accessing a structure which at that point would resemble something like:

{
    "SocialNetworkInstalled": {
        "Facebook": true,
        "Twitter": false
    }
}


texts:
I have an array of objects that I must sort based on two criteria. I've come up with a solution but I'd like to know if there is a better way to do it.

Assume a list of devices:

[
    {"battery_level": 0.45, "network_status": "ok"},
    {"battery_level": 0.45, "network_status": "ok"},
    {"battery_level": 0.50, "network_status": "lost"},
    {"battery_level": 0.35, "network_status": "lost"},
    {"battery_level": 0.75, "network_status": "ok"},
    {"battery_level": 0.05, "network_status": "lost"},
    {"battery_level": 0.75, "network_status": "lost"}
]

All lost devices must be on top and sorted by battery status ascending, so that it looks like this once sorted:

[
    {"battery_level":0.05,"network_status":"lost"},
    {"battery_level":0.35,"network_status":"lost"},
    {"battery_level":0.5,"network_status":"lost"},
    {"battery_level":0.75,"network_status":"lost"},
    {"battery_level":0.75,"network_status":"ok"},
    {"battery_level":0.45,"network_status":"ok"},
    {"battery_level":0.45,"network_status":"ok"}
]

Demo here

var devices = JSON.parse(document.getElementById('devices').innerHTML),
    lostDevices,
    sortBatteryLevelAsc,
    sortNetworkStatusLostAsc,
    i;

devices.sort(function (dev0, dev1) {
    return dev0.network_status === 'lost' ? -1 : 1;
});

lostDevices = devices.filter(function (dev) {
    return dev.network_status === 'lost';
});

lostDevices.sort(function (dev0, dev1) {
    return dev0.battery_level <= dev1.battery_level ? -1 : 1;
});

console.clear();
console.log(devices);

Array.prototype.splice.apply(devices, [0, lostDevices.length].concat(lostDevices));

console.log(devices);

Is it smart enough, or is there a smarter way to do it?


texts: QuickSort C++ Implementation using Iterators

texts:
I implemented quicksort using iterators. I am will be grateful, if someone can review my piece of code. BTW, I am just selecting the last element as the pivot (which I plan to randomize later) I am mainly looking for the following:

1) Correctness of the Implementation

2) Correct usage of iterators

3)  Basic coding style.

Although above are the key things I am looking for, please feel free to point out any mistakes. Thanks!!!

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <utility>

typedef std::vector<int>::iterator itr;

itr partition(itr left,itr right)
{

    itr i=left-1;

    itr it=left;

    while(it<right)
    {
        if(*it<=*right)
        {
            ++i;
            std::swap(*i,*it);
        }
        ++it;
    }

    std::swap(*(i+1),*right);
    return ++i;
}

void quicksort(std::vector<int>& v,itr left, itr right)
{
    if(std::distance(left,right)>=2)
    {
        itr q=partition(left,right);
        quicksort(v,left,q-1);
        quicksort(v,q+1,right);
    }
}

int main()
{
    std::vector<int> v={6,10,4,5,3,9,13,8};

    std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout," "));
    std::cout<<std::endl;

    quicksort(v,std::begin(v),std::end(v)-1);

    std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout," "));
    std::cout<<std::endl;

    return 0;
}


texts: CSS Styling: Should I specify the element type?

texts:
Which of the following is better code:

div#style1{

}

or

#style1{
}

Also, should the element type be specified for classes or not?


texts: Removing duplicate files in a given directory

texts:
The following code is a python script that removes duplicate files in a given directory. At first I considered the most basic thing: relying on identical names, but you might have 2 different files with the same name in 2 different directories. So I decided to rely on md5checksum, since any 2 files that yield the same md5checksum almost invariably have the same content.

#A simple Python script to remove duplicate files...Coded by MCoury AKA  python-scripter
import hashlib
import os

#define a function to calculate md5checksum for a given file:
def md5(f):
    """takes one file f as an argument and generates an md5checksum for that file"""
    return hashlib.md5(open(f,'rb').read()).hexdigest()

#define our main function:
def rm_dup(path):
    """relies on the md5 function above to remove duplicate files"""
    if not os.path.isdir(path):#make sure the given directory exists
        print('specified directory does not exist!')
    else:
        md5_dict={}
        for root, dirs, files in os.walk(path):#the os.walk function allows checking subdirectories too...
            for f in files:
                if not md5(os.path.join(root,f)) in md5_dict:
                    md5_dict.update({md5(os.path.join(root,f)):[os.path.join(root,f)]})
                else:
                    md5_dict[md5(os.path.join(root,f))].append(os.path.join(root,f))
        for key in md5_dict:
            while len(md5_dict[key])>1:
                for item in md5_dict[key]:
                    os.remove(item)
                    md5_dict[key].remove(item)
        print('Done!')

 if __name__=='__main__':
    print('=======A simple Python script to remove duplicate files===========')
    print()
    print('============Coded by MCoury AKA python-scripter===================')
    print()
    print('===========The script counts on the fact the fact=================')
    print('=========that if 2 files have the same md5checksum================')
    print('==========they most likely have the same content==================')
    print()
    path=input(r'Please provide the target path\directory... for example: c: or c:\directory...')
    print()
    rm_dup(path)

Ever since discovering the Zen of python I became obsessed with using the least possible lines of code. Plus I have another (and perhaps more serious) concern; calculating md5checksum for large files takes precious memory real-estate right? Could that limit the functionality of the script? Also, what do you think of the implementation?


texts:
After my question on StackOverflow, I've written code that should create a Config class from an XML file. XML loading is mixed with structures declaration and break in a lot of small pieces.

However, I'm not sure if this is bad or good. How would you refactor this? Probably some simple design pattern can be used, but again, I'm not sure that I should use design patterns for such simple things as XML loading.

using System;
using System.Net;
using System.Xml;

namespace Fast.Config
{
public class Config
{
    public Config(string configFile)
    {
        Load(configFile);
    }

    public Channel Fond { get; private set; }

    private void Load(string file)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(file);

        XmlElement fondChannel = doc.SelectNodes("//channel[@id=\"FOND\"]")[0] as XmlElement;
        Fond = new Channel(fondChannel);
     }
}

public class Channel
{
    public Channel(XmlElement channel)
    {
        Load(channel);
    }

    private void Load(XmlElement node)
    {
        var connections = node.SelectNodes(".//connections");
        var ordersIncrementalConnection = (connections[0] as XmlElement).SelectNodes(".//connection[@id=\"OLR\"]");
        OrdersIncremental = new Connection(ordersIncrementalConnection[0] as XmlElement);
    }

    public Connection OrdersIncremental { get; private set; }
}

public class Connection
{
    public Connection(XmlElement connection)
    {
        Load(connection);
    }

    private void Load(XmlElement connection)
    {
        XmlElement feedA =
            connection.SelectNodes(".//feed[@id=\"A\"]")[0] as XmlElement;
        FeedA = new Feed(feedA);

        XmlElement feedB =
            connection.SelectNodes(".//feed[@id=\"B\"]")[0] as XmlElement;
        FeedB = new Feed(feedB);
    }

    public Feed FeedA { get; private set; }
    public Feed FeedB { get; private set; }
}

public class Feed
{
    public Feed(XmlElement feed)
    {
        Load(feed);
    }

    private void Load(XmlElement feed)
    {
    }

}

}


texts:
I am aware JavaScript does not have the concept of constant variables, which in traditional languages, you would usually define as being static/class related since there's no point in having them defined in each object instance.

So we have to make do with defining regular vars in uppercase, and just treating those like constants.

But I wondered whether there's a particular style to make it clearer to other developers that this variable is a constant, other than to define it in uppercase. I have the following plugin I am writing:

    (function () {
    var URL_KEY = 'CurrentURL',
        appName = 'MyApp',
        directoryName = 'MyAppDir';

    function GUID() {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1);
        }

        return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
    }

    function setURL(domain) {
        if (!domain) {
            throw 'domain parameter required';
        }

        localStorage.setItem(URL_KEY, domain);
    }

    function getURL() {
        return localStorage.getItem(URL_KEY) || null;
    }

    window.App = window.App || {
        name: appName,
        directory: directoryName,
        createGUID: function () {
            return GUID();
        },
        getURL: function () {
            return getURL();
        },
        setURL: function (newURL) {
            setURL(newURL);
        }
    };
}());

My constant currently is URL_KEY - which is blending into the regular variables which is confusing. Is there any particular style recommended to separate the constants and the regular variables?

I am aware there is just one variable currently, but as this module grows there will be more.


texts:
Given the following piece of code, can it be done better:

public object DistanceFrom(
    IEnumerable<Coordinate> coordinates) {
    IEnumerable<DbGeography> addresses = coordinates.Select(
        c =>
            DbGeography.FromText(String.Format("POINT ({0} {1})", c.Longitude, c.Latitude)));
    IEnumerable<VehicleGeography> vehicles = this.GPSInsightProvider.Query().Document.Placemarks.Select(
        p =>
            new VehicleGeography {
                DriverName = p.DriverName,
                Point = DbGeography.FromText(String.Format("POINT ({0} {1})", p.Point.Longitude, p.Point.Latitude))
            });
    ICollection<object> technicians = new List<object>();

    foreach (DbGeography address in addresses) {
        technicians.Add(vehicles.Select(
            v =>
                new {
                    DriverName = v.DriverName,
                    Distance = v.Point.Distance(address) / 1609.344
                }).Where(
            v =>
                v.Distance.HasValue).OrderBy(
            v =>
                v.Distance).Take(3).Select(
            v =>
                new {
                    DriverName = v.DriverName,
                    Distance = String.Format("{0:#.#}", v.Distance)
                }));
    }

    return technicians;
}

GPSInsightProvider parses a KML and returns its object representation. I then take that and convert it temporarily into a VehicleGeography so I can create a DbGeography property for it. I then loop through the addresses I'm checking against and the do a dirty-looking calculation to see which are the closest three vehicles to the address. At most I will be doing this for a maximum of three addresses at a time. I take the resulting object and return it as JSON to my web application.

I'm curious if there's a better way to perform that whole lookup/calculation/whatever-this-is?


texts:
I have written a solution for the codility task which is Binary Gap.
finding the highest gap in Binary. for example 1041 is the input number and convert it to binary the result is 5. here is the code :

package codility

import(
    "strconv"
)

func Solutions(N int) int{
    binary := convertNumberToBinary(N)
    result := getHighestGap(binary)

    return result
}

func convertNumberToBinary(N int)string{
    result := ""

    for N > 0 {
        binary := N%2;
        result = strconv.Itoa(binary) + result
        N = N/2;
    }

    return result
}

func getHighestGap(binary string) int{
    result := 0
    count := 0
    isCount := false
    stringArray := []byte(binary)

    for i:=0; i < len(stringArray); i++{
        if stringArray[i] == '1' {
            if result < count{
                result = count
            }
            count = 0
            isCount = true
        }else if isCount{
            //found 0
            count ++
        }
    }

    return result
}

and the test file :

package codility

import(
    "testing"
)

func TestBinrayGap(testing *testing.T){
    var testObjects = []struct{
        input int
        expected int
    }{
        {1041, 5},
        {529, 4},
        {20, 1},
    }

    for _, t := range testObjects {
        actual := Solutions(t.input)
        if actual != t.expected{
            testing.Errorf("Test failed expected : %s, actual : %s", t.expected, actual)
        }
    }
}

here I'm converting the input number to binary first and then count the highest length of the gap by converting the string to array byte `[]byte'. And for the test I'm using table driven test.


texts: Combining json responses of recursive web service calls with PHP and curl

texts:
I'm implementing the Hotel Price List API from Skyscanner. This requires a first call to the service to implement a session followed by 1 or more calls to the service to get the actual results.  I've used curl to implement this and got a working solution, I just wonder if this solution can be improved.

What I have:

public static function CallAPI($method, $url, $data = false)
  {
    $curl = curl_init();

    switch ($method)
    {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_VERBOSE, 1);
    curl_setopt($curl, CURLOPT_HEADER, 1);

    // Request json
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Accept: application/json'));

    $result = curl_exec($curl);

    $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
    $header = substr($result, 0, $header_size);
    $body = substr($result, $header_size);

    $APIResult['error'] = curl_error($curl);
    $APIResult['info'] = curl_getinfo($curl);
    $APIResult['header'] = $header;
    $APIResult['body'] = $body;

    curl_close($curl);

    return $APIResult;
}

  public function GetHotels($nodeId) {

    $node = Node::find($nodeId);

    $apiKey = 'prtl6749387986743898559646983194'; // This is the test key

    $currency = $this->request->session()->get('currency');
    $locale = Lang::locale();
    $market = $this->request->session()->get('countryCode');
    $entityid = $node->lat . ',' . $node->lng . '-latlong';
    $checkindate = '2016-12-17';
    $checkoutdate = '2016-12-18';
    $guests = 2;
    $rooms = 1;

    $url = 'http://partners.api.skyscanner.net/apiservices/hotels/liveprices/v3/' . $market . '/'. $currency . '/'. $locale . '/'. $entityid . '/'. $checkindate . '/'. $checkoutdate . '/'. $guests . '/'. $rooms;

    // First call to initiate session, no actual results retrieved
    $APIResult = APIServices::CallAPI('GET', $url, array("apiKey" => $apiKey));

    $debugResult = $APIResult['body'];

    if (!empty($APIResult['info']['redirect_url']) ) {
        $APIResult =  APIServices::CallAPI('GET', $APIResult['info']['redirect_url']);
        $json = json_decode($APIResult['body'],true);

        //Concatenate the json results
        $result = $APIResult['body'];

        while ($json['status'] <> 'COMPLETE') {
            $APIResult =  APIServices::CallAPI('GET', $APIResult['info']['redirect_url']);
            $json = json_decode($APIResult['result'],true);
           //Concatenate the json results
           $result = $result . $APIResult['body'];
        }
    }

  }

I know curl is able to automatically follow redirect URL's but I don't know if this would be better?
The current solution to concat the json results in the loop works but is it the proper way to combine multiple JSON results in one?
Any other thoughts, concerns?  This is the first time for me to call a RESTful API.


texts:
So, I've written FizzBuzz for a dialect of JavaScript called Dogescript.

It has the same functionality as JavaScript, it simply changes some of the syntax points:

  [A few from the language spec]

shh [comment] - // [comment]
very [var] is [value] - var [var] = [value]
[var] is [value] - [var] = [value]
such [name] much [variables] - function [name] ([variables])
wow - }
rly [params] - if ([params])
but rly [params] - else if ([params])
but - else

I have a feeling I'm misusing the language syntax in relation to adding strings to result.

I also have a feeling my underlying structure of:

Create result variable
Append "Fizz" and "Buzz" based on rules
Print result variable if it has content, otherwise the iterator value.

such fizzbuzz much max
    much very i is 0 next i smaller max next i more 1
        very result
        rly i % 3 is 0
            result += "Fizz"
        wow
        rly i % 5 is 0
            result += "Buzz";
        wow
        console.loge(result || i);
    wow
wow

You can run this with:

plz fizzbuzz with 30


texts: k th smallest element in row wise and column wise sorted matrix

texts:
Find the kth smallest element in row wise and column wise sorted element:

  Example:

  matrix[row][col] < matrix[row+1][col]

  matrix[row][col] < matrix[row][col+1]

  mat=

    1  2  21

    11 23 25

    31 36 41

I have written following code, How to make more readable and improve its complexity:

import heapq
def kth_smallest(k, mat):
    m = len(mat)
    n = len(mat[0])
    hp = []
    for i in xrange(n):
           heapq.heappush(hp,[mat[0][i], 0, i])
    heapq.heapify(hp)
    while k >1:
        x = heapq.heappop(hp)
        if x[1]+1 < m:
            heapq.heappush(hp,[mat[x[1]+1][x[2]], x[1]+1, x[2]])
        heapq.heapify(hp)
        k-=1

    return hp[0][0]

print kth_smallest(8, [[1,10,12],[2,11,21], [3,31,45]])


texts: Appending and Prepending Text to All Selected Cells

texts:
The purpose of this code is apply a function to each selected cell.  This works on contiguous and non-contiguous selections.
function assignText(value, prepend)
Returns a closure that encapsulates the original parameter values and a callback function which takes a single cell as a parameter.  This closure is then passed into eachSelectedCell(callback).
Specifications:

Cells with formulas are ignored
Only one instance of the value is allowed
Address is loaded for future stack tracing

async function eachSelectedCell(callback)
Iterates over each cell of each area of the ActiveSheet's selection, passing the cell into the callback function.

$("#run").click(() => tryCatch(run));

async function run() {
  /** Test Prepend Value */
  await eachSelectedCell(assignText("<-goodbye", false));

  /** Test Append Value */
  await eachSelectedCell(assignText("hello->", true));
}

function assignText(value, prepend) {
  this.prepend = prepend;
  this.value = value;
  const that = this;
  return async function(cell) {
    cell.load(["values", "address", "formulas"]);
    await cell.context.sync();

    if (!cell.formulas[0][0].toString().startsWith("=")) {
      let value = cell.values.toString();

      if (value.includes(that.value))
        value = value.replaceAll(RegExp(that.value, "g"), "");

      if (that.prepend)
        cell.values = that.value + value;
      else
        cell.values = value + that.value;
    }
  };
}

async function eachSelectedCell(callback) {
  const context = new Excel.RequestContext();
  const cells = [];
  const target = context.workbook.getSelectedRanges();
  context.trackedObjects.add(target);
  const areas = target.areas.load(["areas", "address"]);
  await context.sync();

  for (let n = 0; n < areas.items.length; n++) {
    const area = areas.items[n];
    area.load(["rowCount", "columnCount", "address"]);
    await context.sync();
    for (let i = 0; i < area.rowCount; i++) {
      for (let j = 0; j < area.columnCount; j++) {
        let cell = area.getCell(i, j);
        context.trackedObjects.add(cell);
        await callback(cell);
        cell.untrack();
      }
    }
  }

  target.untrack();
  await context.sync();
}

As is often the case on CR, I'm looking for ways to improve the performance.


texts:
I have a very big class Foo that should be divided into FooBar, FooUtility, FooBench, FooBranch. Each of this "subclasses" should have different methods. So that if Foo has:

public function methodA();
public function methodB();
public function methodC();
public function methodZ();

Then I should be able to divide them as I want. For example:

FooBar:
public function __construct($param);
public function methodA();

FooUtility:
public function __construct($param);
public function methodB();

FooBench:
public function __construct($param);
public function methodZ();

FooBranch:
public function __construct($param);
public function methodC();

But I should be able to call methodB() and methodZ() from the same class Foo.

How should I manage this division? Interfaces? Abstract classes? Inheritance? How?


texts: Applying correction to a time series in Matlab

texts:
I face a computation efficiency problem. I have a time series of a non-monotonically drifting variable, that is measurements of objects going through a machine (where the measurement is made) in a production line. The job to do consists of simulating what this time series would yield if there was a correction made to the object each time the measurement drifts above or below a threshold.

To do that I could simply make a for loop, and each time the thresholds are crossed, apply the correction to the rest of the time series. However the time series is very long and the for loop would take too much time to compute. I would like to improve the performance of my code. Does anyone see a way to do this?

Here is a working example using a for loop:

ts = [1 2 3 4 3 2 1 0 -1 -2 -3];
threshold = [-3.5 3];
correction = [1 -1];
for i = 1:numel(ts)
    if ts(i) > threshold(2)
       ts(i:end) = ts(i:end) + correction(2);
   elseif ts(i) < threshold(1)
       ts(i:end) = ts(i:end) + correction(1);
   end
end
disp(ts)

The result is and should be the following array:

[1 2 3 3 2 1 0 -1 -2 -3 -3]


texts: Remove duplicate values in array with one loop?

texts:
I am writting a program to remove the duplicate values from an array, is any way to optimize code by removing one loop?

var arr=[10,20,30,20,40,10],
newarr=[];
var foo=function(ele, index, array){
     match=array[index];
  for(var m in newarr){
  if(newarr[m]==match)
    return true;
  }
  newarr.push(match);
};
arr.forEach(foo);
console.log(newarr);


texts:
I made a service which saves places to localStorage after the user clicks the left mouse button on the map. When the user clicks the right mouse button on the marker, that marker is removed from localStorage.

var map,
    markersAll = [];

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {lat: -25.363, lng: 131.044}
  });

  renderMarkers();

  map.addListener('click', function(e) {
    var lat = e.latLng.lat();
    var lng = e.latLng.lng();
    generateMarker(lat, lng);
    //console.log(lat, lng);
  });
}

function getMarkersFromLocalStorage() {
  return localStorage.markers ? JSON.parse(localStorage.markers) : [];
};

function addMarkerToLocalStorage(lat, lng) {
  var markers = getMarkersFromLocalStorage();
  markers.push({lat, lng});
  localStorage.markers = JSON.stringify(markers);
};

function removeMarkerFromLocalStorage(lat, lng) {
  var markers = getMarkersFromLocalStorage(),
      newMarkers = [];

  markers.forEach(function(marker) {
    if(marker.lat != lat && marker.lng != lng) {
      newMarkers.push({
        lat: marker.lat,
        lng: marker.lng
      });
    }
  });

  localStorage.markers = JSON.stringify(newMarkers);
};

function clearMarkers() {
  markersAll.forEach((marker) => {
    marker.setMap(null);
  });
};

function renderMarkers() {
  var markers = getMarkersFromLocalStorage();

  markers.forEach(function(marker) {
    //console.log(marker.lat, marker.lng);
    generateMarker(marker.lat, marker.lng);
  });
};

function generateMarker(lat, lng) {
  var marker = new google.maps.Marker({
    position: {lat: lat, lng: lng}
  });
  marker.setMap(map);
  markersAll.push(marker);
  addMarkerToLocalStorage(lat, lng);

  marker.addListener('rightclick', function(e) {
    var lat = e.latLng.lat();
    var lng = e.latLng.lng();
    //console.log('right click', lat, lng);
    clearMarkers();
    removeMarkerFromLocalStorage(lat, lng);
    renderMarkers();
  });

  return marker;
};
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#map {
  height: 100%;
}


texts: Efficient use of regular expression and string manipulation

texts:
The following is my solution to Java vs C++. I think the way I have used the re library is inefficient, and possible erroneous as I am getting tle.

import sys
import re
cpp = re.compile("^[a-z]([a-z_]*[a-z])*$")
java= re.compile("^[a-z][a-zA-Z]*$")
r = re.compile("[A-Z][a-z]*")
lines = [line for line in sys.stdin.read().splitlines() if line!=""]
for line in lines:
    if cpp.match(line) :
        line = line.split("_")
        for i in range(1,len(line)):
            line[i] = line[i].capitalize()
        print "".join(line)
    elif java.match(line):
        namelist = r.findall(line)
        for name in namelist:
             line = line.replace(name , name.replace(name[0],"_"+name[0].lower()))
        print line
    else : print "Error!"

For instance, is there a better way to replace string components inline instead of creating a new string and copying the way I have used :

line = line.replace(name , name.replace(name[0],"_"+name[0].lower()))

or is there a way that is entirely different from my approach?


texts: Fastest and minimal random access data structure in Java

texts:
I have written up a data structure in Java that supports the following features:

get(i)
set(i, e)
add(e)
remove(e)
contains(e)
size

Elements must remain in order and iteration needs to be as fast as possible. The code does not require thread safety.

I am looking for ways to improve the speed further. It is critical to reduce times to as small as possible because this code will be invoked hundreds of thousands of times per second. I believe it's possible to optimize my stream() method!

This is my current solution which seems to work:

import java.util.Iterator;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public final class Indexer<E> implements Iterable<E> {

    private final int minIndex;
    private final Object[] arr;

    private int size = 0;
    private int highest;

    public Indexer(int minIndex, int capacity) {
        this.minIndex = highest = minIndex;
        arr = new Object[capacity];
    }

    public Indexer(int capacity) {
        this(0, capacity);
    }

    @SuppressWarnings("unchecked")
    public E get(int index) {
        return (E) arr[index];
    }

    @SuppressWarnings("unchecked")
    public E set(int index, E element) {
        Object last = arr[index];
        arr[index] = element;
        if (last == null && element != null) {
            size++;
            if (highest < index)
                highest = index;
        } else if (last != null && element == null) {
            size--;
            if (highest == index)
                highest--;
        }
        return (E) last;
    }

    public int add(E element) {
        int index = nextIndex();
        set(index, element);
        return index;
    }

    public void remove(E element) {
        for (int i = minIndex; i <= highest; i++) {
            if (element == arr[i]) {
                set(i, null);
                return;
            }
        }
    }

    public boolean contains(E element) {
        for (E e : this) {
            if (element == e)
                return true;
        }
        return false;
    }

    public int size() {
        return size;
    }

    public int nextIndex() {
        for (int i = minIndex; i < arr.length; i++) {
            if (null == arr[i])
                return i;
        }
        throw new IllegalStateException("Out of indices!");
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {

            private int pointer = minIndex;

            @Override
            public boolean hasNext() {
                return size > 0 && pointer <= highest;
            }

            @Override
            @SuppressWarnings("unchecked")
            public E next() {
                return (E) arr[pointer++];
            }

        };
    }

    public Stream<E> stream() {
        return StreamSupport.stream(spliterator(), false);
    }

}


texts: Given an integer array of size n, find any three numbers

texts:
Return any three descending numbers that appear sequentially in the input such that A[i] > A[j] > A[k] and i < j < k. Since problem description contains 'any', I could not unit test using JUnit.

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

final class DescendingTriplets {

    private final int high;
    private final int mid;
    private final int low;

    DescendingTriplets(int high, int mid, int low) {
        this.high = high;
        this.mid = mid;
        this.low = low;
    }

    public int getHigh() {
        return high;
    }

    public int getMid() {
        return mid;
    }

    public int getLow() {
        return low;
    }

    @Override
    public String toString() {
        return "high: " + high + " mid: " + mid + " low: "  + low;
    }
}

public final class ThreeDescending {

    private ThreeDescending() {}

    /**
     * This class is used to save high and mid values.
     */
    private static class State {
        int mid;
        int high;

        State(int low, int high) {
            this.mid = low;
            this.high = high;
        }
    }

    /**
     * Returns any three descending numbers in an array such that they appear one after other in the original sequence.
     * If such numbers dont exist then null is returned
     *
     * @param a         the input array
     * @return          object with three descending numbers in squence
     */
    public static DescendingTriplets getDescendingTriplets(int[] a) {
        if (a.length < 3) {
            throw new IllegalArgumentException("The arrays size should atleast be three");
        }

        /*
         * The current state of 'high' and 'mid' values to be used to compare 'min' against.
         */
        State stateCurrent = null;
        /*
         * The state of new 'high' and new 'mid' which we obtain as we travel the array.
         * Once both values(high and mid) are populated, we replace the stateCurrent with the stateInProgress.
         */
        State stateInProgress = null;

        int k = 0;
        // fetch the completedstate,
        for (int i = 0; i < a.length - 1; i++) {
            if (a[i] > a[i + 1]) {
                stateCurrent = new State(a[i + 1], a[i]);
                k = i + 1;
                break;
            }
        }

        for (int j = k + 1; j < a.length; j++) {
            // if smallest
            if (a[j] <= stateCurrent.mid) {
                return new DescendingTriplets(stateCurrent.high, stateCurrent.mid, a[j]);
            }

            // if greater than mid but less than high
            if (a[j] <= stateCurrent.high) {
                if (stateInProgress != null) {
                    stateCurrent = stateInProgress;
                }
                stateCurrent.mid = a[j];
            } else {
                // if greater than high
                if (stateInProgress != null) {
                    if (j > stateInProgress.high) {
                        stateInProgress.high = a[j];
                    } else {
                        stateInProgress.mid = a[j];
                        stateCurrent = stateInProgress;
                    }
                } else {
                    stateInProgress = new State(Integer.MIN_VALUE, a[j]);
                }
            }
        }

        return null;
    }

    public static void main(String[] args) {
        int[] a1 = {5, 14, 3, 2, 1};
        System.out.println(getDescendingTriplets(a1));

        int[] a2 = {4,7,5,1,3,8,9,6,2};
        System.out.println(getDescendingTriplets(a2));
    }
}


texts:
EDIT: The result looks like this: http://gomokuu.glitch.me/

This is my code for gomoku. I made it with JavaScript and HTML. I think the checkWinner function can be improved or made shorter. Also, should the functions be re-organized?

Here is the code:

Javascript:

var turn = 0;
var width = 15;
var height = 15;
var gameOver = false;
var board = Array(width * height);

function announceWinner(winner) {
  console.log("a");
  if (winner == 0) {
    window.alert("X wins");
  }
  if (winner == 1) {
    window.alert("O wins");
  }
  if (winner == 2) {
    window.alert("Board filled");
  }
}

function checkWinner() {
  var filled = true;
  for (var i = 0; i < board.length; i++) {
    if (board[i] == undefined) filled = false;
    if (board[i] !== undefined) {
      if (
        (board[i] == board[i + 1] &&
          board[i + 1] == board[i + 2] &&
          board[i + 2] == board[i + 3] &&
          board[i + 3] == board[i + 4]) ||
        (board[i] == board[i + width] &&
          board[i + width] == board[i + 2 * width] &&
          board[i + 2 * width] == board[i + 3 * width] &&
          board[i + 3 * width] == board[i + 4 * width]) ||
        (board[i] == board[i + 1 + width] &&
          board[i + 1 + width] == board[i + 2 + 2 * width] &&
          board[i + 2 + 2 * width] == board[i + 3 + 3 * width] &&
          board[i + 3 + 3 * width] == board[i + 4 + 4 * width]) ||
        (board[i] == board[i - 1 + width] &&
          board[i - 1 + width] == board[i - 2 + 2 * width] &&
          board[i - 2 + 2 * width] == board[i - 3 + 3 * width] &&
          board[i - 3 + 3 * width] == board[i - 4 + 4 * width])
      ) {
        gameOver = true;
        announceWinner(board[i]);
      }
    }
  }
  if (filled) {
    announceWinner(2);
  }
}

function tileClick(row, tile) {
  var clicked = document.getElementById("board").children[row].children[tile];
  if (clicked.innerHTML || gameOver) return;
  board[tile + row * width] = turn;
  if (turn) {
    clicked.innerHTML = "o";
    clicked.style.color = "red";
    turn = 0;
  } else {
    clicked.innerHTML = "x";
    clicked.style.color = "blue";
    turn = 1;
  }
  checkWinner();
}

//generate board and listen to click event
var domBoard = document.createElement("table");
domBoard.id = "board";
for (let i = 0; i < height; i++) {
  var row = document.createElement("tr");
  for (let j = 0; j < width; j++) {
    var tile = document.createElement("td");
    tile.onclick = function() {
      tileClick(i, j);
    };
    row.appendChild(tile);
  }
  domBoard.appendChild(row);
}
document.body.appendChild(domBoard);

HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>gomoku</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <script src="script.js"></script>
  </body>
</html>


texts: C++ Class wrapper on top of WinMain/DllMain

texts:
I've written some code to do the job for me. The final results seems to work fine, but I would like to know if this is how I should Handle classes. And where I can improve or things which are just plain stupid.

class CInit
{
public:
    CInit();
    ~CInit();

    void Check(bool);

    virtual bool Init();
    virtual bool ExInit();

private:
    static CInit* _ThisInit;
};
CInit* CInit::_ThisInit;

CInit::CInit()
{
    if(_ThisInit == 0)
        _ThisInit = this;
}

CInit::~CInit()
{

}

void CInit::Check(bool bStart)
{
    if(bStart)
        _ThisInit->Init();
    else
        _ThisInit->ExInit();
}

bool CInit::Init()
{
    return true;
}

bool CInit::ExInit()
{
    return true;
}

This is my cInit class, as you may see this has a static value, because in when the program execetues it will first run the global class instance which will be used like this. It will overload Init() and there the program starts.

    CRaPE mycp;

bool CRaPE::Init()
{
    return true;
}

bool CRaPE::ExInit()
{
    return true;
}

The program runs from here:

CInit* _Init;

void HandleStartUp()
{
     _Init = new CInit();
    _Init->Check(true); // So Init gets called
}

void HandleExit()
{
    _Init->Check(false); // so ExInit gets called
    delete _Init;
}

BOOL WINAPI DllMain(
    HINSTANCE hinstDLL,
    DWORD fdwReason,
    LPVOID lpReserved )
{
    switch( fdwReason )
    {
    case DLL_PROCESS_ATTACH:
        {
            HANDLE hThread = CreateThread(0,0,(LPTHREAD_START_ROUTINE)HandleStartUp,0,0,0);
            if(hThread == 0)
                return false;
        }
        break;

    case DLL_THREAD_ATTACH:
        break;

    case DLL_THREAD_DETACH:
        break;

    case DLL_PROCESS_DETACH:
        HandleExit();
        break;
    }
    return TRUE;
}

I hope I explained well, thanks for reading.

Gz


texts:
I just started coding a simulation-like application. It's about our solar system. Right now, I'm working on rotating the moon. I have this constructor

function Mass(elm) {
    if (typeof elm == "string") {
        this.elm = document.getElementById(elm);
    } else {
        this.elm = elm;
    }
    this.width      = parseInt(window.getComputedStyle(this.elm).width, 10);
    this.height     = parseInt(window.getComputedStyle(this.elm).height, 10);
    this.top        = parseInt(window.getComputedStyle(this.elm).top, 10);
    this.left       = parseInt(window.getComputedStyle(this.elm).left, 10);
    this.radius     = this.width / 2;
    this.origin     = {
        x : this.left + this.width / 2,
        y : this.top + this.height / 2,
    };
    this.angle = 0;
    this.rotation   = function () {
        if (this.angle >= 360) { this.angle = 0; }
        this.angle += 1;
        this.elm.style.webkitTransform = "rotate(" + this.angle + "deg)";
    };
    this.rotate = function (mthd) {
        setInterval(mthd, 100);
    }
}
var moon = new Mass("moon");
moon.rotate("moon.rotation()");

The issue I'm having is this moon.rotate("moon.rotation()");. There are two methods, and the way I call them is um.. weird? I want to use a single method to rotate the object. Like moon.rotate().

I tried a few ways to put the code in just one method, but couldn't figure it out.

Fiddle

Even though I'm done with the problem mentioned in this question, I wanted to add something, the full code. In case if anyone is interested.

Fiddle


texts: Split mp3 of album into individual tracks

texts:
Recently, I've been transferring some of my old vinyl records to MP3 files.  One of the things I did to make some progress was to automate things, so I initially set things up so that it would record each album to a single MP3 file.  Now I've gotten to the step where I want to separate those out into individual tracks, so I wrote this program to do that automatically.  It takes an input file in this format:

infile=~/vinyl/UK.mp3
artist=UK
genre=Rock
album=UK

1 - 00:00 - In the Dead Of Night
2 - 05:38 - By the Light Of Day
3 - 10:10 - Presto Vivace and Reprise
4 - 13:18 - Thirty Years
5 - 21:30 - Alaska
6 - 26:04 - Time to Kill
7 - 31:02 - Nevermore
8 - 39:20 - Mental Medication

It then takes the input file in this metadata file and splits it into named tracks adding the album, artist and genre into each MP3 file using ffmpeg.  Here's the script:

songsplit.py

#!/usr/bin/python3
import subprocess
import sys

class Track(object):
    def __init__(self, tracknum, starttime, name):
        self.tracknum = int(tracknum)
        self.starttime = starttime
        self.endtime = starttime
        self.name = name

    def setEnd(self, endtime):
        self.endtime = endtime

    def setargs(self, infile, metadata):
        args = ['ffmpeg', '-i', infile, '-ss', self.starttime]
        if self.endtime != self.starttime:
            args.extend(['-to', self.endtime])
        for key in metadata.keys():
            args.extend(['-metadata', "{}={}".format(key, metadata[key])])
        args.extend(['-metadata', "{}={}".format("track", self.tracknum)])
        args.extend(['-metadata', "{}={}".format("title", self.name)])
        args.append("{:02d} {}.mp3".format(self.tracknum, self.name))
        return args

    def __repr__(self):
        return "{}, {}, {}, {}".format(self.tracknum, self.starttime,
                                       self.endtime, self.name)

def extract(file):
    metadata = {}
    tracks = []
    lines = [line.strip("\n") for line in open(file)]
    for line in lines:
        if line.find('=') > 0:
            m = line.split(sep='=', maxsplit=1)
            if m[0] == 'infile':
                infile = m[1]
            else:
                metadata[m[0]] = m[1]
        else:
            m = line.split(sep=" - ", maxsplit=2)
            if len(m) == 3:
                m = [x.strip() for x in m]
                tk = Track(m[0], m[1], m[2])
                tracknum = int(tk.tracknum)
                if tracknum > 1:
                    tracks[tracknum-2].setEnd(tk.starttime)
                tracks.append(tk)
    for track in tracks:
        subprocess.run(track.setargs(infile, metadata))

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: {} metafile".format(sys.argv[0]))
    else:
        extract(sys.argv[1])

If the metadata file shown above is named UK.meta, then this would be invoked as songsplit.py UK.meta and the result would be a directory of MP3 files like this:

01 In the Dead Of Night.mp3
02 By the Light Of Day.mp3
03 Presto Vivace and Reprise.mp3
04 Thirty Years.mp3
05 Alaska.mp3
06 Time to Kill.mp3
07 Nevermore.mp3
08 Mental Medication.mp3

Some particular questions I have are about the use of subprocess.run() and what error handling I should add.  So far, I haven't encountered any problems.


texts: Long cache refresh with guaranteed response

texts:
I am trying to ensure that (once a cache item is populated) even if it's refresh object takes a long time to retrieve, the original cache item can be requested.

using System;
using System.Runtime.Caching;

namespace LongCacheTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Cacher.Add("key", "object", Get);

            Console.ReadLine();
        }

        public static Object Get()
        {
            // load big file from disck
            return "stuff";
        }
    }

    public class Cacheable
    {
        public delegate Object CacheEntryGet();

        public Object Obj { get; set; }
        public CacheEntryGet Getter { get; set; }
    }

    public class Cacher
    {
        private static MemoryCache _cache = null;

        private static MemoryCache Cache => _cache = _cache ?? new MemoryCache("long");

        private static CacheItemPolicy Policy => new CacheItemPolicy
        {
            AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(1)),
            Priority = CacheItemPriority.Default,
            RemovedCallback = DidRemove
        };

        public static void DidRemove(CacheEntryRemovedArguments args)
        {
            Cache.Add(args.CacheItem.Key, args.CacheItem.Value, Policy);

            var item = args.CacheItem.Value as Cacheable;

            item.Obj = item.Getter();

            Cache.Remove(args.CacheItem.Key);
            Cache.Add(args.CacheItem.Key, item, Policy);
        }

        public static void Add(string key, Object obj, Cacheable.CacheEntryGet getter)
        {
            var item = new Cacheable{
                Obj = obj,
                Getter = getter
            };

            Cache.Add(key, item, Policy);
        }
    }
}

The practice here is to provide a method Getter and cache it alongside the cached Object. When the cache item expires, it is reinserted and the Getter method is called to get the refresh object. Once the fresh object is retrieved it replaces the original cache item.


texts:
I will make it more reader friendly after I get the algorithm completed. Does anything with the quick sort algorithm stand out as for why it is not working 100%? This is not homework; I am just practicing problems out of books and I am caught on this one.

Hints, more so than answers, would be more appreciated. Please don't post your own quick sort algorithm, as copying someone else's code does not help me learn. I am just looking for that last bit to help me make the leap across; I don't want you to build another bridge somewhere else, and say "use mine"; it won't help. If my algorithm is a lost cause just say so, and I will go back to the drawing board.

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <cmath>
#include <ctime>
#include <assert.h>

using std::vector;
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::ostream_iterator;
using std::istream_iterator;

void print_part( vector<float>::iterator l,
                 vector<float>::iterator r ) {
    copy( l,r+1,ostream_iterator<float>( cout," " ) );
    cout << endl;
}

void print( std::vector<float> &data ) {
    copy( data.begin( ), data.end( ),
          ostream_iterator<float>( cout," " ) );
    cout << endl;
}

void swap( vector<float>::iterator left,
           vector<float>::iterator right ) {
    cout << "Swaping " << (*left) << " with " << (*right) << endl;
    float tmp = (*right);
    (*right) = (*left);
    (*left) = tmp;
}

int get_pivot_index( vector<float> &data,
                     vector<float>::iterator left,
                     vector<float>::iterator right ) {
    int pivot_index = ((right-left)/2);
    int base = std::distance( data.begin( ),left );
    return ( pivot_index+=base );

}

void my_qsort( vector<float> &data,
               vector<float>::iterator left,
               vector<float>::iterator right,
               int side
             ) {
     ((side==0) ? cout<<"":(side==1) ? cout<<"Left: " : cout<<"Right: " );
     print_part( left,right );
     if( (right-left)>0) {
         vector<float>::iterator lit=left;
         vector<float>::iterator rit=right;
         int pivot_index = get_pivot_index( data,left,right );
         int pivot=data[pivot_index];
         cout << "pivot = " << pivot << endl;
         while( lit <= right && rit > left && lit <= rit ) {
             while( lit <= right && (*lit) < pivot ) {
                 if( lit > rit ) { break; }
                 else { lit++; }
             }
             while( rit > left && (*rit) >= pivot ) {
                 if( lit > rit ) { break; }
                 else { rit--; }
            }
            if( lit < rit ) { swap( lit,rit ); }
        }
        my_qsort( data,left,rit,1 );
        my_qsort( data,lit+1,right,2 );
    }
    char c;
    cin >> c;
}

int main( int argc, char *argv[ ] ) {
    vector<float>
    data(
          ( istream_iterator<float>( cin ) ),
          ( istream_iterator<float>( ) )
        );
    cout << "-----------------------------------------------" << endl;
    my_qsort( data,data.begin( ),data.end( )-1,0 );
    cout << "-----------------------------------------------" << endl;
    print( data );
    return ( 0 );
}


texts: Find the smallest distance between any two given words in a string

texts:
The task:

  Find an efficient algorithm to find the smallest distance (measured in
  number of words) between any two given words in a string.

  For example, given words "hello", and "world" and a text content of
  "dog cat hello cat dog dog hello cat world", return 1 because there's
  only one word "cat" in between the two words.

const s = "dog cat hello cat dog dog hello cat world";

My imperative solution:

function smallestWordDistance2({str, word1, word2}) {
  if (!str.match(word1) || !str.match(word2)) { return 0; }

  const strArr = str.split(" ");
  let iStart, iEnd, min;
  let count = 0;
  for (let x in strArr) {
    if (!iStart) {
      if (strArr[x] === word1) {
        iStart = word1;
        iEnd = word2;
      } else if(strArr[x] === word2) {
        iStart = word2;
        iEnd = word1;
      }
    } else {
      count++;
      if (strArr[x] === iStart) {
        count = 0;
      } else if (strArr[x] === iEnd) {
        if (count === 1) { return 0; }
        if (!min || min > count) {
          min = count;
        }
        [iStart, iEnd] = [iEnd, iStart];
        count = 0;
      }
    }
  }
  return min - 1;
}
console.log(smallestWordDistance2({str:s, word1:"hello", word2:"world"}));

My "functional" solution:

const smallestWordDistance3 = ({str, word1, word2} )=> {
  if (!str.match(word1) || !str.match(word2)) { return 0; }

  const strArr = str.split(" ");
  return strArr.reduce((acc, x, i) => {
    if (!acc.iStart) {
      if (x === word1) {
        acc.iStart = word1;
        acc.iEnd = word2;
      } else if(x === word2) {
        acc.iStart = word2;
        acc.iEnd = word1;
      }
    } else {
      acc.count++;
      if (x === acc.iStart) {
        acc.count = 0;
      } else if (x === acc.iEnd) {
        if (!acc.min || acc.min > acc.count) {
          acc.min = acc.count;
        }
        [acc.iStart, acc.iEnd] = [acc.iEnd, acc.iStart];
        acc.count = 0;
      }
    }
    return acc;

  }, {iStart: null, iEnd: null, count: 0, min: null}).min - 1;
};

console.log(smallestWordDistance3({str:s, word1:"hello", word2:"world"}));

At first I thought this was a good task for a regex solution, but the following code is the best I could do. It works with the given sample string. However a slight variance in the given string would make the code unusable, because it doesn't take into consideration that word1 and word2 can be swapped (the following code would return 2 instead of 1):

const s = "dog cat hello cat dog dog hello cat dog world dog hello";

const smallestWordDistance = ({str, word1, word2} )=> {
  if (!str.match(word1) || !str.match(word2)) { return 0; }
  const reg = new RegExp(`.*\\b${word1}\\s+(.*?)\\s+${word2}\\b`);
  const match = str.match(reg);
  return match ? match[1].split(" ").length : 0;
};

console.log(smallestWordDistance({str:s, word1:"hello", word2:"world"}));

I'm now not so sure anymore whether regex is the right approach. But if anyone got a good regex (JS flavor) solution, then I'd be very much interested.


texts: Bank account balance data structure design and code

texts:
I'm working on designing a bank account data structure and related operations (1. debit, 2. credit and 3. get balance difference).

Debit means withdraw some money from an account, at a certain timestamp
Credit means deposit some money to an account, at a certain timestamp
Get balance means getting the account balance difference between time A and time B (balance of time B - balance of time A).

Suppose the start balance of the account is zero. Assume transactions happen in a timely order.

My major ideas are:

Use a hash table to maintain account ID - list of balance. List of balance is represented by a list of tuple, and each tuple has two elements (time_stamp and balance)
With debit and credit, create a new balance item in a balance list data structure mentioned above
When calculating the balance difference, try to use binary search to find lower bound of time stamp, then get the balance at that timestamp

Example:

Suppose for a specific account, at time 10, credit 10 USD, at time 20, credit 100 USD, and at time 30 withdraw 20 USD, and at time 40, withdraw 50 USD, and at time 50, credit 20 USD. Then at time 25, balance is 10+100=110, at time 45, balance is 10+100-20-50 = 40, so balance diff between 25 to 45 is 40-110=-70.

Any advice on using the right data structure/algorithm for better performance in terms of algorithm time complexity perspective, any code bugs or code style advice is highly appreciated.

from collections import defaultdict
def debit(account, time_stamp, amount, balance_map):
    if len(balance_map[account]) > 0:
        balance_map[account].append((time_stamp, balance_map[account][-1][1]-amount))
    else:
        balance_map[account].append((time_stamp, -amount))
def credit(account, time_stamp, amount, balance_map):
    if len(balance_map[account]) > 0:
        balance_map[account].append((time_stamp, balance_map[account][-1][1]+amount))
    else:
        balance_map[account].append((time_stamp, amount))
def get_balance_diff(account, exclusive_start_timestamp, inclusive_end_timestamp, balance_map):
    start_balance = (0,0)
    end_balance = (0,0)
    matched = False
    if len(balance_map[account]) != 0:
        i = find_lower_bound(balance_map[account], exclusive_start_timestamp)
        if i != -1:
            start_balance = balance_map[account][i]
    if len(balance_map[account]) != 0:
        j = find_lower_bound(balance_map[account], inclusive_end_timestamp)
        if j != -1:
            end_balance = balance_map[account][j]

    return end_balance[1] - start_balance[1]

def find_lower_bound(nums, target):
    i = 0
    j = len(nums) - 1
    while i <= j:
        mid = i + (j-i)/2
        if nums[mid][0] == target:
            return mid
        elif nums[mid][0] > target:
            j = mid - 1
        else:
            i = mid + 1
    return i-1

if __name__ == "__main__":
    balance_map = defaultdict(list)
    account_id = 1
    credit(account_id, 10, 10, balance_map)
    credit(account_id, 20, 100, balance_map)
    debit(account_id, 30, 20, balance_map)
    debit(account_id, 40, 50, balance_map)
    credit(account_id, 50, 20, balance_map)
    print get_balance_diff(account_id, 25, 45, balance_map)
    print get_balance_diff(account_id, 30, 50, balance_map)
    print get_balance_diff(account_id, 0, 5, balance_map)
    print get_balance_diff(account_id, 0, 60, balance_map)


texts:
I have two functions which I would like to simplify. They have largely the same logic, but one is asynchronous and uses one await in a try block. I'd like to have the logic in one place, but could not figure out a clean way of doing that. Any suggestions?

from requests import get, HTTPError

# Dummy functions for external functionality
def sync_send(url):
    return get(url)

async def async_send(url):
    return get(url)

def next(url):
    if url is None:
        return

    try:
        response = sync_send(url)
        return response.json()
    except HTTPError as e:
        if e.response.status_code == 404:
            return
        else:
            raise

async def async_next(url):
    if url is None:
        return

    try:
        response = await async_send(url)
        return response.json()
    except HTTPError as e:
        if e.response.status_code == 404:
            return
        else:
            raise

So the point of this all is to provide a way of requesting for resources in an API two ways, sync and async. Despite the simple (synchronous) dummy functions, in async_next we use asynchronous IO to retrieve things. Other than that, the situation is exactly as it is here.

I have accepted that the if url is None cannot be refactored, and I currently think my only option is to make a more complex exception hierarchy, raising a dedicated 404 error to catch it without logic. Any other ideas?


texts:
Summary: I am using an API which returns paged results. I want to have these results as Java 8 Stream and implemented a Spliterator for this purpose.

I am using AWS S3 Java API to list objects in the S3 bucket. The API returns paged results: when I call client.listObjects(bucketName, rootKey) for the first time, I get an ObjectListing instance which may be complete or truncated i.e. return just one "page" of results.

If ObjectListing is truncated I have to request further "page" via client.listNextBatchOfObjects(objectListing) (providing current "page" as marker) and so on until I get an ObjectListing which is not truncated.

I want to use Java 8 Stream APIs to work with ObjectListings. Ideally, I want to hide querying pages of ObjectListings behind some facility which would just give me a Stream<ObjectListing>. For this I've implemented a Spliterator<ObjectListing>:

import java.util.Objects;
import java.util.Spliterator;
import java.util.function.Consumer;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectListing;

public class ObjectListingSpliterator implements Spliterator<ObjectListing> {

    private final AmazonS3 client;
    private ObjectListing objectListing;
    private volatile boolean split = false;
    private volatile boolean currentObjectListingWasConsumed = false;

    public ObjectListingSpliterator(AmazonS3 client, ObjectListing objectListing) {
        Objects.requireNonNull(client, "client must not be null.");
        Objects.requireNonNull(objectListing, "objectListing must not be null.");
        this.client = client;
        this.objectListing = objectListing;
    }

    @Override
    public boolean tryAdvance(Consumer<? super ObjectListing> action) {
        if (!currentObjectListingWasConsumed) {
            action.accept(objectListing);
            currentObjectListingWasConsumed = true;
            if (!split && objectListing.isTruncated()) {
                objectListing = client.listNextBatchOfObjects(objectListing);
                currentObjectListingWasConsumed = false;
            }
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Spliterator<ObjectListing> trySplit() {
        if (split) {
            // Already split, cannot be split once again
            return null;
        } else if (objectListing.isTruncated()) {
            split = true;
            final ObjectListing nextObjectListing = client
                    .listNextBatchOfObjects(objectListing);
            return new ObjectListingSpliterator(client, nextObjectListing);
        } else {
            return null;
        }
    }

    @Override
    public long estimateSize() {
        if (objectListing.isTruncated()) {
            return Long.MAX_VALUE;
        } else {
            return currentObjectListingWasConsumed ? 0 : 1;
        }
    }

    @Override
    public int characteristics() {
        return Spliterator.ORDERED | Spliterator.IMMUTABLE;
    }
}

Usage example - list all keys from the bucket and root key:

// Get the original objectListing
ObjectListing objectListing = client.listObjects(bucketName,
    rootKey);
// Create a stream of objectListings
Stream<ObjectListing> objectListings = StreamSupport.stream(
    new ObjectListingSpliterator(client, objectListing), false);

List<String> keys = objectListings
    .map(ObjectListing::getObjectSummaries)
    .flatMap(Collection::stream)
    .map(S3ObjectSummary::getKey);

What I'm interested in:

Is my spliterator OK?
I'm not sure if there might be a concurrency issue between tryAdvance and trySplit.
Not sure what characteristics should be.

The question is actually not specific to AWS API, it is generally about streaming paged result where:

there is some way to retrieve the first page;
with every page you know if it is complete or not;
you can get the next page using the previous page.


texts: Find the in-order successor of a given node in a binary search tree

texts:
I have an implementation of an algorithm to return the in-order successor of a given node in a binary search tree. We are allowed to assume that each node in the BST has a reference to its parent node. The in-order successor of a node is the node with the next largest key. So, if we received a node with a value of 5, and the tree contained a node with the value 6, we should return the node with the value 6.

My implementation differs slightly from most I've seen online. Most solutions, when given an input node with no right child, iterate back up the tree until the node is the left child of its parent and then returns the parent. I iterate back up the tree until the node's value is greater than our input node's value and then return that node. I think this is equivalent and results in a little more compact and easier to follow implementation. Let me know if I'm overlooking something with this implementation.

def successor( node, targetValue ):
    if node.right:
        node = node.right
        while node.left:
            node = node.left
    else:
        while node:
            node = node.parent
            if node.value > targetValue:
                break

    return node


texts: Secure way of uploading php images and GIF

texts:
I am creating a social network and I want to know if this is a secure way of uploading pics/gifs and videos.
if(isset($_POST['post'])) {

    $uploadOk = 1;
    $imageName = $_FILES['postToUpload']['name'];
    $errorMessage = "";
    $picdate = date('Y-m-d_H-i-s');

    if($imageName != "") {
        $targetDir = "assets/images/posts/";
        $imageName = $targetDir . uniqid() . basename($imageName);
        $imageFileType = pathinfo($imageName, PATHINFO_EXTENSION);

        if($_FILES['postToUpload']['size'] > 10971520) {
            $errorMessage = "Your file is to large";
            $uploadOk = 0;
        }

        if (strtolower($imageFileType) != "jpeg" && strtolower($imageFileType) != "png" &&
            strtolower($imageFileType) != "jpg" && strtolower($imageFileType) != "gif"
            && strtolower($imageFileType) != "mp4"&& strtolower($imageFileType) != "Ogg"
            && strtolower($imageFileType) != "WebM"){

            $errorMessage = "File type not allowed.";
            $uploadOk = 0;
        }

        if($uploadOk){
            if(move_uploaded_file($_FILES['postToUpload']['tmp_name'], $imageName)) {
                // image uploaded

            } else{
                // image did not upload
                $uploadOk = 0;
            }
        }
    }

    if($uploadOk) {

    $post = new Post($con, $userLoggedIn);

    $post->submitPost(trim(strip_tags(filter_var($_POST['post_text'], FILTER_SANITIZE_STRING))),
        'none', $imageName);

    } else {

        echo "<div class='alert alert-danger'>
                $errorMessage
            </div>";
    }
}