texts: Stack implemented using linked list in x86_64 assembly

texts:
I wrote a stack implementation using a singly linked list in x86_64 assembly. This stack supports the usual push/pop operations as well as first/next for iterating over each element.

I'm looking for general feedback.

Here are the stack subroutines:

; Stack Structure
;   Pointer Head
;   Pointer Current

; Stack Node
;   Pointer Next
;   Pointer Value

; input
;   void
; output
;   stack or 0 on error
StackCreate:
  mov rdi, 24
  call malloc
  test rax,rax
  jz StackCreate_end
  xor rdi, rdi
  mov [rax], rdi
  mov [rax+8], rdi
  ret
StackCreate_end:
  add rsp, 8
  ret

; input
;   stack
; output
;   void
StackDestroy:
  call free
  ret

; input
;   stack
;   value
; output
;   0 on error
StackPush:
  push rdi
  push rsi
  mov rdi, 16
  call malloc
  test rax,rax
  jz StackPush_end
  pop rsi
  pop rdi
  mov rdx, [rdi]
  mov [rax], rdx
  mov [rax+8], rsi
  mov [rdi], rax
  ret
StackPush_end:
  add rsp, 16
  ret

; input
;   stack
; output
;   value or 0 if empty
StackPop:
  mov rsi, rdi
  mov rdi, [rdi]
  test rdi, rdi
  jz StackPop_end
  mov rax, [rdi]
  mov [rsi], rax
  mov rax, [rdi+8]
  push rax
  call free
  pop rax
  ret
StackPop_end:
  xor rax, rax
  ret
  nop;e

; input
;   stack
; output
;   value or 0 if empty
StackFirst:
  mov rax, [rdi]
  test rax, rax
  jz StackFirst_end
  mov rsi, [rax]
  mov [rdi+8], rsi
  mov rax, [rax+8]
StackFirst_end:
  ret

; input
;   stack
; output
;   value or 0 if end
StackNext:
  mov rsi, [rdi+8]
  test rsi, rsi
  jz StackNext_end
  mov rax, [rsi]
  mov [rdi+8], rax
  mov rax, [rsi+8]
  ret
StackNext_end:
  xor rax, rax
  ret

Here is a driver:

[extern puts]
[extern malloc]
[extern free]

[SECTION .data]

arguments:
  db "Incorrect arguments.",10,"Expected: stackme <string1> <string2> ...",0

[SECTION .text]
BITS 64
global main

wrong_arguments:
  mov rdi, arguments
  call puts
  jmp main_end

main:
  cmp rdi, 1
  jle wrong_arguments

  lea r12, [rsi+8]
  lea r13, [rdi-1]

  call StackCreate
  test rax, rax
  jz main_end
  mov r14, rax

pushing_loop:
  test r13, r13
  jz pushing_done
  mov rdi, r14
  mov rsi, [r12]
  call StackPush
  add r12, 8
  dec r13
  jmp pushing_loop
pushing_done:

  mov rdi, r14
  call StackFirst
print_loop:
  test rax, rax
  jz print_done
  mov rdi, rax
  call puts
  mov rdi, r14
  call StackNext
  jmp print_loop
print_done:

stack_delete:
  mov rdi, r14
  call StackPop
  test rax, rax
  jnz stack_delete
stack_delete_done:
  mov rdi, r14
  call StackDestroy

main_end:
  xor eax, eax
  ret

Assembling/Linking

nasm -f elf64 -l stackme.lst stackme.asm
gcc -o stackme stackme.o


texts:
Simple code where family and person instances can be created. There is a method where any instance of Person can be added to any instance of Family.

class Family:
    def __init__(self):
        self.names, self.birthplaces, self.dobs, self.deaths = [], [], [], []

class Person:
    def __init__(self, name, birthplace, dob, death=None):
        self.name, self.birthplace, self.dob, self.death = name, birthplace, dob, death

    def add_member_to(self, family_tree):
        family_tree.names.append(self.name)
        family_tree.birthplaces.append(self.birthplace)
        family_tree.dobs.append(self.dob)

        if self.death is None:
            family_tree.deaths.append('N/A')
        else:
            family_tree.deaths.append(self.death)

family = Family()
mike = Person('Michael', 'Nigeria', '06-07-2004')
esther = Person('Esther', 'KC', '03-25-2009')
mike.add_member_to(family)
esther.add_member_to(family)
print(family.dobs)
print(family.names)
print(family.birthplaces)
print(family.deaths)


texts:
I am trying to speed up some reporting on all employees but I am having difficulty determining where the "proper" place to parallelize my tasks. In order, this is what my code is currently doing.

Ask for all developers
Create a Developer object for each employee
REST call to Jira to get JSON of all tickets for employee
REST call to Github using info from Jira json to get pull request information
Hydrating JiraTicket objects with Jira and Github jsons
Returning developers

I have the below code to make the requests to Github and Jira. The getJiraTicketsAsync takes the json from Jira, the json contains info on all tickets. The getPullRequestURLsFromTicketId method makes another call to Jira as you cannot get development information from the JQL call to get the tickets json. My question is: am I parallelizing in the proper place? Should I move it up to a higher level and just call createDeveloper() in parallel?

private Set<JiraTicket> getJiraTicketsAsync(JsonArray ticketsArray)
{
    List<Callable<JiraTicket>> tasks = createJiraTicketTasks(ticketsArray);
    Set<JiraTicket> tickets = new HashSet<>(tasks.size());
    try
    {
        ExecutorService service = Executors.newCachedThreadPool();
        List<Future<JiraTicket>> futures = service.invokeAll(tasks);
        for(Future<JiraTicket> future: futures){
            try
            {
                tickets.add(future.get());
            } catch (ExecutionException e)
            {
                logger.error("There was an error getting a jira ticket", e);
            }
        }
        service.shutdown();
    } catch (InterruptedException e)
    {
        logger.error("Interrupted hydrating jira ticket", e);
    }
    return tickets;
}

private List<Callable<JiraTicket>> createJiraTicketTasks(JsonArray ticketsArray)
{
    List<Callable<JiraTicket>> tasks = new ArrayList<>(ticketsArray.size());
    for (int n = 0; n < ticketsArray.size(); n++)
    {
        int index = n;
        tasks.add(()->{
            JsonObject ticketJson = ticketsArray.get(index).getAsJsonObject();
            JsonArray pullRequestsJsonArray = getPullRequestURLsFromTicketId(ticketJson.get("id").getAsString());
            ticketJson.add("pullRequestUrls", pullRequestsJsonArray);
            return ticketHydrator.hydrateJiraTicket(ticketJson);
        });
    }
    return tasks;
}


texts:
Exercise 2.54

  Two lists are said to
  be equal? if they contain equal
  elements arranged in the same order.

  For example,

(equal? '(this is a list) '(this is a list))

  is true, but

(equal? '(this is a list) '(this (is a) list))

  is false. To be more precise, we can
  define equal? recursively in terms of
  the basic eq? equality of symbols by
  saying that a and b are equal? if they
  are both symbols and the symbols are
  eq?, or if they are both lists such
  that (car a) is equal? to (car b) and
  (cdr a) is equal? to (cdr b). Using
  this idea, implement equal? as a
  procedure.

I wrote the following:

(define (equal? a b)
  (or (and (and (symbol? a) (symbol? b)) (eq? a b))
      (and (null? a) (null? b))
      (and (and (and (not (null? a))
                     (list? a))
                (and (not (null? b))
                     (list? b)))
           (and (equal? (car a) (car b))
                (equal? (cdr a) (cdr b))))))

Can this be improved?


texts: Screen manager and its screens having access over the screen manager

texts:
I've got this here screen manager system and while it works rather well, I do worry on how practical it all is.

The application creates a screen manager class then enters a message loop which calls the update, render and handle input methods of the screen manager.

The screen manager has a vector container of unique_ptr's.
The main container type is a virtual screen class. It looks like this.

I should mention that vgSreen has a forward declaration of screenManager.

std::vector<std::unique_ptr<vgScreen>> gameScreens;
this->AddScreen(std::unique_ptr<MainMenu>(new MainMenu()));

When the screen manager adds a screen it loads the screens content and initializes it, then adds it to the stack. When it initializes a screen it passes a pointer of itself like this. From here on I'm skeptical about the performance of the program.

gameScreenToAdd.Initialize(*this);

The game screen stores the screen manager parameter as a pointer:

bool MainMenu::Initialize(ScreenManager* sManager)
{
    //manager is a ScreenManager* pointer
    this->manager = sManager;
}

Then when a screen wants to add or remove itself or another screen it can do the following:

manager->AddScreen(std::unique_ptr<Gameplay>(new Gameplay()));

I believe the erase function may result in errors because when a unique_ptr is added to the vector, the vector size increases, but erasing the vector doesn't then resize the container.

bool ScreenManager::RemoveScreen(int index)
{
    unsigned int a = GetCount();

    gameScreen[index]->Shutdown();

    gameScreen[index].release();

    gameScreen.erase(gameScreen.begin() + index);

    return true;
}

If there's a better alternate than using a vector of unique pointers, or if I'm leaking horrendously by passing screen manager to each screen, let me know. Or if you have any thoughts on this in general.


texts:
How can I improve this code? It renders a ML env with openAI gym and matplotlib. I am new to coding so not sure if my variables or format or any lines can be improved.
def _render(self, obs):
    """Renders the environment.
    """

    ball_loc = obs[1]
    x, y = self.circle.center

    new_y = math.tan(-math.radians(obs[3])) * (ball_loc - self.target_location)

    self.circle.center = (ball_loc, 10 + new_y + 1)

    t_start = self.ax.transData
    coords = t_start.transform([self.target_location, 10])
    t = mpl.transforms.Affine2D().rotate_deg_around(coords[0], coords[1], -obs[3])
    t_end = t_start + t
    self.rect.set_transform(t_end)

    self.fig.canvas.draw()
    plt.pause(0.05)


texts: Is this a sensible way of using an IoC container?

texts:
I have a Factory class for a queuing system I'm playing around with.

Consuming classes only care that they get a particular interface (Job) as a result of calling the factory's load method.

Some Jobs may require a database connection, so I want to inject a PDO instance. Others may require something else, and I don't want to give all Jobs a PDO instance regardless of whether they need it.

This is what I've ended up with:

IoC class:

use Queue\Job\MeterData;
use PDO;

class IoC
{

    const DATABASE = 'db';

    const METER_DATA_JOB = 'job_meterData';

    public function get($item)
    {
        switch ($item) {

            case self::DATABASE:
                return new PDO('');

            case self::METER_DATA_JOB:
                return new MeterData($this->get(self::DATABASE));

        }
    }

}

Resulting Queue Factory class:

namespace Queue\Job;

use IoC;

class Factory
{

    const METER_DATA = 'meter-data';

    private $ioc;

    public function __construct(IoC $ioc)
    {
       $this->ioc = $ioc;
    }

    public function load($job)
    {
        switch ($job) {

            case self::METER_DATA:
                return $this->ioc->get(IoC::METER_DATA_JOB);

            default:
                throw new \Exception('No job class found for ' . $job);

        }
    }

}

In my mind having the Factory isn't strictly necessary but is advantageous, as I can doc-comment the load method and it will ensure that consuming code knows what type of object it is dealing with. It'll also keep all queue jobs together neatly, rather than having the consuming code access the IoC container directly instead of the more specific Queue Factory.

