texts: Resume code of a SQL selecting function in Java

texts:
I am new to Java so I started to learn by doing. Right now I am developing a store management software. I'm trying to do it the right and clean way, so I'm looking for some reviews of my code. The code is trying to resume the connection and the selecting from a database, so you will found a demonstration in the main method:

public class DBObject {
    Connection c=null;
    Statement stmt = null;
    ResultSet rs=null;

    public DBObject(Connection c,Statement stmt,ResultSet rs ){
        this.c=c;
        this.stmt=stmt;
        this.rs=rs;
    }
    public DBObject(){

    }
    //excute select query (don't forget to close all of ResultSet,Statment,Connection objects)
    public static DBObject executeSelectQuery(String query,String DBname){
        Connection c = null;
        Statement stmt = null;
        DBObject dbo=null;
        try {
              Class.forName("org.sqlite.JDBC");
              c = DriverManager.getConnection("jdbc:sqlite:"+DBname);
              c.setAutoCommit(false);
              System.out.println("Opened database successfully");
              stmt = c.createStatement();
              ResultSet rs = stmt.executeQuery(query);
              dbo=new DBObject(c,stmt,rs);
            } catch ( Exception e ) {
              System.err.println( e.getClass().getName() + ": " + e.getMessage() );
              System.exit(0);
            }
        return dbo;
    }
    public static void main(String[] args) throws SQLException{
        String q="select *from compte";
        DBObject dbo=null;
        String id=null,password=null,nom=null,prenom=null,adresse=null,numtelephone=null;
        dbo=executeSelectQuery(q, "lib.db");
        while(dbo.rs.next()){
            id=dbo.rs.getString("compte_id");
            password=dbo.rs.getString("password");
            nom=dbo.rs.getString("nom");
            prenom=dbo.rs.getString("prenom");
            adresse=dbo.rs.getString("adresse");
            numtelephone=dbo.rs.getString("numtelephone");
        }
        System.out.println(id+" "+password+" "+nom+" "+" "+prenom+" "+adresse+" "+numtelephone);
    }
}


texts: Python - checking if phrase appears on a list

texts:
I have a big file with a lot of "phrases", like:

  sayndz zfxlkl attjtww cti sokkmty brx fhh suelqbp xmuf znkhaes pggrlp

  zia znkhaes znkhaes nti rxr bogebb zdwrin sryookh unrudn zrkz jxhrdo

  gctlyz bssqn wbmdc rigc zketu ketichh enkixg bmdwc stnsdf jnz mqovwg

  ixgken flawt cpott xth ucwgg xce jcubx wvl qsysa nlg qovcqn zxcz

  vojsno nqoqvc hnf gqewlkd uevax vuna fxjkbll vfge qrzf phwuf ligf xgen

  vkig elptd njdm gvqiu epfzsvk urbltg dqg sfpku viwihi fje umdkwvi

  ejzhzj qrbl sfpku sad nawnow ksnku nzhj mfudick ueaa jnhz kpy pzk

What I need to do is check if any 'phrase' didn't appear twice in a line and count lines where it didn't

def check(phrase):
    phrases = phrase.split()
    for i in range(len(phrases)):
        phrase_tmp = phrases.pop(0)
        if phrase_tmp in phrases:
            return False
        phrases.append(phrase_tmp)
    return True

with open('file_with_phrases.txt', 'r') as file:
    counter = 0
    for line in file:
        if check(line):
            counter += 1
    print(counter)

Can you tell me if I did it all good?


texts:
I'm working on my framework constructor. First I tried to look into jQuery and understand it, but it's so out of my league. Instead I googled and put this code together. Though there aren't many posts about creating a framework. Anyway, since I'm not a guru I might be doing it the wrong way or missing things. Can I take your opinions, suggestions to make it a little more stable?

FIDDLE

var optionalSelector = "$";

