texts: Is there a better flow for returning the response?

texts:
So I have the getSessionNamespace method in the below class in which I am trying to return different scenarios but one json response. So my solution is to store the required message and status code in a response array and vary it depending on the situation.

Is there a cleaner more obvious method?

<?php

namespace Drupal\auth\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\auth\Service\AuthGroupService;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use GuzzleHttp\Exception\ClientException;
use Symfony\Component\HttpKernel\Exception\HttpException;

/**
 * Class SessionController
 * @package Drupal\my_moduke\Controller
 */
class SessionController extends ControllerBase
{
    /**
     * @var AuthGroupService
     */
    protected static $authGroupService;

    /**
     * @param ContainerInterface $container
     *
     * @return static
     */
    public static function create(ContainerInterface $container)
    {
        self::$authGroupService = $container->get('auth.auth_group');
        return parent::create($container);
    }

    /**
     * @param Request $request
     * @param bool    $internal
     *
     * @return mixed|JsonResponse
     */
    public function getSessionNamespace(Request $request, $internal = false)
    {
        try {
            if (!$request->headers->has('host')) {
                throw new \HttpHeaderException('Header \'host\' not found.');
            }

            $host = $request->headers->get('host');

            // Query datastore for the authGroup data for the given host.
            $result = $this->getAuthGroupData($host);
            $configId = \Drupal::config('auth.settings')->get('DS5.auth_group_id');

            if (!$this->allowedAccess($configId, $result['authGroupId'])){
                throw new HttpException(403, 'Not allowed.');
            }

            $response = [
                'result' => $result,
                'status' => 200
            ];
        } catch (ClientException $e) {
            $response = [
                'result' => 'The endpoint responded with a ' . $e->getCode(),
                'status' => $e->getCode()
            ];
        } catch (\Exception $e) {
            $response = [
                'result' => $e->getMessage(),
                'status' => $e->getStatusCode()
            ];
        }

        if ($internal) {
            return $response['result'];
        }

        $jsonResponse = new JsonResponse($response['result'], $response['status']);

        if (!$_COOKIE[$response['result']['cookieName']] && $response['status'] === 200) {
            $this->createSessionCookie($jsonResponse, $response['result']);
        }

        return $jsonResponse;
    }

    /**
     * @param JsonResponse $response
     * @param array        $values
     *
     * @return JsonResponse
     */
    private function createSessionCookie(JsonResponse $response, array $values)
    {
        $dateTime = new \DateTime('+'. $values['sessionTimeToLiveSeconds'] .' seconds');

        $sessionCookie = new Cookie(
            $values['cookieName'],
            session_id(),
            $dateTime,
            '/',
            $values['domain']
        );

        $response->headers->setCookie($sessionCookie);
    }

    /**
     * @param $configId
     * @param $authGroupId
     *
     * @return bool
     */
    private function allowedAccess($configId, $authGroupId)
    {
        return $configId === $authGroupId;
    }

    /**
     * @param $host
     *
     * @return mixed
     */
    private function getAuthGroupData($host)
    {
        // Fetch from authGroup datastore endpoint.
        return self::$authGroupService->fetchAuthGroupData($host);
    }
}


texts:
I would like to a review of my database design.

There are 3 tables + ASP.NET Identity tables.

The Users could have many postcards.

Here's my tables without Identity.

I attached also my scripts of creating tables.

CREATE TABLE [dbo].[Country](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](50) NOT NULL,
    [Code] [nchar](10) NOT NULL
) ON [PRIMARY]