The problem is, if we assume that IoC container is going to be one class for a full application, isn't it going to get very messy very quickly, with a ton of import statements and such?

Is that really such an issue, because at least it will be limited to just the IoC container and it will keep the rest of the application clear?


texts:
In my application, I have a message dispatcher. Each message gets relayed to a dispatcher thread.

In some scenarios, I can get two responses from the third party in the same millisecond:

An "I received your message" ACKnowledgement
"My response to your message" RESPONSE

When I get both messages at the same time, this can create a race condition. It is important to have my EventHandler handle the ACK before I get the RESPONSE, but I cannot guarantee ordering from the Asynchronous networking IO library; I must do it myself.

Below is a working MVCE of this scenario. Most of it is just framework, it's not how it works in the real code, but it's enough to get the bit I'm asking about - the ordering logic - to show it's value. The Proposed Solution to this race condition is the ensureAck method, which is called in the handleResponse method. If you comment out that call, and run the application repeatedly, you will see that there is no guarantee of method ordering. Additionally, and this is the difficult bit: I don't want the RESPONSE to be ignored if, for some reason, the ACK never shows up (a dropped network packet or something) - I want the RESPONSE to get handled, reluctantly, eventually.

Aside: the bit about NOTHING messages are just to warm up the ExecutorService so you can actually see the race condition.

How is my solution?

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RaceSolution {
  private static enum State {
    NEW, READY;
  }

  private static enum Type {
    ACK, RESPONSE, NOTHING;
  }

  private static class EventHandler {
    private volatile State state = State.NEW;
    private final Object lock = new Object();

    public void handleEvent(Event event) {
      switch(event.t) {
      case ACK:
        handleAck(event);
        break;
      case RESPONSE:
        handleResponse(event);
        break;
       default:
      }
    }

    private void handleResponse(Event event) {
      // COMMENT OUT THE NEXT LINE TO SEE THE RACE CONDITION
      ensureAck();
      synchronized(lock) {
        System.out.println("Received response event: " + state);
      }
    }

    private void handleAck(Event event) {
      synchronized(lock) {
        System.out.println("Received ack Event: " + state);
        state = State.READY;
      }
    }

    /* THIS IS THE IMPORTANT BIT */
    private void ensureAck() {
      int tries = 0;
      try {
          while(state == State.NEW && tries < 10) {
              Thread.sleep(1);
              tries++;
          }
      } catch (InterruptedException e) {

      }
    }
  }

  private static class Event {
    Type t;

    public Event(Type t) {
      this.t = t;
    }
  }

  public static void main(String... args) throws InterruptedException {
    RaceSolution solution = new RaceSolution();
    Event nothing = new Event(Type.NOTHING);
    Event ack = new Event(Type.ACK);
    Event response = new Event(Type.RESPONSE);

    for(int i = 0; i < 10; i++) {
      solution.submit(nothing);
    }

    Thread.sleep(100);

    solution.submit(ack);
    solution.submit(response);
    solution.shutdown();
  }

  private final ExecutorService dispatcher = Executors.newCachedThreadPool();
  private final EventHandler handler = new EventHandler();

  public void shutdown() {
    if (!dispatcher.isShutdown()) {
      dispatcher.shutdownNow();
    }
  }

  public void submit(final Event e) {
    dispatcher.execute(new Runnable() {
      @Override
      public void run() {
        handler.handleEvent(e);
      }
    });
  }
}


texts: Determining if one string occurs at the end of another

texts:
This is exercise 5-4 from K&R.  I spent hours tweaking it but now it seems to work.  I'm new to pointers and I'd welcome any comments about how to do it better.

/* Function strend(s, t), which returns 1 if the string t
 * occurs at the end of string s and zero otherwise */
int strend(const char *s, const char *t)
{
    const char *s0, *t0;

    if (s == 0) {
        printf("s is NULL pointer\n");
        return (-1);
    }
    if (t == 0) {
        printf("t is NULL pointer\n");
        return (-1);
    }
    s0 = s;
    t0 = t;

    while (*s++)
        ;
    s -= 2;         /* *s points to last real char in s */

    while (*t++)
        ;
    t -= 2;         /* *t points to last real char in t */

    if ((t-t0) > (s-s0))
            return (0);  /* t is longer than s */

    while (t>=t0) {
        if (*s-- != *t--)
            return (0);  /* Mismatch */
    }

    return (1); /* Match */
}

Here is main():

/* Test the function strend(s, t), which returns 1 if the string t
 * occurs at the end of string s and zero otherwise */
#include "jim.h"
#include "subs.c"

char a[MAXLINE], b[MAXLINE];

int main (void)

{
    printf("Return = %1d, Expect = 1\n", strend("12345", "45"));
    printf("Return = %1d, Expect = 0\n", strend("12345", "35"));
    printf("Return = %1d, Expect = 0\n", strend("45", "345"));
    printf("Return = %1d, Expect = 1\n", strend("12345", "12345"));
    printf("Return = %1d, Expect = 1\n", strend("12345", "5"));
    printf("Return = %1d, Expect = 0\n", strend("12345", "4"));
    printf("Return = %1d, Expect = 1\n", strend("12345", ""));
    printf("Return = %1d, Expect = 0\n", strend("12345", "+"));
    printf("Return = %1d, Expect = 0\n", strend("12345", "a2345"));
    printf("Return = %1d, Expect = 1\n", strend("", ""));
    printf("Return = %1d, Expect = 0\n", strend("", "Z"));
    printf("Return = %1d, Expect = 1\n", strend("1", "1"));
    printf("Return = %1d, Expect = 0\n", strend("1", "1A"));
    printf("Return = %1d, Expect = -1\n", strend(0, "1A"));
    printf("Return = %1d, Expect = -1\n", strend("1", 0));
}

Here is the output:

Return = 1, Expect = 1
Return = 0, Expect = 0
Return = 0, Expect = 0
Return = 1, Expect = 1
Return = 1, Expect = 1
Return = 0, Expect = 0
Return = 1, Expect = 1
Return = 0, Expect = 0
Return = 0, Expect = 0
Return = 1, Expect = 1
Return = 0, Expect = 0
Return = 1, Expect = 1
Return = 0, Expect = 0
s is NULL pointer
Return = -1, Expect = -1
t is NULL pointer
Return = -1, Expect = -1


texts: Filtering or repeating elements as needed

texts:
I'm having trouble thinking of a good name for the following extension method:

public static IEnumerable<T> TrimOrExpand<T>(this T[] items, int desiredCount)
{
    var ratio = (double)items.Length / desiredCount;
    for (int i = 0; i < desiredCount; i++)
        yield return items[Convert.ToInt32(i * ratio)];
}

The thing I don't like about this method name is that "Trim" may communicate to the user that it's cutting off the last x records of the array, when actually it is excluding items at a regular interval throughout the array. Likewise it will also "Expand" the array by repeating items if you specify a count that is larger than items.Length.

Is there a better technical term for what I'm trying to do? Or is TrimOrExpand obvious enough to understand what it does?


texts:
I am trying to learn some generic programming with Java:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by PACKAGE_NAME on 15/11/14.
 */
public class PrintMatrix {
    public static <T> void printma(ArrayList<ArrayList<T>> matrix) {
        ArrayList<Integer> sizes = new ArrayList<>();
        for(ArrayList<T> row : matrix) {
            sizes.add(row.size());
        }
        Set<Integer> sizesSet = new HashSet<>(sizes);
        Integer[] sizesArray = sizesSet.toArray(new Integer[0]);
        Integer nCol = sizesArray[0];
        Integer nRow = matrix.size();

        if(sizesSet.size() > 1) {
            System.err.println("This is not a matrix.");
            return;
        }

        for(int i=0; i<nRow; i++) {
            for(int j=0; j<nCol; j++) {
                System.out.printf("%s\t", matrix.get(i).get(j).toString());
            }
            System.out.println();
        }
    }

    public static <T> void printmb(ArrayList<T[]> matrix) {
        ArrayList<Integer> sizes = new ArrayList<>();
        for(T[] row : matrix) {
            sizes.add(row.length);
        }
        Set<Integer> sizesSet = new HashSet<>(sizes);
        Integer[] sizesArray = sizesSet.toArray(new Integer[0]);
        Integer nCol = sizesArray[0];
        Integer nRow = matrix.size();

        if(sizesSet.size() > 1) {
            System.err.println("This is not a matrix.");
            return;
        }

        for(int i=0; i<nRow; i++) {
            for(int j=0; j<nCol; j++) {
                System.out.printf("%s\t", matrix.get(i)[j].toString());
            }
            System.out.println();
        }
    }
}


texts: Interview solutions to reverse a string and reverse a sentence

texts:
Recently in an interview I was asked to

Write a method to reverse a string. I used StringBuilder but was asked not to use reverse method of builder but iterate over the string. Sample input/output provided by interviewer : "abc" --> "cba"
Next was to reverse a sentence. Sample input/output provided by interviewer : "hello world" --> "world hello"

Total time spent on both the solutions : around 10-12 minutes to write and run

Following is the code I wrote and I got rejected from interview. Would appreciate any helpful feedback.

class Solution {

  public static void main(String[] args) {
    String input = "hello world";
    System.out.println(reverseString(input));
    System.out.println(reverseSentence(input));
  }

  private static String reverseString(final String input){
    if(input == null || input.length() == 0){
      return null;
    }
    StringBuilder sb = new StringBuilder();
      for(int i =input.length()-1; i  >= 0; i--){
      sb.append(input.charAt(i));
    }
    return sb.toString();
  }

  private static String reverseSentence(final String input){

    final String[] wordsInInput = input.split(" ");
    StringBuilder sb = new StringBuilder();
    for(int i = wordsInInput.length-1; i >=0; i--){
      sb.append(wordsInInput[i]);
      sb.append(" ");
    }
    final String reversed = sb.toString();
    return reversed.trim();
  }
}


texts:
I'm sure this can be done in less lines and in a more clean way?

function BaseClass() {
  BaseClass.prototype.talk = function () {
    alert("I'm BaseClass");
  }
}

function MyClass() {
  BaseClass.call(this);
}
MyClass.prototype = new BaseClass();
MyClass.base = {};
MyClass.base.talk = MyClass.prototype.talk;
MyClass.prototype.talk = function () {
  alert("I'm MyClass");
  MyClass.base.talk();
}

var a = new MyClass();
a.talk();