(function () {
    (this[arguments[0]] = function constructor(input) {
        if (!(this instanceof constructor)) {
            return new constructor(input);
        }

        var regExp_id = /^#/;
        var regExp_class = /^\./;
        var regExp_tag = /[^#]|[^.]/;

        var typeOfInput;

        function isElement(obj) {
            if (obj !== null && typeof obj === "object") {
                return obj;
            }
        }

        if (isElement(input)) {
            return input;
        } // this
        else {
            if (input.search(regExp_id) != -1) {
                typeOfInput = "id";
            } else if (input.search(regExp_class) != -1) {
                typeOfInput = "class";
            } else if (input.search(regExp_tag) != -1) {
                typeOfInput = "tag";
            }

            switch (typeOfInput) {

                case "id":
                    if (document.getElementById(input.replace(/#/, ""))) {
                        return document.getElementById(input.replace(/#/, ""));
                    } else {
                        console.log("Invalid id: " + input);
                        return false;
                    }
                    break;

                case "class":
                    if (document.getElementsByClassName(input.replace(/./, "")).length > 0) {
                        return document.getElementsByClassName(input.replace(/./, ""));
                    } else {
                        console.log("Invalid class: " + input);
                        return false;
                    }
                    break;

                case "tag":
                    if (document.getElementsByTagName(input).length > 0) {
                        return document.getElementsByTagName(input);
                    } else {
                        console.log("Invalid tag: " + input);
                        return false;
                    }
                    break;
            }
        }
    })
})(optionalSelector);


texts: Optimizing a raycasting/voxelspace algorithm in Pygame

texts:
In the past three days, I've been developing a simple raycasting algorithm. I've made the renderer work as I'd like to. However, it is extremely slow (5 frames per second) because of two things (as far as I know).

Finding the values of a pixel independently many times, and often it lands on the same pixel.
The large amount of times the code is run.

I'm aiming for speed but the only programming language I have experience in is Python. What are the optimizations I can make to this code? Which other libraries can I use that are faster than Pygame or PIL for this use?
Also, how do I make the pixel coordinates loop (-1 = 1023) without if statements to prevent the game crashing if near the boundary?

from PIL import Image
import pygame

cdef enum resolution:
  resX=720
  resY=540
  qresX=180
cdef extern from "math.h":
  double sin(double x)
  double cos(double x)

screen = pygame.display.set_mode((resX,resY))
pygame.display.set_caption('VoxelSpace')

im=Image.open("data/height.png")
disp=im.load()
col = Image.open("data/colour.png")
rgb_im = col.convert('RGB')
rgb=rgb_im.load()

cdef unsigned char uu
cdef unsigned char height
cdef unsigned char prevHeight
cdef unsigned char heightBuffer
cdef float t
cdef float foga
cdef unsigned char fogb
cdef int x
cdef int y
cdef unsigned char r
cdef unsigned char g
cdef unsigned char b
cdef int pX
cdef int pY
cdef float pAngle
cdef unsigned char u
cdef int v
cdef unsigned char h

def Render(pX,pY,pAngle):
  screen.fill((100,100,255))
  heightBuffer=disp[pX,pY]
  for v from -qresX <= v < qresX by 1:
    prevHeight=0
    for u from 1 <= u < 124 by 1:
      if u<30:
        uu=u
      elif u<60:
        uu=u*2-45
      else:
        uu=u*4-180
      foga=u/60.0+1
      fogb=u/2

      t=v/float(qresX)+pAngle
      x=int(sin(t)*-uu+pX)
      y=int(cos(t)*-uu+pY)
      height=(float(disp[x,y]-heightBuffer-10)/uu*101+135)*2
      if height>prevHeight:
        r,g,b=rgb[x,y]
        pygame.draw.line(screen,(r/foga+fogb,g/foga+fogb,b/foga+u) , (2*(qresX+v),resY-prevHeight),(2*(qresX+v),resY-height),2)
        prevHeight=height
  pygame.display.flip()

I am compiling this code as a .so (via cython) and running it from another .py. Is it faster if I simply use PyPy instead?


texts: Combined looping and recursion when implementing Quicksort, using proper Clojure style

texts:
In "The Joy of Clojure", 2nd edition, code for quicksort is introduced on page 133 that I found hard to digest. I have rewritten it to make it clearer (at least to myself).

Here is the original:

(defn sort-parts-joc [work]
  (lazy-seq
    (loop [[part & parts] work]
      (if-let [[pivot & xs] (seq part)]
        (let [smaller? #(< % pivot)]
          (recur (list*
                  (filter smaller? xs)
                  pivot
                  (remove smaller? xs)
                  parts)))
        (when-let [[x & parts] parts]
            (cons x (sort-parts-joc parts)))))))

Here is the rewritten code:

(defn sort-parts-explicit-lazy [work]
   (lazy-seq
      (loop [loopwork work]
         (let [[ part & partz ] loopwork ]
            (if-let [[pivot & valuez] (seq part)]
                  (let [ smaller? #(< % pivot)
                         smz      (filter smaller? valuez)
                         lgz      (remove smaller? valuez)
                         nxxt     (list* smz pivot lgz partz) ]
                        (recur nxxt))
                  (if-let [[oldpivot & rightpartz] partz]
                          (cons oldpivot (sort-parts-explicit-lazy rightpartz))
                          []))))))

Testing:

(require '( clojure test ))
(clojure.test/is (is-sorted (sort-parts-explicit-lazy [[]])))
(clojure.test/is (is-sorted (sort-parts-explicit-lazy [[1]])))
(clojure.test/is (is-sorted (sort-parts-explicit-lazy [[1 2]])))
(clojure.test/is (is-sorted (sort-parts-explicit-lazy [[1 2 3]])))
(clojure.test/is (is-sorted (sort-parts-explicit-lazy [[3 2 1]])))
(clojure.test/is (is-sorted (sort-parts-explicit-lazy [[3 3 3]])))

So, it works.

Both functions are essentially the same.

However I have a bad feeling about this. The simultaneous use of recur and full recursion, with the full recursion path "leaving" the loop in its middle in the same function feels weird, like unstructured code dropping a good, fat GOTO.

Here is the expression tree for reference:

We are far from from beta-reduction here. The "reduction" can only be understood using explicit instruction flow semantics. Okay, reality meets platonic ideals.

Is the loop-recur/full-recursion supposed to look like this? Is it a style problem that can be improved?


texts: Naive Implementation of Automatic Memoisation

texts:
I wrote code to (naively) perform automatic memoisation. I tried to write it in a functional programming style, and so did not make use of any global variables.
My Code
def naive_memoise(caches):
    def memoise(f):
        nonlocal caches
        def mem_f(n):
            nonlocal caches, f
            if f not in caches:
                caches[f] = {}
            if n not in caches[f]:
                caches[f][n] = f(n)
            return caches[f][n]
        return mem_f
    return memoise

Sample Usage
def fib(n):
    if n in [0, 1]:
        return n
    return  fib(n - 2) + fib(n - 1)

mem = naive_memoise({})
fib = mem(fib)


texts: refactor javascript - show and hide fields based on current selection

texts:
I need help refactoring the javascript. http://jsfiddle.net/BDLYP/

I was able to hide and show fields, but I know this can be improved upon.

If #state is empty, hide #high-schools and #other_high_schools

If #state is picked, show #high-schools and show #other_high_schools (if #high-schools is empty)

I imagine the multiple .live can be cut down. I am fairly new to javascript/jQuery

<select name="state" id="state">
    <option value=""></option>
    <option value="NY">NY</option>
    <option value="CA">CA</option>
</select>

    <select name="high_school_id" id="high_school">
        <option value=""></option>
        <option value="1">Degrassi High</option>
        <option value="2">Bayside High</option>
    </select>

Enter hs if your school is not listed above
        <input type="text" name="other_high_school" id="other-hs-field" />

$(document).ready(function() {
   checkHighSchool();

   $('#high_school').live('change', function() {
    checkHighSchool();
  });

  $('#state').live('change', function() {
    checkHighSchool();
  });
});

function checkHighSchool() {
  var state = $("#state").val();
  var high_school = $("#high_school").val();

  if(state) {
    $("#high-schools").show();
  }

  if(!state) {
    $("#other_high_school").hide();
    $("#high-schools").hide();
    $("#other-hs-field").val('');
    //alert('no state selected');
  }

  if(high_school && state) {
    $("#other_high_school").hide();
    $("#other-hs-field").val('');
  }

  if(!high_school && state) {
    $("#other_high_school").show();
  }
}


texts: Get elementary values from a flagged enum

texts:
I created a little function that returns the elementary values from a flagged enum. By "elementary" I mean the values that are powers of 2, excluding any combined enum values. I was a bit surprised I couldn't find a buit-in method for this in .Net (or I missed it).

Let's take this flagged enum:

[Flags]
public enum WeekDay
{
    Monday = 1 << 0,
    Tuesday = 1 << 1,
    Wednesday = 1 << 2,
    Thursday = 1 << 3,
    Friday = 1 << 4,
    Saturday = 1 << 5,
    Sunday = 1 << 6,

    WeekendDay = Saturday | Sunday,
    BusinessDay = Monday | Tuesday | Wednesday | Thursday | Friday
}

Since the binary representation of its values looks as follows...

1
10
100
1000
10000
100000
1000000

1100000
11111

...I came up with this function to extract the elementary values:

public IEnumerable<TEnum> GetElementaryValues<TEnum>()
    where TEnum: Enum
{
    return Enum.GetValues(typeof(TEnum))
        .Cast<TEnum>()
        .Where(v =>
        {
            var intValue = Convert.ToInt64(v);
            var binary = Convert.ToString(intValue, 2);
            return !binary.Skip(1).Any(c => c == '1');
        });
}

Which basically says: return each value that hasn't got a 1 beyond its first character.

Doest this look OK? Can it be improved? My feeling is that it's a lot of expensive code for such a simple task.


texts:
Is it possible to get rid of the BehaviourSubject to have an Observable with an initial value? Another thing I don't like is that I'm using getValue() and then modify this value and push it with next back to the Observable. Maybe there is a more elegant way to get the same thing?

import { Injectable } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class UserProvider {

  users$: Observable<{ id: string; name: string }[]>;

  private usersSource: BehaviorSubject<{ id: string; name: string }[]>;

  constructor() {
   this.usersSource = new BehaviorSubject<any>([
     { id: '111', name: 'Jack' },
     { id: '222', name: 'John' },
     { id: '333', name: 'Foo' },
   ]);
   this.users$ = this.usersSource.asObservable();
  }

  addUser(user: { id: string; name: string }) {
    const currentUsers = this.usersSource.getValue();
    currentUsers.push(user);
    this.usersSource.next(currentUsers);
  }

  removeUser(userId: string) {
    const currentUsers = this.usersSource.getValue();
    const index = currentUsers.findIndex(user => user.id === userId);
    if (index !== -1) {
      if (this.selectedUserIdSource.getValue() === currentUsers[index].id) {
        this.selectedUserIdSource.next(null);
      }
      currentUsers.splice(index, 1);
      this.usersSource.next(currentUsers);
    }
  }
}


texts:
How could this constructor code be improved? I feel like I'm not doing something optimally here...

@interface JGProduct : NSObject {
    NSString *identifier;
}

+(JGProduct *)productWithIdentifier:(NSString *)identifier_;
-(JGProduct *)initWithIdentifier:(NSString *)identifier_;

@end

@implementation JGProduct

+(JGProduct *)productWithIdentifier:(NSString *)identifier_ {
    return [[[[self class] alloc] initWithIdentifier:identifier_] autorelease];
}

-(JGProduct *)initWithIdentifier:(NSString *)identifier_ {
    self = [super init];
    if (self) {
        _identifier = [identifier_ retain];
    }

    return self;
}

@end

id or JGProduct return type?

I see a lot of people writing

-(id)initWithIdentifier:(NSString *)identifier_ {

instead - why is this?

Surely any subclass of JGProduct would be exchangeable for the superclass... Or should I be returning something that is id but conforms to a protocol (if present)?

JGProduct or [self class] in initialiser?

I also see this:

+(JGProduct *)productWithIdentifier:(NSString *)identifier_ {
    return [[[JGProduct alloc] initWithIdentifier:identifier_] autorelease];
}

or

+(JGProduct *)productWithIdentifier:(NSString *)identifier_ {
    return [[[self alloc] initWithIdentifier:identifier_] autorelease];
}

Why would someone write either of these? The top one surely would not make the right kind of object if ran by a subclass. And what's the difference between self and [self class] if you're in a class method?

Thanks for any feedback!


texts: Add or remove a class on two elements when two different events fire

texts:
I want to add/remove a class on the html and body tags in the dom when my nav menu is opened or closed. Is this the most optimal way of writing this logic?

$( '#navbarNav' ).on( 'show.bs.collapse', function() {
    $( 'html, body' ).addClass( 'noscroll' );
});

$( '#navbarNav' ).on( 'hide.bs.collapse', function() {
    $( 'html, body' ).removeClass( 'noscroll' );
});


texts:
I have been working on a function that return a FSM that searches a specific word based on the argument of the constructor. The idea was to use those routines as means to learn about regular expressions and maybe implement a very basic regexp system, so I thought that matching normal string was a good first step in that direction.

This is actually my first "complex" program in Scheme. I learnt to program in C so it has been a little hard to switch my way of thinking into a functional approach, so any comments in my way of programming in Scheme would also be very useful.

NOTES:

I know that using lists might not be the most efficient thing to do, but they allowed me to program in a more functional way without using vector-set!
If there is something to add or to fix please don't just put the answer, that way I won't learn. Try to use code only if necessary.
Sadly Emacs uses tabs for indentation so formatting may be a little messy.

An automata in my code is represented as a list of states where each one is described as a pair of the form (a . b) where a is the matched character and b is the index of the state it transitions to.
If no pair contains a specific character then it defaults to the invalid state (index = 0).

The run-automata function searches a matching substring and returns its offset or #f if it is not contained inside string.

(define (string-null? s) (= (string-length s) 0))
(define (string-append-c s c) (string-append s (string c)))
(define (string-tail str) (substring str 1 (string-length str)))

;; is s2 a prefix of s1?
;; [TODO] - Use offset instead of string-tail
(define (string-prefix? s1 s2)
  (cond
    [(string-null? s2) #t]
    [(string-null? s1) #f]
    [(not (char=? (string-ref s2 0)
                  (string-ref s1 0))) #f]
    [else (string-prefix? (string-tail s1)
                          (string-tail s2))]))

(define (enumerate start end)
  (define (iter start end acc)
    (if (> start end)
        acc
        (iter start (- end 1) (cons end acc))))

  (iter start end '()))

(define (build-automata needle)
  (define (max-suffix-that-is-prefix str)
    (cond
      [(string-null? str) ""]
      [(not (string-prefix? needle str))
         (max-suffix-that-is-prefix (string-tail str))]
      [else str]))

  (define (build-transitions state-string transitions dictionary)
    (if (null? dictionary)
        transitions
        (let* ([c (car dictionary)]
               [suffix (max-suffix-that-is-prefix (string-append-c state-string c))])
          (build-transitions
            state-string
            (if (string-null? suffix)
                transitions
                (cons (cons c (string-length suffix))
                      transitions))
            (cdr dictionary)))))

  ;; Last state does not require a transition as it is the final state.
  ;; "We are done by that point".
  (let ([dictionary (string->list "abcdefghijkmnopqrstuvwxyz")])
    (map (lambda (n)
           (build-transitions
             (substring needle 0 n)
             '()
             dictionary))
         (enumerate 0 (- (string-length needle) 1)))))

;; Takes an automata and a string and returns the offset of the pattern the
;; automata was built to search
(define (run-automata automata string)
  (define (search-transition c state-transitions)
    (cond
      [(null? state-transitions) 0]
      [(char=? (caar state-transitions) c) (cdar state-transitions)]
      [else (search-transition c (cdr state-transitions))]))

  (define (step state automata-size offset)
    (cond
      [(= state automata-size) (- offset automata-size)]
      [(>= offset (string-length string)) #f]
      [else (step (search-transition (string-ref string offset)
                                     (list-ref automata state))
                  automata-size
                  (+ offset 1))]))

  (step 0 (length automata) 0))


texts: Class method with begin transaction and return errors

texts:
I've created a method which is useful for executing multiple queries, and it works perfectly.  Is this a good way to handle this?

public function foo($rQuery)
{
    try {
        $this->done->beginTransaction();
        foreach($rQuery as $val) {
            $rSql = $this->done->prepare($val);
            $rSql->execute();
        }

        $commitCode = $this->done->commit();
    }
    catch (PDOException $ex) {
        $errorInfo = "Ooops: ".$ex->getMessage();

        $roalBackCode = $this->done->rollBack();
    }

    return array('errorInfo' => $errorInfo, 'commitCode' => $commitCode, 'roalBackCode' => $roalBackCode);
}


texts: Allowing "plugin" programmers to subscribe to messages

texts:
I am having difficulty deciding how to implement an exception handling strategy.

I am using an observer pattern to allow "plugin" programmers to subscribe to Messages. These subscribers generally log a unique error (and do some other stuff) under an exceptional circumstance during handling the message. The code snippet below is an example of what a common implementation (and its interface) looks like:

// API interface
interface IMessageListener {
   void onMessage(Message m);
}

class StuffMessageListener implements IMessageListener {
    ...

    @Override void onMessage(Message m) {

        try {
            Stuff s = stuffDAO.getStuff(..); // throws SQLException

            ...

            m.reply(true);
        } catch (SQLException e) {
            // if an exception happens, log it, and reply to the message
            log.error(A_UNIQUE_ERROR_CODE, e);
            m.reply(false);
        }
    }
}

What irks me is that the catch block has become very redundant code, copied throughout 95% of the ~50 existing listeners. Can we come up with something better?

A good solution should:

be easy to use/understand for an amateur programmer
keep the programmer aware of the existence/potential of exceptions
minimize the chance of a programmer accidentally "swallowing" an exception
reduce the amount of "boilerplate" code

There is a subtle requirement needed for the solution. The UNIQUE_ERROR_CODE should be unique across all declarations of the listeners. That way, I could gain statistics based upon where the error was caught across all listeners.

If the UNIQUE_ERROR_CODE is buried underneath an abstract class, or is used outside onMessage(..), I will lose the needed "uniqueness."


texts: Project Euler #2 - Even Fibonacci numbers

texts:
Given:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

MAX_LIMIT = 4000000 # Four million inclusive
FIB_CACHE = {}

def fib(n):
    """ Calculates nth fibonacci term.
    Args:
        n: The nth term.
    Returns:
        The nth fibonacci term of the series.
    """
    if (2 >= n):
        return n
    if (n not in FIB_CACHE):
        FIB_CACHE[n] = fib(n-1) + fib(n-2) # linear recurrence
    return FIB_CACHE[n]

def sum_fib():
    sum = 0
    i = 1
    ith_fib = 0
    while (1):
        ith_fib = fib(i)
        if (ith_fib > MAX_LIMIT):
            return sum
        if (ith_fib % 2 == 0):
            sum += ith_fib
        i += 1
    return sum

print fib(1)
print fib(2)
print fib(10)
print sum_fib()

Note: Without caching, it was taking too long to complete since it's an exponential algorithm.
Few important points:

I read somewhere about putting fewer changing values on the left. Is this true?
I am always confused about when to use an if-if branch and anif-else branch. Is there any heuristic? For example, could I write cache-checking code in the else branch too?


texts: LINQ method that selects an item based on previous one

texts:
my requirement is to implement a way to filter a collection of elements based on a value of previous one.
For example to only select a number that is larger than the previous one. I don't currently know of any LINQ method that would allow me to do such a thing, so I decided to create one.

This is a code I have so far:

        public static IEnumerable<T> WherePrevious<T>(this IEnumerable<T> collection, Func<T, T, bool> predicate)
    {
        if (collection == null) throw new ArgumentNullException(nameof(collection));
        if (predicate == null) throw new ArgumentNullException(nameof(predicate));

        T previous = default(T);
        bool firstIteration = true;

        foreach (var item in collection)
        {
            if (firstIteration)
            {
                previous = item;
                firstIteration = false;
                yield return item;
            }
            else
            {
                if (predicate(previous, item))
                {
                    yield return item;
                }

                previous = item;
            }
        }
    }

Are there any ways to improve my code in terms of performance, readability or more generalization to make?

For example I'm not sure if it's clear to the caller of the method what the predicate inputs actually are


texts:
In my previous NQueens Code Review question, I received feedback saying that I should write a program that would find all solutions. This revised program should be more general than before.

import java.util.*;

public class RedoNQueens {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter number of queens: ");
        int nQueens = input.nextInt();
        //Create board and clear it
        int[] board = new int[nQueens];
        for (int i = 0; i < board.length; i++) {
            board[i] = -1;
        }

        //Place the first piece to get started
        int row = 0;
        board[row] = 0;
        row++;
        int column = 0;
        long solutions = 0;
        while (row >= 0) {
            if (isValid(row, column, board)) {
                board[row] = column;
                row++;
                column = 0;

                //Board completed?
                if (row >= board.length) {
                    solutions++;
                    System.out.println("Solution " + solutions);
                    printBoard(board);
                    row--;
                    column = board[row] + 1;
                }
            }
            else {
                //If current column is not valid
                column++;
                if (column >= board.length) {
                    board[row] = -1;
                    row--;
                    if (row >= 0)
                        column = board[row] + 1;
                }
            }
        }
        System.out.println("Number of solutions for " + nQueens + " queens is " + solutions);
    }

    public static boolean isValid(int row, int column, int[] board) {
        if (column >= board.length)
            return false;

        for (int i = 0; i < row; i++) {
            //Check if column appears in any other row
            if (board[i] == column)
                return false;

            //Check both diagnals
            if (Math.abs(row - i) == Math.abs(column - board[i]))
                return false;
        }

        return true;
    }

    public static void printBoard(int[] board) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board.length; j++) {
                if (board[i] == j)
                    System.out.print("|Q");
                else
                    System.out.print("| ");
            }
            System.out.println("|");
        }
    }
}


texts:
I'd like this code reviewed.

import java.util.NoSuchElementException;

public class MergeSort {

    private Node first;
    private Node last;

    private static class Node {
        int element;
        Node next;
        Node(int element, Node node) {
            this.element = element;
            this.next = node;
        }
    }

    public void displayList() {
        Node tempFirst = first;
        while (tempFirst != null) {
            System.out.print(tempFirst.element + " ");
            tempFirst = tempFirst.next;
        }
    }

    public void add (int val) {
        final Node l = last;
        final Node newNode = new Node(val, null);
        last = newNode;
        if (first == null) {
            first = newNode;
        } else {
            l.next = newNode;
        }
    }

    public void sort() {
        /**
         * QQ: should there be an exception check for last == null also ?
         */
        if (first == null) {
            throw new NoSuchElementException("The linkedlist doesnot contain any node.");
        }

        first = divide(first, last);
    }

    private Node getMidPoint(Node node) {
        assert node != null;

        Node fast = node.next;
        Node slow = node;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    private Node divide(Node node1, Node node2) {
        if (node1 == node2) return node1;

        Node midPoint = getMidPoint(node1);
        Node midpointNext = midPoint.next;
        midPoint.next = null;

        Node n1 = divide(node1, midPoint);
        Node n2 = divide(midpointNext, node2);
        return mergeLinkedList(n1, n2);
    }

    private Node mergeLinkedList(Node node1, Node node2) {
        assert node1 != null;
        assert node2 != null;

        Node current = null;
        Node currentHead = null;

        while (node1 != null && node2 != null) {

            if (node1.element < node2.element) {
                if (current == null) {
                    currentHead = node1;
                    current = node1;
                } else {
                    current.next = node1;
                    current = current.next;
                }
                node1 = node1.next;
            } else {
                if (current == null) {
                    currentHead = node2;
                    current = node2;
                } else {
                    current.next = node2;
                    current = current.next;
                }
                node2 = node2.next;
            }
        }

        current.next = node1 != null ? node1 : node2;

        return currentHead;
    }

    public static void main(String args[]) {
        // odd size list
        MergeSort ms1 = new MergeSort();
        int[] a1 = {5, 4, 3, 2, 1};
        for (int i : a1) {
            ms1.add(i);
        }
        ms1.sort();
        ms1.displayList();

        System.out.println();

        // even size list.
        MergeSort ms2 = new MergeSort();
        int[] a2 = {5, 4, 3, 2};
        for (int i : a2) {
            ms2.add(i);
        }
        ms2.sort();
        ms2.displayList();

        System.out.println();

        // list of size 1
        MergeSort ms3 = new MergeSort();
        int[] a3 = {1};
        for (int i : a3) {
            ms3.add(i);
        }
        ms3.sort();
        ms3.displayList();

        System.out.println();

        // list of size 2
        MergeSort ms4 = new MergeSort();
        int[] a4 = {2, 1};
        for (int i : a4) {
            ms4.add(i);
        }
        ms4.sort();
        ms4.displayList();

        System.out.println();

    }
}


texts:
I had an algorithm test.

I was asked Selection sort algorithm to program.

I coded it in javascript and shown to examiner.

But he was not satisfied, he said its too complicated.

I think I have written correctly.

this is the code below,

function selectionSort(inputArray){
  var swapElementIndex = 0;
  var shouldSwap = false;
  var temp = 0;
  var minNum = 0;
  for(var i = 0;i < (inputArray.length - 1);i++){
    minNum = 0;
    for(var currentIndex = (i+1); currentIndex < inputArray.length; currentIndex++){

        if(inputArray[i] > inputArray[currentIndex]){
            if(minNum === 0){ // when first minimum element is found
                swapElementIndex = currentIndex;
                shouldSwap = true;
                minNum = inputArray[swapElementIndex];
            }else{// when we have an minimum element

                /* further check whether min element is less than the new found [min] element,
                   if yes set it as min element.
                */
                if(minNum > inputArray[currentIndex]){
                    minNum = inputArray[currentIndex];
                    swapElementIndex = currentIndex;
                    shouldSwap = true;
                    minNum = inputArray[swapElementIndex];
                }
            }
        }
    }

    if(shouldSwap === true){
        temp = inputArray[i];
        inputArray[i] = inputArray[swapElementIndex];
        inputArray[swapElementIndex] = temp;
        shouldSwap = false;
    }
  }

  return inputArray;
}

console.log(selectionSort([1,31,26,4,3,12]));
console.log(selectionSort([5,6,1,2,3,4]));

The output when I run is as follows,

rahul@rahul:~/myPractise/Algo$ node sorting.js
[ 1, 3, 4, 12, 26, 31 ]
[ 1, 2, 3, 4, 5, 6 ]
rahul@rahul:~/myPractise/Algo$

So you can see that its working fine.

Please tell me how can I improve my code


texts:
I have a simple strategy game, and I implemented a simple counter object to count down a number whenever the game ticks.  I have heard about something called NSTimer but I haven't messed with it at all yet.  I have also heard that you should use Core Animations to move objects around when rendering rather than a tick based system, because tick based movement would be jerky.  However I wanted to make sure to handle animation and rendering separately from the underlying game model, so that part doesn't matter as much.  This is just to be used in the game model, and the actual animations of everything will be handled by the scene.

I realize I am probably reinventing the wheel here, but I wanted to build something dead simple that I could use in a few places right away, and I wanted the experience.  I am hoping most of all that the class is easy to understand, so let me know what you think.

The scene updates the game object according to the following method:

- (void)update:(NSTimeInterval)currentTime {
    CFTimeInterval timeSinceLast = currentTime - self.lastUpdateTimeInterval;

    //update game and hud counters every quarter second
    if (!_game.isPaused) {
        self.countdownInterval += timeSinceLast;
        if (self.countdownInterval > 0.25) {
            [self updateGame];
            [self buildResourceCounters];
            self.countdownInterval = 0;
        }
    }

    self.lastUpdateTimeInterval = currentTime;
    if (timeSinceLast > 1) { // more than a second since last update
        self.lastUpdateTimeInterval = currentTime;
    }
}

And here is the Countdown class which the game will update each tick:

typedef NS_ENUM(NSInteger, CountdownState){
    CountdownNotStarted = 0,
    CountdownCounting,
    CountdownPaused,
    CountdownFinished
};

DTCountdown.h:

#import <Foundation/Foundation.h>
#import "DTCountdownStates.h"

@interface DTCountdown : NSObject

-(id) initWithCount:(int)startCount;

-(void) update;
-(void) startCountdown;
-(void) pauseCountdown;
-(void) restartCountdown;
-(void) cancelCountdown;

@property CountdownState state;

@end

DTCountdown.m:

#import "DTCountdown.h"

@implementation DTCountdown {
    int _currentCount;
    int _startCount;
}

-(id) initWithCount:(int)startCount {
    self = [super init];
    if (self) {
        _startCount = startCount;
        _currentCount = _startCount;
        _state = CountdownNotStarted;
    }
    return self;
}

#pragma mark - Update Loop
-(void) update {
    switch (self.state) {
        case CountdownNotStarted:
            break;
        case CountdownCounting:
            [self doCountdown];
            break;
        case CountdownPaused:
            break;
        case CountdownFinished:
            break;
        default:
            break;
    }
}
-(void) doCountdown {
    if (_currentCount > 0) {
        _currentCount--;
    } else {
        self.state = CountdownFinished;
    }
}

-(void) startCountdown {
    self.state = CountdownCounting;
}
-(void) pauseCountdown {
    self.state = CountdownPaused;
}
-(void) restartCountdown {
    _currentCount = _startCount;
    self.state = CountdownCounting;
}
-(void) cancelCountdown {
    _currentCount = _startCount;
    self.state = CountdownNotStarted;
}

@end


texts:
Problem:
I have seen a few questions around hangman. Usually this is done in a very hackish way, which usually can not be generalized any further. My thought or question is about the creation of the gown, which is a central part in any hangman game.
I want to create the ASCII image below
 _____
 |   |
 O   |
/|\  |
/ \  |
     |
 ----------

Where one "limb" of the stick figure should appear each time the function is prompted.
I also wanted to be able to specify both the height and width of the gown. However I was not able to scale the stick figure relative to the gown size. The code is provided below and I have two simple questions about it =)
Question:

Is there a cleaner way to hang the man? I feel my method is very barbaric (I used some black voodo graduate mathematics to get it to look correct).
Is there a way to make the stick figure scale with the size of the gown? (essentially providing more guesses).

Code:
from math import ceil

def create_gown(width, height):
    gown = []
    gown.append('{:>{}s}'.format('_'*int(width/2), 10))
    gown.append('{:>{}s} {:>{}s}'.format(
        '|', 11 - int(width/2), '|', int(width/2)-2))
    for i in range(height-3):
        gown.append('{:^{}s}'.format('|', 20))
    gown.append('{:^{}s}'.format('-'*width, 20))
    return gown

def wrong_answer(gown, attempt=0):

    height, width = len(gown), len(gown[-1].strip())

    offset1 = int((-width+23)*0.5)+1
    offset3 = int(ceil(0.5*(width-7)))
    if attempt == 0:
        return gown
    elif attempt == 1:
        new_line = '{:>{}s} {:>{}s}'.format('O', offset1-1, '|', offset3+1)
        row = 2
    elif attempt == 2:
        new_line = '{:>{}s} {:>{}s}'.format('|', offset1-1, '|', offset3+1)
        row = 3
    elif attempt == 3:
        new_line = '{:>{}s} {:>{}s}'.format('/| ', offset1, '|', offset3)
        row = 3
    elif attempt == 4:
        new_line = '{:>{}s} {:>{}s}'.format('/|\\', offset1, '|', offset3)
        row = 3
    elif attempt == 5:
        new_line = '{:>{}s} {:>{}s}'.format('/  ', offset1, '|', offset3)
        row = 4
    elif attempt == 6:
        new_line = '{:>{}s} {:>{}s}'.format('/ \\', offset1, '|', offset3)
        row = 4
    else:
        raise Exception("Ops! The number of attempts must be an integer from 0 to 6.")
    gown[row] = new_line
    return gown

def print_gown(gown):
    for line in gown:
        print line

if __name__ == '__main__':
    gown = create_gown(10, 7)
    print len(gown)
    for i in range(7):
        gown = wrong_answer(gown, i)
        print_gown(gown)


texts: find if a number divisible by the input numbers

texts:
Given two numbers a and b, we have to find the nth number which is
  divisible by a or b.

  The format looks like below:

  Input: First line consists of an integer T, denoting the number of test cases. Second line contains three integers a, b and N

  Output: For each test case, print the Nth number in a new line.

  Constraints:

  1≤t≤105

  1≤a,b≤104

  1≤N≤10

  Sample Input

1

2 3 10

  Sample Output

15

  Explanation

  The numbers which are divisible by 2 or 3 are: 2,3,4,6,8,9,10,12,14,15
  and the 10th number is 15.

For single test case input 2000 3000 100000 it is taking more than one second to complete. I want to know if I can get the results in less than 1 second. Is there a time efficient approach to this problem, maybe if we can use some data structure and algorithms here?

test_case=input()

if int(test_case)<=100000 and  int(test_case)>=1:
    for p in range(int(test_case)):
        count=1
        j=1

        inp=list(map(int,input().strip('').split()))
        if inp[0]<=10000 and  inp[0]>=1 and  inp[1]<=10000 and  inp[1]>=1 and inp[1]<=1000000000 and  inp[1]>=1:
            while(True ):
             if count<=inp[2] :
               k=j
               if j%inp[0]==0 or j%inp[1] ==0:
                   count=count+1
                   j=j+1

               else       :
                   j=j+1
             else:
                 break
            print(k)
        else:
            break


texts:
I'm new to Python and I am learning database connections from here.

This is the code I am using to insert e-mail subscribers into a table:

conn = mysql.connector.connect(user="user", password="password", host="127.0.0.1", database="db")
cursor = conn.cursor()
query = ("INSERT INTO test(name,email) VALUES(%s,%s)")
data = ("cool", "cool")
cursor.execute(query, data)
conn.commit()
cursor.close()
conn.close()

Is this type of data insertion safe and can stop SQL injections?


texts: Pull, Tag, Save, Delete Multiple Docker Containers

texts:
First time posting and first real Python program that I use fairly frequently. I needed a way to pull a large amount of containers, re-tag them, save them (docker save) and clean up the recently pulled containers.

I did this pretty easily with bash, though depending on the container and depending how many containers I quickly did not like how slow it was and wanted a way to do it faster.

I am looking to make any improvements possible, it works, and it works well (at least I think). I tend to always come across more Pythonic ways to do things and would love the additional feedback.

Couple things that I am currently tracking:

I need docstrings (I know, small program, but I want to learn to do it
right)
I tossed in the if __name__ == "__main__":, and if I am being honest, I am not confident I did that right.
I know, I am terrible at naming functions and variables :(

#!/usr/bin/env python3

import sys
import os
from os import path
import concurrent.futures  # https://docs.python.org/3/library/concurrent.futures.html
import docker  # https://docker-py.readthedocs.io/en/stable/

cli = docker.APIClient(base_url="unix://var/run/docker.sock")
current_dir = os.getcwd()
repository = sys.argv[2]
tar_dir = os.path.join(current_dir, "move")

if path.exists(tar_dir) is not True:
    os.mkdir(tar_dir)

def the_whole_shebang(image):
    img_t = image.split(":")
    img = img_t[0].strip()
    t = img_t[1].strip()
    image = f"{img}:{t}"

    print(f"Pulling, retagging, saving and rmi'ing: {image}")
    # Pulls the container
    cli.pull(image)
    # Tags the container with the new tag
    cli.tag(image, f"{repository}/{img}", t)

    new_image_name = f"{img}{t}.tar"
    im = cli.get_image(image)
    with open(os.path.join(tar_dir, new_image_name), "wb+") as f:
        for chunk in im:
            f.write(chunk)

    # Deletes all downloaded images
    cli.remove_image(image)
    cli.remove_image(f"{repository}/{image}")

if __name__ == "__main__":
    with concurrent.futures.ProcessPoolExecutor() as executor:
        f = open(sys.argv[1], "r")
        lines = f.readlines()
        executor.map(the_whole_shebang, lines)

Anyways, I assume there are many things that I can do better, I would love to have any input so that I can improve and learn.

Thank you!


texts: Wheel based unbounded sieve of Eratosthenes in Python

texts:
Answering this SO question recently, I've developed the following code (based on a well-known Active Code recipe, as discussed here):

wheel = [2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,
         4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10]
wsize = 48

def primes():
    yield from (2, 3, 5, 7)
    yield from wsieve()

def wsieve():       # wheel-sieve, by Will Ness. cf. ideone.com/WFv4f
    yield 11        # cf. https://stackoverflow.com/a/10733621/849891
    mults = {}      #     https://stackoverflow.com/a/19391111/849891
    ps = wsieve()
    p = next(ps)
    psq, c, i = p*p, 11, 0                   # 13 = 11 + wheel[0]
    cbase, ibase = 11, 0
    while True:
        c += wheel[i] ; i = (i+1) % wsize    # 17 = 13 + wheel[1]
        if c in mults:
            (j,pbase) = mults.pop(c)         # add(mults, NEXT c, j, pbase)
        elif c < psq:
            yield c ; continue
        else:          # (c==psq)
            while not cbase == p:
                cbase += wheel[ibase]
                ibase = (ibase+1) % wsize    # ibase - initial offset into wheel, for p
            j, pbase = ibase, p              # add(mults, NEXT c, ibase, p)
            p = next(ps) ; psq = p*p
        m = c + pbase*wheel[j] ; j = (j+1) % wsize    # mults(p) = map (*p)
        while m in mults:                             #              roll(wheel,ibase,p)
            m += pbase*wheel[j] ; j = (j+1) % wsize
        mults[m] = (j,pbase)

Comparing its performance on ideone with its odds-based predecessor reveals it runs about 1.5x faster. Empirical complexity seems okay (~ n1.1, for n primes produced).

Theoretically, it's supposed to be 1 / (2/3 * 4/5 * 6/7) = 2.1875x times faster, if I'm not mistaken (indeed, taking ratio of circumference over number of teeth, (210/48) / (2/1) = 2.1875).  But it is slower than that.

Is this just because of the increased code complexity? Is there a way to make it run faster, without changing it drastically? Improve it in some other sense, or make it prettier/more pythonic without loosing performance? Will appreciate a review.

In particular, I have the rolled wheel streams inlined, using different variables for different "objects". It seems all over the place; is there a way to encapsulate it into a bona fide object, without loosing performance? (last time when I used functions for some encapsulation, efficiency suffered).


texts:
I'm in a class that is using C, and my instructor has unfortunately used gets() in sample code.

As this is obviously a heinous oversight, likely to cause undefined behavior and other various issues (only a little sarcasm), I decided to implement gets_s(), because it was a fun exercise and sometimes it's just not worth it to do full error checking with fgets() and you just want to truncate unexpectedly long lines.

I'm not concerned whether this fully implements gets_s() as specified in the C11 standard -- this is just supposed to be a drop-in replacement for gets() that doesn't overrun your buffer.

However, what is very important is that this function actually does what it advertises: it's safe and doesn't overrun the buffer.

This is my first time working in C (I usually use java or kotlin), and I appreciate all tips, though I'd like at least some mention of the safety of this code, and am also interested in portability (to current compilers).

gets_s.h

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

#define GETS_S_OK 0
#define GETS_S_ERROR 1
#define GETS_S_OVERRUN 2

static inline int gets_s( char str[], int n )
{
  char *str_end, *fgets_return;
  int temp;

  fgets_return = fgets( str, n, stdin );

  /* If fgets fails, it returns NULL.
  This includes the case where stdin is exhausted. */
  if ( fgets_return == NULL )
  {
    str[0] = '\0';
    return GETS_S_ERROR;
  }

  str_end = str + strlen(str) - 1;

  if ( str_end == '\n' )
  {
    *str_end = '\0';
    return GETS_S_OK;
  }

  temp = fgetc( stdin );
  if (temp == EOF || temp = '\n')
    return GETS_S_OK;

  do temp = fgetc( stdin );
  while ( temp != EOF && temp != '\n' );

  return GETS_S_OVERRUN;
}

and a small test file:

gets_s.c

#include "gets_s.h"
#include <stdio.h>

int main()
{
  char buffer[10];
  int gets_s_return;

  printf("Enter up to %d characters safely.\n", sizeof(buffer) - 1);

  gets_s_return = gets_s( buffer, sizeof(buffer) );

  printf("buffer = %s", buffer);
  printf("gets_s return = %d", gets_s_return);

  return 0;
}

It compiles successfully with gcc -Wall -Wextra -Wpedantic -Werror gets_s.c, so that's a plus.


texts: Best practice to change item based on RoomDB value before inserting it using Kotlin

texts:
In my App i use Room database and i have three tables where two of them are connected.
The app just save the user input and insert it in the database. The user actually just insert as input a code and quantity but before inserting that value in my table i have to check if there is in another table (items get from an API) there is yet an item with that code and if it exist i have to set the description to the item the user is inserting from the item in another table get from the API.
Which practice would be the best to do so?
The tables of items get from the API are two:
one with the main item and the code and another that contains all secondary codes which belong to that item, so i have to check if the insert code is in the secondary code table and get it's primary, while if it's not i have to check if it's a primary code or if it's not i just add it without description.
My code looks like this (i have added all comments which specify what i'm doing)
ArticoliDAO.kt
@Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(articolo: Articolo)

    @Update
    suspend fun update(articolo: Articolo)

    @Query("SELECT * FROM articoli_letti_table WHERE barcode = :key")
    suspend fun get(key: String): Articolo?

    @Query("UPDATE articoli_letti_table SET qta = qta + :qta WHERE barcode = :barcode")
    suspend fun updateQuantity(qta: Float, barcode: String)

    // Inserting the item if not exist in the table, else i'm updagint the quantity
    suspend fun insertOrUpdate(articolo: Articolo) {
        // here i check if the item exist in the table with items synched from my API
        val prodotto = selectProdotto(articolo.barcode)
        // if the item exist i update the description of the item the user is adding
        // and i'm also multiply the quantity by default item quantity
        if (prodotto != null) {
            articolo.desc = prodotto.desc
            articolo.qta = articolo.qta * prodotto.qta
        }
        // here i check if the item has been yet added
        val itemFromDB = get(articolo.barcode)
        if (itemFromDB == null) {
            // adding the item if it's new
            insert(articolo)
        }else {
            // else i sum the quantity of the old item with the new one
            updateQuantity(articolo.qta, articolo.barcode)
        }
    }

    @Query("SELECT codart FROM barcode_prodotti_table WHERE barcode = :barcode")
    suspend fun getCodart(barcode: String): String?

    @Query("SELECT * FROM prodotti_table WHERE codart = :barcode")
    suspend fun getProdotto(barcode: String): Prodotto?

    suspend fun selectProdotto(barcode: String): Prodotto? {
        // here i check if the code insert by user exist in my barcode_table
        // barcode_table contains all secondary codes of an item
        val codart = getCodart(barcode)
        return if (codart.isNullOrEmpty()) {
            // if the secondary code doesn't exist i check if it's the primary code of the item and get it's object
            getProdotto(barcode)
        }else {
            // else i get the item object by setting the primary code in the SELECT get previously or return null
            val prodotto = getProdotto(codart)
            prodotto
        }
    }

My code is working but i would know if it's okay to do so for the performance and if i could improve the code somewhere


texts:
In web api controller:
I am a newer in parallel and Async&Task programming. Need someone help me code review.

public async Task<IHttpActionResult> DoWork()
{
    List<string> listTask = await Helper.GetBlockBlock();
    userIds = listTask;
    this.ParallelTaskWork();//step 1,must be finished,but I an not sure when..
    await this.Service.GetAllClientInterestInfoList();//executing after step 1
    return this.Ok();
}
public async void ParallelTaskWork()
{
    Task[] taskList = this.TaskMaker(totalNum);
}
public Task[] TaskMaker(int threadNum)
{
    Task[] taskList = new Task[threadNum];
    Parallel.For(0, taskList.Length, i => taskList[i] = new Task(this.ProcessDealTask));
    Parallel.ForEach(taskList, t => t.Start());
    return taskList;
}
private void ProcessDealTask()
{
    for (int i = 0; i < totalNum; i++)
    {
        List<string> users = this.GetPartitionOfList(userIds, i, totalNum);
        Task task = this.ParallelDealUserList(users);
        task.Wait();
    }
}
private List<T> GetPartitionOfList<T>(List<T> userList, int index, int total)
{
    int section = (userList.Count / total) + 1;
    int end = (index + 1) * section > userList.Count ? userList.Count - index * section : section;
    if (end < 0) end = 0;
        int start = index * section < userList.Count ? index * section : userList.Count - 1;
    if (start < 0) start = 0;
        return userList.GetRange(start, end);
}
private async Task ParallelDealUserList(IEnumerable<string> list)
{
    await Task.Run(() => Parallel.ForEach(list, async (id, loopState) =>
    {
        try
        {
            await GrainClient.GrainFactory.GetGrain<IUser>(id.ToGuid()).DoProcessInterestAsync(true);
        }
        catch (Exception e)
        {
        }
    }));
}

Any performance problem? The method ParallelDealUserList I refer to https://stackoverflow.com/questions/19102966/parallel-foreach-vs-task-run-and-task-whenall
somebody said

  there is a disadvantage to use Task.Run in a loop- With
  Parallel.ForEach, there is a Partitioner which gets created to avoid
  making more tasks than necessary

and  The method TaskMaker
https://stackoverflow.com/questions/22988630/parallel-for-w-action-that-creates-different-tasks-c-sharp


texts: PHPSpec, testing code that uses fluent mock

texts:
I've just completed writing a spec for a Doctrine2 repository. The repo contains only one method so far, the spec for which takes in an OAuth Identity token object (that contains an ID that matches up with a database table in my system) and returns either NULL or a UserAccount entity.

Due to the fluent nature of Doctrine query building, my test seems quite verbose, and I have used a lot of lines in my test wiring the 'fluent' aspect of the Query api together.

Repository:

namespace Users\Repository;

use Users\Entity\UserAccount;
use ZF\MvcAuth\Identity;

class UserAccountRepository extends \Doctrine\ORM\EntityRepository
{
    public function getFromIdentity(Identity\IdentityInterface $identity)
    {
        if ($identity instanceof Identity\GuestIdentity) {
            return null;
        }

        if (!$identity instanceof Identity\AuthenticatedIdentity) {
            return null;
        }

        /** @var $identity Identity\AuthenticatedIdentity */
        $id = $identity->getRoleId();

        if (!is_int($id)) {
            return null;
        }

        return $this->createNamedQuery('u')
            ->where('u.id = :id')
            ->setParameter(':id', $id)
            ->getQuery()
            ->getResult();
    }
}

Spec:

/**
 * @mixin \Users\Repository\UserAccountRepository
 */
class UserAccountRepositorySpec extends ObjectBehavior
{
    function let(
        ORM\EntityManager $em,
        ORM\Mapping\ClassMetadata $classMetadata
    )
    {
        $this->beConstructedWith($em, $classMetadata);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Users\Repository\UserAccountRepository');
    }

    function it_get_a_user_account_from_an_identity(
        ORM\EntityManager $em,
        Identity $identity,
        TestQuery $query
    )
    {
        $identity->getRoleId()->willReturn(4);

        $em->createQuery(Argument::any())->willReturn($query);
        $query->where('u.id = :id')->willReturn($query);
        $query->setParameter(':id', 4)->willReturn($query);
        $query->getQuery(Argument::any())->willReturn($query);
        $query->getResult(Argument::any())->shouldBeCalled();

        $this->getFromIdentity($identity);
    }

    function it_should_always_return_null_when_passed_a_guest_identity(
        GuestIdentity $identity
    )
    {
        $this->getFromIdentity($identity)->shouldBeNull();
    }
}

/** concrete mock due to ORM\Query being final */
class TestQuery extends ORM\AbstractQuery
{
    public function getSql(){}
    public function _doExecute(){}
    public function where(){}
    public function getQuery(){}
}


texts: Creating and finding posts using Parse.com

texts:
The following code calls Parse. And uses its API to create two functions: post.create and post.find. As the names imply, one is for creating posts and the other for fetching them.

Example:

import Parse from 'parse'

Parse.initialize('APP_ID', 'CLIENT_KEY')

const post = {}

post.create = json => {
  const Post = Parse.Object.extend('Post')
  const post = new Post()
  post.save(json).then(object => {
    console.log('yay! it worked', object)
  })
}

post.find = () => {
  const query = new Parse.Query(Post)
  let arr = []
  query.find({
    success: function (results) {
      results.forEach(function (result) {
        arr.push(result.toJSON())
      })
    },
    error: function (error) {
      alert('Error: ' + error.code + ' ' + error.message)
    }
  })
  return arr
}

export default post

As you can see, const Post = Parse.Object.extend('Post') is being written twice. I could just declare it once at the top of the file, on the other hand, they would be farther from the place they are used.

What's the conventional option here?


texts: Implementing bounds-checking with exceptions based on an existing bitset container

texts:
BitPat here is a wrapper around a bitset.

class BitPat
{
private:
    boost::dynamic_bitset<> data;
public:
    bool BitPat::operator[](size_t coord) const
    {
        if(coord < length)
            return data[coord];
        else
            throw std::out_of_range(std::string("Pattern coord out of range")
                + " (" + std::to_string(coord%_width) + ", " + std::to_string(coord/_width) + ") "
                + "[" + std::to_string(coord) + "]");
    }

    // vs:

    bool BitPat::operator[](size_t coord) const
    {
        if(coord >= _length){
            throw std::out_of_range(std::string("Pattern coord out of range")
                + " (" + std::to_string(coord%_width) + ", " + std::to_string(coord/_width) + ") "
                + "[" + std::to_string(coord) + "]");
        }
        return data[coord];
    }
};

I have additional getters and setters where I'd implement bounds-checking like this. It generates a lot of boilerplate code though.
As a first step maybe I should define some little formatting functions, but most importantly I'm curious which version of the if statements is more conventional.
Not sure if omitting return statements like in the first case is good practice either.


texts:
I'm trying to solve the sorting problem but I always get TLE(Time Limit Exceeded/ 1s) so... can you guys suggest a more efficient way to solve this problem?
(i can't link the exercise because it is on the closed server)
code reads test count t , <int, string>   pairs then sorts by integer in ascending order and prints median
#include <bits/stdc++.h>
using namespace std;
 int main(int argc, char *argv[]) {
   vector< pair <int,string> > median;
   int t;  cin >> t;
   int num; string name;
   for(int i=0;i<t;i++) {
     cin>>name; cin>>num;
     median.push_back( make_pair(num,name));
   }
  sort(median.begin(), median.end());

    if(t%2!=0){
      cout << median[t/2].second << " " << median[t/2+1].first << endl;
    }else{
      cout << median[t/2-1].second << " " << median[t/2+1].first << endl;
      cout << median[t/2].second << " " << median[t/2+1].first << endl;

        }
 }

input:
Gilbert 35
Anna 35
Anna 15
Mary 15
Joseph 40

output:
Anna 35


texts: Raku multiplication using prompt and say

texts:
I have extensively consulted Raku documentation and have tried many combinations to finally arrive at this working solution.
#!/usr/bin/perl6
use v6;

my $a;
my $b = 34;
my $c;
$a = prompt "enter number: ";
$c = ($a * $b);
say  "$a multiplied by  $b is $c";


texts:
This is a registration and login script I have made in Python 3. It uses a MySQL database. In the future I might use it with my Blackjack game and add a row called money, but for now I would like to hear your opinion about this script since I have little to no experience in SQL.

import cymysql
from getpass import getpass

def get_user_info():
    while True:
        email = input("Input your Email address (max. 64 chars.): ")
        password = getpass("Input a password (max. 64 chars.): ")
        if len(email) < 64 and len(password) < 64:
            return email, password

def register(cur, email, password):
    cur.execute("INSERT INTO `users` (`Email`, `Password`) VALUES (%s, %s)", (email, password))
    print("You've succesfully registered!")

def login(cur, email, password):
    cur.execute("SELECT * FROM `users` WHERE `Email`=%s AND `Password`=%s LIMIT 1", (email, password))
    rows = cur.fetchall()
    if rows:
        print("You've succesfully logged-in!")
    else:
        print("You failed logging-in!")

def check_account(cur, email):
    cur.execute("SELECT * FROM `users` WHERE `Email`=%s LIMIT 1", (email,))
    row = cur.fetchone()
    return row

def main():
    conn = cymysql.connect(
        host='127.0.0.1',
        user='root',
        passwd='',
        db='david'
    )
    cur = conn.cursor()
    email = ''
    password = ''
    email, password = get_user_info()
    check = check_account(cur, email)
    if check:
        login(cur, email, password)
    else:
        register(cur, email, password)
    cur.close()
    conn.close()

if __name__ == '__main__':
    main()


texts: PHP framework building: System Class (reads configuration .ini file)

texts:
I am building a PHP framework and would like to get some feedback on a few different sections of the project so far. I consider myself still a neophyte in PHP so I would like to ask if I'm going about completing these different tasks in an efficient and or correct way.

This section is of the system configuration file (.ini). Similar PHP core configuration file it is meant to hold values used through out the framework; for instance default MySQL database connection values. The class also can define values of and array as constants. The reason for creating the feature was to combine values used through out the framework in one place in a familiar format.

I have posted the System class, ini file and script to show how it is used.

System Class

class System{
    //Path to core.ini file
    private $inipath = 'core.ini';
    private $inifile;
    protected $parseini;
    private $arrvalue;

    //Instantiation
    public function __construct(){
        //Path to core.ini file
        $this->inifile = $this->inipath;
        //Parse the ini file
        $this->parseini = $this->ParseINI();
    }
    /**
     * Parse system configuration file
     * @param void
     * @return Array - multidimensional array
     */
    public function ParseINI(){
        //Path to core.ini file
        //Moved to the method because construct
        //is not used
        if(!file_exists($this->inifile)){
            trigger_error("System file not found",E_USER_ERROR);
        }
        return parse_ini_file($this->inifile,true);
    }

    public function GetValue($value = null){
      if(!empty($this->parseini) && isset($value)){
        return $this->parseini[$this->arrvalue][$value];
      }
      return $this->parseini[$this->arrvalue];
    }

    public function SetValue($value){
        $this->arrvalue = $value;
    }

    public function DefineINI(){
        if(isset($this->arrvalue)){
            foreach ($this->GetValue() as $key => $value) {
                define(strtoupper($key),$value);
            }
        }
    }

    //End Scope
    public function __destruct(){
        //Empty
    }
}

core.ini file

[system_paths]
DIRECT_URL = "http://localhost/fw/";
ROOTDIR = "root/";
FILESDIR = "root/files/";

;System database connection parameters
;Used for interaction with the systems database
[sys_db]
host = "localhost";
user = "root";
password = "password";
database = "fwsystemdb";

;Default connection parameters
[database_connection]
db_host = "localhost";
db_user = "root";
db_password = "passowrd";
db_database = "dummy";

;Session settings
[session_settings]
session_localsave = false;
session_dir = "http://localhost/fw/root/sessions";

;Error Loggin
[error_log]
log_activity = false;
log_file = "http://localhost/fw/root/systemlog";

Script using System Class

$system = new System();
//Set array [system_paths] to search for value
$system->SetValue('system_paths');
//Get valuse DIRECT_PATH from file
echo $system->GetValue('DIRECT_URL ');
//Define array values as constant
$system->DefineINI('system_paths');

Any feedback would be appreciated.


texts:
how can I optimalize this code?

#include<bits/stdc++.h>
using namespace std;

class Graph {
    int V;
    list<int> *adj;
    void DFSUtil(int v, bool visited[]);
public:
    Graph(int V);
    void addEdge(int v, int w);
    void DFS(int v);
};

Graph::Graph(int V) {
    this->V = V;
    adj = new list<int>[V];
}

void Graph::addEdge(int v, int w) {
    adj[v].push_back(w);
}

void Graph::DFSUtil(int v, bool visited[]) {
    visited[v] = true;
    cout << v << " ";

    list<int>::iterator i;
    for (i = adj[v].begin(); i != adj[v].end(); ++i)
        if (!visited[*i])
            DFSUtil(*i, visited);
}

void Graph::DFS(int v) {
    bool *visited = new bool[V];
    for (int i = 0; i < V; i++)
        visited[i] = false;
    DFSUtil(v, visited);
}

int main() {
    Graph g(4);
    g.addEdge(0, 1);
    g.addEdge(0, 2);
    g.addEdge(1, 2);
    g.addEdge(2, 0);
    g.addEdge(2, 3);
    g.addEdge(3, 3);

    for (int i = 0; i < 4; i++) {
        g.DFS(i);
        puts("");
    }
    return 0;
}

I mean, for now I calculate path for each vertex all over again. Well, it's very inefficient for many vertex, so my answer is: How can I rebuild this code such that I don't must calculate from zero


texts:
I am a C# developer learning F#. Would appreciate any suggestions on how this code can be improved. Main points I am interested in:

Functional style of the code, absense of imperative style(C#) artifacts
F# collection data types and functions usage
General code(not algorithm) efficiency
Code style, naming etc.

let life board =
    let flatten = Seq.cast<int> >> Seq.toArray

    let neighboursCount (board: int[,]) x y =
        board.[y..y+2, x..x+2]
        |> flatten
        |> Array.mapi (fun i el -> (i <> 4, el))
        |> Array.filter fst |> Array.map snd
        |> Array.filter ((=) 1) |> Array.length

    let expandBoard board =
        let N = Array2D.length1 board
        array2D [|
            yield                        [| yield board.[N - 1, N - 1]; yield! board.[N - 1, *]; yield board.[N - 1, 0] |]
            for i in [0..N - 1] do yield [| yield board.[i,     N - 1]; yield! board.[i,     *]; yield board.[i,     0] |]
            yield                        [| yield board.[0,     N - 1]; yield! board.[0,     *]; yield board.[N - 1, 0] |]
        |]

    let getNextBoard board =
        let eBoard = expandBoard board
        board |> Array2D.mapi (fun i j elem ->
            match neighboursCount eBoard j i with
            | 2 -> elem
            | 3 -> 1
            | _ -> 0)

    let isGameOver board prevBoards =
        board |> flatten |> Array.forall ((=) 0) || List.contains board prevBoards

    let rec lifeRec board prevBoards =
        printfn "%A \n" board
        if isGameOver board prevBoards
        then ()
        else getNextBoard board |> lifeRec <| board::prevBoards

    lifeRec board []

let N = 5
let rnd = System.Random()
Array2D.init N N (fun _ _ -> rnd.Next 2) |> life


texts:
I am practicing for technical interviews and I am encountering a lot of problems relating to the tree data structure. I have gone through other posts that discuss about the tree data structure and come up with the class definition and method signatures for the some of the operations as below:

class Tree {
    struct Node {
        int data;
        Node *left;
        Node *right;
        Node(int d): data(d), left(nullptr), right(nullptr) {}
    };
    Node *root_;
    Tree(Node *r): root_(r) {};
public:
    Tree(): root_(nullptr) {};
    ~Tree();
    void deserializeTree(std::string serializedTree);
    Tree::Node* deserializeTreeHelper(Tree::Node *root, std::string serializedTree, int *start);
    void printTreeHelper(Node *root);
    void printTree();
    void mirrorTree();
};

Since a lot of operations related to trees can be modeled as recursive functions, with my above class definition, I seem to end up having a method that can be invoked on the tree object and another helper method that does the recursive operation.

My reasoning in having a helper method is because recursive tree operations like the one below needs to return the root of a sub tree and root is of type Tree::Node which is private to the Tree. Hence I can't have the parent method (the method that invokes the recursive helper method) returning Tree::Node.

void
Tree::deserializeTree(std::string serializedTree) {
    if (serializedTree.length() <= 0 || serializedTree.substr(0, 1) == std::string("#"))
        return;
    int start = 0;
    root_ = deserializeTreeHelper(root_, serializedTree, &start);
}

Tree::Node*
Tree::deserializeTreeHelper(Node *root, std::string serializedTree, int *start) {
    if (*start == serializedTree.length()) return nullptr;
    if (serializedTree.substr(*start, 1) == "#") *start = *start + 2;
    if (*start >= serializedTree.length()) return nullptr;

    std::stringstream ss; ss << serializedTree.substr(*start, 1);
    int data; ss >> data;
    root = new Node(data);
    *start = *start + 1;
    root->left = deserializeTreeHelper(root->left, serializedTree, start);
    root->right = deserializeTreeHelper(root->right, serializedTree, start);
    return root;
}

I want to know if having this kind of operation-operationHelper method combination a good design or is there a better way to design the methods?


texts:
I usually like to use entr when developing on my own hardware to run commands when a directory changes.
However, sometimes I'm working in an environment where I don't have much control over the availability of helpful programs so many of us take for granted.
I've been using Git Bash on Windows, and I've been getting tired of hunting down my build terminal, pressing up in my last history to get to the build command, and hitting enter to build my project. I want it to automatically run when I save a new change. But I don't have entr or any of the other usual suspects (like inotifywait) to assist me.
So to overcome this problem, with a bit of Internet searching to assist, I wrote a Bash function to watch the src/ directory and build the project when anything in the directory changes (including timestamps, because -l):
monitor_and_build () {
  local sauce=$(ls -l $1)
  while [ true ] ;
  do
    sleep 1
    local newsauce=$(ls -l $1)
    if [[ "$sauce" != "$newsauce" ]]; then
      make
    fi
    local sauce="$newsauce"
  done
}

to be invoked:
$ monitor_and_build src/

I have a working directory Makefile that calls make -C src/.
Since I did it in such an ad-hoc way, I'm sure I missed a trick or there's some edge cases this has a problem with. Please review!
Bonus question: aside from the obvious "writing your own programs in Bash is error-prone and foolish" (I admit it took me a few drafts to get it working) - suppose I had entr available, and then what are the benefits of using a program like entr instead?


texts: Handling Java instant Ajax request/respond with Angular

texts:
I am trying to build a food search app. I am using Angular and Spring. I am currently using the yelp API, but it's done on the Java side.

I think what I have achieved is really bad design. It works, but the data is not always updated correctly.

For Java, I created two methods and one string variable:

private String response;

@RequestMapping(value = "/searchRestaurant", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public void searchRestaurantWithYelp(@RequestBody String jsonData) {

    //here i process the json string and pass the values to yelp function,
    // then yelp sends the respond as a json string, i assigned the value
    // to the response variable.
    response = queryYelp();
}

As you can see, this post request receive a json string from client side, and pass the string to the yelp java API I created. The yelp respond is a json string, and I assign it to the response variable.

I also created a GET method, which simply returns the response, which contains the data yelp returned. I want to immediately return this data to the client/browser, with angular.

@RequestMapping(value = "restaurantResult", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String returnRestaurantSearchResultWithYelp() {
    return response;
}

Now for my JS/angular side of code:

function HomeCtrl($scope, $http) {
    $scope.term = "";
    $scope.location = "";
    $scope.submitSearch = function () {
        var data = {
            term: $scope.term,
            location: $scope.location
        }; //end data
        var res = $http.post('/searchRestaurant', data);
        $http.get('/restaurantResult').
              success(function (data) {
        $scope.response = data;
        });
    }
 }

I wrapped a $http.get inside the $http.post. This function first sends data, which invoke my Java post method, then retrieves the data right after. I am binding the json data with angular so my app is single page. And with angular two way data binding the {{response}} contains the yelp response and will display instantly to the user.

My simplified HTML:

 <input type="text" ng-model="term"/>
 <input type="text" ng-model="location"/>
 <button ng-click="submitSearch()">Search</button>

 {{response}}

It works, sort of. But I feel there is a better way to do it.

The issue: The {{response}} sometimes cannot be updated instantly. For instance, I search burger king, the response will show me the address, location, etc. Then I type McDonalds, the response still shows the info of Burger King. I have to refresh the browser to get the latest and correct response.

I was wondering what the issue is causing the response not update instantly? Is it because of browser cache?

In terms of the my project build design, what part I did wrong? Is there a better way to handle this type of request?


texts:
Given a Binary Search Tree, determine its k-th  element in inorder traversal.

Here's my node structure:

struct node
{
    int elem;
    node *left, *right;

    static node* create(int elem)
    {
        node *newnode = new node;
        newnode->elem = elem;
        newnode->left = newnode->right = NULL;
        return newnode;
    }

        // Forget freeing up memory

};

Here's my BST:

class tree
{
  private:
  node *root;

  public:
  tree(int elem)    { root = node::create(elem); }

  bool insert(int elem)
  {
    node *newnode = node::create(elem);
    node *travnode = root;

    while(1)
    {
      if(elem &lt travnode->elem)
      {
        if(travnode-> left == NULL)
    {
      travnode->left = node::create(elem);
      return true;
    }
    else travnode = travnode->left;
      } // elem < travnode->elem
      else
      if(elem > travnode->elem)
      {

        if(travnode->right == NULL)
    {
      travnode->right = node::create(elem);
      return true;
    }
    else
          travnode = travnode->right;

      }
      else
         return false;
 }

  /*  findKthInorder
  @param mynode [in]     -- the root of tree whose kth largest is to be found
  @param k [in]          -- value k
  @param count [in]      -- a counter to keep track of which node we're in
  @param result [in,out] -- returns mynode->elem once we're in kth node
  */
  void findKthInorder(const node *mynode, const int k, int &count,  int &result) const
  {
    if(mynode != NULL)
    {
      findKthInorder(mynode->left,k,count,result);
      if(!--count)
      {
        result = mynode->elem;
    return;
      } // if (!--count)

      findKthInorder(mynode->right,k,count,result);
    } // if (mynode != NULL)
  } // findKthInorder

  /* findKthInorder
     abstracts away previous function and is exposed to outside world
  */
  int findKthInorder(const int k) const
  {
    int count = k,result = 0;
    findKthInorder(root,k,count,result);
    return result;

   }

}; // class tree

Here's some test code that I wrote:

int main()
{
   tree T = tree(5);
   T.insert(1); T.insert(7);   T.insert(-1);T.insert(6);

   for(int i = 1;i != 5; ++i)
       printf("%d, " T.findKthInorder(i)); // -1, 1,5,6,7
   return 0;
}

I'll be happy to listen to any suggestions for a more  elegant findKthInorder() function.


texts: A clean tacit version of (n choose k) in J

texts:
Listing all \$\binom{n}{k}\$ combinations of i is a well-solved problem in J. From that article, there is this implementation:

comb=: 4 : 0
 k=. i.>:d=.y-x
 z=. (d$<i.0 0),<i.1 0
 for. i.x do. z=. k ,.&.> ,&.>/\. >:&.> z end.
 ; z
)

used as follows:

   4 comb 6
0 1 2 3
0 1 2 4
0 1 2 5
0 1 3 4
0 1 3 5
0 1 4 5
0 2 3 4
0 2 3 5
0 2 4 5
0 3 4 5
1 2 3 4
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5

I am interested primarily in clean, tacit version. Here's what I have so far:

comb=. ~.@:(/:~"1)@(i.@[ {"1 (i.@! A. i.)@])

but that feels overly complex and verbose. Is there a better tacit implementation?


texts: Representing a long regular expression in a Polynomial class

texts:
I wrote a simple Polynomial class:

class Polynomial
  def initialize(coefficients)
    @coefficients = coefficients.reverse
  end

  def to_s
    return '0' if @coefficients.all?(&:zero?)
    @coefficients.map.with_index do |k, index|
      " #{Polynomial.sign(k)} #{k.abs}x^#{index}"
    end.reverse.join.strip          # removes whitespace at the front
    .gsub(/\A\+\s/, '')             # removes + if first coefficient is positive
    .gsub(/x\^0/, '')               # removes x to the power of 0
    .gsub(/\s(\+|-)\s0x\^\d/, '')   # removes 0 coefficients
    .gsub(/\s(\+|-)\s0/, '')        # removes 0 at the end of the expression
    .gsub(/\^1/, '')                # removes power of 1
    .gsub(/1x/, 'x')
  end

  def evaluate(x)
    @coefficients.map.with_index { |k, index| k * (x**index) }.reduce(0, :+)
  end

  private

  def self.sign(integer)
    integer >= 0 ? '+' : '-'
  end
end

There are a few things that bother me in the to_s method:

Is it bad that I wrote the short comments explaining what each gsub does? Bad in terms of "Would you do this in production code?".
Since all but one of the gsubs do the same, I could replace them with a single gsub, containing a long regexp with lots of ors (|):

.gsub(/\A\+\s|x\^0|\s(\+|-)\s0x\^\d|\s(\+|-)\s0|\^1/, '')

In that case though the regexp become quite unreadable. Which of the two is better?
Regarding the map.with_index part:

I use do/end, but than the chaining of methods on the end doesn't look good.
If I use curly braces on multiple lines, I break the convention curly braces for single-line blocks, do/end for multi-line blocks.
If I use curly braces with a single-line block, the line will be more than 80 characters long. So which of the three variants would you use?


texts:
Typeclassopedia presents the following exercise:

  Maybe can easily be made an instance of Applicative; writing such an instance is left as an exercise for the reader.

Here's my implementation:

data Option a = Some a
                | None deriving Show

instance Functor Option where
   fmap _ None     = None
   fmap f (Some x) = Some (f x)

instance Applicative Option where
   pure x                = Some x
   (Some f) <*> (Some x) = Some (f x)
   _ <*> _               = None

How does this look? In particular, I'm curious if the second line of the Applicative Option looks good.

Should I be using fmap on the right-hand side instead of Some (f x)?


texts: Hashing array of strings as Merkle tree in one function

texts:
I want to hash an array of strings into one hash as shown on scheme on the image below. But I do not want to implement some class based Merkle tree. It's just a simple function. Is this a good implementation or are there any possible improvements?

public static String hashStrings(@NotNull String [] strs)
{
    if (strs.length == 1) return hashString(strs[0]);

    List<String> hashes = new ArrayList<>();

    for (int i = 0; i < strs.length; i++)
    {
        hashes.add(hashString(strs[i]));
    }

    while(hashes.size() > 1)
    {
        int currentSize = hashes.size();
        int nextSize = currentSize % 2 == 0 ? currentSize / 2 : (currentSize + 1) / 2;

        for (int i = 0; i < currentSize - 1; i += 2)
        {
            hashes.set(i / 2, hashString(hashes.get(i) + hashes.get(i + 1)));
        }

        if (currentSize % 2 == 1)
        {
            hashes.set(nextSize - 1, hashString(hashes.get(currentSize - 1)));
        }

        hashes = hashes.subList(0, nextSize);
    }

    return hashes.get(0);
}


texts:
I have been writing a Simple Port scanner in C, once I got it to work I decided I wanted to make it faster because it takes a very long time for it to get done with scanning all of the ports.Is there anything I can improve on in my code to make it faster? Here is my Code :

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <time.h>
#define MAX 65536

int main(int argc, char ** argv)
{
    time_t begin, end;
    time(&begin);

    printf("Scanning ports 0 - 65535 for IP address : %s\n", argv[1]);

    FILE * file = fopen("/home/ether/Desktop/Projects/Ports_log.txt", "w");//open log file

    for (unsigned short port = 0; port < MAX; port++)//loop through and scan all ports
    {
        int Connection = socket(AF_INET,SOCK_STREAM, 0);
        sockaddr_in temp = { 0 };

        //fill the struct with information on the computer you wish to scan
        temp.sin_addr.s_addr = inet_addr(argv[1]);
        temp.sin_family = AF_INET;
        temp.sin_port = htons(port);

        int error = connect(Connection, (sockaddr*)&temp, sizeof temp);
        if(error != -1)
        {
            //if the port is open then get information about that port and print it to the log file
            char host[128];
            char service[128];
            getnameinfo((sockaddr*)&temp, sizeof temp, host, (sizeof host), service, sizeof service, 0);
            printf("Port : %d, Service : %s, Open\n", port, service);
            fprintf(file, "Port : %d, Service : %s, Open\n", port, service);
        }
        close(Connection); //Destroy socket
    }
    fclose(file);//Close the file

    //calculate the time that elapsed since the program was started and rint it
    time(&end);
    double elapsed_secs = difftime(end, begin);
    printf("Elapsed Seconds : %lf", elapsed_secs);
    return 0;
}


texts: Instantiating a Database connection class in PHP

texts:
I am building my own MVC and I have a couple questions about making a database connection and what is the best practice. I have a model User which interacts with the database and I wonder what is the best practice to instantiate the database connection class. Currently I made it so my User class extends the Database class because I don't feel like instantiating it in a constructor for example.

class User extends Database
{

    public function data($userid)
    {
        $getRow = $this->getConnect()->getRow("SELECT * FROM users WHERE userid = ?", [$userid]);

        return $getRow;
    }

}

And my Database class:

class Database
{

    private $dbh = NULL;
    private $instance = NULL;

    public function __construct($username = 'root', $password = '', $host = '127.0.0.1', $dbname = 'testdb', $options = [])
    {
        try  {
            $this->dbh = new PDO("mysql:dbname={$dbname};host={$host};charset=utf8", $username, $password);
            $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
        } catch (PDOException $ex) {
            throw new Exception($ex->getMessage());
        }

    }

    public function getConnect()
    {
        if($this->instance == NULL)
        {
            $this->instance = new self();
        }
        return $this->instance;
    }
}

Also, my getConnect method seems kinda hard coding. Do you think there is a smarter way to do this?

And one more thing, about public/private if anything is better to be private, I'd appreciate if you let me know.


texts: Make better solution for Bean counting example from "Eloquent JavaScript" book

texts:
How can this code be improved by "closuring" of functions here?

// Your code here.
let countBs = countChar();

function countChar(str, letter = 'B') {
  if (letter === 'B') return (str, letter = 'B') => String(str).split('').filter(ltr => ltr == letter).length;
  return String(str).split('').filter(ltr => ltr == letter).length;
}

console.log(countBs("BBC"));
// → 2
console.log(countChar("kakkerlak", "k"));
// → 4


texts:
I am aiming to implement a calculator in an object-oriented way.

Here is the solution by using the strategy pattern.

Looking forward to some valuable comments.

package oopdesign.calculator;

public class AdditionStrategy implements CalculationStrategy {

    @Override
    public int calculate(int value1, int value2) {
        return value1 + value2;
    }
}

package oopdesign.calculator;

public interface CalculationStrategy {

    int calculate(int value1, int value2);
}

package oopdesign.calculator;

public class Calculator {

    public static Calculator instance = null;

    CalculationStrategy calculationStrategy;

    public void setCalculationStrategy(CalculationStrategy calculationStrategy) {
        this.calculationStrategy = calculationStrategy;
    }

    public static Calculator getInstance(){
        if(instance == null){
            instance = new Calculator();
        }
        return instance;
    }

    public int calculate(int value1, int value2) {
       return calculationStrategy.calculate(value1, value2);
    }
}

package oopdesign.calculator;

public class CalculatorMain {

    public static void main(String[] args) {

        Calculator c = Calculator.getInstance();

        c.setCalculationStrategy(new AdditionStrategy());
        System.out.println(c.calculate(5 ,2));

        c.setCalculationStrategy(new SubtractionStrategy());
        System.out.println(c.calculate(5 ,2));

        c.setCalculationStrategy(new MultiplicationStrategy());
        System.out.println(c.calculate(5 ,2));

        c.setCalculationStrategy(new DivideStrategy());
        System.out.println(c.calculate(5 ,2));
    }
}

package oopdesign.calculator;

public class DivideStrategy implements CalculationStrategy {

    @Override
    public int calculate(int value1, int value2) {
        return value1 / value2;
    }
}

package oopdesign.calculator;

public class MultiplicationStrategy implements  CalculationStrategy{

    @Override
    public int calculate(int value1, int value2) {
        return value1 * value2;
    }
}

package oopdesign.calculator;

public class SubtractionStrategy implements CalculationStrategy {

    @Override
    public int calculate(int value1, int value2) {
        return value1 - value2;
    }
}


texts: Passing anonymous functions and getting variables from an outer scope

texts:
I'm doing something quite strange.  I'm trying to create a tiny system for creating templates inline in PHP, so that I can refactor by creating multiple templates in the original script, and eventually move the templates to separate scripts.

Here's the silly/basic template library that just calls an anonymous function that gets passed in after some HTML header stuff, and then calls a footer:

<?php
// System for using simple, native php templates.

// TODO: Put this in a namespace to keep it clean and separate.

function display_page_inline($templates, $options, $data){
    $title = @$options['title'];
    echo "<title>".$title."</title>";

    if(is_array($templates)){
        foreach($templates as $template_function){
            $template_function($data);
        }
    } else{
        $template($data); // Call & display the template.
    }

    echo "
Footer
";
    echo "";
}

?>

Here's where it's going to get strange.  In the scripts I'm creating anonymous functions, saved to variables, and then passing them to the template library for outputting.  To avoid having to call an array element (and check whether the element exists each time), I'm trying to export the array passed in to get standard variables in the template (e.g. $name instead of $data_array['name']).  Is there a way to abstract away this behavior in PHP?

<?php
require_once('core.php');

// Inclusion of the template library
require_once('../core/inline_templates.php');
// Initialization Logic
$title = 'Bob';

// Decide what will be able to be output and put it into an array to pass to the template
$template_output_variables = array('name'=>'no name');

// The page gets displayed at the bottom.

// =================== Templates ========================================
// Todo: Potentially namespace the stuff here.
// Define the anonymous template function here, has html and such in native php here.
$contact_us = function ($template_output_variables=null){
    extract($template_output_variables); // Pull the variables.
    // Leave php in the template function.
    ?>

    Hello World Body Text, Hello <?php h($name);?>.

    <?php
}; // End of template function declaration.

$killer_section = function ($data=null){
    extract($data); // Pull the variables.
    ?>
    Breaking news, There is a killer among us.

    <?php
}; // End of killer section anon. function.

// Display the page.

// call & display the template via delayed execution, display it within a pre-set head and footer.
display_page_inline($templates=array($contact_us, $killer_section), $options=array('title'=>$title), $template_output_variables);

?>

It's very strange, I know, but I'm trying to do a whole new approach to refactoring, and make use of some new PHP 5.3 features while doing it.  The goal is to have inline templates that I can put in any script, as many as I want, and move anywhere I want later, or merge the templates, etc.


texts:
In a user registration form, the validator currently checks not only user input, but also whether or not the user exists. This seems like business logic, which in terms of design should be in the service layer in a "save user" type method. On the other hand, it is highly convenient to keep it in the validator.

Should there be a non-input related check in the validator?

public void validate(Object target, Errors errors) {
    User user = (User) target;
    ValidationUtils.rejectIfEmpty(errors, "name", "name.required", "Error msg...");
    ValidationUtils.rejectIfEmpty(errors, "username", "username.required", "Error msg...");
    ValidationUtils.rejectIfEmpty(errors, "password", "password.required", "Error msg...");

    // check if user already exists
    String username = user.getUsername();
    if (username != null && userService.userExists(username)) {
        errors.rejectValue("username", "username.exists", "Username is taken.");
    }
}


texts: Storing temporary data in ETS - for example, using ETS in a web wizard

texts:
I'm learning the Elixir language and the Phoenix web framework. And I had an idea. What if, in a web wizard (multi-step form) scenario, I stored the intermediate data in a ETS table instead of the relational database?

So I wrote this controller:

defmodule PlayPhoenixWeb.ThingsController do
  use PlayPhoenixWeb, :controller
  require Logger
  @moduledoc false

  @form_ets :things_forms

  alias PlayPhoenixWeb.Router.Helpers, as: Routes
  alias PlayPhoenixWeb.Endpoint

  def step_1_display(conn, _params) do
    render(conn, "form_1.html")
  end

  def step_1_process(conn, params) do
    data = Map.take(params, ["name", "vcode"])
    key = make_key()
    write_data(key, data)
    Logger.debug inspect(data)
    redirect(conn, to: Routes.thing_form_2_path(Endpoint, :step_2_display, key))
  end

  def step_2_display(conn, %{"key" => key}) do
    render(conn, "form_2.html", key: key)
  end

  def step_2_process(conn, %{"key" => key} = params) do
    {:ok, data} = get_data(key)
    full_data = Map.take(params, ["description", "value"]) |> Map.merge(data)
    # In production, processing full data would happen here
    Logger.debug inspect(full_data)
    redirect(conn, to: Routes.page_path(Endpoint, :index))
  end

  # This method is called by the Application on startup
  def init_ets(), do: :ets.new(@form_ets, [:public, :named_table])

  defp make_key(), do: :crypto.hash(:md5, DateTime.utc_now() |> DateTime.to_iso8601) |> :base64.encode

  defp get_data(key) do
    case :ets.lookup(@form_ets, key) do
      [{^key, value}] -> {:ok, value}
      _ -> {:not_found}
    end
  end

  defp write_data(key, data) do
    :ets.insert(@form_ets, {key, data})
  end

  defp delete_data(key), do: :ets.delete(@form_ets, key)

end

(It's purely for the sake of playing/research, and currently doesn't store or process any data).

Is this the Elixir way/the Phoenix way?

Thank you very much.


texts:
I am a bit new to Python. This is my first code review, and I am excited to get a critique on how to make this (very simple) shift cipher more Pythonic, cleaner, and more organized.

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

def shift(offset):

    message = input("Input Message You Would Like Encrypted:\n")
    new_message = ''

    for letter in message:

        letter = letter.lower() #doesn't handle upper-case yet

        if letter.isalpha():
            shift_pos = alphabet.index(letter) + offset
            new_pos = alphabet[shift_pos]
            new_message += new_pos

        #these will not be shifted

        elif ' ' or '/t' or '/n' in letter:
            new_message += letter

        elif letter.isnumeric():
            new_message += letter

        else:
            print("An error took place in recording the message. Check input.\n")

    print(new_message)

shift(-1)


texts:
I have the following code which iterates over all pixels of an image and does some manipulations on two images of the same size. I would like to speed it up and to avoid iterating over the positions in a for loop:

import numpy as np
import cv2

# Two images of same size
image_in = cv2.imread('my_image.png')
image_in2 = cv2.imread('my_image2.png')
image_new = np.ones(image_in.shape[:2], dtype="uint8") * 255

counter = 0
counter2 = 0

for i in range(image_in.shape[0]):
    for j in range(image_in.shape[1]):
        if image_in[i, j] < 255:
            counter += 1
            if image_in2[i, j] == 0:
                image_new[i, j] = 0
            else:
                image_new[i, j] = 255
                counter2 += 1

How can I improve my code?