CREATE TABLE [dbo].[Error](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Message] [nvarchar](max) NULL,
    [Stacktrace] [nvarchar](max) NULL,
    [CreatedDate] [nvarchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

CREATE TABLE [dbo].[Postcard](
    [Id] [bigint] IDENTITY(1,1) NOT NULL,
    [CountryFromId] [int] NOT NULL,
    [CountryToId] [int] NOT NULL,
    [TravelTime] [int] NULL,
    [Confirmation] [bit] NOT NULL,
    [UserFromId] [int] NULL,
    [UserToId] [int] NOT NULL,
    [Status] [int] NULL,
    [SentDate] [datetime2](7) NOT NULL,
    [ReceivedDate] [datetime2](7) NULL,
    [ImageId] [int] NULL
) ON [PRIMARY]

Do you think is it good design, or shoud I change something? I know that proper databse design is key in good application architecture so I would like to have good database design.


texts:
On many articles and blogs, I have read that exceptions should not decide flow of your code.

I have wrote the following code using one thread:

public void run() {
        while (true) {
            if (jobQueue.size() != 0) {
                Job job =
                    (Job) jobQueue.pop();
                try {
                    JobProc jobProc = new JobProc(job);
                    Thread threadJP = new Thread(jobProc);
                    threadJP.start();
                } catch (Exception e) {
                    try {
                        jobQueue.push(job);
                    } catch (StorageFailed | InternalError e1) {
                        try {
                            writeJobToFile(job);
                        } catch (ExecFailed e2) {
                            logger.logFatal("failed to push back job"+ job.getId(), e2);
                        }
                    }
                }
                } else {
                    sleep(5000);
                }
        }
    }

In the first catch exception I can push job back to queue. In the second catch, if it fails to push it back to queue, I am writing that job to file. In third catch, I logging it as FATAL error event.

Am I doing it wrong or is there any better way of doing this?


texts: Approximating the square root using an iterative method

texts:
I wrote this code, based on the Newton-Raphson method, to find the square root of a number. I'm wondering how I can optimise this code, as I am out of ideas.

#include <stdio.h>

int main(void)
{
     float n, x, i;

     printf("Enter the number you wish to find the square root of.\n");
     printf("\n");
     scanf("%f", &n);

     x = n/2;

     for (i = 0; i < 100; i++)
         x = x - (((x*x) - n)/(2*x));

     printf("The square root of %.0f is %.4f.\n", n, x);

     return 0;

}


texts:
Haven't put one of these together since college. How does this look overall?

public class HashTable<T, TU>
    {
        private LinkedList<Tuple<T, TU>>[] _items;
        private int _fillFactor = 3;
        private int _size;

        public HashTable()
        {
            _items = new LinkedList<Tuple<T, TU>>[4];
        }

        public void Add(T key, TU value)
        {
            var pos = GetPosition(key, _items.Length);
            if (_items[pos] == null)
            {
                _items[pos] = new LinkedList<Tuple<T, TU>>();
            }
            if (_items[pos].Any(x=>x.Item1.Equals(key)))
            {
                throw new Exception("Duplicate key, cannot insert.");
            }
            _size++;
            if (NeedToGrow())
            {
                GrowAndReHash();
            }
            pos = GetPosition(key, _items.Length);
            if (_items[pos] == null)
            {
                _items[pos] = new LinkedList<Tuple<T, TU>>();
            }
            _items[pos].AddFirst(new Tuple<T, TU>(key, value));
        }

        public void Remove(T key)
        {
            var pos = GetPosition(key, _items.Length);
            if (_items[pos] != null)
            {
                var objToRemove = _items[pos].FirstOrDefault(item => item.Item1.Equals(key));
                if (objToRemove == null) return;
                _items[pos].Remove(objToRemove);
                _size--;
            }
            else
            {
                throw new Exception("Value not in HashTable.");
            }
        }

        public TU Get(T key)
        {
            var pos = GetPosition(key, _items.Length);
            foreach (var item in _items[pos].Where(item => item.Item1.Equals(key)))
            {
                return item.Item2;
            }
            throw new Exception("Key does not exist in HashTable.");
        }

        private void GrowAndReHash()
        {
            _fillFactor *= 2;
            var newItems = new LinkedList<Tuple<T, TU>>[_items.Length * 2];
            foreach (var item in _items.Where(x=>x != null))
            {
                foreach (var value in item)
                {
                    var pos = GetPosition(value.Item1, newItems.Length);
                    if (newItems[pos] == null)
                    {
                        newItems[pos] = new LinkedList<Tuple<T, TU>>();
                    }
                    newItems[pos].AddFirst(new Tuple<T, TU>(value.Item1, value.Item2));
                }
            }
            _items = newItems;
        }

        private int GetPosition(T key, int length)
        {
            var hash = key.GetHashCode();
            var pos = Math.Abs(hash % length);
            return pos;
        }

        private bool NeedToGrow()
        {
            return _size >= _fillFactor;
        }
    }


texts: Simple Haskell calculator, using Maybe for error handling

texts:
I'm reading through Write Yourself a Scheme after finishing going through Learn You a Haskell. I attempted one of the early exercises: writing a program to get an operator and two numbers and do a computation. It works fine.

Things I would like to know:

How should I structure a program, in terms of building larger functions out of smaller functions? Are there redundancies in my code?

What's the most effective way to use the Maybe type to indicate failure when main is of type IO ()? Is my checkSuccess an appropriate way to do this?

module Main where

import System.Environment

-- parses the first arithmetic operator in a string
parseOperator :: String -> Maybe Char
parseOperator [] = Nothing
parseOperator (x:xs)
    | x == '*' = Just '*'
    | x == '/' = Just '/'
    | x == '+' = Just '+'
    | x == '-' = Just '-'
    | otherwise = parseOperator xs

parseNum :: String -> Maybe Double
parseNum x =
    let parsed = reads x :: [(Double,String)]
    in case parsed of
        [(a,"")] -> Just a
        [(_,_)] -> Nothing
        [] -> Nothing

compute :: Maybe Char -> Maybe Double -> Maybe Double -> Maybe Double
compute Nothing _ _ = Nothing
compute _ Nothing _ = Nothing
compute _ _ Nothing = Nothing
compute (Just c) (Just x) (Just y)
    | c == '*' = Just $ x * y
    | c == '/' = Just $ x / y
    | c == '+' = Just $ x + y
    | c == '-' = Just $ x - y

checkSuccess :: Maybe Double -> IO ()
checkSuccess Nothing = putStrLn "Failed. Check correctness of inputs"
checkSuccess (Just r) = putStrLn $ "Result: " ++ (show r)

runSequence :: String -> String -> String -> IO ()
runSequence os xs ys =
    checkSuccess $ compute (parseOperator os) (parseNum xs) (parseNum ys)

main = do
    putStrLn "Enter operator: * / + -"
    operator <- getLine

    putStrLn "Enter first number"
    first <- getLine

    putStrLn "Enter second number"
    second <- getLine

    runSequence operator first second


texts:
I am trying to suppress debug with doing a JSON request.

Is this too early or too late in the request lifecycle? Is there a better variable to tap into?

In application.cfc

function before()   {

    if (cgi.http_accept CONTAINS "application/json")    {
        setting showdebugoutput="false";
        }

    } // end before

In a typical controller

void function resetpassword(required struct rc) output="false" {

    framework.renderData( "json", { "results" : "Success. Check your email for a temporary password." } );

    return;
    }


texts: Most common occurrence of an int in an array

texts:
I am prepping for a junior level interview in C#.  I am hoping I can get some feedback on how to improve my code to print the most common occurrence of an int in an array.

using System;
using System.Collections;

namespace FrequentInt
{
    class MainClass
    {

        static void CommomOcurrence (int [] array, Hashtable hs)
        {
            int mostCommom = array[0];
            int occurences = 0;
            foreach (int num in array)
            {
                if (!hs.ContainsKey (num)) {
                    hs.Add (num, 1);
                }
                else
                {
                    int tempOccurences = (int)hs [num];
                    tempOccurences++;
                    hs.Remove (num);
                    hs.Add (num, tempOccurences);

                    if (occurences < tempOccurences)
                    {
                        occurences = tempOccurences;
                        mostCommom = num;
                    }
                }
            }
            foreach(DictionaryEntry entry in hs)
            {
                Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
            }
            Console.WriteLine ("The commmon numer is " + mostCommom + " And it appears " + occurences + " times");
        }

        public static void Main (string[] args)
        {

            int[] array = new int[20]{ 3,6,8,5,3,5,7,6,4,3,2,3,5,7,6,4,3,4,5,7};
            Hashtable hs = new Hashtable ();
            CommomOcurrence (array, hs);

        }
    }
}


texts:
The problem that I have is to find the minimum number of ways to go from one box to another box of a chess board. Now, I have created a code which is not very elegant but works. I am interested in if the code will give me the correct answer. Here is the code:

import java.util.*;
class Main{
  public static void main(String []sad){
    String str[] = new String[]{"2 1", "1 2","-1 -2","-1 2","1 -2","2 -1","-2 1","-2 -1"};
    String start = "8,8";
    Set<String> set = new HashSet<String>();
    String goal = "1,1";
    int s0 = Integer.parseInt(start.split(",")[0]);
      int s1 = Integer.parseInt(start.split(",")[1]);
      int s2 = Integer.parseInt(goal.split(",")[0]);
      int s3 = Integer.parseInt(goal.split(",")[1]);
    int dist = 0;
    Stack<String> stk = new Stack<String>();
    stk.push(start);
    set.add(start);
    while(!stk.empty()){
      dist++;
      String ele = stk.pop();
      for(int i=0;i<str.length;i++){
        int d0 = Integer.parseInt(ele.split(",")[0]) + Integer.parseInt(str[i].split(" ")[0]);
        int d1 = Integer.parseInt(ele.split(",")[1]) + Integer.parseInt(str[i].split(" ")[1]);
        if(d0<1 || d0>8 || d1<1 || d1>8)
          System.out.println("No Pushing allowed");
        else{
        String sr = d0+","+d1;
        System.out.println(sr);
        if(sr.equals(goal)){
          System.out.println("YES "+dist);
          return;}
          if(!set.contains(sr))
          {
            set.add(sr);
            stk.push(sr);
          }
      }
      }
    }
  }
}

Thanks.


texts:
I feel like this maybe to much for one method...  This method lives inside of a service class which is called by an interface. It dumps data into three different tables within a database.

public UserAccount CreateAccount(NewAccount newAccount)
{
  if (!AccountAlreadyExists(newAccount.UserName))
  {
    string salt = StringCipher.GenerateCypher();
    UserAccount account = new UserAccount()
    {
      UserId = newAccount.UserName,
      PasswordHash = CreatePasswordHash(newAccount.Password),
      Lock = true,
      Created = DateTime.UtcNow
    };
    User user = new User()
    {
      UserId = newAccount.UserName
    };
    UserContact contact = new UserContact()
    {
      ContactTypeId = ContactType.EmailPrimary,
      Contact = StringCipher.Encrypt(newAccount.UserEmail, salt),
      UserId = account.UserId,
      Active = true,
      Created = DateTime.UtcNow
    };
    db.Entry(account).State = EntityState.Added;
    db.Entry(contact).State = EntityState.Added;
    db.Entry(user).State = EntityState.Added;
    db.SaveChanges();
    return account;
  }
  return null;
}

any suggestions on how to slim this down or streamline?


texts: Adding two numbers represented as linked lists

texts:
I have some imminent interviews and want to sharpen my game before going into them. I'm running through some practice problems. This LeetCode challenge is to add two numbers represented as linked lists.

If you can critique this solution quite harshly, as though you would in a full-fledged SWE interview, I'd greatly appreciate it. I'm particularly concerned about memory usage and variable names.

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        final_l = None
        curr_l = None
        remainder = 0
        while l1 or l2:
            digit = 0
            if l1:
                digit += l1.val
                l1 = l1.next

            if l2:
                digit += l2.val
                l2 = l2.next

            if remainder != 0:
                digit += remainder

            remainder = digit // 10
            digit = digit % 10

            if final_l is None:
                final_l = ListNode(digit)
                curr_l = final_l
            else:
                curr_l.next = ListNode(digit)
                curr_l = curr_l.next

        if remainder > 0:
            curr_l.next = ListNode(remainder)

        return final_l


texts: Extracting and reformatting dates from text

texts:
The task is find by pattern d--m--y---- all occurrences in text, reformat it to yyyy:mm:dd and print it separately from initial text. Actually I done all except  formatting. And even in my written code I have some doubts because I just begun to learn this language. Maybe someone would help me and say what's wrong with my code and how to finish that task on a better way. Any comments are appreciated.

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

#define MAXLINE 1000
#define CONT 1000000

int getlin(char *, int);
int pickDates(char *, char *);
int isDate(char *, int);

int main()
{
    int len;
    char line[MAXLINE];
    char accum[CONT];
    char *dates = malloc(sizeof(char *) * CONT);

    while ((len = getlin(line, MAXLINE)) > 0)
        strcat(accum, line);

    pickDates(dates, accum);
    printf("%s\n", dates);

    free(dates);

    return 0;
}

int getlin(char *s, int lim) {
    int i, c, j = 0;

    for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
    if (i < lim - 2)
    {
        s[j] = c;
        ++j;
    }
    if (c == '\n')
    {
        s[j] = c;
        ++i;
        ++j;
    }
    s[j] = '\0';

    return i;
}

int pickDates(char *dates, char *cont)
{
    int j = 0;
    const char *template = "d--m--y----";
    char *date;
    int temp_len = strlen(template);

    for (int i = 0; i < strlen(cont); i++)
        if (cont[i] == template[0] && cont[i+3] == template[3] && cont[i+6] == template[6])
        {
            date = malloc(sizeof(char) * temp_len);
            memcpy(date, &cont[i], temp_len);
            if (isDate(date, temp_len))
            {
                j += 8;
                strcat(dates, date);
            }
            free(date);
        }

    dates = realloc(dates, sizeof(char) * j);

    return 0;
}

int isDate(char *date_str, int len)
{
    int i = 0;
    int dd = atoi(&date_str[i+1]);
    int mm = atoi(&date_str[i+4]);
    int yy = atoi(&date_str[i+7]);
    char tmp[5] = {'0'};

    memset(date_str, 0, len - 3);
    date_str = realloc(date_str, sizeof(char) * (len - 3));

    if (dd < 32 && dd > 0 && mm < 13 && mm > 0 && yy > 0)
    {
        sprintf(tmp, "%04d", yy);
        strcat(date_str, tmp);
        sprintf(tmp, "%02d", mm);
        strcat(date_str, tmp);
        sprintf(tmp, "%02d", dd);
        strcat(date_str, tmp);

        return 1;
    }
    else return -1;
}


texts:
I took a test on Codility for coding the minimum number of frog jumps to reach from position x to position y:

  A small frog wants to get to the other side of the road. The frog is
  currently located at position X and wants to get to a position greater
  than or equal to Y. The small frog always jumps a fixed distance, D.
  Count the minimal number of jumps that the small frog must perform to
  reach its target.

  Write a function: def solution(x, y, d) that, given
  three integers X, Y and D, returns the minimal number of jumps from
  position X to a position equal to or greater than Y.

  For example,
  given:
  X = 10
             Y = 85
             D = 30

  the function should return 3,
  because the frog will be positioned as follows:

  after the first jump,
  at position 10 + 30 = 40

  after the second jump, at position 10 + 30 +
  30 = 70

  after the third jump, at position 10 + 30 + 30 + 30 = 100
  Assume that:

  X, Y and D are integers within the range
  [1..1,000,000,000];

  X ≤ Y.

  Complexity: expected worst-case time
  complexity is O(1);

  expected worst-case space complexity is O(1).

Here is my solution:

def solution(x, y, d)
    position = x
    positions = []
    until position >= y
        position += d
        positions << position
    end
    return positions.length

end

This solution works, but got a performance score of 0% and a correctness score of 100%.

My solution works on smaller data sets, but always times out on larger data sets.


texts: Array-based MinHeap implementation in Java

texts:
This is my implementation of MinHeap in Java.

public class MinHeap {

        int[] heap;
        int pos;
        int size;

        public MinHeap(){
            this.size = 2;
            heap = new int[size];
            this.pos = 0;

        }

        private void minHeapify(int index){

            int child = index;
            int parent = child/2;

            while(heap[parent] > heap[child] && parent > 0){
                int temp = heap[parent];
                heap[parent] = heap[child];
                heap[child] = temp;

                child = parent;
                parent = child/2;
            }

        }
        public void add(int item){

            if(pos == heap.length) resize();
            heap[pos++] = item;

            minHeapify(pos-1);

        }
        public void delete(int item){
            boolean found = false;
            int start = 0;
            for(int i = 0; i< heap.length; i++){
                if(heap[i] == item){
                    found = true;
                    start = i;
                    break;
                }
            }
            if(found == false) throw new IllegalStateException("Item doesn't exist.");
            pos--;
            for(int i= start; i< pos; i++){
                heap[i]= heap[i+1];
            }
            for(int i=pos; i > 0; i--){
                minHeapify(i);
            }
        }

        public int min(){

            return heap[1];
        }

        private void resize(){

            size = size*2;
            int[] curr = new int[size];
            for(int i=0; i< heap.length; i++){
                curr[i] = heap[i];
            }
            heap = curr;

        }
    }

Invite comments and suggestions to improve.


texts:
This code integrates with dweet and freeboard to produce a dashboard display of which occupants of a house are probably at home, based on the presence or absence of their phones' MAC addresses on the local network.
An important distinction to meke is between current and marked presence. For instance, with a 15 minute grace period set through the config file, users marked as currently present at any time within the past 15 minutes will be marked present, even if they're not currently present right now. In other words, current presence is known for certain at the time that a line of code is run, whereas marked presence is 'probably accurate' and takes into account a longer period of time.
The program also reads a config file in YAML format, stored by default at /etc/homepresenced/homepresenced.yaml. An example config file is shown below.
from time import sleep
import subprocess
import datetime
import yaml
import dweepy

CONFIG_FILE_PATH = '/etc/homepresenced/homepresenced.yaml'

class Occupant:
        def __init__(self, name, mac):
                self.name = name
                self.mac = mac
                self.lastPresent = None

        def registerPresence(self):
                self.lastPresent = datetime.datetime.now()

with open(CONFIG_FILE_PATH) as f:
        # load configuration into conf dictionary
        conf = yaml.safe_load(f)

        # replace yaml-style occupant listings with instances of Occupant object
        for i, occupant in enumerate(conf['occupants']):
                conf['occupants'][i] = Occupant(occupant['name'], occupant['mac'])

try:
        while True:
                occupancy_report = {}  # data sent to dweepy about occupant presence

                # perform network scan. this takes time so it's more efficient to do it once per loop, rather than once per occupant per loop
                arp_scan = str(subprocess.check_output("sudo arp-scan -l", shell=True))

                for occupant in conf['occupants']:
                        if occupant.mac in arp_scan:
                                occupant.registerPresence()  # register occupant as CURRENTLY present if mac is in scan

                        # should the occupant be MARKED as present (taking into account the 'grace period')?
                        presence = datetime.datetime.now() - occupant.lastPresent < datetime.timedelta(minutes=conf['presence_grace_period']) if occupant.lastPresent else None

                        # format time of last CURRENT presence. if not set (==None) then use "never"
                        lastPresent = occupant.lastPresent.strftime(conf['time_format']) if occupant.lastPresent else "never"

                        print(f"Occupant {occupant.name}'s device is {'PRESENT' if presence else 'ABSENT' if presence == False else 'UNSEEN'} (last present: {lastPresent})")

                        # add to dictionary that will be sent to dweepy
                        occupancy_report[occupant.name] = {
                                'presence': presence,
                                'lastPresent': lastPresent
                        }

                dweepy.dweet_for(conf['dweet_thing'], occupancy_report)

# catch keyboard ctrl+c interrupt signals and exit cleanly
except KeyboardInterrupt:
        exit()

presence_grace_period: 15

dweet_thing: identifier_for_dweet_io
time_format: "%Y/%m/%d at %HL%M:%S"

occupants:
    - name: User One
      mac:  11:aa:11:aa:11:aa
    - name: User Two
      mac: 22:bb:22:bb:22:bb
    - name: User Three
      mac: 33:cc:33:cc:33:9cc


texts: Duplicate method call or add logic to set local variables as parameters?

texts:
This is a fairly trivial example of a question I come up to often.  In the example below I tend to think that allowing duplication sometimes results in clearer code.

Does anyone agree/disagree on this point?

First way: an additional local variable is used so method.Invoke is called just once on the last line. I think this has slightly more logic to decode than the second way.

private static void Invoke<T>(string[] args, MethodInfo method) where T : new()
{
    T target = new T();
    target.InvokeMethod("Initialize", errorIfMethodDoesNotExist: false, accessNonPublic: true);
    string[] methodArgs = null;
    if (args.Length > 1)
    {
        methodArgs = args.Skip(1).ToArray();
    }
    method.Invoke(target, methodArgs);
}

Second way: No additional local variable but the call to method.Invoke is duplcated in both branches of the if statement.  I think this is clearer even though logic was duplicated.

private static void Invoke<T>(string[] args, MethodInfo method) where T : new()
    {
        T target = new T();
        target.InvokeMethod("Initialize", errorIfMethodDoesNotExist: false, accessNonPublic: true);
        if (args.Length > 1)
        {
            method.Invoke(target, args.Skip(1).ToArray());
        }
        else
        {
            method.Invoke(target, null);
        }
    }


texts:
I'm trying to learn how chained hashing works, but can't get any further than this.
I think hashing works, but after finishing this little program, someone told me that what I have created so far has nothing to do with hashing.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define size 5
//This is my struct I wanted to add to the hashtable
struct customer{
    char name[20];
    int id;
    int pin;
    double money;
    struct customer *next;
};

//creating the table
struct customer *hash_table[size];
struct customer *next=NULL;
//my hashfunction
int hash_function(int id){
    unsigned int adress_hash;
    adress_hash = 31 * id;
    return adress_hash % 5;
}

//Adding the cust elements to my table
void add_customer(){
    int id_set = rand() % 8999 + 1000;
    struct customer *start;
    struct customer *pointer;
    int adress = hash_function(id_set);

     //first element

    if(hash_table[adress]==NULL)
    {
        hash_table[adress] = malloc(sizeof(struct customer));
        hash_table[adress]->id= id_set;
        hash_table[adress]->pin= rand() % 8999 + 1000;

        hash_table[adress]->money= 0;
        hash_table[adress]->next=NULL;
    } else {
        //Adding new files if the first element of the table is NOT NULL
        pointer=hash_table[adress];
        while(pointer->next != NULL)
        {
            pointer= pointer->next;
        }
        pointer->next = malloc(sizeof(struct customer));
        pointer=pointer->next;
        pointer->id=id_set;
        pointer->pin= rand() % 8999 + 1000;
        pointer->money = 0;

        pointer->next=NULL;
    }
}

void list_customer(int a){
    struct customer *pointer;
    int x;
    for(x=0;x<5;x++){
        pointer = hash_table[x];
        printf("%d. ----------\n", x);
        while(pointer != 0){
            printf("KNR: %d, PIN: %d\n", pointer->id, pointer->pin);
            pointer = pointer->next;
        }
        printf("-------------------------\n");
    }
}

int main(){
    int adr,x;
    srand(time(NULL));
    for(x=0;x<5;x++){
        add_customer();
    }
    list_customer(size);
    getchar();getchar();
    return 0;
}


texts:
I have made a form where the submit button will show if the text box is focused and the button will hide if the text box is blurred.

These codes work fine. But I wonder if the jQuery code could be more simplified. Or is there any toggle function available?

var search = $("#search");
var button = $("#submit-button");
search.focus(function(){
    button.slideDown("slow");
});
search.blur(function(){
   button.slideUp("slow");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="" method="get">
    <div>
        <input type="text" name="search" title="search" class="search" id="search" placeholder="Enter text here"/>
    </div>
    <button type="submit" class="submit-button" id="submit-button" name="submit" style="display: none">Click to Search</button>
</form>

Note: I can do it with click function. But I want to do it with focus and blur


texts: Converting an array of users into an array of teams with an array property for listing the users

texts:
Jst to clarify, teams and groups are the same thing in this case.

$data comes from a database and is an array of objects. Each object contains information about a user including what team/group they are in. I want to convert this to an array of groups which includes an array of users belonging to that group inside. Users can be in multiple groups too so in the original list of users, a lot of entries will have repeating group id's.

The code I have works but it's very blocky and I feel like it could be shortened a lot.

$groups = [];

foreach($data as $user)
{
    $userGroupId = $user['GroupId'];
    $exists = false;

    foreach($groups as &$group)
    {
        $groupId = $group['GroupId'];

        if ($groupId == $userGroupId)
        {
            $users = &$group['users'];

            $currentUser = array(
                'UserId'=>$user['UserId'],
                'UserName'=>$user['UserName'],
                'Surname'=>$user['Surname']
            );

            array_push($users, $currentUser);
            $exists = true;
            break;
        }
    }

    if (!$exists)
    {
        $addGroup = array(
            'GroupId'=>$user['GroupId'],
            'GroupName'=>$user['GroupName'],
            'users'=>[array(
                'UserId'=>$user['UserId'],
                'UserName'=>$user['UserName'],
                'Surname'=>$user['Surname']
              )]
        );

        array_push($groups, $addGroup);
    }
}


texts:
I have been experimenting around with generating all the n-combinations of an array. This code quickly generates all \$\text{k-combinations}\$ of a given array. I am testing my own implementation because of some restrictions in coding competitions (also, knowing the basics never hurts).

"""
Generates 3-combinations of an array.

A B C D E F G H
^ ^ ^
i j k

A B C D E F G H
^ ^   ^
i j   k

A B C D E F G H
^   ^   ^
i   j   k
"""
from itertools import combinations
import time

def combinations_3(ary):
    l = len(ary)
    for i in xrange(l-2):
        for j in xrange(i+1, l-1):
            for k in xrange(j+1, l):
                yield (ary[i], ary[j], ary[k])

start = time.time()
for combination in combinations_3([1, 2, 3, 4]):
    print combination
print time.time() - start

print("===========Library Implementation============")
start = time.time()
for combination in combinations([1, 2, 3, 4], 3):
    print combination
print time.time() -start

Output

(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)
0.00043797492981
===========Library Implementation============
(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)
6.19888305664e-05

It seems that my implementation is a lot slower than the library code. How can I improve performance of my code.


texts: Searching a string of consecutive characters in a binary bar code

texts:
I am writing a program that will take a binary bar code and convert it to a zip-code. I need to validate the bar code. A valid binary bar code contains no more and no less than two 1s in any position per five digits. This is what I have for the validation part so far and would like simplify this code.

#include <iostream>
#include <string>

using std::cout;
using std::string;

int main()
{
    const int SIZE = 5;//number of characters to test in a set
    string bar = "100101010010001";

    string tempstring;
    int count = 0;
    while (count < bar.length())
    {
        int test = 0;
        tempstring = bar.substr(count, SIZE);//split bar string into next five characters

        for (int index = 0; index < SIZE; index++)
        {
            if (tempstring[index] == '1')
            {
                ++test;
            }
        }

        if (test != 2)
        {
            cout << "Invalid bar code!\n";
            exit(1);
        }

        count += 5;
    }

    cout << "Valid bar code!\n";
}


texts:
I have been working on some code for a basic inventory management system and I have all the features that I believe are need like adding parts displaying parts list and the such as you can see. I believe I have worked out all the bugs I can find. I'm looking to see if I got all the bugs out and maybe some optimizations that I am not seeing. The code is fully working and I'm just making sure I am not overlooking anything before I start using this code.

dict_member = {}
parts = dict_member
class Parts():
    def __init__(self, part, part_number, quantity):
        self.part = part
        self.part_number = part_number
        self.quantity = quantity
    def display (self):
        for part_number, parts in dict_member.items():
            print('Part Name:', parts.part + ', ''Part Number:' + parts.part_number + ', ''Quantity:' + parts.quantity)
            if parts == 0:
                print('No Parts Found in List')
    def add(self):
            part = input("Enter Name of Part:\n ")
            part_number = input("Enter Part Number:\n ")
            quantity = input("Enter Quantity:\n ")
            dict_member[part] = Parts(part, part_number, quantity)
    def remove(self):
            part = str(input("Enter Part Name to Remove\n"))
            if part in parts:
                del parts[part]
            else:
                print("Part Not Found.")
    def edit(self, part):
            if part in parts:
                par = input("Enter New Part\n")
                num = input("Enter New Part Number\n ")
                quan = input("Enter New Quantity\n ")
                del dict_member[part]
                dict_member[part] = Parts(par, num, quan)
            else:
                print("No such Part exists")

    def saveData(self):
        filename = input("Filename to save: ")
        out_file = open(filename, "wt")
        for part_number, parts in dict_member.items():
            out_file.write(parts.part + "," + parts.part_number + "," + parts.quantity + "\n")
        out_file.close()
        print("File Saved")

    def loadData(self):
        try:
            filename = input("Filename to load: ")
            in_file = open(filename, "rt")
            while True:
                in_line = in_file.readline()
                if not in_line:
                    break
                in_line = in_line[:-1]
                part, part_number, quantity = in_line.split(",")
                dict_member[part] = Parts(part, part_number, quantity)
            in_file.close()
        except FileNotFoundError:
            print("File Not Found.")
        return parts

def display_menu():
    try:
        print("")
        print("1. Parts ")
        print("2. Add Part")
        print("3. Remove Part ")
        print("4. Edit Part")
        print("5. Save Part List")
        print("6. Load Part List")
        print("9. Exit ")
        print("")
        return int(input("Selection> "))
    except ValueError:
        print("Selection Not Valid.")
    return parts

print("Welcome Sticks&Stones Inventory System")
part_instance = Parts(None, None, None)
menu_item = display_menu()
while menu_item != 9:
    if menu_item == 1:
        part_instance.display()
    elif menu_item == 2:
        part_instance.add()
    elif menu_item == 3:
        part_instance.remove()
    elif menu_item == 4:
        m = input("Enter Part Name to Edit\n")
        part_instance.edit(m)
    elif menu_item == 5:
        part_instance.saveData()
    elif menu_item == 6:
        part_instance.loadData()
    menu_item = display_menu()
print("Exiting Program...")


texts:
I have a class which parses a .csv file and converts it into successful rows and errors. Currently I have 12 different kind of errors (mail is not valid, missing column x, row is duplicate etc.).

Each error has a custom message. I also need to know in other classes what kind of error a row was, so a simple string is not enough. So far I am using this error class:

<?php

namespace App\Registration\GroupUploads;

/**
 * Represents all possible errors that may occur during a group upload.
 */
class Error
{

  const USEREXISTS  = 7;
  const MAILINVALID = 1;
  const SEALUSED    = 2;
  const MIXEDUP     = 3;
  // ..

  protected $id;
  protected $options;

  /**
   * Each error has a unique ID
   * @param int $id
   * @param array $options optional
   */
  protected function __construct($id, $options = null)
  {
    $this->id      = $id;
    $this->options = $options;
  }

  /**
   * Get Message of current object
   * @return string
   */
  public function getMessage()
  {
    switch ($this->id) {
      case static::USEREXISTS:
        return 'User already exists';
        break;

      case static::MAILINVALID:
        return 'Mail is not valid';
        break;

      case static::SEALUSED:
        return 'Sealnr is already used by other user.';
        break;

      case static::SEALUSED:
        return 'They messed up and mixed the seals inbetween orgas.';
        break;

      // ...

      default:
        return 'No message provided for error code';
        break;
    }
  }

  /**
   * Create error for an existing user
   * @return bool
   */
  public static function getDuplicateUserError()
  {
    return new static(static::USEREXISTS);
  }

  /**
   * Check if class is duplicate user error
   * @return bool
   */
  public function isDuplicateUserError()
  {
    return $this->id == static::USEREXISTS;
  }

  // ...

}

There are 12 constants, each representing the id of a specific error. There is one method getMessage() which uses a switch with 12 cases. Then I have 12 messages of the kind getErrorMessageX and another 12 methods isThisErrorNameX.

I feel that this is kind of messy and redundant. Also their might be me more error cases in the future, which will bloat up the class even more.

I thought about creating 12 separate classes, each class named by the error name. Something like that:

<?php

namespace App\Registration\GroupUploads;

/**
 * Error for existing user
 */
class UserExistsAlreadyError
{

  public function getMessage()
  {
    return 'User already exists';
  }

}

So instead of if($error->isDuplicateUserError()) I would write if($error instanceof UserExistsAlreadyError) .

However, I think creating 12 different classes, where each consists only of 12 lines, is a bit too much. Is there a better solution then those two extremes?


texts: Most efficient way to iterate through arrays/can I use .times method in place of while method?

texts:
I created a quick program to test the precision of randomness generated by the .rand method. The primary question is whether I can use the .times method in place of the while code blocks to increase efficiency and:

Whether such a practice would reduce the amount of processing required/if this would be at all significant.
Whether it's a more common approach, or alternatively is it an infeasible/awkward approach.
Even if it is a less acceptable approach than the one I've taken, how would I use the .times method to execute the same task. If it is inappropriate when should I use .times?

# Initializes array and iterator.
x = []
i = 0

# Stores 4000 random numbers 0..1 in array 'x'
while i < 4000
  x << rand(2)
  i += 1
end

# Initializes array for the purpose of storing zeros and ones in separate
#  arrays for the sake of counting how many instances of each occur in the sample
count_one = []
count_zero = []

# Resets iterator to 0
i = 0

# Stores instances of zero in `count_zero` and instances of one in `count_one`
while i < x.length
  if x[i] == 1
    count_zero << x[i]
    i += 1
  else
    count_one << x[i]
    i += 1
  end
end

# Calculates final averages
zero_average = count_zero.length.to_f/x.length.to_f * 100.0
one_average = count_one.length.to_f/x.length.to_f * 100.0

Additionally, I am curious as to:

How I could possibly have coded this for flexibility to better anticipate future needs. Example: If I later needed to perform the same operations on a larger range of numbers.
If I am using extraneous/obvious facts in my commenting or if my commenting is otherwise not in good practice.
What more insight I might be able to gain in general regarding my current coding practices. Thank you.


texts: Java method to check if a binary tree is a valid BST

texts:
I wrote a Java method (along with a private class) to check if a binary tree is also a binary search tree (BST). I would like some feedback on the design of my solution. Here is a brief description and the code is provided below it :

Do a depth-first traversal of the tree and test if each node satisfies the binary search tree property. The binary search tree property states that a node is valid if its key is greater than every ancestral node in whose right-subtree it resides and less than every ancestral node in whose left-subtree it resides. Instead of checking the node against all of its ancestors, simply check the largest number it should be greater than (its lower bound) and the smallest number it should be less than (its upper bound).

private class Bounds {

    Node node;
    int min_bound;
    int max_bound;

}

public boolean check_if_valid_binary_search_tree(Node node) {

    if (node == null) return true;

    Deque<Bounds> stack = new ArrayDeque<Bounds>();

    Bounds bounds = new Bounds();

    bounds.node = node;
    bounds.max_bound = Integer.MAX_VALUE;
    bounds.min_bound = Integer.MIN_VALUE;

    stack.push(bounds);

    while (!stack.isEmpty()) {

        bounds = stack.pop();

        Node curr_node = bounds.node;
        int lower_bound = bounds.min_bound;
        int upper_bound = bounds.max_bound;

        if (curr_node.val < lower_bound || curr_node.val > upper_bound) return false;

        if (curr_node.left != null) {

            Bounds left = new Bounds();

            left.node = curr_node.left;
            left.max_bound = curr_node.val;
            left.min_bound = lower_bound;

            stack.push(left);

        }

        if (curr_node.right != null) {

            Bounds right = new Bounds();

            right.node = curr_node.right;
            right.min_bound = curr_node.val;
            right.max_bound = upper_bound;

            stack.push(right);

        }

    }

    return true;

}

Note : The approach I use is modelled after a solution written in python by Parker Phinney (of Interview Cake) to the problem of checking if a binary tree is a valid BST.


texts:
I wrote two functions that creates two 2 dimensional arrays, but there is a lot of duplicate code and I don't know how to split it in one function. Is it even possible? I know the rule don't repeat yourself but I don't know how to use it because I learn javascript and programming. Also do you recommended books to learn how to write clean code.

First function

function createMatrixA() {

    var i, j;
    var htmlElements = "";
    var matrixWidth = parseInt(document.getElementById("matrix-width-a").value, 10);
    var matrixHeight = parseInt(document.getElementById("matrix-height-a").value, 10);

    if (matrixWidth <= 7 && matrixHeight <= 7) {
        matrixA = new Array(matrixHeight);
        for (i = 0; i < matrixA.length; i++) {
            matrixA[i] = new Array(matrixWidth);
        }
        for (i = 0; i < matrixA.length; i++) {
            htmlElements += "
";
            for (j = 0; j < matrixA[i].length; j++) {
                matrixA[i][j] = "
<input type=\"number\" class=\"form-control\" id=\"a" + (i + 1) + (j + 1) + "\" placeholder=\"a" + (i + 1) + (j + 1) + "\" >
";
                htmlElements += matrixA[i][j];
            }
            htmlElements += "
";
        }
        document.getElementById("matrix-a").innerHTML = htmlElements;
    } else {
        document.getElementById("matrix-a").innerHTML = "
Maximum matrix size is 7x7.
";
    }
}

Second function

function createMatrixB() {
    var i, j;
    var htmlElements = "";
    var matrixWidth = parseInt(document.getElementById("matrix-width-b").value, 10);
    var matrixHeight = parseInt(document.getElementById("matrix-height-b").value, 10);

    if (matrixWidth <= 7 && matrixHeight <= 7) {
        matrixB = new Array(matrixHeight);
        for (i = 0; i < matrixB.length; i++) {
            matrixB[i] = new Array(matrixWidth);
        }
        for (i = 0; i < matrixB.length; i++) {
            htmlElements += "
";
            for (j = 0; j < matrixB[i].length; j++) {
                matrixB[i][j] = "
<input type=\"number\" class=\"form-control\" id=\"b" + (i + 1) + (j + 1) + "\" placeholder=\"b" + (i + 1) + (j + 1) + "\" >
";
                htmlElements += matrixB[i][j];
            }
            htmlElements += "
";
        }
        document.getElementById("matrix-b").innerHTML = htmlElements;
    } else {
        document.getElementById("matrix-b").innerHTML = "
Maximum matrix size is 7x7.
";
    }
}


texts: Code Review for Adding two numbers without using the + operator

texts:
Here's my code. Please review it for correctness, readability and efficiency. If you think it can be improved also let me know. This code works fine for positive numbers but doesn't for negative. How can I change it ? Any comments for improvement will be appreciated.

int sum(int a, int b)
    {
       int sum = 0;
       int carry = 0;
       int mask = 1;
       sum = doAdd(a,b,mask,carry, 0);
       return sum;
    }

    int doAdd(int a,int b, int mask, int carry, int sum)
    {
       int aBit = a&mask;
       int bBit = b&mask;

       if(mask<a||mask<b||carry!=0)
       {
          sum = sum | (carry^aBit^bBit);
          carry = (carry==0) ? (aBit&bBit) : (carry&a|carry&b);
          mask = mask << 1;
          if(carry!=0)
          carry = mask;
          return (doAdd(a,b,mask,carry, sum));
       }

       return sum;
    }


texts: Error-testing be with cucumber/capybaraweb

texts:
I'm working on writing tests for a rails application using cucumber and capybara. I have a scenario for a user editing a post, and making it invalid.

The scenario looks like this:

Scenario: I edit a post and make the data invalid.
  Given I have 1 post
  And I view my 1st post
  Then I click "Edit"
  And I fill in the edit post form with bad data
  When I click the "Update post" button
  Then I should see "Title is too short (minimum is 3 characters)"
  And I should see "Body is too short (minimum is 30 characters)"

Should I leave the scenario as-is, or create a scenario for entering the title incorrectly, and another scenario for entering the body incorrectly, like this:

Scenario: I edit a post and make the title too short.
  Given I have 1 post
  And I view my 1st post
  Then I click "Edit"
  And I fill in the edit post form with a title that is too short
  When I click the "Update post" button
  Then I should see "Title is too short (minimum is 3 characters)"

Scenario: I edit a post and make the body too short.
  Given I have 1 post
  And I view my 1st post
  Then I click "Edit"
  And I fill in the edit post form with a body that is too short
  When I click the "Update post" button
  Then I should see "Body is too short (minimum is 30 characters)"

If the post has several more fields, should I still create a scenario for each one, or would it be more DRY to use one scenario?


texts:
I am new to rust and wanted to get going with a medium-sized project to help learn. I've settled on creating some basic quantum mechanics code which starts with this bare-bones file reader. It takes a pdb file which is just a list of atom coordinates and the connections between them - with some extra information. I've included a basic pdb for testing below, the location string for the file requires changing.

I'm trying to use rust style as much as possible. Any suggestions on code/style improvement, no matter how small, are very welcome, thanks.

methanol.pdb:

COMPND    methanol
HETATM    1   C  UNL     1      -0.372   0.002   0.003  1.00  0.00           C
HETATM    2   O  UNL     1       0.898  -0.575  -0.119  1.00  0.00           O
HETATM    3   H  UNL     1      -0.674  -0.119   1.051  1.00  0.00           H
HETATM    4   H  UNL     1      -0.314   1.066  -0.315  1.00  0.00           H
HETATM    5   H  UNL     1      -1.083  -0.525  -0.643  1.00  0.00           H
HETATM    6   H  UNL     1       1.545   0.150   0.024  1.00  0.00           H
CONECT    1    2    3    4    5
CONECT    2    6
END

file_readers.rs:

use std::fs;

#[derive(Debug)]
struct Atom {
    /// May include atomic charges, masses etc in future
    atomic_symbol: String,
    index: i16,
    coords: (f64, f64, f64),
}

#[derive(Debug)]
struct Bond {
    atom_1_index: i16,
    atom_2_index: i16,
}

pub fn read_pdb() {
    /// Iterates over lines in any pdb file to produce vec of Atom structs
    /// Will be expanded in future to build graph of molecule as well

    let data = fs::read_to_string(
        "/home/b8009890/Documents/rusty_rockets/src/bin/euler_000_099/methanol.pdb")
        .expect("Unable to read file");

    // vec of strings where each element in vec is a line in the file
    let lines: Vec<&str> = data.lines().collect();
    let name: &str = &lines[0][10..];
    let mut molecule = Vec::new();
    let mut bonds = Vec::new();

    // loop over each element in the vec, starting from the 1st (not 0th)
    for line in lines[1..].iter() {
        if &line[..3] == "HET" {
            // atomic_symbol may be 1/2 chars so it's defined over a range not a specific index
            let atom = Atom {
                atomic_symbol: line[13..15].trim().parse::<String>().unwrap(),
                // pdbs count from 1, hence the -1
                index: line[10..13].trim().parse::<i16>().unwrap() - 1,
                // trim removes whitespace when there isn't a minus sign
                coords: (
                    line[32..38].trim().parse::<f64>().unwrap(),
                    line[40..46].trim().parse::<f64>().unwrap(),
                    line[48..54].trim().parse::<f64>().unwrap(),
                )
            };
            molecule.push(atom);
        } else if &line[..3] == "CON" {
            let parent_index = line[10..13].trim().parse::<usize>().unwrap() - 1;

            for atom_index in line[14..].split_whitespace() {
                let child_index = atom_index.parse::<usize>().unwrap() - 1;
                let bond = Bond {
                    atom_1_index: molecule[parent_index].index,
                    atom_2_index: molecule[child_index].index,
                };
                bonds.push(bond);
            }
        } else {
            break
        }
    }

    println!("{:?}\n{:?}\n{:?}\n", molecule, name, bonds);
}

Please be aware the very specific ranges for extracting the coords and such are from the official pdb format guide. Occasionally coords can overlap if using high precision e.g. -0.56789-0.12345 so generally slicing is used instead of splitting over whitespace.

EDIT: After trying to implement a graph structure using petgraph for the molecule, I instead just added a Vec of tuples for my bonds. This seems much easier than a (potentially) cyclic graph; I know they cause issues with the borrowing system. Anyway, the code is updated and now slightly longer than before but not really anymore complex.


texts:
I've an ArrayList of Object that could contain String, Date and Long. The Object list is nearly mandatory. (I obtain this list through reflection, reading all the member variables of an unknown class.)

    ArrayList <Object> values = new ArrayList<Object>();

I build dynamically a query for Alfresco cmis from it:

        addObjectToQueryStatement(qs, i+1, values.get(i));

I came only with this idea:

private void addObjectToQueryStatement(QueryStatement qs, int parameterIndex, Object value)
{
    if (value instanceof String)
    {
        qs.setString(parameterIndex, (String) value);
    }
    else if (value instanceof Date)
    {
        qs.setDateTime(parameterIndex, (Date)value);
    }
    else if (value instanceof Long)
    {
        qs.setNumber(parameterIndex, (Long)value);
    }
}

Does it exist a better and more elegant implementation?


texts:
A twinoid is defined to be an array that has exactly two even values that are adjacent to one another. For example {3, 3, 2, 6, 7} is a twinoid array because it has exactly two even values (2 and 6) and they are adjacent to one another. The following arrays are not twinoid arrays.

{3, 3, 2, 6, 6, 7} because it has three even values.
{3, 3, 2, 7, 6, 7} because the even values are not adjacent to one another.
{3, 8, 5, 7, 3} because it has only one even value.

I wrote Twinoid to check that given array is twinoid or not.

public class Twinoid {

public static void main(String args[]) {
    System.out.println("The result is: " + isTwinoid(new int[]{3, 3, 2, 6, 7}));
}

public static boolean isTwinoid(int[] a) {
    boolean status = false;
    int i;
    int count = 0;
    for (i = 0; i < a.length; i++) {
        if (a[i] % 2 == 0) {
            count++;
        }
    }
    if (count == 2) {
        int j;
        for (j = 0; j < a.length; j++) {
            if (a[j] % 2 == 0) {
                System.out.println(a[j]);
                break;
            }
        }
        int nextValue = a[j + 1];
        System.out.println(nextValue);
        if (nextValue % 2 == 0) {
            status = true;
        }
    } else {
        status = false;
    }
    return status;
}
}


texts: Divide a 3D matrix into multiple smaller 3D matrix

texts:
I'm trying to build an extension method that will allow me to subdivide a huge array into much smaller ones. My current code is the following but it still takes about 2s to generate with an array of size 512x512x512 and the size of the sub cubes set to 32x32x32
public static T[][][][] Divide<T>(this T[][][] array, int xSize, int ySize, int zSize)
{
    int numberOfCubesInAxisX = array.Length / xSize;
    int numberOfCubesInAxisY = array[0].Length / ySize;
    int numberOfCubesInAxisZ = array[0][0].Length / zSize;
    T[][][][] arrayDivided = new T[numberOfCubesInAxisX * numberOfCubesInAxisY * numberOfCubesInAxisZ][][][];
    int index = 0;
    while (index < arrayDivided.Length)
    {
        int xIndex = index / numberOfCubesInAxisZ / numberOfCubesInAxisX;
        int yIndex = index / numberOfCubesInAxisZ % numberOfCubesInAxisY;
        int zIndex = index % numberOfCubesInAxisZ;
        arrayDivided[index] = new T[xSize][][];
        for (int x = 0; x < xSize; x++)
        {
            arrayDivided[index][x] = new T[ySize][];
            for (int y = 0; y < ySize; y++)
            {
                arrayDivided[index][x][y] = new T[zSize];
                for (int z = 0; z < zSize; z++)
                {
                    arrayDivided[index][x][y][z] = array[x + (xIndex * xSize)][y + (yIndex * ySize)][z + (zIndex * zSize)];
                }
            }
        }
        index++;
    }

    return arrayDivided;
}

If anyone have any clue on how to optimize it, i'll be glad to hear it!
Thanks!


texts: Blocking and async UDP communication with an IR camera

texts:
I'm writing a Java application to control a custom IR research camera that will be installed on an aircraft.  The camera connects to the the computer using UDP sockets via a direct LAN cable. The camera does not initiate any communications; it just replies to commands, 5-character strings, sent to it (the camera code is in C BTW).  There are about 16 commands most of which reply more or less instantly with the string ACKNO if the command is recognized, 3 reply with very short data strings, and the last replies with 480 packets of 640 bytes: the image data.

My intent is to send a command and either get the reply buffer(s) or a time out. It must be blocking.

I last worked on this code about 5 months ago and then had to put it on hold while I wrote the interface for the user and the camera was still being built.  I'm self taught in Java (my title is Ecologist).  I've included code for sending a command and waiting for an ACKNO or time out response.  It appears complicated and somewhat verbose to me so I'd like someone else to look at it and comment it or point me in a better direction.  I'm using Java 8.

How it might be used in a method:

if (!waitForACK(waitMS, filter).isSuccess) {
    // do something
    return "Failed to receive ACK.";
}

Top code:

private SendAndWaitForACK sendAndWaitForACK = null;
sendAndWaitForACK = new SendAndWaitForACK();

public Result waitForACK(int waitMS, CameraCommands cmd) {
    result.isSuccess = false;
    result.dataBytebuffer = ackByteBuffer;
    sendAndWaitForACK.setCommand(cmd); // set the comand
    Future<?> future = executor.submit(sendAndWaitForACK);
    try {
        result = (Result) future.get(waitMS, TimeUnit.MILLISECONDS);
    } catch (Exception e) {

    } finally {

    }

    return result;
}

private class SendAndWaitForACK implements Callable<Result> {
    private CameraCommands cmd;

    @Override
    public Result call() throws Exception {
        // does not return on timeout
        result.dataBytebuffer = postCommand(cmd);
        result.isSuccess = true;
        return result;
    }

    /**
     * setCommand must be called prior to use.
     *
     * @param cmd
     *            : CameraCommands
     */
    public void setCommand(CameraCommands cmd) {
        this.cmd = cmd;
    }
}

This is the method that actually deals with the socket.

/**
 * postCommand configures the ackByteBuffer prior to writing it to the
 * camera. It is invoked by postCommand call method.
 *
 * @return ackByteBuffer : tByteBuffer The image.
 * @throws IOException
 *
 */
    private ByteBuffer postCommand(CameraCommands command) throws IOException {
    ackByteBuffer.rewind();
    writeCommand(command); // to UDP Socket
    // blocking read reply from UDP Socket
    datagramChannel.read(ackByteBuffer);
    return ackByteBuffer;

}


texts:
I have a modal for adding new contacts, in order to disable the save button if no data has entered I check if the contact object is empty, is there a shorter way to check for an empty complex object?
  let isContactEmpty = true

  Object.keys(contact).forEach(field => {
    if (typeof contact[field] === 'string' && contact[field]) {
      isContactEmpty = false
      return
    }
    if (typeof contact[field] === 'object') {
      contact[field].forEach(fieldVal => {
        if (fieldVal.value.length) {
          isContactEmpty = false
        }
      })
    }
  })


texts:
I'm posting a solution for LeetCode's "Design Circular Deque". If you'd like to review, please do so. Thank you!
Problem
Design your implementation of the circular double-ended queue (deque).
Your implementation should support following operations:

MyCircularDeque(k): Constructor, set the size of the deque to be k.
insertFront(): Adds an item at the front of Deque. Return true if the operation is successful.
insertLast(): Adds an item at the rear of Deque. Return true if the operation is successful.
deleteFront(): Deletes an item from the front of Deque. Return true if the operation is successful.
deleteLast(): Deletes an item from the rear of Deque. Return true if the operation is successful.
getFront(): Gets the front item from the Deque. If the deque is empty, return -1.
getRear(): Gets the last item from Deque. If the deque is empty, return -1.
isEmpty(): Checks whether Deque is empty or not.
isFull(): Checks whether Deque is full or not.

Example:
MyCircularDeque circularDeque = new MycircularDeque(3); // set the size to be 3
circularDeque.insertLast(1);            // return true
circularDeque.insertLast(2);            // return true
circularDeque.insertFront(3);           // return true
circularDeque.insertFront(4);           // return false, the queue is full
circularDeque.getRear();            // return 2
circularDeque.isFull();             // return true
circularDeque.deleteLast();         // return true
circularDeque.insertFront(4);           // return true
circularDeque.getFront();           // return 4

Note:

All values will be in the range of [0, 1000].
The number of operations will be in the range of [1, 1000].
Please do not use the built-in Deque library.

Code:

// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);
    return 0;
}();

// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <vector>

struct MyCircularDeque {
        MyCircularDeque(int k): stream(k, 0), counts(0), k(k), head(k - 1), tail(0) {}

        const bool insertFront(
            const int value
        ) {
            if (isFull()) {
                return false;
            }

            stream[head] = value;
            --head;
            head += k;
            head %= k;
            ++counts;

            return true;
        }

        const bool insertLast(const int value) {
            if (isFull()) {
                return false;
            }

            stream[tail] = value;
            ++tail;
            tail %= k;
            ++counts;

            return true;
        }

        const bool deleteFront() {
            if (isEmpty()) {
                return false;
            }

            ++head;
            head %= k;
            --counts;

            return true;
        }

        const bool deleteLast() {
            if (isEmpty()) {
                return false;
            }

            --tail;
            tail += k;
            tail %= k;
            --counts;

            return true;
        }

        const int getFront() {
            return isEmpty() ? -1 : stream[(head + 1) % k];
        }

        const int getRear() {
            return isEmpty() ? -1 : stream[(tail - 1 + k) % k];
        }

        const bool isEmpty() {
            return !counts;
        }

        const bool isFull() {
            return counts == k;
        }

    private:
        using ValueType = std::uint_fast16_t;
        std::vector<ValueType> stream;
        ValueType counts;
        ValueType k;
        ValueType head;
        ValueType tail;
};


texts: Decide the start of the circular gas station path

texts:
Suppose there is a circle. There are n petrol pumps on that circle. You are given two sets of data.

The amount of petrol that petrol pump will give.
Distance from that petrol pump to the next petrol pump.

Calculate the first point from where a truck will be able to complete the circle (The truck will stop at each petrol pump and it has infinite capacity). Expected time complexity is O(n). Assume for 1 litre petrol, the truck can go 1 unit of distance.
For example, let there be 4 petrol pumps with amount of petrol and distance to next petrol pump value pairs as {4, 6}, {6, 5}, {7, 3} and {4, 5}. The first point from where truck can make a circular tour is 2nd petrol pump. Output should be “start = 1″ (index of 2nd petrol pump).

Looking for code-review, best-practices and optimizations.
public final class PetrolPumpCircularTour {

    private PetrolPumpCircularTour() {};

    public static int startingStations(List<PetrolPumpData> gasStations) {

        if (gasStations.size() == 0) {
            throw new IllegalArgumentException("There should be atleast a single gas stats");
        }

        int front = 0;
        int rear = 0; // is actually 0, after a circle. but 1 is just a game we play for circular queue.

        int statationsCovered = 0;
        int gasSavedSoFar = 0;

        while (statationsCovered < gasStations.size()) {
            int currentPetrol = gasStations.get(rear).getLitres() + gasSavedSoFar;
            int currentDistance = gasStations.get(rear).getDistance();
            gasSavedSoFar = currentPetrol - currentDistance;
            statationsCovered = statationsCovered + 1;

            if (gasSavedSoFar < 0) {
                rear = (rear + 1) % gasStations.size();
                front =  (front + 1) % gasStations.size();
                gasSavedSoFar = 0;
                statationsCovered = 0;
                if (rear == 0) {
                    return -1;
                }
            } else {
                rear = (rear + 1) % gasStations.size();
            }
        }

        return front;
    }
}

public class PetrolPumpCircularTourTest {

    @Test
    public void test1( ) {
        List<PetrolPumpData> list1 = new ArrayList<PetrolPumpData>();
        list1.add(new PetrolPumpData(4, 6));
        list1.add(new PetrolPumpData(6, 5));
        list1.add(new PetrolPumpData(7, 3));
        list1.add(new PetrolPumpData(4, 5));

        assertEquals(1, PetrolPumpCircularTour.startingStations(list1));
    }

    @Test
    public void test2() {
        List<PetrolPumpData> list2 = new ArrayList<PetrolPumpData>();
        list2.add(new PetrolPumpData(40, 6));
        list2.add(new PetrolPumpData(6, 5));
        list2.add(new PetrolPumpData(7, 3));
        list2.add(new PetrolPumpData(4, 5));

        assertEquals(0, PetrolPumpCircularTour.startingStations(list2));
    }

    @Test
    public void test3() {
        List<PetrolPumpData> list3 = new ArrayList<PetrolPumpData>();
        list3.add(new PetrolPumpData(4, 6));
        list3.add(new PetrolPumpData(3, 5));
        list3.add(new PetrolPumpData(70, 3));
        list3.add(new PetrolPumpData(4, 5));

        assertEquals(2, PetrolPumpCircularTour.startingStations(list3));
    }

    @Test
    public void test4( ) {
        List<PetrolPumpData> list4 = new ArrayList<PetrolPumpData>();
        list4.add(new PetrolPumpData(4, 6));
        list4.add(new PetrolPumpData(3, 5));
        list4.add(new PetrolPumpData(2, 3));
        list4.add(new PetrolPumpData(40, 5));

        assertEquals(3, PetrolPumpCircularTour.startingStations(list4));
    }
}


texts: Given a list and a number k return whether any two numbers from the list add up to k

texts:
The task:

  Given a list of numbers and a number k, return whether any two numbers
  from the list add up to k.

  For example, given [10, 15, 3, 7] and k of 17, return true since 10 +
  7 is 17.

  Bonus: Can you do this in one pass?

const lst = [14, 10, 3, 7, 0];
const k = 14;

My solution 1:

const addUpTo = (lst, k) => lst.some((x, i) => !isNaN(lst.find((y, j) => i !== j && y === k - x)));

console.log(addUpTo(lst, k));

My solution 2:

const addUpTo2 = (lst, k) => lst.some((x, i) => {
  const find = k - x;
  return !isNaN(lst.slice(i + 1).find(y => y === find));
});

console.log(addUpTo2(lst, k));


texts:
Hello fellow programmers. I started learning C last week and today I wanted to see if I can make a working program, so I made this game:
/*
 * TESTED IN LINUX - 2020
*/

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

int player = 1, choice;
int places[10] = {'o', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

void switchPlayers();
void displayBoard();
int markBoard(char mark);
int checkForWin();

int main() {

    while (!checkForWin()){
        system("clear");
        displayBoard();
        switchPlayers();
    }
    system("clear");
    displayBoard();
    checkForWin();

    return 0;
}

void switchPlayers(){
    if (player == 1) {
        printf("     Player 1 choose: ");
        scanf("%d", &choice);
        if (markBoard('X'))
            player = 1;
        else
            player = 2;

    }
    else if (player == 2){
        printf("     Player 2 choose: ");
        scanf("%d", &choice);
        if (markBoard('O'))
            player = 2;
        else
            player = 1;

    }
}

void displayBoard(){
    printf("\n             X & O           \n Player 1 (X) - Player 2 (O)\n\n");

    printf("\t    |   |   \n"
           "\t  %c | %c | %c \n"
           "\t ___|___|___\n"
           "\t    |   |   \n"
           "\t  %c | %c | %c \n"
           "\t ___|___|___\n"
           "\t    |   |   \n"
           "\t  %c | %c | %c \n"
           "\t    |   |   \n\n"
           ,  places[1], places[2],
           places[3], places[4], places[5],
           places[6], places[7], places[8], places[9]);
}

int markBoard(char mark){
    for (int i = 1; i < 10; ++i) {
        if (choice == i && places[i]-48 == i) {
            places[i] = mark;
            return 0;
        }
    }
    return 1;
}

int checkForWin() {
    short draw = 0;

    //Horizontal check
    for (int i = 1; i < 10; i += 3) {
        if (places[i] == places[i + 1] && places[i + 1] == places[i + 2]) {
            printf("\tYou won!\n");
            return 1;
        }
    }
    //Vertical check
    for (int i = 1; i < 4; i += 1) {
        if (places[i] == places[i + 3] && places[i + 3] == places[i + 6]) {
            printf("\tYou won!\n");
            return 1;
        }
    }
    //Diagonal check
    if (places[1] == places[5] && places[5] == places[9]) {
        printf("\tYou won!\n");
        return 1;
    } else if (places[3] == places[5] && places[5] == places[7]) {
        printf("\tYou won!\n");
        return 1;
    }
    //Check for draw
    for (int j = 1; j < 10; ++j) {
        if (places[j] - 48 != j)
            draw++;
    }
    if (draw == 9){
        printf("\t  Draw!\n");
        return 1;
    }

    return 0;
}

Do you have any tips on how I could make it more efficient or fix something I did wrong?


texts: Algorithm to find connected tiles (percolation)

texts:
I wrote a little program in JavaFX which displays a path of neighbouring open tiles going from top to bottom. It should simulate a percolation.

The algorithm iterates through the whole grid (every tile) populating a list with tiles that have a continuous connection to the top. It all works somewhat. My concern however is that it probably is highly inefficient and I don't really know how to improve said efficiency as we didn't learn anything of that sort in my school.

burnt is just another ArrayList initialised as a member variable.

GitHub link

public void searchCluster(Grid grid){
    Node[][] array = grid.getNodeArray();
    ArrayList<Node> tmpBurnt = new ArrayList();
    LinkedList<Node> tmpSave = new LinkedList();
    Node left;
    Node right;
    Node below;

    for(Node n : array[0]){
        if(n.isSet()){
            tmpBurnt.add(n);
        }
    }

    for(;;){
        if(tmpBurnt.isEmpty()){
            return;
        }
        for(Node n : tmpBurnt){
            //-----check left--------
            if(n.getX() > 0){
                left = array[n.getY()][n.getX() - 1];
                if(left.isSet() && !tmpBurnt.contains(left) && !this.burnt.contains(left)){
                    tmpSave.add(left);
                }
            }
            //-----check right--------
            if(n.getX() < array[n.getY()].length - 1){
                right = array[n.getY()][n.getX() + 1];
                if(right.isSet() && !tmpBurnt.contains(right) && !this.burnt.contains(right)){
                    tmpSave.add(right);
                }
            }
            //-----check below--------
            if(n.getY() < array.length - 1){
                below = array[n.getY() + 1][n.getX()];
                if(below.isSet() && !tmpBurnt.contains(below) && !this.burnt.contains(below)){
                    tmpSave.add(below);
                }
            }
        }
        for(Node n : tmpBurnt){
            this.burnt.add(n);
        }
        tmpBurnt.clear();
        for(Node n : tmpSave){
            tmpBurnt.add(n);
        }
        tmpSave.clear();
    }
}


texts:
Based on this question, I have made a simple program to print a sequence of random numbers. The program seems to run fine, but I would like to know if my implementation is correct and how I can improve it.

#include <random>
#include <array>
#include <algorithm>
#include <functional>
#include <iostream>

template<class T = std::mt19937, std::size_t N = T::state_size>
auto randomEngine() -> typename std::enable_if_t<!!N, T>
{
    std::array<typename T::result_type, N> seed_data;
    thread_local static std::random_device source;
    std::generate(std::begin(seed_data), std::end(seed_data), std::ref(source));
    std::seed_seq seeds(std::begin(seed_data), std::end(seed_data));
    thread_local static T seeded_engine(seeds);
    return seeded_engine;
}

template<typename T>
T random(T min, T max)
{
    static_assert(std::is_integral<T>::value || std::is_floating_point<T>::value, "!");

    using UniformInt = std::uniform_int_distribution<T>;
    using UniformReal = std::uniform_real_distribution<T>;
    using DistType = std::conditional_t<std::is_integral<T>::value, UniformInt, UniformReal>;

    static auto RandomEngine = randomEngine();

    DistType uniformDistribution(min, max);

    return uniformDistribution(RandomEngine);
}

int main()
{
    for (auto i = 0u; i < 16; ++i)
        std::cout << random(0u, 15u) << ' ';
}


texts: Solo dice game (from Reiner Knizia’s Decathlon)

texts:
I'm trying to implement Reiner Knizia’s Decathlon, a set of 10 solo dice games played with 8 dices named after Decathlon events in Olympics.

The first event is called "100 Metres".
The player divides 8 dices into two sets of 4, then pick a set and throw.
He may keep the dice (freeze) or rethrow. After he is satisfied with the result, he does the same with the other set. He has a total of 5 rethrows. The score is the total of the dice after he freezes all dice.

My approach:
There are 10 events, so it is going to be a lot of repetitive code. I made a Event class, and each Event will have a self.state dict object keeping tracking of dice rolls and number of rethrows. Each event will also have a self.print_game_state object.

Here is the code. Any idea to write this code smarter?

common.py

import random

class DiceRoller:

    def __new__(cls, num_dice=1):
        return [random.randint(1, 6) for _ in range(num_dice)]

class Event:
    def __init__(self):
        if not hasattr(self, 'state'):
            self.state = dict()

    def print_game_state(self):
        for key, value in self.state.items():
            print(f'{key}: {value}')
        print(f'Score: {self.score()}')
        if self.game_finished():
            print('Game Finished')

e100metres.py

from common import DiceRoller, Event

class E100Metres(Event):
    '''100 metres event.'''

    def __init__(self):
        super().__init__()
        self.state.update({
            'frozen_sets': 0,
            'remaining_rerolls': 5,
            'frozen_dices': [],
            'current_rolls': DiceRoller(4)
        })
        self.print_game_state()

    def game_finished(self):
        return self.state['frozen_sets'] >= 2

    def no_more_rerolls(self):
        return self.state['remaining_rerolls'] <= 0

    def reroll(self):
        if self.game_finished():
            raise Exception('Game already finished')
        if self.no_more_rerolls():
            raise Exception('No more rerolls')
        self.state['remaining_rerolls'] -= 1
        self.state['current_rolls'] = DiceRoller(4)
        self.print_game_state()

    def freeze(self):
        if self.game_finished():
            raise Exception('Game already finished')
        self.state['frozen_dices'] += self.state['current_rolls']
        self.state['frozen_sets'] += 1
        if self.game_finished():
            self.state['current_rolls'] = list()
        else:
            self.state['current_rolls'] = DiceRoller(4)
        self.print_game_state()

    def score(self):
        return sum(self.state['frozen_dices'])


texts: Checking if a string contains all unique characters

texts:
I am currently reviewing CTCI(Cracking the Coding Interview)
The question is asking me to implement an algorithm which checks whether the characters in a string are all unique however they do not want me to use any auxillary data structures
My Algorithm is relatively straight forward, Two nested loops one starting at 0(i)  and another at 1(i+1)
If the condition finds two characters that are equal then I print duplicate characters have been found.
 public static void checkUnique(String s)
{

    for(int i = 0; i<s.length(); ++i)
    {
        for(int j = i +1; j<s.length(); ++j)
        {
            if(s.charAt(i) == s.charAt(j))
            {
                System.out.println("Duplicates found");
            }
        }
    }

}

My question

Is this an optimal algorithm, my second approach was to sort, and find a  pair which contains the same characters.
Obviously a hashmap would be beneficial here, but questions does not really want me to use it.

I have refactored the code and hopefully now it is correct.
Is there any way of reducing it to an O(N) runtime. What if we keep track of the Unicode code's for each char character. I doubt O(N^2) is the best we can do here.


texts:
I am a beginner to Java and have just written a number guessing game which involves guessing numbers from 1 to 10. I would like to improve my code by sticking strictly to conventions, improving code efficiency and forming good coding habits from the beginning.

Main class:

public class Main {

    public static void main(String[] args) {
        while (GuessingGame.play) {
            GuessingGame.play();
        }
    }
}

GuessingGame class:

import java.util.Random;
import java.util.Scanner;

public class GuessingGame {

    public static boolean play = true;

    private static int number = 0;
    private static int guess = 0;
    private static Random random = new Random();
    private static Scanner scanner = new Scanner(System.in);

    private static int nextInt(Random r, int lower, int higher) {
        int ran = r.nextInt(higher - lower);
        return (int) lower + ran;
    }

    public static void play() {
        number = nextInt(random, 1, 10);
        System.out.println("Insert your guess from 1-10!");
        guess = scanner.nextInt();
        if (guess == number) {
            System.out.println("Correct!");
            play = false;
        } else {
            System.out.println("Wrong! The number is: " + number);
            System.out.print("Do you want to try again? Y/N");
            String s = scanner.next();
            play= s.equalsIgnoreCase("Y") ? true : false;
        }
    }
}


texts: Python Optimizing/Speeding up the retrieval of values in a large string

texts:
I have a string containing around 1 million sets of float/int coords, i.e.:

    '5.06433685685, 0.32574574576, 2.3467345584, 1,,,'

They are all in one large string and only the first 3 values are used. The are separated by 3 commas. The code i'm using right now to read through them and assign them to a list is below:

    def getValues(s):
        output = []
        while s:
            v1, v2, v3, _, _, _, s = s.split(',', 6)
            output.append("%s %s %s" % (v1.strip(), v2.strip(), v3.strip()))
        return output
    coords = getValues(tempString)

The end results need to be a list of the three floats in each set separated by a space, i.e.:

    ['5.06433685685 0.32574574576 2.3467345584']

The code I defined above does work for what I want, it just takes much longer than I would like. Does anyone have any opinions or ways I could speed it up? I would like to stay away from external modules/modules i have to download.

Btw I don't think it's my computer slowing it down, 32gb ram and 350mb/s write speed, the program that creates the original string does it in about 20 secs, while my code above gets that same string, extracts the 3 values in around 30mins to an hour.

P.s. Using python 2.6 if it matters

EDIT:
Tried replacing the while loop with a for loop as I did some reading and it stated for loops were faster, it might have shaved off an extra minute but still slow, new code:

    def getValues(s, ids):
        output = []
        for x in range(len(ids)):
            v1, v2, v3, _, _, _, s = s.split(',', 6)
            output.append("%s %s %s" % (v1.strip(), v2.strip(), v3.strip()))
        return output


texts: Refactoring a class hierarchy to remove subclasses

texts:
I have the following class inheritances hierarchy:

First the abstract parent class:

<?php
abstract class SegmentParserAbstract{
/** @var ParserResult */
protected $_result;
protected $_invalidSegmentMessage;
protected $_segmentRegex;
protected $_segment;

abstract protected function createSegmentObject();
public function __construct() {
    $this->_result = new ParserResult();
}
public function setSegment($Segment) {
    $this->_segment = $Segment;
}
/**
 * Function will parse the Segment  by validating the input string.
 * If valid it will create the Segment Object in the result array with no errors.
 * If invalid it will populate the result array with the error, but no object will be created.
 */
public function parse() {
    if ($this->isValidSegment()) {
        $this->createSegmentObject();
    } else {
        $this->createErrorMessage();
    }
    return $this->_result;
}
protected function isValidSegment() {
    $matchesFound = preg_match($this->_segmentRegex, $this->_segment);
    return ($matchesFound > 0);
}
protected function createErrorMessage() {
    $this->_result->addError(array($this->_invalidSegmentMessage . $this->_segment));
}
}
?>

The first child:

<?php
class GsParser extends SegmentParserAbstract {
    const SUPPLIER_ID_INDEX = 2;
    const GROUP_HEADER_INDEX = 6;
    protected $_invalidSegmentMessage= 'Invalid GS segment: ';
    protected  $_segmentRegex="/^GS\*IN\*\w{2,15}\*\w{2,15}\*(\d{6}|\d{8})\*\d{4}\*\d{1,9}\*X\*\d{1,12}$/";

    protected function createSegmentObject() {
        $elements = explode('*', $this->_segment);
        $gs = new Gs();
        $gs->setSupplierId($elements[self::SUPPLIER_ID_INDEX]);
        $gs->setGroupReference($elements[self::GROUP_HEADER_INDEX]);
        $this->_result->setSegment($gs);
    }
}
?>

The second child:

<?php
class IsaParser extends SegmentParserAbstract {
    const SUPPLIER_ID_INDEX = 6;
    protected $_invalidSegmentMessage= 'Invalid ISA segment: ';
    protected $_segmentRegex="/^ISA\*00\*.{10}\*00\*.{10}\*ZZ\*.{15}\*ZZ\*.{15}\*\d{6}\*\d{4}\*U\*.{5}\*\d{9}\*[0-1]\*[PT]\*>$/";

    protected function createSegmentObject() {
        $elements = explode('*', $this->_segment);
        $isa = new Isa();
        $isa->setSupplierId($elements[self::SUPPLIER_ID_INDEX]);
        $this->_result->setSegment($isa);
    }
}
?>

Now I'll be having about nearly 16 other parsers extending the same abstract class SegmentParserAbstract with only differing in the implementation of createSegmentObject() and the number of constants (which might have different names of course).

Somehow I feel that I can remove all sub classes and only keep the parent class and make it a concrete class that can be configured to work on any Segment provided it knows its regular expression and the data that needs to be extracted and the resulting object type.

Any help?!


texts:
I just figured out Project Euler problem #12. This the first one I've done in Python, so I'm putting my code out there to hopefully get some constructive criticism.

If anyone is interested, would you mind looking over my solution and letting me know how I can improve on it, either through optimization or style?

Thanks!

from math import*

def divisorCount(n):
    nDivisors = 0

    integerSqrt = int(sqrt(n))

    if sqrt(n) == integerSqrt:
        nDivisors += 1

    for i in range(1, integerSqrt - 1):
        if n % i == 0:
            nDivisors += 2

    return nDivisors

def main():

    divisors = 0

    incrementTriangle = 1
    triangleNumber = 1

    while True:

        divisors = divisorCount(triangleNumber)

        if divisors < 500:
            incrementTriangle += 1
            triangleNumber = triangleNumber + incrementTriangle
        elif divisors >= 500:
            print "The first triangle number w/ 500+ divisors is", triangleNumber
            return 0

main()


texts:
Please let me know if you think I can improve the structure of his table code.

      Date

      Tournament

      Tournament Scores

      Result

      Score

Card

      Event/Scores Type

      Score

      -Par+

      R1

      R2

      R3

      R4

      R5

      Pos.

      SAR

      06-02-14

      Tourn

      (Gross)

      148

      +5

      72

      76


texts:
To learn Rust, I tried to write a function that takes string input and then converts it to integers for a time calculation for a delay.

Is this approach ok? Have I made any mistakes? I kind of struggled with needing to do two separate error checks for the string. First for the parse result and second for the limiting the unwrapped value. I was hoping to combine the is_ok call and then unwrapped value check in one condition. Ran into some borrowing error messages and type problems.

use std::io;

fn read_time(message : &str, max : u64) -> u64 {
    let mut input = String::new();

    loop {
        println!("{}", message);
        input.clear();
        io::stdin().read_line(&mut input).unwrap();
        let num = input.trim().parse::<u64>();

        if num.is_ok() {
            let n = num.unwrap();

            if n < max {
                return n;
            }
            else {
                println!("exceeded max value of {}", max - 1);
            }
        }
        else {
            println!("Need a number above 0 and less than {}", max);
        }
    }
}

fn main() {

    println!("Waiting Sample Program");

    let hours = read_time("Enter hours: ", 24);

    let minutes = read_time("Enter minutes: ", 100);

    let wait = hours * 60 + minutes;

    println!("Going to wait {} minutes", wait);

    std::thread::sleep(std::time::Duration::new(wait * 60, 0));

    println!("done.");
}


texts: This code is a non-static C# class for rolling a number of dice

texts:
Hello Everyone!
Fellow human beings, today I present to you my dice rolling script! Behold, in my amateurish attempt at some raw C# code. Perhaps this will remain here regardless of the dozens of other dice rolling scripts out there.
Contains a 'for' loop, a 'switch', and a method that returns a value.
using System;

namespace C_
{
    class RollDice : Program
    {

        //Variables

        int numOfDice;
        int numOfSides;

        int maxDice = 100;
        int minDice = 1;
        int maxSides = 100;
        int minSides = 1;
        int totalRolled;

        //Start method for number of Dice to throw - take the player input in InputMethod() which returns an int. If returning 0, then restart. Clamp the value between min/max. Continue to next function.

        public void GetDice()
        {
            Console.WriteLine("Welcome to Roll Dice!");
            Console.WriteLine("How many dice do you want to throw?");
            numOfDice = InputMethod();
            if(numOfDice == 0)
            {
                GetDice();
            }
            if (numOfDice > maxDice || numOfDice < minDice)
            {
                numOfDice = Math.Clamp(numOfDice, minDice, maxDice);
                Console.WriteLine($"Number of Dice set to {numOfDice}");
            }

            GetSides();
        }

        // Get the sides of each dice by using a similar process. Roll() for each dice, then sum the totals in RollTotal().

        public void GetSides()
        {
            Console.WriteLine("How many sides does each dice have?");
            numOfSides = InputMethod();
            if(numOfSides == 0)
            {
                GetSides();
            }
            if (numOfSides > maxSides || numOfSides < minSides)
            {
                numOfSides = Math.Clamp(numOfSides, minSides, maxSides);
                Console.WriteLine($"Number of Sides set to {numOfSides}");
            }

            for (int x = 1; x <= numOfDice; x++)
            {
                Roll();
            }

            RollTotal();
        }

        // Create a new Random() instance for the number of sides and add it to the totalRolled variable.

         public void Roll()
        {
            Console.WriteLine(".....");
            Console.WriteLine("Rolling");
            Random r = new Random();
            var result = r.Next(1, numOfSides + 1);
            Console.WriteLine($"You rolled {result}");
            totalRolled += result;
        }

        // Output the total and prompt to roll again or quit. Reset the total..

        public void RollTotal()
        {
            Console.WriteLine($"Total sum rolled is {totalRolled}");
            Console.WriteLine(" ");
            Console.WriteLine("Enter 1 to re-roll or 2 to quit.");
            var answer = InputMethod();

            switch (answer)
            {
                case 0:
                RollTotal();
                break;

                case 1:
                totalRolled = 0;
                GetDice();
                break;

                case 2:
                totalRolled = 0;
                Environment.Exit(0);
                break;

                default:
                Environment.Exit(0);
                break;
            }
        }

        //Convert the input to an integer if valid and return the value. Else return 0.

        public int InputMethod()
        {
            var input = Console.ReadLine();
            if(!Int32.TryParse(input, out int convertedStringToInt))

            {
                Console.WriteLine("You need to enter a valid number!");
                return 0;
            }

            else

            {
                return Convert.ToInt32(input);
            }

        }

    }
}


texts: Have I missed some obvious XSS vulnerabilities?

texts:
As the question states: have I missed some obvious security vulnerabilities in this code? Particularly interested in XSS...

I'm trying to create something more robust that strip_tags, but simpler than HTML Purifier which just feels like overkill.

class StripTags {
    private $tags;
    private $dom;
    function __construct($html, $tags = null) {
        // Setup tags
        $this->setTags($tags);

        //Initialise document using provided HTML
        $doc = new DOMDocument();
        @$doc->loadHTML($html);         //suppress invalid HTML warnings
        $doc_elem = $doc->documentElement;

        $this->traverseAndRemove($doc_elem);

        // Store DOM for processing in __toString()
        $this->dom = $doc;
    }
    public function __toString() {
        // Remove unwanted DOCTYPE etc
        $str = $this->dom->saveHTML();
        $str = str_replace('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">', "", $str);
        $str = preg_replace("/^<html><body>/", "", trim($str));
        $str = preg_replace("/<\/body><\/html>$/", "", trim($str));
        return $str;
    }

    private function setTags($t) {
        if (empty($t) or !is_array($t)) {
            $this->tags = array("html", "body", "p", "span", "div", "img", "b", "i", "em", "strong", "h1", "h2", "h3", "h4", "a", "pre");
        } else {
            $this->tags = $t;
        }
        if (!in_array("html",$this->tags)) {
            $this->tags[] = "html";
        }
        if (!in_array("body",$this->tags)) {
            $this->tags[] = "body";
        }
    }

    private function traverseAndRemove(&$elem) {
        // Check node type, attributes and child nodes
        // Reset child/attribute loops if one is removed
        if ($elem->nodeType === XML_ELEMENT_NODE) {
            $tagName = $elem->tagName;
            if (!in_array($tagName, $this->tags)) {
                // Remove any elements in the tags array and stop processing it
                $elem->parentNode->removeChild($elem);
                return;
            }
            // Check attributes for Javascript events and src/hrefs with javascript too...
            if ($elem->hasAttributes()) {
                $attrs = $elem->attributes;
                for ($i=0,$max=$attrs->length; $i<$max; $i++) {
                    $name = $attrs->item($i)->name;
                    if (in_array($name, array("onload", "onclick","onmouseover","onmousemove","onmousehover","onmousedown","onmouseup", "onunload"))) {
                        $elem->removeAttribute($name);
                        $max--;
                        $i--;
                    }
                    if (in_array($name,array("src", "href")) and preg_match("/^javascript:/i", $attrs->item($i)->value)) {
                        $elem->removeAttribute($name);
                        $max--;
                        $i--;
                    }
                }
            }
        }
        // Check all child nodes too
        if ($elem->hasChildNodes()) {
            $children = $elem->childNodes;
            for ($i=0, $max=$children->length; $i<$max; $i++) {
                $this->traverseAndRemove($children->item($i));
                if ($children->length < $max) {
                    $i -= ($max - $children->length);
                    $max = $children->length;
                }
            }
        }
    }
}