texts:
A few weeks ago I posted a code review of a linked list so I decided to implement bubble sort on my journey of learning C. Here is the referenced linked list library, though this isn't really what's being reviewed (feel free if you'd like!).

Linked lists seem inefficient for bubble sort as deletes and gets both have to walk the list. So it's probably something like \$ O\left( n^{3} \right) \$?

I implemented it with arrays too, which is faster because the swapping can be done in place.

LinkedList.h

LinkedList.c

BubbleSort.c:

#include "../linked_list/ll.h"

void sort_linked_list(linked_list *list) {
  assert(list);
  int sorted = 1;
  for (int x = 0; x < list->size; x++) {
    /* don't do it if this is the last value */
    if (x + 1 == list->size) {
      continue;
    }
    int first = linked_list_get(list, x);
    int second = linked_list_get(list, x + 1);
    if (first > second) {
      sorted = 0;
      int temp = linked_list_get(list, x);
      /* {1, 7, 3}, 1 -> {1, 3} */
      linked_list_delete_at(list, x);
      /* {1, 3}, 7, 1 -> {1, 3, 7} */
      linked_list_insert_after(list, temp, x);
    }
  }
  /* do it again if it's not fully sorted */
  if (!sorted) {
    sort_linked_list(list);
  }
}

void sort_array(int *array, int size) {
  assert(size >= 0);
  int sorted = 1;
  for (int x = 0; x < size; x++) {
    /* don't do it if this is the last value */
    if (x + 1 == size) {
      break;
    }
    /* get int address */
    int *first = array + x;
    /* get int address after that one */
    int *second = first + 1;
    if (*first > *second) {
      /* we did some sorting so not sorted */
      sorted = 0;
      int temp = *first;
      int temp2 = *second;
      /* swap values */
      *first = temp2;
      *second = temp;
    }
  }
  /* do it again if it's not fully sorted */
  if (sorted == 0) {
    sort_array(array, size);
  }
}

void print_array(int *array, int size) {
  printf("{ ");
  for (int x = 0; x < size; x++) {
    printf("%d ", *array);
    array++;
  }
  printf("}\n");
}

int main() {
  linked_list *list = new_linked_list();
  linked_list_append(list, 7);
  linked_list_append(list, 5);
  linked_list_append(list, 3);
  linked_list_append(list, 8);
  linked_list_append(list, 1);
  linked_list_print(list);
  sort_linked_list(list);
  linked_list_print(list);
  int a[5] = {7, 5, 3, 8, 1};
  print_array(a, 5);
  sort_array(a, 5);
  print_array(a, 5);
  return 0;
}

Makefile:

    all: ../linked_list/ll.h bubble.c
        gcc -std=c99 -Wall -o bubble bubble.c ../linked_list/ll.c
        ./bubble

As you can see, linked_list is in another directory. Is this the correct way to include this in my project? I don't fully understand Makefiles quite yet.

Also, any general style tips for my bubble sort would be appreciated. I use pointer arithmetic with my arrays because it helps me understand what's really going on (which is why I'm learning C) but let me know if that's messy. I'd just like to keep learning how to write good C code.


texts: Calculating Euclidean distance and performing unit-testing

texts:
The method creates a link, an edge between two nodes, and calculates the Euclidean distance.

I'm testing that after linking, the link does indeed exist, and that the distance is correct.

I've used a variety of test cases, to check that it works for both horizontal and vertical links (just incase there's a divide by zero error), and as well as forward and backwards to check that it doesn't return a negative value.

import unittest
from graph import SpatialGraph

class TestSpatialGraph(unittest.TestCase):
    #cleardown any existing graph.
    def setUp(self):
        print "TestSpatialGraph Setup"

        g = None

    def testCreateLink_00_01(self):
        g = SpatialGraph(2,2)
        g.addNode(0, 0,0)
        g.addNode(1,0,1)
        g.createLink(0,1)

        self.assertTrue(g.link_matrix[0][1])
        self.assertTrue(g.link_matrix[1][0])

        self.assertEquals(g.distMatrix[0][1],1000)
        self.assertEquals(g.distMatrix[1][0],1000)

    def testCreateLink_00_11(self):
        g = SpatialGraph(2,2)
        g.addNode(0, 0,0)
        g.addNode(1,1,1)
        g.createLink(0,1)

        self.assertTrue(g.link_matrix[0][1])
        self.assertTrue(g.link_matrix[1][0])

        self.assertEquals(g.distMatrix[0][1],1414)
        self.assertEquals(g.distMatrix[1][0],1414)

    def testCreateLink_00_10(self):
        g = SpatialGraph(2,2)
        g.addNode(0, 0,0)
        g.addNode(1,1,0)
        g.createLink(0,1)

        self.assertTrue(g.link_matrix[0][1])
        self.assertTrue(g.link_matrix[1][0])

        self.assertEquals(g.distMatrix[0][1],1000)
        self.assertEquals(g.distMatrix[1][0],1000)

    def testCreateLink_10_00(self):
        g = SpatialGraph(2,2)
        g.addNode(0, 1,0)
        g.addNode(1,0,0)
        g.createLink(0,1)

        self.assertTrue(g.link_matrix[0][1])
        self.assertTrue(g.link_matrix[1][0])

        self.assertEquals(g.distMatrix[0][1],1000)
        self.assertEquals(g.distMatrix[1][0],1000)

    def testCreateLink_11_00(self):
        g = SpatialGraph(2,2)
        g.addNode(0, 1,1)
        g.addNode(1,0,0)
        g.createLink(0,1)

        self.assertTrue(g.link_matrix[0][1])
        self.assertTrue(g.link_matrix[1][0])

        self.assertEquals(g.distMatrix[0][1],1414)
        self.assertEquals(g.distMatrix[1][0],1414)

    def testCreateLink_01_00(self):
        g = SpatialGraph(2,2)
        g.addNode(0, 0,1)
        g.addNode(1,0,0)
        g.createLink(0,1)

        self.assertTrue(g.link_matrix[0][1])
        self.assertTrue(g.link_matrix[1][0])

        self.assertEquals(g.distMatrix[0][1],1000)
        self.assertEquals(g.distMatrix[1][0],1000)

Here's some questions I have:

Obviously the code is repetitive. But I'm told that for unit tests, you shouldn't genericise, and instead should repeat yourself. (But what if I change one of the methods use? Won't going through each of the tests and refactoring be a pain?).
It assumes that addNode is working correctly. But is this how unit tests work? I then also have tests to check that addNode is working correctly, and then assume after that that everywhere else it is indeed working correctly.
I'm not testing for more distances. This was perhaps laziness on my part. I check just the one diagonal, and it's indeed calculating that distance correctly.
What else am I meant to have in a setUp method?
Each test is in its own method. Should they perhaps be all just one test?


texts:
Given the following CreditCard object, how would you get a count of unexpired credit cards? What are the pros/cons of using each method? Or is there a better/optimal way?

public class CreditCard
{
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
}
public class User
{
    public User()
    {
        CreditCards = new List<CreditCard>();
    }

    public List<CreditCard> CreditCards { get; set; }

    public int NumberOfCreditCards
    {
        get
        {
            int count = 0;
            DateTime localDate = DateTime.Now;
            foreach (CreditCard creditCard in CreditCards)
            {
                DateTime expDate = new DateTime(creditCard.Year, creditCard.Month, creditCard.Day);
                if (DateTime.Compare(expDate, localDate) > 0)
                {
                    count++;
                }
            }

            return count;
        }
    }
}

Is LINQ a better performer?

public int NumberOfCreditCards
{
    get
    {
        DateTime localDate = DateTime.Now;
        return CreditCards.Select(creditCard => new DateTime(creditCard.Year, creditCard.Month, creditCard.Day))
            .Count(expDate => DateTime.Compare(expDate, localDate) > 0);
    }
}


texts:
Problem:

  You are given n types of coin denominations of values \$v(1) < v(2) < ... < v(n)\$ (all integers). Assume \$v(1) = 1\$, so you can always make change for any amount of money \$C\$. Give an algorithm which makes change for an amount of money \$C\$ with as few coins as possible.

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

int main()
{
    int i,n,den[20],temp[20],min,min_idx, S, numcoins = 0;
    printf("Coin Change with min no. of coins\nEnter the total change you want: ");
    scanf("%d",&S);
    printf("Enter the no. of different denominations of coins available: ");
    scanf("%d",&n);
    printf("Enter the different denominations in ascending order: \n");
    for(i=0;i<n;i++)
        scanf("%d",&den[i]);
    while(S>0)
    {
        for(i=0;i<n;i++)
        temp[i] = S / den[i] ;
        /*calculate min from temp */
        min = temp[0] ;
        for(i=0;i<n;i++)
        {
            if(min > temp[i] && temp[i]!=0)
            {
                min = temp[i] ;
                min_idx = i ;
            }
        }
        numcoins += min ;
        S -= den[min_idx] * min ;
    }
    printf("min no of coins = %d" , numcoins) ;
    return 0;
}

In several solutions on the internet, I saw code using an array of the size of the total sum or value S, whereas I use only 2 arrays of size n, the number of different denominations available. That's why I was wondering whether my approach is correct or whether it's flawed.

Is it better or worse in terms of time complexity? Also, am I properly using dynamic programming principles in my code? Can it be made more efficient? The code ran correctly for several test cases.

I am sorry for poor code formatting and a not-so-clean code. It is a small code, so I hope it is understandable. My main concern is whether the code is dp or not, and if it can be improved for efficiency.


texts: Testing if numbers in the array can be added up to equal the largest number in the array

texts:
Okay, here's a challenge at Coderbyte that completely stumped me. I came up with a solution, but I know it is flawed.

  Have the function ArrayAdditionI(arr) take the array of numbers stored in arr and return the string true if any combination of numbers in the array can be added up to equal the largest number in the array, otherwise return the string false. For example: if arr contains [4, 6, 23, 10, 1, 3] the output should return true because 4 + 6 + 10 + 3 = 23. The array will not be empty, will not contain all the same elements, and may contain negative numbers.

It is easy enough to find the highest value in the array.  If the length of the array was fixed, I could probably come up with a way to test various combinations, but I'm not sure how to handle different arrays. I wonder if the solution involves recursion? Or perhaps there is a way to call a function a number of times depending on the size of the array. Anyway, my "solution" is below. I would love to see a real solution, or if anyone wants to give me some hints, I am happy to give it another try.

function ArrayAdditionI(arr) {
  var greatest = -100;
  var index = -1;
  var sum = 0;

  for (var i = 0; i<arr.length; i++){
    if (arr[i] > greatest){
      greatest = arr[i];
      index = i;
    }
  }
    arr.splice(i,1)
      for (var i = 0; i<arr.length; i++){
        sum += arr[i];
        if (greatest = sum){
          return true;
        }else{
          return false;
        }
      }
  }


texts:
I have the task to create a function that adds some messages to the page and another to show them in last to first order with a jQuery slideDown() effect.

jsFiddle

jQuery("#input1").click(function()
{
    //Represents the first function to add the messages
    jQuery.each(["
1
", "
2
", "
3
"],
        function(index, item)
        {
            var jDiv =jQuery(item);
            jDiv.hide();
            jQuery(".parent").prepend(jDiv);
        });

    //represents the second function to show them.
    var jParent = jQuery(".parent");
    jParent.children().reverse().each(function()
    {
        var jThis= jQuery(this);
        jParent.queue( function()
       {
           jThis.slideDown(function()
           {
               jParent.dequeue();
           });

       });
    });
});

(reverse from this answer)

jQuery.fn.reverse = [].reverse;

This seems to be an awful bunch of code just to show them one after another. Is there any way to clean up/remove redundant code?


texts: Python code to guess the roots of any integer

texts:
I'm new to programming and python,this one of my biggest codes in python yet...
I just wanted to know if you can simplify it further...
English is not my first language, so corrections in the language are also welcomed!
Thank You In advance!
x = int(input('Enter an integer who\'s root value you need: '))

e = int(input('Enter an +ve integer for root value: '))

#Removing the possiblities of zero in eihter of the variables

if x==0:
    print('Zero power anything is zero!')
elif e==0:
    print('Anything power zero is one!')
else:
    while e < 0:
        print('I SAID +VE INTEGER FOR ROOT!')
        x = int(input('Enter an integer who\'s root value you need: '))
        e = int(input('Enter an +ve integer for root value: '))

    while e %2 == 0 and x < 0:
        print('-ve nos. can\'t have root value for even roots!')
        x = int(input('Enter an integer who\'s root value you need: '))
        e = int(input('Enter an +ve integer for root value: '))
    epsilon = 0.0000001
    numGuesses = 0
    if x>0:
        low = -x
    elif x<0:
        low = x
    if x>0:
        high = max(1.0,x)
    elif x<0:
        high = max(1.0,-x)
    ans = (high + low)/2.0
    while abs(ans**e - x) >= epsilon:
        print('low =', low, 'high =', high, 'ans =', ans)
        numGuesses += 1
        if ans**e < x:
            low = ans
        else:
            high = ans
        ans = (high + low)/2.0
    print('numGuesses =', numGuesses)
    print(ans, 'is close to the value of', e, 'root', x)


texts:
Everyone knows "99 bottles of beer on the wall".

Mat's Mug made a comment about mugs on the wall in The 2nd Monitor and I realized I never wrote a "beer on the wall" program. But that seemed way too easy, so I made it a "n number of x on the y" instead. It also seemed like a good excuse to use templates in Python, which I hadn't done before.

import sys

n = int(sys.argv[1])
x = sys.argv[2]
y = sys.argv[3]

template = '''\
%i %s on the %s
%i %s
Take one down, pass it around
%i %s on the %s
'''

for n in range(n, 0, -1):
    print template % (n, x, y, n, x, n-1, x, y)

Usage:

python script.py 99 "mugs of beer" wall

For obvious reasons there's no way (that I know of) to remove multiples of x if n = 1. Sure, it's not hard to turn mugs of beer into mug of beer, but it's generic. One can input anything and I can't catch all methods of pluralization.

I prefer readability over 'clever code' and my naming is probably not too good.


texts: Multiple SELECT with LEFT JOIN to order results

texts:
I have two tables, looking like this:

Table 1

id | name |          date
---+------+---------------------
 1 | zaak |  2016-08-03 11:37:40  -- top 1 dates, name #5
 2 | aap  |  2016-08-01 11:40:35
 3 | corn |  2016-08-02 11:42:16  -- top 3 dates, name #3
 4 | quar |  2016-08-02 11:42:28  -- top 2 dates, name #4
 5 | alfa |  2016-07-04 11:44:29

Table 2

id | open | name  | name_id | type
---+------+-------+---------+-----
 1 |   1  | aap   |    2    |   2  -- type = 2, open = 1 : 1
 2 |   1  | quar  |    4    |   2  -- type = 2, open = 1 : 1
 3 |   1  | quar  |    4    |   2  -- type = 2, open = 1 : 1
 4 |   1  | dinky |    1    |   1  -- type = 1, open = 1 : NULL
 5 |   2  | quar  |    1    |   1  -- type = 1, open = 2 : NULL

The result I need is id and name from table 1 and open from table 2.

The requirements:

from table 1: select the newest three by date
order those three by name from A - Z
from table 2: select open

IF name not there return NULL
IF type <> 2  return NULL
IF open <> 1  return NULL
ELSE              return 1

With a lot of trial and error I constructed this query:

-- get id, name and open only once
SELECT DISTINCT t1.id , t1.name , t3.open

-- select names from table 1, order them by date and return first 3
FROM (SELECT id , name FROM table1 ORDER BY date DESC LIMIT 3) AS t1

-- get open from table 2 IF id is there, open = 1 and type =2
LEFT JOIN ( ( SELECT open , name_id
              FROM table2
              WHERE open=1 AND type=2
            ) AS t3
          )
ON t1.id = t3.name_id

-- order by name from A-Z
ORDER BY t1.name ASC

The result I get is correct:

id | name | open
---+------+-----
 3 | corn | NULL  (correct)
 4 | quar | 1     (correct)
 1 | zaak | NULL  (correct)

As my knowledge of MYSQL is limited, I wonder

would this query always return the desired result? (the data in the tables is limited at the moment and I have to change values by hand to see different results, so testing all variations proves a bit difficult)
is there anything I could improve on this query, or should I construct an entirely different query? (as triple SELECT to get the desired result seems a bit overdone)


texts: Simple carbon emissions from fuel and fire calculations

texts:
I would like to get the simple carbon emissions calculations below written in the most Pythonic / straightforward way.

FUEL_FACTORS = {'diesel': {'energy_factor': 38.6,
                           'co2_emission_factor': 69.9,
                           'ch4_emission_factor': 0.1,
                           'n2o_emission_factor': 0.5
                          },
                'petrol': {'energy_factor': 34.2,
                           'co2_emission_factor': 67.4,
                           'ch4_emission_factor': 0.5,
                           'n2o_emission_factor': 1.8
                           },
                'avgas':  {'energy_factor': 33.1,
                           'co2_emission_factor': 67.0,
                           'ch4_emission_factor': 0.05,
                           'n2o_emission_factor': 0.7}
                }

FIRE_FACTORS = {'gwp_co2': 1,
                'gwp_ch4': 25,
                'gwp_n2o': 298,
                'ch4_co2_mass_ratio': 7.182e-3,
                'n2o_co2_mass_ratio': 1.329e-5,
                }

def get_fuel_emission_factor(fuel):
    """Get fuel total CO2 emission factor."""
    factors = FUEL_FACTORS[fuel]
    energy_f = factors['energy_factor']
    fuel_emission_factor = 0
    for i in ['co2', 'ch4', 'n2o']:
        gas_emission_factor = factors[i + '_emission_factor']
        fuel_emission_factor += energy_f * gas_emission_factor * 1e-3
    return fuel_emission_factor

def fuel_to_co2(fuel, quantity):
    """Get total tCO2 emission by kL of fuel."""
    fuel_emission_factor = get_fuel_emission_factor(fuel)
    return fuel_emission_factor * quantity

def burned_c_to_co2(tC):
    """Get CH4 and N2O emissions in tCO2 from tonnes of C burned"""
    ch4_emissions = tC * FIRE_FACTORS['gwp_ch4'] * FIRE_FACTORS['ch4_co2_mass_ratio']
    n2o_emissions = tC * FIRE_FACTORS['gwp_n2o'] * FIRE_FACTORS['n2o_co2_mass_ratio']
    return ch4_emissions + n2o_emissions

fuel_emissions = fuel_to_co2('petrol', 2.7395)
fire_emissions = burned_c_to_co2(5.74)


texts: Improving design for a CustomerDAO with DatabaseManager object

texts:
I'm learning about SRP and had to reduce the responsibility of a customer object, which contained too much info. So I turned that into just a Pojo and pulled out the database logic.
I'm trying to find the best design for this setup and am split between making the DatabaseManager class be a parent class, or a singleton that can return the single connection object. This system will be used to insert and delete customers from the database. I don't want my domain objects/DAOs to worry about the connection details. Is the design I currently have a strong follower of OOP design principles?

public class DatabaseManager {

    private Connection conn;

    private static DatabaseManager managerInstance = new DatabaseManager();

    private DatabaseManager() {

    }

    public static DatabaseManager getInstance() {
        return managerInstance;
    }

    /**
     * contains connection details
     *
     * @throws SQLException
     */
    public void connect() throws SQLException {
        System.out.println("Established Database Connection...");
        conn = DriverManager.getConnection("Some/Database/URL");
    }

    public Connection getConnectionObject() {
        return conn;
    }

    public void disconnect() throws SQLException {
        conn.close();
        System.out.println("Disconnected from Database...");
    }
}

Here is the Customer Object:

public class Customer {

       private int id;
       private String name;
       private boolean active;

       public Customer(int id, String name, String department, boolean working) {
              super();
              this.id = id;
              this.name = name;
              this.department = department;
              this.working = working;
       }

       @Override
       public String toString() {
              return "Customer [id=" + id + ", name=" + name + ", department="
                           + department + ", working=" + working + "]";
       }
}

The customer DAO:

public class CustomerDAO {

    public CustomerDAO() {
    }

    public void addCustomer(Customer Customer) throws SQLException {
        DatabaseManager.getInstance().getConnectionObject().prepareStatement("some sql... ");
    }

    public void removeCustomer(Customer Customer) throws SQLException {
        DatabaseManager.getInstance().getConnectionObject().prepareStatement("some sql... ");
        // implementation details avoided
    }

}


texts: Using custom negotiator and custom formatter in Web API 2

texts:
Here's my custom formatter which I want to use for "application/x.product" content type:

public class ProductFormatter : MediaTypeFormatter
    {
        public ProductFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/x.product"));
        }
        public override bool CanReadType(Type type)
        {
            return false;
        }
        public override bool CanWriteType(Type type)
        {
            var result = (type == typeof(Product) || type == typeof(IEnumerable<Product>));
            return result;
        }

        public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            List<string> productStrings = new List<string>();
            IEnumerable<Product> products = value is Product ? new Product[] { (Product)value } : (IEnumerable<Product>)value;
            foreach (Product product in products)
            {
                productStrings.Add(string.Format("{0},{1},{2}",
                product.ProductID, product.Name, product.Price));
            }
            StreamWriter writer = new StreamWriter(writeStream);
            await writer.WriteAsync(string.Join(",", productStrings));
            writer.Flush();
        }
    }

Registered as:

config.Formatters.Add(new ProductFormatter());

I also have a custom negotiator (also registered):

public class CustomNegotiator : DefaultContentNegotiator
    {
        public override ContentNegotiationResult Negotiate(Type type,
        HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
        {
            // look for an appropriate formatter
            MediaTypeFormatter formatter = null;
            foreach(var f in formatters)
            {
                var mediaType = f.SupportedMediaTypes.Where(mt => mt.MediaType == "application/x.product").SingleOrDefault();
                if (mediaType != null)
                {
                    formatter = f;
                    break;
                }
            }
            if (request.Headers.UserAgent.Where(x => x.Product != null
            && x.Product.Name.ToLower().Equals("chrome")).Count() > 0 && formatter != null)
            {
                // if client is chrome then return superproduct and use custom formatter for it
                return new ContentNegotiationResult(formatter,
                new MediaTypeHeaderValue("application/x.product")
                );
            }
            else
            {
                return base.Negotiate(type, request, formatters);
            }
        }
    }

I also want to use this with application/x.product when a client is Google Chrome.

Is my way of searching an appropriate formatter okay, or is there a better way?


texts: Storing data into an SQL table using multiple threads and queues

texts:
I have a process running in a separate thread which reads data over Ethernet and raises an event for each read. Then, this data is processed over a tree of classes. At the top of my class tree, I want to store the processed data to SQL tables. This read rate can be rather fast and often at times but on average its slower than my write rate to SQL. This is why I want a queue. Also I want my window not to freeze, so I want a separate thread.

The code below works but I'm fairly inexperienced in multi threading. Is this a good and robust way to accomplish my task?

Private addLogQueue As New Queue
Private dequeueing As Boolean = False
Public Sub addLogHandler(ByVal machineName As String, ByVal LogTime As Date, ByVal EventLog As String, ByVal EventValue As String)
    addLogQueue.Enqueue("INSERT INTO ... some SQL CODE")
    Dim Thread1 As New System.Threading.Thread(AddressOf addLog)
    Thread1.Start
End Sub
Private Sub addLog()
    If Not dequeueing Then
        dequeueing = True
        While addLogQueue.Count <> 0
            Try
                SQLCon.Open()
                SQLCmd = New SqlCommand(addLogQueue.Dequeue(), SQLCon)
                SQLCmd.ExecuteNonQuery()
                SQLCon.Close()
            Catch ex As Exception
                MsgBox(ex.Message)
                If SQLCon.State = ConnectionState.Open Then
                    SQLCon.Close()
                End If
            End Try
        End While
        dequeueing = False
    End If
End Sub

After thinking a bit I realize I might not even need a queue or the dequeueing boolean, can I just start a new thread for every write maybe. I added the queue before I added the multi thread because at times I had to write before the SQLcon is even closed. Since I've added a thread, should I even keep the queue?


texts: Simple program that simulates StackOverflow post

texts:
I'm doing a C# tutorial by Mosh and one of the exercises is creating a program that simulates a stack overflow post upvoting/downvoting system. Very simple and short app but still wanted to know if my solution is okay and ways to improve it! I'm trying to make it as object-oriented as I possibly can, but I'm not sure I'm getting OOP correctly.

Program.cs

using System;

namespace StackOverflowPost
{
    class Program
    {
        static void Main(string[] args)
        {
            var newPost = new Post
            {
                Title = "HELLO WORLD",
                Description = "This is some awesome hello world description."
            };

            Console.WriteLine(newPost.Title);
            Console.WriteLine(newPost.Description);
            Console.WriteLine(newPost.CreationDateTime);

            newPost.UpVote();
            newPost.UpVote();
            newPost.DownVote();

            Console.WriteLine("Number of votes: " + newPost.DisplayVotes());
        }
    }
}

Post.cs

using System;

namespace StackOverflowPost
{
    class Post
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public readonly DateTime CreationDateTime = DateTime.Now;
        private int _votes;

        public int DisplayVotes()
        {
            return _votes;
        }

        public void UpVote()
        {
            _votes++;
        }

        public void DownVote()
        {
            _votes--;
        }
    }
}


texts:
I had to create this method GetModelFormat and wanted to see if there is a better way to format the view model that is being return. I would be happy for any kind of feedback since this is quite critical a part of my application.
    static void Main(string[] args)
    {
        try
        {
            List<carmake> listofcarmakes = new List<carmake>();

            List<carmnodeltype> cartype = new List<carmnodeltype>();
            cartype.Add(new carmnodeltype() { TypeId = 1, Type="Red" });
            List<carmnodeltype> cartype1 = new List<carmnodeltype>();
            cartype1.Add(new carmnodeltype() { TypeId = 2, Type = "Green" });
            List<carmodel> carmodel = new List<carmodel>();
            carmodel.Add(new carmodel() { Modelid = 4, Model = "535d" , ListOfCarType = cartype });
            carmodel.Add(new carmodel() { Modelid = 5, Model = "535", ListOfCarType = cartype1 });

            carmake carmakes = new carmake();
            carmakes.MakeName = "BMW";
            carmakes.Makeid =1;
            carmakes.ListOfCarModel = carmodel;

            listofcarmakes.Add(carmakes);

            var listOfcarmodel = listofcarmakes
                 .Select(x => new CarViewModel
                 {
                     MakeName = x.MakeName,
                     CarModelViewModel = x.ListOfCarModel?.Select(z => new CarModelViewModel
                     {
                         Type = GetModelFormat(z.ListOfCarType)
                     }).ToList()
                 }).ToList();

            foreach (var obj in listOfcarmodel)
            {
                foreach (var vm in obj.CarModelViewModel)
                {
                    Console.WriteLine(vm.Type);
                }
            }

        }
        catch (Exception ex)
        {
            ex.ToString();
        }
    }
    private static string GetModelFormat(IEnumerable<carmnodeltype> ListOfModel)
    {
        StringBuilder builder = new StringBuilder();
        foreach (var item in ListOfModel)
        {
            if (item.Type == "Red")
            {
                if (item.TypeId == 1)
                {
                    builder.Append("Super Car");
                    builder.Append("
");
                }
                else if (item.TypeId == 2)
                {
                    builder.Append("diesel engine");
                    builder.Append("
");
                }
                else
                {
                    builder.Append(item.Type);
                    builder.Append("
");
                }
            }

        }
        return builder.ToString();
    }

Model
class carmake
    {
        public int Makeid { get; set; }
        public string MakeName { get; set; }

        public List<carmodel> ListOfCarModel { get; set; }
    }
    class carmodel
    {
        public int Modelid { get; set; }
        public string Model { get; set; }
        public List<carmnodeltype> ListOfCarType { get; set; }
    }

    class carmnodeltype
    {
        public int TypeId { get; set; }
        public string Type { get; set; }
    }
    class CarViewModel
    {
        public string MakeName { get; set; }
        public string Type { get; set; }
        public List<CarModelViewModel> CarModelViewModel { get; set; }
    }
    class CarModelViewModel
    {
        public string Model { get; set; }
        public string Type { get; set; }
    }
}


texts: Displaying fields in a sidebar of a custom page template

texts:
I'm beginning with PHP programming and would appreciate a critique on my code and how I could make it more efficient, rather than repeating the if statements.

What I'm basically doing is getting the fields typed in by the user and displaying these fields in a sidebar of a custom page template.

<?php

            $name = (get_field('name'));
            $address = (get_field('address'));
            $business= (get_field('company'));
            $phone= (get_field('phone'));
            $fax= (get_field('fax'));
            $mobile= (get_field('mobile'));
            $email =  (get_field('email'));
            $personalemail =  (get_field('second_email'));
            $website =  (get_field('website'));
            $facebook =  (get_field('facebook'));
            $twitter =  (get_field('twitter'));
            $linkedin =  (get_field('linkedin'));

            if (!empty($name)) {
                echo $name . "
";
            }

            if (!empty($business)) {
                echo $business . "
";
            }

            if (!empty($address)) {
                echo $address . "
";
            }

            if (!empty($phone)) {
                echo $phone . "
";
            }

            if (!empty($fax)) {
                echo $fax . "
";
            }

            if (!empty($mobile)) {
                echo $mobile . "
";
            }

            if (!empty($email)) {
                echo "$email" . "
";
            }

            if (!empty($personalemail)) {
                echo "$personalemail" . "
";
            }

            if(!empty($website)){
                $final_url = (!preg_match("~^(?:f|ht)tps?://~i", $website))? 'http://'.$website: $website;
                echo "$final_url" . "
";

            }

            if(!empty($facebook)){
                $final_url = (!preg_match("~^(?:f|ht)tps?://~i", $facebook))? 'http://'.$facebook: $facebook;
                echo "";

            }

            if(!empty($twitter)){
                $final_url = (!preg_match("~^(?:f|ht)tps?://~i", $twitter))? 'http://'.$twitter: $twitter;
                echo "";

            }

            if(!empty($linkedin)){
                $final_url = (!preg_match("~^(?:f|ht)tps?://~i", $linkedin))? 'http://'.$linkedin: $linkedin;
                echo "";

            }

            ?>


texts: Interpolation across different dataframes with Pandas

texts:
Context of the Problem
I am running a discrete event simulation where at the end of each event I store the state of the system in a row of a dataframe. Each simulation run has a clock which determines which events are run and when, all the simulation have the same initial clock (0) and the same end clock (simulation end). but the number of rows for the dataframes may be different because the simulation has several stochastic components. The clock column is then converted to timestamp and use as index of the dataframe.
Whenever one does a simulation, it is good practice to run it many times and then average over all the replicates, doing so in this setup is a bit complicated because each simulation produced a dataframe which different indexes.
Proposed Solution
So far this is the solution I found:
# Auxiliary functions
def get_union_index(dfs):
    index_union = dfs[0].index
    for df in dfs[1:]:
        index_union = index_union.union(df.index)
    return pd.Series(index_union).drop_duplicates().reset_index(drop=True)

def interpolate(df, index, method='time'):
    aux = df.astype(float)
    aux = aux.reindex(index).interpolate(method=method).fillna(method='ffill').fillna(method='bfill')
    return aux

# Simulation
dfs = []
replicates = 30
seeds = list(range(40, 40 + replicates))
dfs = [simulate(seed=seed, **parameters) for seed in seeds]

# Main Code
union_index = get_union_index(dfs)
dfs_interpolates = [interpolate(df, union_index) for df in dfs]
df_concat = pd.concat(dfs_interpolates)
by_row_index = df_concat.groupby(df_concat.index)

# Averaging
df_means = by_row_index.mean()
df_std = by_row_index.std()

Explanation
First, it is necessary to combine all the indexes, then this combined index is used to re-index all the dataframes and the nan values are filled using interpolation.
Questions

Is there a native pandas function that could simplify this?

(If not 1) Is there an alternative way to combine the datasets directly, since the majority of the index are disjoint, union_index has a length of approximately len(df) * len(dfs) which is actually huge.

Which should be the best interpolation method to use in the interpolate? Since each row is an event and only a few variables are changed per event, from one row to the next only a few columns are modified, making it possible to have several consecutive rows with identical values in several columns (but not all).


texts: Check if we find new value from a request

texts:
I have created a script where I add a timestamp to each value that has been found with a code that I have written:
import random
from datetime import datetime, timedelta
from typing import Dict, List
import time

class RequestFilter:
    """Tracks requests and filters them to prevent hammering."""

    def __init__(self, cooldown: timedelta):
        self._cooldown = cooldown
        self._requests: Dict[str, datetime] = {}

    def filter(self, requests: List[str], time: datetime) -> List[str]:
        """Filter requests to only those that haven't been made
        previously within our defined cooldown period."""
        # Get filtered set of requests.
        filtered = [
            r for r in list(set(requests))
            if (
                    r not in self._requests or time - self._requests[r] >= self._cooldown
            )
        ]
        # Refresh timestamps for requests we're actually making.
        for r in filtered:
            self._requests[r] = time

        print(self._requests)
        return filtered

if __name__ == '__main__':
    from time import sleep
    request_filter = RequestFilter(timedelta(minutes=5))

    firstReq = []
    for _ in range(random.randint(1,5)):
        firstReq.append(f"US {random.randint(1, 10)}")

    for _ in range(100):

        newReq = []
        for _ in range(random.randint(2, 8)):
            newReq.append(f"US {random.randint(1, 10)}")

        if len(newReq) > len(firstReq):
            print(request_filter.filter(newReq, datetime.now()), datetime.now())
            sleep(1)
            firstReq = newReq
        else:
            print("Length is not bigger, testing again in 3 sec...")
            time.sleep(3)
            firstReq = newReq

As you can see at the very bottom i'm checking if the list size from previous request is less than newest request (at this momentit just random function but it would be reading from a HTML later on) and if it is, that means that something has been added to a webpage and we want to see what value has been added. If the value has already a timestamp then we check "filter" and see if it has been over 5 minutes difference in the timestamp and if its true then we should say "New value has been found!"
However my improvements in general here is that I am not quite happy with the way that I check for length of firstReq vs newReq. and reason if that could be etc if I request a page and it has US 3 and then the newReq has value US 6 but it still will have 1 > 1 which is false but still different value which will not print due to the 1 > 1. My question is, how can I improve the code that I could skip the < function and check maybe the sizes directly?


texts: How should I read coordinates from a text file?

texts:
I have a text file with lines that look like this:

Robot(479.30432416307934|98.90610653676828)
Robot(186.42081184420528|213.11277688981409)
Robot(86.80794277768825|412.1359734884495)

or, more general:

Robot(DOUBLE|DOUBLE)

How should I parse it in Java?

I have written the following (tested and working) code:

private static List<Position> getPositions(File myFile)
        throws FileNotFoundException, IOException {
    List<Position> result = new ArrayList();
    BufferedReader br = new BufferedReader(new FileReader(myFile));
    try {
        String line = br.readLine();
        while (line != null) {
            String coordinates = line.substring(6, line.length() - 1);
            int splitpoint = coordinates.indexOf('|');
            double x = Double.parseDouble(coordinates.substring(0,
                    splitpoint));
            double y = Double.parseDouble(coordinates
                    .substring(splitpoint + 1));
            result.add(new Position(x, y));
            line = br.readLine();
        }
    } finally {
        br.close();
    }
    return result;
}

It looks a too complicated for such a simple task for me. I mean, with the RegEx

Robot\(\d+\.\d+|\d+\)

I can match a line. According to Regextester my regex is correct. But how can I get the interesting part (the two doubles) from the regex?

Result after answer

/**
 * Read a file with positions of roboters.
 * @param file the file with positions
 * @return the list with roboter positions
 * @throws FileNotFoundException
 * @throws IOException
 */
private static List<Position> getPositions(final File file)
        throws FileNotFoundException, IOException {
    if (file == null || !file.canRead()) {
        throw new IllegalArgumentException("file not readable: " + file);
    }

    final Scanner s = new Scanner(file).useDelimiter("Robot\\(|\\||\\)\n?");
    final List<Position> positions = new ArrayList<Position>();
    while (s.hasNext()) {
        positions.add(new Position(s.nextDouble(), s.nextDouble()));
        s.nextLine();
    }

    return positions;
}


texts: Click a link to delete targeted content using Ajax

texts:
I used a glyphicon as a link to delete a comment:

    delete

I send the request using Ajax.

retrieve the comment_url
get the grand-grand-parent element to hide
send request to views.py and delete the target comment

$(document).ready(function () {
    $("body").on("click",".delCommentLink",function (e) {
        e.preventDefault();
        var comment_url = $(e.target).parent().attr("href");
        var $commentEle = $(e.target).closest(".comment");
        if (window.confirm("Delete this comment?")) {
            $.ajax({
                type: "get",
                url: comment_url,
                success: function (data) {
                    var ret = JSON.parse(data);
                    if (ret['status'] == 1) {
                        $commentEle.hide();
                    } else {
                        alert(ret['msg']);
                };
            },//success
        });//ajax
        } else {
            e.preventDefault()
        }
    });//click event
})

Click a link to delete it. My code seems like it has too many lines for such a routine task.
How can I complete it elegantly?


texts:
I've a small assignment to do: style a given HTML file with CSS.

My result looks exactly as it should. But I'm not really satisfied with my style sheet. I'm sure there are better ways to achieve the same.

The different sizes are not specified. I had just an image as template.

How would a real web design solve this task?

jsFiddle

body > div {
    width: 404px;
    border: 1px solid black;
    padding: 8px;
}

.header {
    margin-bottom: 5px;
}

.header input {
    width: 400px;
    height: 40px;
    border: 1px solid black;
    text-align: right;
}

.numberFields {
    margin: 0;
    width: 360px;
    font-size:0;
    overflow: auto;
    float: left;
}

.numberFields input {
    background-color: green;
    border: 1px solid black;
    width: 120px;
    height: 40px;
}

.numberFields input[name="0"] {
    width: 360px;
}

.operations {
    margin-left: 4px;
    width: 40px;
    font-size: 0;
    display: inline-block;
}

.operations input {
    background-color: purple;
    border: 1px solid black;
    width: 40px;
    height: 40px;
}

.sum {
    margin-top: 5px;
}

.sum input {
    background-color: purple;
    border: 1px solid black;
    width: 404px;
    height: 40px;
}

            <input name="1" value="1" disabled />

            <input type="button" name="1" value="1" />
            <input type="button" name="2" value="2" />
            <input type="button" name="3" value="3" />
            <input type="button" name="4" value="4" />
            <input type="button" name="5" value="5" />
            <input type="button" name="6" value="6" />
            <input type="button" name="7" value="7" />
            <input type="button" name="8" value="8" />
            <input type="button" name="9" value="9" />
            <input type="button" name="0" value="0" />

            <input type="button" name="+" value="+" />
            <input type="button" name="-" value="-" />
            <input type="button" name="*" value="*" />
            <input type="button" name="/" value="/" />

            <input type="button" name="=" value="=" />


texts: CSS mask clipping and overlay SVG to achieve a two effect

texts:
I am currently attempting to create a two SVG overlay / masking like the image below:

I have created a SVG for the overlay. As it stands, I am trying to create two elements one for the green side and one for the blue side.

For what I am trying to achieve, is this the best approach? If not, what is?

Is it worth creating two SVGs to achieve the overlay in the example below?

    .hero-overlay {
       position: absolute;
        top: 0;
       height: 100%;
       width: 100%;
     -webkit-mask: url("https://dl.dropboxusercontent.com/u/58412455/circle-mask.svg") no-repeat center center;
      mask: url("https://dl.dropboxusercontent.com/u/58412455/circle-mask.svg") no-repeat center center;
      clip: rect(0px, 580px, 500px, 0px); }

    .mask-left {
      background-color: red; }

.mask-right {
   -webkit-transform: rotate(180deg);
  -ms-transform: rotate(180deg);
      transform: rotate(180deg);
      background-color: blue; }

jsFiddle


texts:
This is my peak finding algorithm. I try to split the 2D array in half and find the maximum element in the middle column. After that, the algorithm will check whether there are any other element bigger than it on the left or the right side. If there is any, the matrix will slice in half depending on the position of the element and go into recursion. You can simply change the size or the elements of the matrix.

How can I improve my coding to make it more efficient or concise?

import numpy as np
matrix=np.array([[3,2,3],
    [100,55,7],
    [344,9,37]
   ])

def algo(problem):
    print('matrix =' + str(problem))
    Nrow=len(problem)
    print("row"+str(Nrow))
    for i in problem:
        Ncol=len(i)
        break
    if Nrow <=0 or Ncol<=0:
        return None
    print("col"+str(Ncol))
    mid=Ncol//2
    (substartR,subnrow)=(0,Nrow)
    (substartc1,subncol1)=(0,mid)
    (substartc2,subncol2)=(mid,Ncol-mid+1)
    subproblem=[]
    subproblem.append((substartR,substartc1,subnrow,subncol1))
    subproblem.append((substartR,substartc2,subnrow,subncol2))
    print(subproblem)

    loc=[]
    for i in range(Nrow):
        loc.append((i,mid))
    # bestloc is a tuple of location and biggest val
    bestloc=findmax(loc,problem)
    print("bestloc" + str(bestloc[0]))

    bestloc1=bestneighbour(bestloc,Nrow,Ncol,problem)
    print("bestloc1 =" + str(bestloc1))

    if bestloc[0] != bestloc1:
        print('sub problem')
        #print(problem)
        new_matrix=get_subproblem(subproblem,bestloc1,problem)
        return algo(new_matrix)
    else:
        (x,y)=bestloc1
        #print("the peak " +str( problem[x][y]))
        print( problem[x][y])

def findmax(loc,matrix):
    (bestloc,bestval)=(None,0)

    for i in loc:

      if bestloc == None or bestval < get_value(i,matrix) :
        #print(get_value(i))

          bestloc=i
          bestval= get_value(i,matrix)

    return (bestloc,bestval)

def get_value(i,matrix):

    y=i[1]
    x=i[0]

    return matrix[x][y]

def bestneighbour(i,Nrow,Ncol,matrix):

    y=i[0][1]
    x=i[0][0]
    bestval=i[1]

    inew=(x,y)
    if x-1>=0 and matrix[x-1][y]>bestval:
        inew=(x-1,y)
        bestval=matrix[x-1][y]
    if x+1<Nrow and matrix[x+1][y]>bestval:
        inew=(x+1,y)
        bestval=matrix[x+1][y]

    if y-1>=0 and matrix[x][y-1]>bestval:
        inew=(x,y-1)
        bestval=matrix[x][y-1]

    if y+1<Ncol and matrix[x][y+1]>bestval:
        inew=(x,y+1)
        bestval=matrix[x][y+1]

    return inew
def get_subproblem(sub,bestloc,matrix1):
    #global matrix
    (row,col)=bestloc
    #print(row)
    #print(col)
    for i in sub:
        print(i)
        (start_R,start_C,num_of_row,num_of_col)=i
        if start_R<=row and row<start_R+num_of_row:
            if start_C<=col and col<start_C+num_of_col:
                matrix1=matrix1[start_R:num_of_row,start_C:num_of_col+start_C]
                return matrix1

algo(matrix)


texts: Map groups to parent products using nested subqueries

texts:
I have the following tables

productstbl
===========================================
SegmentCode CategoryId ParentId
============================================

-----------------------------------------------------
categoriestbl

==================
CategoryId  name
====================

---------------------------------------------------------

Groupstbl

=====================
GroupId name
=====================

---------------------------------------------------------
CategoriesGroupsInfo

=======================
id  CategoryId  GroupId
=======================

---------------------------------------------------------

the logic goes like this: I want to map groups to parent products (root node which have parentid = 0)
and the subproducts of that parent will inherit theses groups by default.

The levels of products are unlimited, for example:

1   Basic foods (root node )
    1.1 Baked goods
        1.1.1 American breads
              1.1.1.1 Adobe bread
    1.2 Breads

2 Prepared foods(root node )
    2.1 Appetizers
    2.2 Condiments
    2.3 Confectionery

Note that I know the root node of any product through first char of segmentcode.

For example,  root node of  1.1.1.1 Adobe bread will have segment code 1 which is Basic foods.

Groups are only applied for root nodes and to know the subproducts have to match first number of segment code.

Here is my query it do the work but the execution plan is a headache.

 select * from productstbl
    where substring(SegmentCode,1,1)
    like ( select substring(SegmentCode,1,1)
           from categoriestbl where CatID in(
           select CatID from CategoriesGroupsInfo where GroupID = 1))

Is there any alternative query?


texts: remove duplicates in a sorted array if duplicates are allowed at most twice

texts:
Given a sorted array, remove the duplicates in place such that each element appear at most twice and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].

The following is my code:

int rightMost_of_curElem(int A[], int curElem, int ind, int n)
{
    while(ind<n)
    {
        if(A[ind]!=curElem)
            break;
        ++ind;
    }

    return --ind;
}

int remove_duplicates(int A[], int n)
{
    int i=0;
    int unique_num = 0;
    while(i<n)
    {
        int cur_elem = A[i];
        int pos = rightMost_of_curElem(A, cur_elem, i, n);

        if(A[pos]==A[pos-1])
        {
            A[unique_num++] = A[pos];
        }
        A[unique_num++] = A[pos];

        i = pos+1;
    }

    return unique_num;
}


texts: Monte-Carlo method to check triangle inequality

texts:
This is code for finding if inequality \$abc > 2(\text{area of triangle})\$
 where \$a\$, \$b\$ and \$c\$ are the sides of any triangle.

The below, and repl, code work as intended. However they take a long time. Can the performance be improved without reducing max_tries?

import random
import math
hn=100000000
num=0
max_tries=10000000
tries = 0
while tries != max_tries:
  a= random.randint(1,hn)
  b= random.randint(1,hn)
  c= random.randint(1,hn)
  if a+b>c and c+b>a and a+c>b :
    s=(a+b+c)/2
    tries= tries +1
    k =math.sqrt(s*(s-a)*(s-b)*(s-c))
    if a*b*c> 2*k:
      num= num+1

print(num/max_tries)


texts: Lcation of redux "random" state initialization

texts:
I'm creating 2048 to practice React/Redux. I've got a game board that appropriately shifts, and follows the game rules (it works).

I'm more concerned with my understanding of handling Redux reducers (that seems to be a problematic area for myself, like when I misunderstood reducer purity by adding randomness).

Initially, I was (incorrectly) having my Board reducer handle randomness. I've updated it so that the Board is currently initialized with 0's and the action creator determines the random values and tiles to place them in (there's a touch of currying and thunk in there).

const getNewTileDispatch = (board) => {
  var indicies = getEmptyIndexes(board);
  var toFill = randomFromArray(indicies);
  var value = getNewTileValue();
  return {
    type: 'ADD_TILE',
    x: toFill[0],
    y: toFill[1],
    value: value
  }
}

export const initializeBoard = () => {
  return(dispatch, getState) =>{
    let board = getState().Board.present;
    let minTiles = 2;
    let maxTiles = 5;
    let numTiles = Math.floor(Math.random() * (maxTiles-minTiles+1))+minTiles;
    for(let i=0;i<numTiles;i++){
      dispatch(getNewTileDispatch(board));
    }
  }
}

I've bound the initializeBoard function to the props, and I'm calling it in componentDidMount:

componentDidMount() {
    document.onkeydown = this.handleKeyDown.bind(this);
    this.props.initializeBoard();
}

And here's the board reducer case for good measure:

  case 'ADD_TILE':
      var newState = state.slice();
      newState[action.x][action.y]=action.value;
      return newState;

Is this an appropriate way to handle "guaranteed randomness" within initialization? Are there any glaring pitfalls that I've overlooked? The code appears to function and "randomly" initialize the board in my browser, while allowing me to unit test the tile placement, and 0-initialization.

Full code if anyone is interested, it's still fairly rudimentary but I figured I'd start asking earlier rather than later.


texts: Memory efficient way to merge multiple Pandas DataFrames

texts:
I am trying to merge multiple pandas data-frames that I read from a file.
Here is the function I wrote:

def merge_files(args):

    list_df = {}
    with args.input as data_in:
        for line in data_in:
            line = line.strip()
            df = pd.read_csv(line, sep="\s+")
            df.drop_duplicates(inplace = True)
            # change second column name (from the file)
            df.columns = ["sample", line.split("/")[-4]]
            list_df[line.split("/")[-4]] = df
    # Merging all the files into one and fill the missing ratio values with 0
    df_merged = reduce(lambda  left,right: pd.merge(left,right,on=['sample'], how='outer'), list(list_df.values())).fillna(0)
    df_merged.to_csv(args.output, sep='\t', encoding='utf-8', index=False)

But this approach consumes too much memory, Is there a better solution?

Update

The function is called in a script and given args contains input file
(contain locations of the csv files one per line) and output file.
The input file contains locations of 20 files each is ~2M in size and
contains ~59133 lines.
Using Python 3, Pandas version '0.25.2'


texts: Koch Curve algorithm in Python without using Turtle/Logo logic

texts:
Inspired by the motivations expressed in this question.

I created some code to generate the point list (and also display a pretty picture) using just analytic geometry (no Logo/Turtle, no trigonometry). Also, instead of recursively inserting new points to a growing list, I calculated the final length, and then assigned values to the already initialized positions.

I would like to know if there is some obvious improvement to make it faster, cleaner, more pythonic and/or more canonical.

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

def kochenize(a,b):
    HFACTOR = (3**0.5)/6
    dx = b[0] - a[0]
    dy = b[1] - a[1]
    mid = ( (a[0]+b[0])/2, (a[1]+b[1])/2 )
    p1 = ( a[0]+dx/3, a[1]+dy/3 )
    p3 = ( b[0]-dx/3, b[1]-dy/3 )
    p2 = ( mid[0]-dy*HFACTOR, mid[1]+dx*HFACTOR )
    return p1, p2, p3

def koch(steps, width):
    arraysize = 4**steps + 1
    points = [(0.0,0.0)]*arraysize
    points[0] = (-width/2., 0.0)
    points[-1] = (width/2., 0.0)
    stepwidth = arraysize - 1
    for n in xrange(steps):
        segment = (arraysize-1)/stepwidth
        for s in xrange(segment):
            st = s*stepwidth
            a = (points[st][0], points[st][1])
            b = (points[st+stepwidth][0], points[st+stepwidth][1])
            index1 = st + (stepwidth)/4
            index2 = st + (stepwidth)/2
            index3 = st + ((stepwidth)/4)*3
            result = kochenize(a,b)
            points[index1], points[index2], points[index3] = result
        stepwidth /= 4
    return points

if __name__ == '__main__':
    TOTALWIDTH = 1000.
    points = koch(7, TOTALWIDTH)

    # If you want a pretty picture (and have Cairo and PIL modules installed)
    if True:
        import cairo, Image

        width = int(TOTALWIDTH)
        height = int(TOTALWIDTH*0.32)
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
        cr = cairo.Context(surface)
        cr.set_source_rgb(1,1,1)
        cr.rectangle(0, 0, width, height)
        cr.fill()
        cr.translate(width*0.5, height*0.95)
        cr.scale(1, -1)

        cr.set_source_rgb(0,0,0)
        cr.set_line_width(0.5)
        cr.move_to(*points[0])
        for n in range(len(points)):
            cr.line_to(*points[n])
        cr.stroke()

        im = Image.frombuffer("RGBA", (width, height), surface.get_data(), "raw", "BGRA", 0,1)
        im.show()


texts: Finding the biggest product of two integers formed by the digits 1-9

texts:
The question was, which is the biggest product you can make from the digits of 1 to 9 (which is 9642*87531, BTW). It is pretty clear that one number starts with 9 and the other with 8, and that you need to append the remaining digits in descending order to one or the other number.

buildList x y [] acc = (x,y):acc
buildList x y (z:zs) acc = buildList (10*x+z) y zs (buildList x (10*y + z) zs acc)

list = buildList 9 8 [7,6,5,4,3,2,1] []

Sorting it by descending products, and taking the beginning of the list:

import Data.List
import Data.Function
result = take 10 $ sortBy (compare `on` (negate.uncurry (*))) list

I'm not satisfied with my solution for buildList, which uses explicit recursion. I'd like to have something like a fold, just not linear but with different "branches".


texts: Calculating pi to 7 significant figures without using Math.PI

texts:
I need to calculate pi to 7 significant figures in Java—without using Math.PI.

Here is the code I came up with to do that:

public class ComputePI
{
    public static void main(String[] args)
    {
        double sum = 0.0;
        double sumOne = 0.0;
        double delta;
        int counter = 0;
        final double DENOMINATOR_CANCEL = 4.0;
        final int LARGE_NUMBER = 5000000;
        final double SMALLEST_DELTA = 0.0000004535899;
        boolean closeEnough = false;

        for (int j = 1; j < LARGE_NUMBER; j += 2) // Computes number close to pi
        {
            double firstFrac = (1.0 / (j * 2.0 - 1.0));
            double secondFrac = (1.0 / (j * 2.0 + 1.0));
            sumOne += firstFrac - secondFrac;
        }

        for (int i = 1; (!closeEnough); i += 2)   //"My computed value of pi"
        {
            double firstNum = (1.0 / (i * 2.0 - 1.0));
            double secondNum = (1.0 / (i * 2.0 + 1.0));
            sum += firstNum - secondNum;
            delta = sumOne * DENOMINATOR_CANCEL - sum * DENOMINATOR_CANCEL;
            if (delta < SMALLEST_DELTA)     // If delta reaches 7-sig accuracy
            {
                closeEnough = true;         // End loop
            }
            counter = i / 2;        // Counts iterations
        }

                        /*  output results      */
        System.out.println("My computed value of pi is: " + sum * DENOMINATOR_CANCEL);
        System.out.println("The library constant value of pi is: " + Math.PI);
        System.out.println("The number of iterations needed to reach " + "seven-significant digit accuracy is: " + counter);
    }
}

Is this a good approach, or is it horribly inefficient? How might I improve it?

Perhaps having a for loop inside a for loop would work better. One with n+1 iterations, the other with n iterations. The loop would terminate if the two sums were subtracted, and produced a difference of 0.0000009 or less (7 significant figure accuracy).


texts:
I need to read n chars from a binary file into a string. Currently, what I do is:

static string Read(istream &stream, uint32_t count)
{
    auto bytes = unique_ptr<char[]>(new char[count]);

    stream.read(bytes.get(), count);

    return string(bytes.get(), count);
}

I found the way I deal with the array of chars quite messy. If I used new and delete[] directly, it would make the code messy in another way (I would need to add a local variable for the result). And I'm trying to avoid delete as a general rule.

Is there a clear way to write this code? The fact that it uses twice as much memory as it needs is probably not a big deal, but fixing that would be nice too.


texts: Off Canvas Menu and Content Panels with Transitions

texts:
Any and all feedback appreciated but I'd especially like suggestions pertaining to:

Naming of classes
CSS code organization
Possible performance improvements
Alternative approaches

There also seems to be a lag/jolting when transitioning to the off canvas content but only in Chrome and only on the first time the transition occurs. Is this something to do with the % widths? Seems to work fine in FF and Edge.

Thanks.

Working Codepen

HTML

<button id='menuBtn'>menu</button>

Content Headline

        <button id='offcanvasContentBtn'>Show Off Canvas</button>

Off Canvas Panel

        <button id='hideoffcanvascontent'>Back to Content</button>

CSS

html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

.group:after {
  content: "";
  display: table;
  clear: both;
}

.html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
  font-family: Gill Sans Extrabold, sans-serif;
}

.pageContainer {
  overflow: hidden;
  height: 100%;
  margin-bottom: -10px;
  background-color: red;
}

.pageContainer:after {
  content: "";
  display: block;
  height: 10px;
}

.layoutContainer {
  height: 100%;
  transition: transform 0.2s ease-in-out;
}

.header {
  background-color: #3299bb;
  padding: 16px;
}

.header button {
  float: right;
}

.offcanvas {
  position: fixed;
  top: 0;
  width: 200px;
  background-color: #9dd46d;
  height: 100%;
  z-index: 5000;
  right: -200px;
  border-left: 2px solid #424242;
}

.pushedContainer {
  transform: translate3d(-200px, 0, 0);
}

.contentContainer {
  position: relative;
  height: 100%;
  overflow: hidden;
  width: 100%;
  background-color:
}

.content, .offcanvasContent {
  transition: transform 0.3s ease-in-out;
}

.content {
  height: 100%;
  padding: 8px;
  background-color: #efefef;
}

.offcanvasContent {
  padding: 8px;
  position: absolute;
  top: 0;
  width: 100%;
  background-color: #cadee6;
  height: 100%;
  z-index: 5000;
  right: -100%;
}

.pushedContent .content,
.pushedContent .offcanvasContent {
  transform: translate3d(-100%, 0, 0);
}

JS

var menuBtn = document.getElementById('menuBtn')
var container = document.getElementById('container')
var offcanvasContentBtn = document.getElementById('offcanvasContentBtn')
var content = document.getElementById('content')
var hideoffcanvascontent = document.getElementById('hideoffcanvascontent')
var contentContainer = document.getElementById('contentContainer')

menuBtn.addEventListener('click', function(){

  var cls = container.className
  var pushedCls = ' pushedContainer'

  if(cls.indexOf(pushedCls) === -1){
    container.className = 'layoutContainer pushedContainer'
    return
  }

  container.className = 'layoutContainer'

}, false)

offcanvasContentBtn.addEventListener('click', function(){
  contentContainer.className = 'contentContainer pushedContent'
}, false)

hideoffcanvascontent.addEventListener('click', function(){
  contentContainer.className = 'contentContainer'
}, false)


texts:
This function takes an array of HTML objects and returns those currently on the screen. I try to optimize for readability and performance. I myself find this function a bit confusing.

function(elements, margin) {
    var inViewport = [];

    if(elements.constructor !== Array){ elements = [elements]; }
    margin = margin || 0;

    for (var i = elements.length - 1; i >= 0; i--) {
      var element = elements[i],
        bounds = element.getBoundingClientRect();
        if( bounds.top+margin < window.innerHeight && bounds.bottom-margin > 0 ){
          inViewport.push(element);
        }
    }
    return inViewport;
  }


texts:
Its an Basic Calculator I worked on, and now I wanna know if I can make something better like not so "much" Code or I made somthing to complicated? Have a nice day! Keep safe!
 import java.util.Scanner;

public class learningCode {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("Bitte geben sie einen Rechenoperator für ihre Rechnung ein! (+, -, *, /)");

        String numberTest = scan.nextLine();

        if (numberTest.equals("+")) {
            String questionOne = "Bitte gebe deine erste Zahl ein: ";
            System.out.println(questionOne);
            double number1 = scan.nextDouble();
            String questionTwo = "Bitte gebe deine zweite Zahl ein: ";
            System.out.println(questionTwo);
            double number2 = scan.nextDouble();
            double finalResult = number1 + number2;

            String Answer = "Dein Ergebnis ist: ";

            System.out.println(Answer  + finalResult );

            scan.close();
        }
        else {

            if (!"+".equals(numberTest) && !"-".equals(numberTest) && !"*".equals(numberTest) && !"/".equals(numberTest)) {
                System.out.println("Das ist kein Rechenoperator. Bitte versuche es erneut!");
            }

            if (numberTest.equals("*")) {
                String questionTwo = "Bitte gebe deine erste Zahl ein: ";
                System.out.println(questionTwo);
                double number1 = scan.nextDouble();
                String questionThree = "Bitte gebe deine zweite Zahl ein: ";
                System.out.println(questionThree);
                double number2 = scan.nextDouble();
                double finalResult = number1 * number2;

                String Answer = "Dein Ergebnis ist: ";

                System.out.println(Answer  + finalResult );

                scan.close();
            }
            if (numberTest.equals("/")) {
                String questionThree = "Bitte gebe deine erste Zahl ein: ";
                System.out.println(questionThree);
                double number1 = scan.nextDouble();
                String questionFour = "Bitte gebe deine zweite Zahl ein: ";
                System.out.println(questionFour);
                double number2 = scan.nextDouble();
                double finalResult = number1 / number2;

                String Answer = "Dein Ergebnis ist: ";

                System.out.println(Answer  + finalResult );

                scan.close();
            }
            if (numberTest.equals("-")) {
                String questionFive = "Bitte gebe deine erste Zahl ein: ";
                System.out.println(questionFive);
                double number1 = scan.nextDouble();
                String questionSix = "Bitte gebe deine zweite Zahl ein: ";
                System.out.println(questionSix);
                double number2 = scan.nextDouble();
                double finalResult = number1 - number2;

                String Answer = "Dein Ergebnis ist: ";

                System.out.println(Answer  + finalResult );

                scan.close();
            }

        }

    }
}


texts: T-SQL Query remove duplicates except for original row from the table

texts:
Question:
There is an Exam_Merge table into which to import
records from a similarly structured table in another database.
In this case, the Exam_Merge table contains the values of the primary key ID
from another database, but this field is not unique.
For some reason, some of the entries in it were duplicated:
an entry with the same ID is contained in the table 2 times,
the values of the remaining field of duplicate records also coincide.

It is necessary to remove duplicates, leaving only non-duplicate IDs.

My question -  is it correct and efficient approach or something efficient way exists?
sqlfiddle: http://www.sqlfiddle.com/#!18/dce35/1

DDL:

CREATE TABLE exam_merge
  (
     id           INT NOT NULL,
     student_code NVARCHAR(10) NOT NULL,
     exam_code    NVARCHAR(10) NOT NULL,
     mark         INT NULL
  );

QUERY:

WITH cte
     AS (SELECT id,
                student_code,
                exam_code,
                mark,
                Row_number()
                  OVER(
                    partition BY id, student_code, exam_code, mark
                    ORDER BY student_code) AS rn
         FROM   exam_merge)
DELETE cte
WHERE  rn > 1


texts: Efficient way to remove duplicate records

texts:
Is there more efficient way remove duplicate records?

strsql := 'delete from ' || TableName || ' a

where rowid <
(
  select max(rowid) from ' || TableName || ' b
  where a.val=b.val
)';


texts: Take a limited number of items from a potentially infinite generator

texts:
Hypothetically, I have a bunch of generators that never end, like:

function* progression() {
  let n = 0;

  while (true) {
    yield n++;
  }
}

I want to take first N items from that generator. So I made a function take for that:

function* take(n, generator) {
  let i = 0;
  let values = generator();

  for (let v of values) {
    if (++i > n) {
      return;
    }

    yield v;
  }
}

Is there a better way, maybe standard ES6+ API or a more concise syntax to achieve the same thing? If this function could fail under circumstances that I didn't account for, please give me a hint.


texts: Team Fortress 2 item price lookup using Trade.tf developer API and Steam WebAPI

texts:
I've made a nice little Python program using the requests module using the Trade.tf Developer API and the Steam WebAPI allowing the user to look up the price of Team Fortress 2 items through Trade.tf's spreadsheet.

For those of you that may not know, Team Fortress 2 is a free-to-play team-based shooter game which also features quite a large e-economy for in-game items. Sites such as Backpack.tf and Trade.tf exist to show pricing of items in terms of various currency-like items such as refined metal (a crafting ingredient in-game) and keys (used to open supply crates which can unlock various items within them).

I know there's definitely something that can be improved in this program, but I'm not fully sure on how I can accomplish this. Feel free to make any suggestions for it.

import json
import requests
import time

with open('keys.json', 'r') as f:
    keys = json.load(f)
    schema = requests.get('http://api.steampowered.com/IEconItems_440/GetSchema/v0001/?key=' + keys['steam'])
    spreadsheet = requests.get('http://www.trade.tf/api/spreadsheet.json?key=' + keys['tradetf'])

qualities = {"uncraft"    : -1,
             "genuine"    : 1,
             "vintage"    : 3,
             "unique"     : 6,
             "strange"    : 11,
             "haunted"    : 13} # all qualities currently tracked by Trade.TF

def get_item_defindex_from_name(name):
    for items in schema.json()["result"]["items"]:
        if items["name"] == name:
            defindex = items["defindex"]
    if defindex:
        return defindex
    else:
        print("Invalid item.")

def get_quality_id_from_name(name):
    return qualities[name]

def get_price_unit(unit):
    return {
    "r": " refined",
    "k": " keys",
    "b": " buds"}.get(unit, " ")

def get_tradetf_price(item, quality):
    price = spreadsheet.json()["items"][str(item)][str(quality)]["regular"]["hi"]
    unit  = get_price_unit(spreadsheet.json()["items"][str(item)][str(quality)]["regular"]["unit"])
    return str(price) + unit

def get_input(dialog, validation, error_message):
    while True:
        answer = input(dialog)
        if validation(answer):
            return answer
        else:
            print(error_message)

def main():
    try:
        while True:
            try:
                item_name = str(input("Enter item name: "))
                item_ = get_item_defindex_from_name(item_name)
                break
            except UnboundLocalError:
                print("Invalid item.")

        quality = get_input(
            "Enter item quality: ",
            lambda quality: quality.lower() in qualities,
            "Quality not tracked by Trade.tf."
        )
        quality_ = get_quality_id_from_name(quality.lower())

        print("\n", quality, item_name, "price: ", get_tradetf_price(item_, quality_))
    except KeyError:
        print("Item not currently tracked by Trade.tf.")

if __name__ == "__main__":
    main()
    print("Shutting down...")
    time.sleep(3)


texts: Script to encrypt a file and add it to IPFS(ipfs.io)

texts:
Here is the script that I would like reviewed for the following:

Best practices and design pattern usage
Correctness in unanticipated cases

The script is made to store (IPFS) Interplanetary File System hash objects. If you would like to know more check out https://ipfs.io

3rd party packages:

ipfsapi PyPi page
gnupg PyPi page

Script:

#!/usr/local/bin/python3

import os
import gnupg
import ipfsapi

# Set GPG Home directory
gpg = gnupg.GPG(homedir='')
fileToEncrypt = input("Full path to file to encrypted and posted \n:")
encryptedFile = (fileToEncrypt + ".gpg")

def encryptFileFunction():
    passphrase = input("Password you would like encrypt with \n:")
    with open(fileToEncrypt, 'rb') as f:
        status = gpg.encrypt(f,
        encrypt=False,
        symmetric='AES256',
        passphrase=passphrase,
        armor=False,
        output=fileToEncrypt + ".gpg")

def ipfsFileFunction(encryptedFile):
    # Tell module where IPFS instance is located
    api = ipfsapi.connect('127.0.0.1', 5001)
    # Add Encrypted file to IPFS
    ipfsLoadedFile = api.add(encryptedFile)
    # Return Hash of new IPFS File
    ipfsHash = (ipfsLoadedFile['Hash'])
    return ipfsHash

def delEncryptedFile(encryptedFile):
    if os.path.isfile(encryptedFile):
        os.remove(encryptedFile)
    else:
        print("Error: %s file not found" % encryptedFile)

def main():
    encryptFileFunction()
    ipfsFileFunction(encryptedFile)
    print ("File encrypted and added to IPFS with this hash " +  ipfsFileFunction(encryptedFile))
    delEncryptedFile(encryptedFile)

main()


texts:
I am preparing to write a widget for the browser that is both visual and interactive. I am a newbie to Javascript/Ecmascript and prototyping. I want to encapsulate the canvas element, abstract the data, and render visuals. A major design goal is to minimize developer effort. I am looking for direction and best practices. Nuff said here is what I have so far:

My WidgetLib.js

var WidgetFactory = WidgetFactory || (function() {
  this.Kanvas = function(doid) {
  this.domObjectID_ = doid;
  this.domObject_ = document.getElementById(this.domObjectID_);
  this.domObject_.addEventListener('click', Kanvas.onClick, false);
  this.domObject_.addEventListener('mousedown', Kanvas.onMouseDown, false);
  this.domObject_.widget_ = this;
  this.domObject_.widget_.data_ = {};
  this.domObject_.widget_.data_.cnt = 0;
  // Get/Set canvas size, do other initialize stuff...
};

this.Kanvas.onClick = function() {
   alert(this.widget_.domObjectID_ + " has been clicked " +
    this.widget_.data_.cnt + " times");
};

this.Kanvas.onMouseDown = function(e) {
  this.widget_.data_.cnt++;
};

return {
  Kanvas: Kanvas
};

}()); // end of namespace

Put this in the HTML head section

<script src="WidgetLib.js">

Put this in HTML body section

 <canvas id="C01"></canvas>

Put this in window.onLoad function

var k = new WidgetFactory.Kanvas("C01");

Is this a good design? I know there are good libraries (paper,easeljs,...) but I have specific requirements not to use them and implement specific/proprietary drawing functions.