Generate new latitude and longitude in decimal I have created simple algorithm to generate the new Location from given latitude and longitude.

// How to use : first call SetupLocation(InputLat,InputLon float64) to set base latitude and longitude.
// To genreate the location you can call RandomLatLong() to generate using seconds degree.
// And RandomLatLongMinute to genereate new location using minute degree.
package location

import "math/rand"

var lat, lon float64

type LocationDegree struct {
    Degree  int
    Minutes int
    Seconds int
}

// setup base location for generating the new randon lat, lon value.
func SetupLocation(InputLat, InputLon float64) {
    lat = InputLat
    lon = InputLon
}

func ToDegree(location float64) LocationDegree {
    // get degree
    degree := int(location)
    location = location - float64(degree)

    // get minute
    multiply := location * 60.0
    minutes := int(multiply)
    location = multiply - float64(minutes)

    // get seconds
    multiply = location * 60
    seconds := int(multiply)

    // check if the decimal is 9 or 8 we are gointo round up
    location = multiply - float64(seconds)
    if location > 0.5 {
        seconds += 1
    }

    return LocationDegree{
        Degree:  degree,
        Minutes: minutes,
        Seconds: seconds,
    }

}

func ToDecimal(locationDegree LocationDegree) float64 {
    var result float64
    result = float64(locationDegree.Seconds) / 60.0

    result += float64(locationDegree.Minutes)

    result = result / 60.0

    result += float64(locationDegree.Degree)

    return result
}

// add seconds to lat or lon so we can get new location.
// we created array location so we can randomly select lat and lon to add new seconds degree.
// getting seconds value using pseu-do random from given seconds.
// returning latitude and longitude in order.
func RandomLatLong(seconds int) (float64, float64) {
    location := []float64{lat, lon}
    randomIndex := rand.Intn(len(location))

    randomSeconds := rand.Intn(seconds)

    // convert the lat or lon depends on random selection to degree
    degreeLocation := ToDegree(location[randomIndex])
    degreeLocation.Seconds += randomSeconds

    // convert the degree to decimal degree and replace it to the current index
    degreeDecimal := ToDecimal(degreeLocation)
    location[randomIndex] = degreeDecimal

    // return lat and lon in orner
    return location[0], location[1]
}

// add minute to lat or lon so we can get new location.
// we created array location so we can randomly select lat and lon to add new seconds degree.
// getting minute value using pseu-do random from given minute.
// returning latitude and longitude in order.
func RandomLatLongMinute(minute int) (float64, float64) {

    location := []float64{lat, lon}
    randomIndex := rand.Intn(len(location))

    randomMinute := rand.Intn(minute)

    // convert the lat or lon depends on random selection to degree
    degreeLocation := ToDegree(location[randomIndex])
    degreeLocation.Minutes += randomMinute

    // convert the degree to decimal degree and replace it to the current index
    degreeDecimal := ToDecimal(degreeLocation)
    location[randomIndex] = degreeDecimal

    // return lat and lon in orner
    return location[0], location[1]
}

I have created this during my spare time, and wanted to give it a try.
I know that this is not the best generated algorithm since it only add new random value to seconds or minutes and convert it to decimal again.

But I want to share this code and wanted to know if there are something that could be improved.

Source Code

Bugs
You have a couple of bugs in your code which will crop up occasionally. The first I noticed is this:

// check if the decimal is 9 or 8 we are gointo round up
location = multiply - float64(seconds)
if location > 0.5 {
    seconds += 1
}

There's two things in there, firstly, the comment is a lie ;-) The code does nothing with 8 or 9 decimals... it rounds "half-up".
The second issue is that the rounding is inaccurate if/when the location is something like 59.8, which your code will round-up to 60. This is a problem, because it should round up to 0, and the minutes should be increased (and, worse, if the minutes is 59, you need to round up the degrees... for example, rounding the value 8°59'59.8" should be 9° 0' 0" seconds - but your code gives 8° 59' 60")
Half-up rounding
There's an easy trick for half-up rounding when dealing with integer-casting in programs, the trick is to add a half-unit to the source value before doing any calculations, and then truncating the result as an integer. For example, to half-up round a float value n to an int, you do int(n + 0.5) You can use this in your code quite nicely.
I would also reverse the logic you have in your toDegrees function... convert everything to seconds (half-up rounded in int) and then extract the values from that. Note that you can express the location in total seconds, total minutes, and total degrees, and then get the "remainder" (modulo) to get just the incremental part:
func ToDegree(location float64) LocationDegree {
    // get the location in seconds, rounded up if needed
    seconds := int(location * 60.0 * 60.0 + 0.5)
    minutes := seconds / 60
    degrees := seconds / (60 * 60)

    return LocationDegree{
        Degree:  degree,
        Minutes: minutes % 60,
        Seconds: seconds % 60,
    }
}

Simplified ToDecimal
Similarly, for the ToDecimal function, I would keep most of the calculation in integer space... Your code is not to bad, but can be improved:

func ToDecimal(locationDegree LocationDegree) float64 {
    var result float64
    result = float64(locationDegree.Seconds) / 60.0

    result += float64(locationDegree.Minutes)

    result = result / 60.0

    result += float64(locationDegree.Degree)

    return result
}

I would have it like:
func ToDecimal(locationDegree LocationDegree) float64 {
    totalSeconds := locationDegree.Degree * 60 * 60
    totalSeconds += locationDegree.Minutes * 60
    totalSeconds += locationDegree.Seconds
    return float64(totalSeconds) / (60.0 * 60.0)
}

General issues
Your code relies on the global values lat and lon. These should be declared in a struct, and your methods should be on that struct:
type Position struct {
    Lat float64
    Lon float64
}

func (p Position) RandomLatLong(seconds int) (float64, float64) {
        location := []float64{p.Lat, p.Lon}
    ....
}

Random adjustments
Your code converts the float64 positions to °'" in order to add an adjustment of minutes and seconds. There is no need to do that. Just have the adjustment in the format of a float64 and apply it directly. For example, for the seconds, have:
randomSeconds := float64(rand.Intn(seconds))

and for the minutes have:
randomMinutes := float64(rand.Intn(minutes)) * 60.0

Now you can add those directly to the value


Find the product of digits at odd/even places The 'score' of a race is given.

We have to calculate the 'bonus points' to be given to the participant.

The 'bonus points' are dependent on the relation between product of digits at even places and product of digits at odd places.

So essentially I have to find the product of digits at even and odd places.

I first counted the number of digits in 'score' and then went on storing the product of digits in odd/even places in separate integers reducing one digit at a time

Code in Java

import java.util.Scanner;

class BonusPoints {
    public static int countDigits(int dist) {
        int counter=0;
        while (dist>0) {
            dist /= 10;
            counter++;
        }
        return counter;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int dist = sc.nextInt();
        int bonus=0;
        int prodOdd = 1;
        int prodEven = 1;
        int currDigit = 0;

        if (dist < 0) {
            System.out.printf("Invalid Input ");
            System.exit(0);
        }

        int counter = countDigits(dist);
        int lol = counter;
        //System.out.println("Number of Digits are " + counter);

        for (int i = 0; i < lol; i++) {

            //System.out.println("Current Dist " + dist);

            currDigit = dist % 10;
            //System.out.println("Current Digit " + currDigit);

            if (counter % 2 == 0){
                prodEven *= currDigit;
                //System.out.println("Current ProdEven "+prodEven);
            }
            else {
                prodOdd *= currDigit;
                //System.out.println("Current ProdOdd " +prodEven);
            }

            dist /= 10;
            counter--;
        }

        if (prodOdd == prodEven)
            bonus = 2 * prodOdd;
        else
            bonus = prodOdd > prodEven ? prodOdd : prodEven;

        System.out.println("The bonus is "+bonus);
    }
}

Those comments were used for debugging process while writing the code

Is there a better method to do this and what are changes that one can make to this code to optimize it?

Program structure

Separate I/O from the calculation and keep the main function short:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int dist = sc.nextInt();
    if (dist < 0) {
        // ... report error and terminate  program.

    }

    int bonus = calculateBonus(dist);
    System.out.println("The bonus is " + bonus);
}

That makes the program structure clearer, makes the functions reusable, and allows to add test cases easily.

Handle invalid input

By convention, error messages are written to the standard error output, and a nonzero exit code indicates an abnormal program termination. Instead of "Invalid Input" I suggest to print a message indicating the correct usage:

if (dist < 0) {
    System.err.printf("Input must be a non-negative integer.");
    System.exit(1);
}

Miscellaneous

Inconsistent white space here:

int bonus=0;
int prodOdd = 1;

It can be difficult to choose a good variable name, but I am sure that you'll find something better here:

int lol = counter;

Declare variables at the nearest scope where they are used. As an example, currDigit is only used inside the for-loop:

for (int i = 0; i < lol; i++) {
    int currDigit = dist % 10;
    // ...
}

Simplifiying the program

The calculation of

    if (prodOdd == prodEven)
        bonus = 2 * prodOdd;
    else
        bonus = prodOdd > prodEven ? prodOdd : prodEven;

does not change if we exchange the even and the odd product. Therefore it does not matter if we count even and odd position from the most significant (decimal) digit or from the least significant digit.

As a consequence, we can process the digits starting with the least significant one, and it is not necessary to calculate the number of digits beforehand.

Instead of the counter, a boolean variable is sufficient to keep track of even and odd positions.

So the countDigits() function is obsolete, and calculateBonus() could be implemented like this:

public static int calculateBonus(int dist) {
    int prodOdd = 1;
    int prodEven = 1;
    boolean evenPosition = true;

    while (dist > 0) {
        int currDigit = dist % 10;
        if (evenPosition) {
            prodEven *= currDigit;
        } else {
            prodOdd *= currDigit;
        }

        dist /= 10;
        evenPosition = !evenPosition;
    }

    return prodOdd == prodEven ?
        2 * prodOdd :
        prodOdd > prodEven ? prodOdd : prodEven;
}


Super fancy list constructing in Python Out of curiosity I was discovering the potential of the Ellipsis object in Python (...), and I discovered it doesn't do a whole lot except for a handful of minor features. In an effort to make it useful, I decided to create the most fancy-pants constructor for a list that I could.

The function, super_list, takes an arbitrary number of arguments to be added to the list. Here are the features:

super_list(multiple, arguments, provided) -> Generates a list using the arguments provided. If an argument doesn't follow any of the special features below, it is just appended to the array at the proper nesting level. This example returns [multiple, arguments, provided], a list of the arguments.
super_list(5, ..., 9) -> Takes advantage of the Ellipsis object to create something that looks like "x to y", or a range. This particular example would produce a list containing [5,6,7,8,9], the number between 5 and 9.
super_list(arg, array.move_up, higher_arg, array.move_down, lower_arg) -> Sets the nesting level inside the list. Including array.move_up or array.move_down moves up or down one level of nesting in the list. This example produces [arg, [higher_arg], lower_arg], moving up and down the array chain with array.move_up and array.move_down.

One last big example:

super_list("first level", 5, ..., 9, array.move_up, array.move_up, "second level", 10, ..., 15, array.move_down, "down one level")

produces

['first level', 5, 6, 7, 8, 9, [['second level', 10, 11, 12, 13, 14, 15], 'down one level']]

So this is my current implementation:

def get_in_list(lst, indexes):
  """Gets an item in a nested list by a list of indexes."""
  return functools.reduce(operator.getitem, indexes, lst)

def super_list(*args):
  """Special initialization syntax for lists."""
  curr_index = []
  result = []
  for index, item in enumerate(args): # Iterate over args with indexes
    el_type = type(...) # Type of the Ellipsis object
    if isinstance(item, el_type): # Case: Ellipsis range generator
      if index == 0:
        get_in_list(result, curr_index).append(item)
      else:
        get_in_list(result, curr_index).extend(list(range(args[index-1]+1, args[index+1])))
    elif item == array.move_up: # Case: move up one level in list
      get_in_list(result, curr_index).append([])
      curr_index.append(len(get_in_list(result, curr_index))-1)
    elif item == array.move_down: # Case: move down one level in list
      try:
        curr_index.pop()
      except IndexError: # Silently catch if user tries to move down too far in the list
        pass
    else: # Case: No special syntax - regularly append item to list
      get_in_list(result, curr_index).append(item)
  return result

get_in_list is a function used to get an item at a list of indexes. This means that a[0][1] == get_in_list(a, [0, 1]).

My questions:

Is it too messy?
Is anything too long and could be implemented in a shorter way?
Is the program too confusing, and do you think it could be more verbose?

And obviously, any other comments you may want to add are appreciated. Thanks in advance!

I'm severely confused by array.move_down, because I don't see any array or anything moving anywhere. If you are doing a super_list, wouldn't it be more readable to have sublist.begin and sublist.end?

Also I don't like fail-later approach with hiding an exception. If user makes an error in nesting lists, I would fail fast instead. It's a common behavior of all the languages I know (with an exception of early/ancient HTML).


Modular sum of square numbers in C++ So I've got an assignment which sounds like this:

  Given a number n, calculate the result of this sum, modulo 10,234,573:
  12 + 22 + 32 + … + n2

This is what I've come up with :

 #include <iostream>
 using namespace std;

 int main()
 {
     uint n;
     cin >> n;

     uint num{10234573};
     uint64_t sum{0};
     for (uint i = 1; i <= n; ++i) {
         sum += (i*i)%num;
         sum %= num;
     }

     cout << sum;

     return 0;
 }

And I can check my algorithm on a website, but it tells me that it is "too slow"... How can I optimise it so it will be faster?
I know there is a formula for this, but the given number n can be as big as 2,000,000,000, so it will obviously overflow...

To use the modulo in equations, You need to maintain the equivalence of the Equation. The Equation you wrote in comment is not according to equivalence. See Division Under Equivalences

So, going by the equivalence you have to calculate it like this :

  [ ( (n) %x ) * ( (n+1) %x ) * ( ( 2*n + 1 ) %x ) ) * ( (1/6)%x ) ] %x

Have a look at this.

Note that this will not work If given n is any multiple of x. So, n & x must be Co-prime. In your case, x = 10234573 is already a prime number as pointed by Toby's Comment


Linear Equation in Two Variables Solver using Python I made this simple program that can solve every set of linear equations in two variables.

You just need to enter two linear equations of the form ax+by=c (without any unnecessary spaces) where 'a' is a positive integer (i.e. x should not have a negative coefficient) and b and c are just integers.

The program can also show outputs like "The two equations have no solution" or "the two equations have infinite solutions" if it is so...

I only used the knowledge of 9th and 10th grade Python along with the concept of functions to make this program and I will update it on the basis of the suggestions that I got from some great people in my last question. I will try to make it shorter, more readable and definitely more efficient soon, will post that too when done.

Here's the Python code :

def getindex(a,b):
    size = len(b)
    status = 0
    for i in range(0,size,1):
        element = b[i]
        if (element == a):
            index = i
            status = 1
            break
    if (status == 1):
        return index
    else:
        return "not found"

def getstring(a,b,c):
    string = c[a]
    for i in range(a+1,b,1):
        element = c[i]
        string = string + element
    return string

def lcm(a,b):
    found = False
    if (a>b):
        larger = a
    else:
        larger = b
    i = larger
    while found == False:
        if (i%a == 0) and (i%b == 0):
            found = True
            break
        else:
            i += larger
    return i

print ()
print ("Please enter two equations of the form ax+by=c where a is a positive integer and b and c are integers...")
print ()
a = str(input("Please enter the first equation : "))
b = str(input("Please enter the second equation : "))
a = list(a)
b = list(b)
sizea = len(a)
sizeb = len(b)

# Getting a, b and c of equation one

symbolindexone = getindex('+',a)
equalindexone = getindex('=',a)
symbolstatusone = "positive"
if (symbolindexone == "not found"):
    symbolindexone = getindex('-',a)
    symbolstatusone = "negative"
xindexone = getindex('x',a)
yindexone = getindex('y',a)
a1 = getstring(0,xindexone,a)
if (a1 == 'x'):
    a1 = 1
else:
    a1 = int(a1)
b1 = getstring(symbolindexone+1,yindexone,a)
if (b1 == 'y'):
    if (symbolstatusone == 'positive'):
        b1 = 1
    else:
        b1 = -1
else:
    b1 = int(b1)
    if (symbolstatusone == "negative"):
        b1 = -b1
c1 = getstring(equalindexone+1,sizea,a)
c1 = int(c1)

# getting a, b and c of equation two

symbolindextwo = getindex('+',b)
equalindextwo = getindex('=',b)
symbolstatustwo = 'positive'
if (symbolindextwo == 'not found'):
    symbolindextwo = getindex('-',b)
    symbolstatustwo = 'negative'
xindextwo = getindex('x',b)
yindextwo = getindex('y',b)
a2 = getstring(0,xindextwo,b)
if (a2 == 'x'):
    a2 = 1
else:
    a2 = int(a2)
b2 = getstring(symbolindextwo+1,yindextwo,b)
if (b2 == 'y'):
    if (symbolstatustwo == 'positive'):
        b2 = 1
    else:
        b2 = -1
else:
    b2 = int(b2)
    if (symbolstatustwo == 'negative'):
        b2 = -b2
c2 = getstring(equalindextwo+1,sizeb,b)
c2 = int(c2)

# LCM and the final phase

lcma = lcm(a1,a2)
tmbone = lcma/a1
tmbtwo = lcma/a2
a1 *= tmbone
b1 *= tmbone
c1 *= tmbone
a2 *= tmbtwo
b2 *= tmbtwo
c2 *= tmbtwo
ratioa = a1/a2
ratiob = b1/b2
ratioc = c1/c2
print ()
if (ratioa == ratiob == ratioc):
    print ("The equations that you entered have infinite solutions...")
elif ((ratioa == ratiob) and (ratioa != ratioc)):
    print ("The equations that you entered have no solution...")
else:
    ysolution = (c1-c2)/(b1-b2)
    xsolution = ((c1)-(b1*ysolution))/(a1)
    print ("The value of x is : ",xsolution)
    print ("The value of y is : ",ysolution)

Let me know what you think

Thanks :)

Some comments:

Rename functions to follow the PEP8 naming convention, here.
Do not use range to iterate over the a list of elements, iterate directly over it. If you need the index, as in your case, use enumerate.
No need to wrap the boolean clauses in parenthesis, moreover you can use the truth(y) values directly, see truth value testing.
Is possible add comments on what does the function does.

After a first rewrite the code of your function should look something like this:

def get_index(a, b):
    """Get the index of and element or else return 'not found' """
    status = 0
    index = 0
    for i, element in enumerate(b):
        if element == a:
            index = i
            status = 1
            break
    if status:
        return index
    else:
        return "not found"

def get_string(a, b, c):
    """Build a sub-string from c starting on a"""
    string = c[a]
    for i in range(a + 1, b, 1):
        element = c[i]
        string = string + element
    return string

def lcm(a, b):
    """Find the least common multiple"""
    if a > b:
        larger = a
    else:
        larger = b
    i = larger
    while True:
        if (i % a == 0) and (i % b == 0):
            break
        else:
            i += larger
    return i

if __name__ == "__main__":
    assert get_index(1, [1, 2, 3]) == 0
    assert get_index(1, [2, 3]) == "not found"
    assert get_string(0, 3, "hello world") == "hel"
    assert lcm(2, 5) == 10

I added some (basic) test, to validate any further change you could make in the future to this functions.

The above comments are superficial, if you want speed and reliability use the functions provided by the standard library, in the end your functions should look like something like this:

from math import gcd

def get_index(a, b):
    """Get the index of and element or else return 'not found' """
    try:
        return b.index(a)
    except ValueError:
        return "not found"

def get_string(a, b, c):
    """Build a sub-string from c starting on a"""
    return c[a:b]

def lcm(a, b):
    """Find the least common multiple"""
    return abs(a * b) // gcd(a, b)

The lcm implementation uses the gcd, see more in the wikipedia page.


Best accuracy and performance with timers in JS Regular timers in JavaScript (setInteval & setTimeout) have two problems:

They aren't as much accuracy as you can get in JS. If you set it like this:

setInterval(fn, 1000);

You can't be sure that it will be called every 1000 ms. It'll be called 1000 + 1-10ms or even more if some heavy tasks were before the tick.

This is normal behaviour. The bad thing about it is that these delays will accumulate.
Throttling when tab is inactive. When you switch tabs for a while, timers that are in a invisible tab will tick at a higher frequency because of CPU saving. It's a reasonable thing, but killer for multiplayer gaming.

Both problems can be solved by webworker and some variables. That's why I've built a class for it and need a review.

My class also provide anti-blocking mechanism. When there was heavy tasks before timer tick and we need to deal with lag - timer will make up all lost ticks but it can be "forever" loop. To prevent this you can set the max ms for "making lost ticks" and after them will be a break for other code/events/etc and back to work.

module.exports = UberTimer = function UberTimer(callback, interval, blockThreadMaxMs) {
  this.callback = callback;
  this.interval = interval;

  this.lastTickTime = -1;

  this.blocking = {};
  this.blocking.maxTime = blockThreadMaxMs;
  this.blocking.startTime = -1;
}

////////////////////////////////////////////////////////////////////////

UberTimer.worker = null;
UberTimer.instances = [];

UberTimer.__startWorker = function() {
  if ( UberTimer.worker ) return;

  var blobURL = URL.createObjectURL( new Blob([ '(', (

    function() {
      setInterval(() => self.postMessage(0), 1);
    }

  ).toString(), ')()' ], { type: 'application/javascript' } ) );

  UberTimer.worker = new Worker(blobURL);
  UberTimer.worker.onmessage = UberTimer.__tick;
}

UberTimer.__stopWorker = function() {
  UberTimer.worker.terminate();
  UberTimer.worker = null;
}

UberTimer.__tick = function(timer) {
  for ( var timer of UberTimer.instances )
    timer.__workerTick();
}

UberTimer.create = function(callback, interval, blockThreadMaxMs=100) {
  var timer = new UberTimer(callback, interval, blockThreadMaxMs);

  UberTimer.instances.push(timer);
  UberTimer.__startWorker();

  return timer;
}

UberTimer.release = function(timer) {
  var i = UberTimer.instances.indexOf(timer)
  if ( i ) UberTimer.instances.splice(i, 1);

  if ( UberTimer.instances.length == 0 )
    UberTimer.__stopWorker();
}

////////////////////////////////////////////////////////////////////////

UberTimer.prototype.__makeCall = function() {
  this.callback();
  this.lastTickTime += this.interval;
}

UberTimer.prototype.__workerTick = function() {
  if ( this.lastTickTime == -1 ) return;

  var now = performance.now();

  if ( this.blocking.startTime == -1 )
    this.blocking.startTime = now;

  var elapsedTime = now - this.lastTickTime;

  if ( elapsedTime >= this.interval ) {
    this.__makeCall();

    var blockingTime = now - this.blocking.startTime;

    if ( blockingTime < this.blocking.maxTime )
      this.__workerTick();
    else
      this.blocking.startTime = -1;
  }
}

UberTimer.prototype.start = function() {
  this.__makeCall();
  this.lastTickTime = performance.now();
}

UberTimer.prototype.stop = function() {
  this.lastTickTime = -1;
}

Usage:

var timer = UberTimer.create(callback, intevalInMs, optional: maxBlockingTime);

timer.start();
timer.stop();

UberTimer.release(timer);

BUGs
First some logic and flow bugs.

The function release uses indexOf to get the timer index i then you use the statement if(i) { ... which fails to remove the first item in the instances array. The result is the worker is never shut down.

Calling UberTimer.stop(timer) from within the callback function timer.callback fails to stop the timer, the callback continues to be called. Because you set lastTickTime to -1 your code then tries to catch up by calling the callback at the full rate of the worker's messages.

And related to how you call the callback function.

If the callback function timer.callback fails to return (throws an error) on the function timer.start the timer.lastTickTime property is not set and remains the init value of -1. The callback is then call in rapid succession, and if the callback continues the throw it just continues tring to catch up every time the worker sends a message. The is in  effect an infinite message incomplete loop

Because you call the callback function from the function timer.start any error in the callback will stop current execution context. This is not what one would expect from a timer.

When you have many timers. If any callback throws the remaining callbacks (higher on the instance array) will not get called as the UberTimer.__tick does not get to complete the timer iteration loop.

Danger potencial silent bug.
Because the property UberTimer.worker is exposed there is a danger that you loose the reference to the worker, if it is accidentally or deliberately overwritten. This could result in a silent bug that makes its way to release degrading performance. You should make it safer (protect your state).
Some style notes

Underscore prefixes do not create private / protected variables. If you wish to protect your object's state don't expose functions and properties that you don't want messed with.

C like languages allow the lazy programmers to save milliseconds typing by not including {...} for single line statement blocks. The irony is that the cost is hours of bug hunting. Your eyes don't look for { and } when you think you are looking for a logic bug.
For your coding sanity ALWAYS delimit blocks with {...}

if(foo === blah)
    foo = 1;

 // then later you make the change

 if(foo === blah)
    foo = 1;
    blah = 1;

// Yes obvious in isolation. But in 100's of lines of code with many unblocked statements
// the eye sees the indent and the mind puts in the {}

// never an issue if you always do
if (foo === blah) { foo = 1 }
// or
if (foo === blah) {
    foo = 1;
}

Use === or !== never use == or !=

For variables that never change declare them with const

Don't define a variable in one type only to convert it to another when you use it. The worker function can be defined as a constant string.

Don't add redundant or superfluous code it only reduces the quality of the code. module.exports = UberTimer = function UberTimer( reassigning the UberTimer serves no purpose in your code.

 this.blocking = {};
 this.blocking.maxTime = blockThreadMaxMs;
 this.blocking.startTime = -1;

 // should be

 this.blocking = {
     maxTime : blockThreadMaxMs,
     startTime : -1,
 };

Use object function shorthand if you can.

UberTimer.prototype.__makeCall = function() { ... }

UberTimer.prototype.__workerTick = function() { ... }

UberTimer.prototype.start = function() { ... }

UberTimer.prototype.stop = function() { ... }

Is better as
UberTimer.prototype = {
     __makeCall() { ... },
    __workerTick() { ... },
    start() { ... },
    stop() { ... },
};


Find element that has been removed from a shuffled array For a function to determine which element has been removed from a shuffled array, I came up with:

def finder(arr1, arr2):
  l = len(arr1) - 1
  result = list(arr1)
  for i in range(l):
    current = arr1[i]
    if current in arr2:
      result.remove(current)
      arr2.remove(current)
  return result[0]

In the solution for my course it says:

  The naive solution is go through every element in the second array and
  check whether it appears in the first array. Note that there may be
  duplicate elements in the arrays so we should pay special attention to
  it. The complexity of this approach is \$O(N^2)\$, since we would need
  two for loops.

However doing the other way round, i.e. as I've done above seems to avoid a nested for loop, and is therefore linear as far as I can tell. Am I missing something? Have I made an error in my code or my analysis of its efficiency?

When you don't know how long a built-in function call will take, then the TimeComplexity page on the Python wiki comes to the rescue. This tells us that both item in list and list.remove(item) take time proportional to the length of the list.

So although current in arr2 and result.remove(current) are single expressions in Python, in fact each of them has a loop hidden inside it, and this makes the overall runtime \$Θ(n^2)\$.

If you're having trouble with the analysis, there's no substitute for actually running the code and timing how long it takes on different inputs! This is really easy to do, for example, you might write:

from random import randrange
from timeit import timeit

def test(n):
    """Time finder on lists of length n."""
    a = list(range(n))
    b = list(a)
    del b[randrange(n)]
    return timeit(lambda:finder(a, b), number=1)

and then:

>>> for i in range(5):
...     n = 10000 * 2 ** i
...     print(n, test(n))
...
10000 0.020456696045584977
20000 0.07089142000768334
40000 0.361092661973089
80000 1.5187797680264339
160000 6.356738713919185

You can see that when \$n\$ doubles, the runtime increases by around four times, which is what we expect for an \$Θ(n^2)\$ algorithm. Here's a plot showing a least-squares fit of the measurements collected above to the function \$t = an^2\$, and you can see that the fit is pretty good:


rails method for transaction type I am trying to make a rake task but after completion my code i realized i need some refactorization. How could I do refactorization of the following code?

def self.transaction_type(row)
    if row['SENDER_BLZ'] == '00000000' and row['RECEIVER_BLZ'] == '00000000'
      return 'AccountTransfer'
    elsif row['SENDER_BLZ'] == '00000000' and row['UMSATZ_KEY'] == '10'
      return 'BankTransfer'
    elsif row['RECEIVER_BLZ'] == '70022200' and ['16'].include?row['UMSATZ_KEY']
      return 'Lastschrift'
    else
      return false
    end
  end

and second method is

def self.import_file_row_with_error_handling(row, validation_only, errors, dtaus)
  error_text = nil
  self.import_retry_count = 0
  5.times do
    self.import_retry_count += 1
    error_text = nil
    begin
      import_file_row(row, validation_only, errors, dtaus)
      break
    rescue => e
      error_text = "#{row['ACTIVITY_ID']}: #{e.to_s}"
      break
    end
  end
  errors << error_text if error_text

  [errors, dtaus]
end

Just need bit guid. thanks

It looks like row is simply a hash, but it has various value combinations that are significant.

You could refactor the detection of those combinations, for example by creating a class based on the row that has an attribute for #transaction_type ...

class Row
  def initialize(row)
    @row = row
  end

  def sender_blz
    row['SENDER_BLZ']
  end

  def receiver_blz
    row['RECEIVER_BLZ']
  end

  def umsatz_key
    row['UMSATZ_KEY']
  end

  def transaction_type
    return "AccountTransfer" if sender_blz   == "00000000" && receiver_blz == "00000000"
    return "BankTransfer"    if sender_blz   == "00000000" && umsatz_key == "10"
    return "Lastschrift"     if receiver_blz == "70022200" && umsatz_key == "16"
    false
  end
end

Then your method becomes

Row.new(row).transaction_type

I would rather see magic strings like "00000000" replaced with constants, and conditions like sender_blz == "00000000" replaced with methods that give a name to the condition, like:

def sender_not_specified?
  sender_blz == NOT_SPECIFIED
end

... thus you would have something like ...

  def transaction_type
    return "AccountTransfer" if sender_not_specified? && receiver_not_specified?
    return "BankTransfer"    if sender_not_specified? && something_about_umsatz?
    return "Lastschrift"     if receiver_not_specified? && something_else_about_umsatz?
    false
  end


Simple Console Calculator This is my Java 8 code for a console calculator. I just want to know if it can be improved in any way. Just so you know i am a real beginner just got into java about a couple of weeks ago.

    import java.util.Scanner;

public class Algorithm1 {
public static int FirstNumber, SecondNumber;
public static float TheAnswer;
public static String Action;
public static Scanner ScanInt1, ScanString;
public static boolean hasString;
public static boolean hasString2, hasInt;
public static void main(String args[]){
hasString = false;//sets up the booleans
hasString = false;
hasInt = false;
ScanInt1 = new Scanner(System.in);
ScanString = new Scanner(System.in);
System.out.println("Give your First input please.");
while  (FirstNumber < 1){
FirstNumber = ScanInt1.nextInt();
}
System.out.println("Give your Second input please.");
hasString = true;
if (SecondNumber < 1){
SecondNumber = ScanInt1.nextInt();
}
else {
System.out.println("Now * or / or + or -");
hasString2 = true;
}
Action = ScanString.nextLine();
System.out.println(Answer());
}
public static float Answer(){
//This method is for the math
    if (Action.equals("*")){
        TheAnswer = FirstNumber * SecondNumber;

    }
if (Action.equals("/")){
    TheAnswer = FirstNumber / SecondNumber;

}
if (Action.equals("+")){
    TheAnswer = FirstNumber + SecondNumber;

}
if (Action.equals("-")){
    TheAnswer = FirstNumber - SecondNumber;

}
return TheAnswer;
}

}

A CLI-based calculator is often a good way to prepare one for bigger programming tasks, as there are just so many ways of doing it, catering for beginner to advanced implementations. I happen to have one myself about two months ago, for reference. :)

Indentation

There's no other way of putting this, but your indentation is extremely poor. Nested code blocks inside { } braces should be indented accordingly, instead of left-aligning everything.

Naming style

Please use camelCase instead of PascalCase for your variable and method names. As you can tell from the syntax highlighting on your present code, PascalCase is the naming convention for type/class names. This makes reading your code slightly harder as other developers have to 're-parse' your variable/method names from what looks like class names.

try-with-resources

Since Java 7, try-with-resources is the recommended approach to read from an I/O source, such as wrapping a Scanner over System.in:

try (Scanner scanner = new Scanner(System.in)) {
    // ...
    String line = scanner.nextLine();
    // ...
}

This lets the JVM close I/O resources automatically for you.

Less reliance on 'global' static variables

You should slowly adopt better object-oriented (OO) programming practices, such as relying less on static variables. It's better to make more effective use of method arguments so that other developers can understand what the method requires. More on this will be illustrated below.

return early

Inside your Answer() method, you should return early so that you can do away with temporary variables. In my opinion, temporary variables are often a crutch to writing longer methods, which makes code harder to read and understand in the long run. A possible improvement can be:

private static float getAnswer(String action, int first, int second) {
    switch (action) {
    case "+":
        return (float) first + second;
    case "-":
        return (float) first - second;
    // ...
    }
}


Making thousands of DOM elements draggable with JavaScript This is a very simple implementation of dragging elements in html/js. I'm working on a web application that could have thousands of draggable elements on screen at any given time.

Currently, this code works perfectly as shown below (with only one draggable element), however if I copy and paste that element (This is draggable) a few thousand times (I've been using around 4000 for testing) page load is significantly slower, and the framerate slows considerably.

I can understand the page load slowing due to the number of elements, but is there anything that can be done to ensure the frame rate remains smooth while dragging an element given large numbers of draggable elements in the DOM?

Note - The implementation here deliberately ignores various issues like scrolling and so on that I will be implementing later, and I believe will have a largely negligible effect on performance. If that's an incorrect assumption please let me know.

dragdrop.html

<!doctype html>

        <title>Drag + Drop</title>
        <link rel="stylesheet" type="text/css" href="dragdrop.css" />

            This is draggable

dragdrop.css

span {
    position:absolute;
    background: #FF8888;
    cursor: pointer;
}

.noselect {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

dragdrop.js

var dragDrop = (function() {
    var elementBeingDragged;
    var clickPointOffsetX;
    var clickPointOffsetY;

    function _dragging(e) {
        elementBeingDragged.style.left = (e.clientX - clickPointOffsetX) + "px";
        elementBeingDragged.style.top = (e.clientY - clickPointOffsetY) + "px";
    }

    function _stopDrag(e) {
        document.removeEventListener('mousemove', _dragging);
        document.removeEventListener('mouseup', _stopDrag);
    }

    function startDrag(e) {
        elementBeingDragged = this;
        document.addEventListener('mouseup', _stopDrag);
        document.addEventListener('mousemove', _dragging);

        var rect = elementBeingDragged.getBoundingClientRect();

        clickPointOffsetX = e.clientX - rect.left;
        clickPointOffsetY = e.clientY - rect.top;
    }

    var publicAPI = {
        startDrag: startDrag
    };

    return publicAPI;
})();

$(function() {
    $('#draggableItemContainer').on('mousedown', '.draggable', dragDrop.startDrag);
});

Here are some suggestions to improve the fluidity of your app:

Use translate instead of top/left positioning

According to this blog post: https://www.paulirish.com/2012/why-moving-elements-with-translate-is-better-than-posabs-topleft/, translate is much more efficient regarding the CPU usage

Use requestAnimationFrame

https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

This function allows you to do the computation only if required (see this SO answer on how to combine it with mousemove: https://stackoverflow.com/a/23658815/3207406)


Convert characters to octal, binary, and integer I have implemented a sample program that converts vector of characters to its integer representation depending on the bit size specified. I was hoping to get some input on how to simplify the sequence. I think my approach is convoluted.

#include "stdafx.h"

#include <iostream>
#include <vector>
#include <iomanip>
#include <bitset>
#include <sstream>
#include <algorithm>
#include <iterator>

int OctalToBinary(int octalNum) {
    int decimalNum = 0, binaryNum = 0, count = 0;

    while (octalNum != 0) {
        decimalNum += (octalNum % 10) * pow(8, count);
        ++count;
        octalNum /= 10;
    }
    count = 1;
    while (decimalNum != 0) {
        binaryNum += (decimalNum % 2) * count;
        decimalNum /= 2;
        count *= 10;
    }
    return binaryNum;
}

int main()
{
    std::vector<char> buffer = { '3','7','4','3','0'};
    std::vector<int> bitsize = { 3,3,8 };
    std::vector<char> collection;
    std::vector<std::string> output;

    // convert characters to octal and

    for each ( char c in buffer)
    {
        int x = c - '0';
        std::stringstream opt;
        opt << std::setw(3) << std::setfill('0') << OctalToBinary(x) << "\n";

        std::string val = opt.str();

        std::copy(val.begin(), val.end()-1, std::back_inserter(collection));
    }

    int start_index = 0;
    int end_index = 0;

    // convert binary values to integer
    for (int i = 0; i < bitsize.size(); i++)
    {
        start_index = end_index;
        end_index += bitsize[i];

        std::string temporary_string(collection.begin() + start_index, collection.begin() + end_index);
        int converted_integer = std::stoi(temporary_string.c_str(), nullptr, 2);
        std::cout << temporary_string << " " << converted_integer << "\n";
    }

    // output should be 3, 7 , 140

    int x;
    std::cin >> x;
    return 0;
}

Unnecessary Headers
The #includes for iterator and bitset are not needed, the code compiles fine without them, iterator may be included indirectly through vector.

Adding unnecessary headers can increase compile/build times and may cause other problems in larger more complex programs.

Portability
This program is currently not portable for 2 reasons, the use of the Visual Studio generated #include "stdafx.h" and the use of the non-standard for each loop. It might be better to embed #include "stdafx.h" within ifdef/endif.

#ifdef windows
#include "stdafx.h"
#endif

I compiled this in Visual Studio 2017 on Windows 10 and it actually reported a compile error on the for each loop. The suggested fix was to use a range based for loop.

1>------ Build started: Project: octbinintconv0, Configuration: Debug Win32 ------
1>octbinintconv0.cpp
1>d:\projectsnfwsi\codereview\octbinintconv0\octbinintconv0\octbinintconv0.cpp(18): warning C4244: '+=': conversion from 'double' to 'int', possible loss of data
1>d:\projectsnfwsi\codereview\octbinintconv0\octbinintconv0\octbinintconv0.cpp(40): error C4496: nonstandard extension 'for each' used: replace with ranged-for statement
1>d:\projectsnfwsi\codereview\octbinintconv0\octbinintconv0\octbinintconv0.cpp(55): warning C4018: '<': signed/unsigned mismatch
1>Done building project "octbinintconv0.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

You might want to replace the for each loop with the following code, which uses an iterator and is part of standard C++.

    for (auto c : buffer)
    {
        int x = c - '0';
        std::stringstream opt;
        opt << std::setw(3) << std::setfill('0') << OctalToBinary(x) << "\n";

        std::string val = opt.str();

        std::copy(val.begin(), val.end() - 1, std::back_inserter(collection));
    }

Type Mismatches
A good practice is treating warning messages as errors, since they point to potential logic errors. The pow() function returns double and the result is being truncated, it might be better to use a static cast in the code to show that this is intentional.

    decimalNum += (octalNum % 10) * static_cast<int>(pow(8, count));

In this for loop it would be better to define the local variable i as size_t rather than int, in any of the STL container classes the function size() returns size_t.

    for (size_t i = 0; i < bitsize.size(); i++)

Complexity
Creating the function OctalToBinary(int octalNum) was good but there are two more functions that main() can be broken up into, they have even been identified by comments, both of the for loop are good candidates for functions.


Unix timestamp to days, months, years Imagine you can't use the standard functions for time calculation or anything alike. You have to start from scratch as it is the case on embedded systems.
Thus I came with the following code to determine the seconds, minutes, hours, days, months and years from unix timestamp. Tested the code, works for everything I threw at it so far, but wonder if there is a better way to do it without using the standard functions
#include <iostream>

int main(int argc, char* argv[])
{
    /* Subtract 2 years to start on leaping year, later add 1972 instead. */
    auto now = std::atoi(argv[1]) - 63072000;
    auto days = (now / 86400);
    auto hours = (((now - days * 86400) / 3600) % 24);
    auto minutes = ((((now - days * 86400) - hours * 3600) / 60) % 60);
    auto seconds = (((((now - days * 86400) - hours * 3600) - minutes * 60)) % 60);

    /* Get number of 4years to accomodate for leap years */
    auto q_years = (days / 1461);

    /* Recalculate the number of years */
    auto years = q_years * 4 + (days - (q_years * 1461)) / 365;

    /* Deterimne no. of days in the current year */
    auto days_last = (days - (q_years * 1461)) % 365;
    static uint8_t days_in_month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    /* Fix for leap year */
    if (years % 4 == 0)
    {
        days_in_month[1] = 29;
        days_last++;
    }

    /* Retrace current month */
    int month = 0;
    while (days_last > days_in_month[month])
    {
        days_last -= days_in_month[month++];
    }

    printf("Year: %d, Month: %d\n", 1972 + years, month + 1);
    printf("Days: %d, Hours: %d, Minutes: %d, Seconds:%d\n", days_last, hours, minutes, seconds);

    return 0;

}

yes, the code is in c++ but I'll be rewriting it to C afterwards - basically letting go of auto.

What I am not looking at is code readability error checking (what if argv does not have 2 el.) et cetra. I am purely looking for a better algo to get the job done.

std::atoi() is a poor choice of conversion function, as its means of reporting errors is indistinguishable from a valid conversion.  The necessary header hasn't been included anyway.
uint8_t is not declared - did you mean std::uint8_t from <cstdint>?  Similarly, you probably meant to include <cstdio> for std::printf, and <iostream> isn't used.
The repeated calculations during the division of seconds into days, hours, minutes and seconds should be simplified.  I'd go with something like
auto seconds = now % 60;
auto minutes = now / 60;
auto hours = minutes / 60;
auto days = hours / 24;
minutes %= 60;
hours %= 24;

Perhaps even consider making a class for mixed base arithmetic.
The calculation of leap years is flawed, because it gives 100 leap years per 400 years, rather than the 97 expected.
Instead of looping over months, it might be better to keep an array of the start of month as Julian day, so we can use a straightforward binary search to identify the month number and day within month.
Calendrical calculations are often easier if we use a year beginning on the 1st of March for computation (so that leap day is the last day in year), then convert January/February dates to the correct year as a final step.
I'd encourage the use of a function (perhaps with the same signature as std::gmtime()) rather than shoving everything directly into main().
return 0; can be omitted from the end of main() .


Simple backup script in Python Since rsync lacks compression and I'm not a big fan of rdiff, I thought I'd try my own little backup script. Since I'm very inexperienced with file management in Python, I'm sure there is lot of room for improvement.

The script creates the entire folder structure within the backup folder and then creates syncs recursively for all files within the source folders. Every file above a certain threshold gets gziped  on the way.

A possible command would be:

  python3 sync.py -target MY_BACKUPFOLDER -source IMPORTANT_1 IMPORTANT_2

Please tell me what you think of the source:

""" Simple backup script which just creates the root structure in an other
folder and syncs everything which recursevely lies within one of the source
folders. For files bigger than a threshold they are first gziped."""

import argparse
import gzip
import os
import shutil
import sys

def parse_input():
    parser = argparse.ArgumentParser()
    parser.add_argument('-target', nargs=1, required=True,
                        help='Target Backup folder')
    parser.add_argument('-source', nargs='+', required=True,
                        help='Source Files to be added')
    parser.add_argument('-compress', nargs=1,  type=int,
                        help='Gzip threshold in bytes', default=[100000])

    # no input means show me the help
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit()

    return parser.parse_args()

def size_if_newer(source, target):
    """ If newer it returns size, otherwise it returns False """

    src_stat = os.stat(source)
    try:
        target_ts = os.stat(target).st_mtime
    except FileNotFoundError:
        try:
            target_ts = os.stat(target + '.gz').st_mtime
        except FileNotFoundError:
            target_ts = 0

    # The time difference of one second is necessary since subsecond accuracy
    # of os.st_mtime is striped by copy2
    return src_stat.st_size if (src_stat.st_mtime - target_ts > 1) else False

def sync_file(source, target, compress):
    size = size_if_newer(source, target)

    if size:
        transfer_file(source, target, size > compress)

def transfer_file(source, target, compress):
    """ Either copy or compress and copies the file """

    try:
        if compress:
            with gzip.open(target + '.gz', 'wb') as target_fid:
                with open(source, 'rb') as source_fid:
                    target_fid.writelines(source_fid)
            print('Compress {}'.format(source))
        else:
            shutil.copy2(source, target)
            print('Copy {}'.format(source))
    except FileNotFoundError:
        os.makedirs(os.path.dirname(target))
        transfer_file(source, target, compress)

def sync_root(root, arg):
    target = arg.target[0]
    compress = arg.compress[0]

    for path, _, files in os.walk(root):
        for source in files:
            source = path + '/' + source
            sync_file(source, target + source, compress)

if __name__ == '__main__':
    arg = parse_input()
    print('### Start copy ####')
    for root in arg.source:
        sync_root(root, arg)
    print('### Done ###')

This program is really a pleasure to read. It accomplishes the desired outcome neatly and succinctly. The only thing I could think of that might be an improvement is threading. Other than that this program looks fantastic.

I can see where making this program threaded can be a great benefit when dealing with smaller files. I'm not sure, but I fear with larger files or smaller buffering, having this program run copy routines in parallel might bring the system to a halt. I wrote up a minor modification to your excellent source code to illustrate my idea:

""" Simple backup script which just creates the root structure in an other
folder and syncs everything which recursevely lies within one of the source
folders. For files bigger than a threshold they are first gziped."""

import argparse
import gzip
import os
import shutil
import sys
import threading

def parse_input():
    parser = argparse.ArgumentParser()
    parser.add_argument('-target', nargs=1, required=True,
                        help='Target Backup folder')
    parser.add_argument('-source', nargs='+', required=True,
                        help='Source Files to be added')
    parser.add_argument('-compress', nargs=1,  type=int,
                        help='Gzip threshold in bytes', default=[100000])

    # no input means show me the help
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit()

    return parser.parse_args()

def size_if_newer(source, target):
    """ If newer it returns size, otherwise it returns False """

    src_stat = os.stat(source)
    try:
        target_ts = os.stat(target).st_mtime
    except FileNotFoundError:
        try:
            target_ts = os.stat(target + '.gz').st_mtime
        except FileNotFoundError:
            target_ts = 0

    # The time difference of one second is necessary since subsecond accuracy
    # of os.st_mtime is striped by copy2
    return src_stat.st_size if (src_stat.st_mtime - target_ts > 1) else False

def threaded_sync_file(source, target, compress):
    size = size_if_newer(source, target)

    if size:
        thread = threading.Thread(target=transfer_file,
                                  args=(source, target, size > compress))
        thread.start()
        return thread

def sync_file(source, target, compress):
    size = size_if_newer(source, target)

    if size:
        transfer_file(source, target, size > compress)

def transfer_file(source, target, compress):
    """ Either copy or compress and copies the file """

    try:
        if compress:
            with gzip.open(target + '.gz', 'wb') as target_fid:
                with open(source, 'rb') as source_fid:
                    target_fid.writelines(source_fid)
            print('Compress {}'.format(source))
        else:
            shutil.copy2(source, target)
            print('Copy {}'.format(source))
    except FileNotFoundError:
        os.makedirs(os.path.dirname(target))
        transfer_file(source, target, compress)

def sync_root(root, arg):
    target = arg.target[0]
    compress = arg.compress[0]
    threads = []

    for path, _, files in os.walk(root):
        for source in files:
            source = path + '/' + source
            threads.append(threaded_sync_file(source,
                           target + source, compress))
#            sync_file(source, target + source, compress)
    for thread in threads:
        thread.join()

if __name__ == '__main__':
    arg = parse_input()
    print('### Start copy ####')
    for root in arg.source:
        sync_root(root, arg)
    print('### Done ###')


Parroting user input The below may not look like much, but the ability to call methods in other classes, offloading all the work onto other classes from MainClass, and returning a variable to be passed to the next method is a rather large leap for me at least.

using System;

namespace CSharpTutoriel
{
    class Work
    {
        public static string TellMeWhatToSay(out string passTheQuote)
        {
            string whatIsWritten;
            Console.WriteLine("Tell Me What To Say");
            whatIsWritten = Console.ReadLine();
            passTheQuote = whatIsWritten;
            return passTheQuote;
        }
        public static void HelloWorld(string itWillBeSpoken)
        {
            Console.WriteLine(itWillBeSpoken);
        }
        public static void PressToContinue()
        {
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }

    class MainClass
    {

        public static void Main(string[] args)
        {
            string whatToSay;

            Work.TellMeWhatToSay(out whatToSay);
            Work.HelloWorld(whatToSay);
            Work.PressToContinue();
        }
    }
}

Redundancy of both out parameter and return

    public static string TellMeWhatToSay(out string passTheQuote)
    {
        string whatIsWritten;
        Console.WriteLine("Tell Me What To Say");
        whatIsWritten = Console.ReadLine();
        passTheQuote = whatIsWritten;
        return passTheQuote;
    }

You both write the result to an out parameter and return it. A violation the DRY principle, this outputs the same information twice. As the out parameter does not feel appropriate for a modern language to me, I will leave only the return:

    public static string TellMeWhatToSay()
    {
        string whatIsWritten;
        Console.WriteLine("Tell Me What To Say");
        whatIsWritten = Console.ReadLine();
        passTheQuote = whatIsWritten;
        return passTheQuote;
    }

Now that we eliminated that redundancy, we can simplify by returning directly:

    public static string TellMeWhatToSay()
    {
        Console.WriteLine("Tell Me What To Say");
        return Console.ReadLine();
    }

Unecessary alias of a built-in Console.ReadLine

    public static void HelloWorld(string itWillBeSpoken)
    {
        Console.WriteLine(itWillBeSpoken);
    }

HelloWorld is the same as Console.WriteLine so there is no need to write it.


remove kth last element from singly-linked list I have implemented a code to solve following problem. I would like to improve the code efficiency.

Pardon if I just printed out the result.
Code has O(N) time and constant space complexity.

Given a singly linked list and an integer k, remove the kth last
element from the list.

k is guaranteed to be smaller than the length of the list.
The list is very long, so making more than one pass is prohibitively expensive.
Do this in constant space and in one pass.

I used a window with the length of k and 2 pointers to track kth last element in the list. 2 pointers are: (1): previous to the first element, (2): the last element of window:
llnode *prev = llist->head;
llnode *last = llist->head;

CODE:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct llnode
{
    int value;
    struct llnode *next;
} llnode;

typedef struct xllist
{
    llnode * head;
    llnode * tail;
    size_t length;
} xllist;

bool create_node(xllist *list, int value)
{
    llnode *node = malloc(sizeof *node);
    if(!node)
    {
        return false;
    }
    list->length++;

    node->value = value;
    node->next = NULL;
    if(!list->head)
    {
        list->head = node;
        list->tail = node;
    }
    list->tail->next = node;
    list->tail = node;
    return true;
}

bool del_element_from_last(xllist *llist, int k)
{
    printf("len:%d \n", llist->length);
    //window with 2 pointers, length of k
    //prev is the prev node to the window
    llnode *prev = llist->head;
    llnode *last = llist->head;

    if(k > (size_t)llist->length)
    {
        return false;
    }
    else if (k == (size_t)llist->length)
    {
        llist->head = llist->head->next;
        return true;
    }

    for(int i=0; i<k; i++)
    {
        last = last->next;
    }

    //move window until last reaches end
    while(last)
    {
        prev = prev->next;
        last = last->next;
    }

    //remove first node of the window
    printf("deleted element:%d \n", prev->next->value);
    prev->next = prev->next->next;

}

int main(void)
{
    /*Given a singly linked list and an integer k, remove the kth last element from the list.
    k is guaranteed to be smaller than the length of the list.
    The list is very long, so making more than one pass is prohibitively expensive.
    Do this in constant space and in one pass.*/
    xllist llist = {NULL, NULL, 0};

    for(int i=0; i<100; i++)
    {
        if(!create_node(&llist, 100+i))
            printf("create fail\n");
    }

    del_element_from_last(&llist, 15);

}

I don't know what OS and compiler you use but running gcc -O2 main.c -o main -Wall -Wextra produces several warnings:
main.c: In function ‘del_element_from_last’:
main.c:41:18: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘size_t’ {aka ‘long unsigned int’} [-Wformat=]
   41 |     printf("len:%d \n", llist->length);
      |                 ~^      ~~~~~~~~~~~~~
      |                  |           |
      |                  int         size_t {aka long unsigned int}
      |                 %ld
main.c:47:10: warning: comparison of integer expressions of different signedness: ‘int’ and ‘long unsigned int’ [-Wsign-compare]
   47 |     if(k > (size_t)llist->length)
      |          ^
main.c:51:16: warning: comparison of integer expressions of different signedness: ‘int’ and ‘long unsigned int’ [-Wsign-compare]
   51 |     else if (k == (size_t)llist->length)
      |                ^~
main.c:73:1: warning: control reaches end of non-void function [-Wreturn-type]
   73 | }
      | ^

valgrind reports memory leak:
$ valgrind ./main
==10611== Memcheck, a memory error detector
==10611== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==10611== Using Valgrind-3.16.1 and LibVEX; rerun with -h for copyright info
==10611== Command: ./main
==10611==
len:100
deleted element:186
==10611==
==10611== HEAP SUMMARY:
==10611==     in use at exit: 1,600 bytes in 100 blocks
==10611==   total heap usage: 101 allocs, 1 frees, 2,624 bytes allocated
==10611==
==10611== LEAK SUMMARY:
==10611==    definitely lost: 32 bytes in 2 blocks
==10611==    indirectly lost: 1,568 bytes in 98 blocks
==10611==      possibly lost: 0 bytes in 0 blocks
==10611==    still reachable: 0 bytes in 0 blocks
==10611==         suppressed: 0 bytes in 0 blocks
==10611== Rerun with --leak-check=full to see details of leaked memory
==10611==
==10611== For lists of detected and suppressed errors, rerun with: -s
==10611== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)`

Why does this function
bool del_element_from_last(xllist *llist, int k)

and others return non-zero on success? Usually, functions in C return
0 on success and non-zero on failure. The current behavior in your
code is counter-intuitive.
You should add a function that prints the entire list.
If you do this:
del_element_from_last(&llist, 1);

your code crashes:
$ ./main
len:100
Segmentation fault


Fisher-Yates shuffle algorithm in javascript, modern and inside-out versions I've implemented two different versions of the Fisher-Yates shuffle in javascript, and I'd like to know if I've made any mistakes.

I'm creating a deck of playing cards. I'm interested in these shuffle algorithms.

The object passed to the rng parameters below is a wrapper for Johannes Baagøe's Alea, a seedable PRNG that should produce a better sample of random numbers than built-in Math.random. Its API is the same as that of Math.random.

I am mostly wondering if I have made any fencepost errors or misunderstood the examples I'm referencing.

/** shuffle

    Shuffle an array.

    @see http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm

    @param {Array} array
    @param {Function} random Optional RNG. Defaults to Math.random.
    @return {Array} The original array, shuffled.
*/
function shuffle (array, random) {
  var i = array.length, j, swap;
  while (--i) {
    j = (random ? random() : Math.random()) * (i + 1) | 0;
    swap = array[i];
    array[i] = array[j];
    array[j] = swap;
  }
  return array;
}

/** pushRand

    Insert a value into an array at a random index. The element
    previously at that index will be pushed back onto the end.

    @see http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_.22inside-out.22_algorithm

    @param {Array} object to shuffle.
    @param {Mixed} value to insert.
    @param {Function} optional RNG. Defaults to Math.random.
    @return {Number} The new length of the array.

*/
function pushRand (array, value, random) {
  var j = (random ? random() : Math.random()) * array.length | 0;
  array.push(array[j]);
  array[j] = value;
  return array.length;
}

Here's a demo of the shuffle. Reloading the page does the inside-out shuffle, and clicking the face-down card does the modern shuffle.

Edit: I found a fencepost error in the "modern" version and fixed it here, but it's still in the demo. Not sure about the "inside-out" version yet.

Edit: I stopped being lazy and factored this stuff out, so it should easier to look at now. New demo up.

Edit: inside-out ver had the fencepost error too. It should look like this, I think:

function pushRand (array, value, random) {
  var j = (random ? random() : Math.random()) * (array.length + 1) | 0;
  array.push(array[j]);
  array[j] = value;
  return array.length;
}

Thanks, Paul!

Edit: Taking Adam's optimization suggestion into account, the new code looks like this:

/** shuffle

    Shuffle an array.

    @see http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_.22inside-out.22_algorithm

    @param {Array} array Array to shuffle.
    @param {Object} rng Optional RNG. Defaults to Math.
    @return {Array} The original array, shuffled.
*/
function shuffle (array, rng) {
  var i = array.length, j, swap;
  if (!rng) rng = Math;
  while (--i) {
    j = rng.random() * (i + 1) | 0;
    swap = array[i];
    array[i] = array[j];
    array[j] = swap;
  }
  return array;
}

/** pushRand

    Insert a value into an array at a random index. The element
    previously at that index will be pushed back onto the end.

    @see http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm

    @param {Array} array Array to insert into.
    @param {Mixed} value Value to insert.
    @param {Object} rng Optional RNG. Defaults to Math.
    @return {Number} The new length of the array.

*/
function pushRand (array, value, rng) {
  var j = (rng || Math).random() * (array.length + 1) | 0;
  array.push(array[j]);
  array[j] = value;
  return array.length;
}

Here's the updated editable demo (relevant code at the bottom).

Unless you modify the inside out code to scale by (index+1)

       randomIndex = rand()*(index+1)|0;

You will not be covering all the possibilities.
For index == 0, you always generate 0 -- this is correct, but only by accident.

For index == 1, you also always generate 0 -- instead of a 50/50 split between 0 and 1

The second card in the deck misses its ONLY chance to get to be card[1].

The same problem continues for each card from then on, without the +1, randomIndex < index  when you want randomIndex <= index.

The problem may be even clearer for the last card placed in the deck. For a 52 card deck, index == 51, so randomIndex can be at most 50. So any prior card has a possibility of ending up at card[51], but not the last card. It can get no closer than card[50].

It should be reassuring that this change makes the math for the initial shuffle look more like that of the re-shuffle.


Using Try & Catch to solve exception I am working on a ADDIN that works on 3D drafting program. This ADDIN has historically grown and now I am doing a big rewrite.

During this rewrite I came across a issue. I have 2 (fairly similar) types of models I am trying to edit using the same code block ADDIN. They both have a property name (inside the 3D drafting progam) that does the same but the property name is different.

This difference is giving me a exception. But I am sure that there is only are two different names.

Is it acceptable to use Try and Catch like this?

' Set reference to the user defined property set
Dim oUserProperties As PropertySet =
    ReferencedDocument.PropertySets.Item("Inventor User Defined Properties")

Try
    oUserProperties.Item("Noz_Eccentric").Value = Eccentric
Catch ex As Exception
    oUserProperties.Item("Noz_Radius").Value = Eccentric
End Try

OR would it be better to rename the property when the exception is encountered? (sort of a file migration)

' Set reference to the user defined property set
Dim oUserProperties As PropertySet =
    ReferencedDocument.PropertySets.Item("Inventor User Defined Properties")

Try
    oUserProperties.Item("Noz_Eccentric").Value = Eccentric
Catch ex As Exception
    oUserProperties.Item("Noz_Radius").Name = "Noz_Eccentric"
    oUserProperties.Item("Noz_Eccentric").Value = Eccentric
End Try

Please do not comment on the o prefix used. It is common within the 3D drafting program API sample and I kinda inherited this behavior..

This question is highly specific to the Autodesk Inventor SDK.

While it's not really nice way to check if a property exists, it's documented by Autodesk
Inventor as the way to do it, since there's not a simple "Check if a property exists" method on the property set (which is very stupid).

The sample in VBA (not VB.Net) that Autodesk Provides can be found there

The main reason being that catching an Exception can be slower than checking if a method exists.

So in theory if you use this a lot (e.g. 1000 times in a loop), it may be theoreticaly be cleaner/faster/better, to first check which properties are defined, using the method:

PropertySet.PropertyInfo()

And check if the property exists.

That being said, Inventor may or may not use a COM+ interface which is not too fast.

If performance is not an issue, a practical advice can be to try to set the property and otherwise add it, if it does not exist.


Java Concurrent Recursive API Access I don't get to write multithreaded applications very often, so be gentle with my threads :-)

I have an API input which contains a "score" and then a bunch of child nodes which also have scores, and perhaps child nodes of their own. I need to quickly sum up the total score of the entire tree.

I've elected a newWorkStealingPool as I have read that this is a good implementation for applications where workers may spawn other workers.

My handler is awfully static. I don't always work in Java, but this felt like the appropriate solution. Correct if wrong? :-)

I think I've made thread safe the methods that could be troublesome. I'd obviously like to remove the synchronization from methods that maybe don't need it.

I'm very concerned about how I monitor the running threads to decide when my work is done. I think there is a race condition here that I am having trouble understanding, even if for now, this project works.

Don't worry too much about my throwing an Exception, please :-). It's just for now so as to not clutter up the other code.

Thank you!!

Oh! Java 8 is pretty new to me, too. I only just considered where I could use some new functionality.

Runner

import java.net.URL;

public class Runner {

    public static void main(String[] args) throws Exception {
        try{
            NodeHandler.addNode(new Node(new URL(args[0])));
        }catch(java.net.MalformedURLException e){
            System.out.println("Malformed URL Exception: " + e.getMessage());
        }
        System.out.println(Double.toString(NodeHandler.getTotal()));
    }

}

Node Handler

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

public class NodeHandler {
    private static int runningThreads = 0;
    private static double rewardsTotal = 0;
    private static ExecutorService es = Executors.newWorkStealingPool();

    public static synchronized void addNode(Node node) {
        es.execute(node);
    }

    public static synchronized void incrementThreadCount() {
        runningThreads++;
    }

    public static synchronized void decrementThreadCount() {
        runningThreads--;
    }

    public static synchronized void updateScore(double score){
        scoreTotal += score;
    }

    public static int getRunningThreads() {
        return runningThreads;
    }

    public static double getTotal(){
        while(getRunningThreads() > 0){
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return scoreTotal;
    }

}

Node

import java.util.*;
import java.net.URL;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class Node implements Runnable{

    private URL url;
    private StringBuilder rawJson = new StringBuilder();

    Node(URL url){
        NodeHandler.incrementThreadCount();
        this.url = url;
    }

    private void processNode() throws Exception{
        Scanner sc = new Scanner(url.openStream());

        while (sc.hasNext()) {
            rawJson.append(sc.nextLine());
        }
        sc.close();

        JSONParser jParser = new JSONParser();
        JSONObject jObj = (JSONObject) jParser.parse(rawJson.toString());
        JSONArray children = (JSONArray) jObj.get("children");
        NodeHandler.updateScore(Double.parseDouble(jObj.get("score").toString()));

        if (children != null && children.size() > 0) {
            for (Object o : children) {
                URL url = new URL(o.toString());
                NodeHandler.addNode(new Node(url));
            }
        }
        NodeHandler.decrementThreadCount();
    }
    @Override
    public void run(){
        try {
            processNode();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

A few things that I noticed, not necessarily in order:

The globally locked and secured total is an unnecessary bottleneck. The aggregation you're performing is really well-suited for subresult aggregation. Instead of updateScore which can only ever be entered by one thread, you should have a running aggregate as you traverse the node hierarchy.
Node should not know about NodeHandler. You're tightly coupling these two together through a static method, which makes your code hard to test. Instead of a static class, use dependency-injection
Your termination condition isn't perfectly secure against premature termination. Also the getTotal is basically busy-waiting. You also only ever have multiples of seconds when running this task, which doesn't bode well for smaller node-structures.
Declaring rawJson as a member-variable is not a good solution. The compiler may or may not notice that it's in fact a local variable and may or may not correctly free the memory you're not using anymore.
Java EE has a JsonParser implementation since Java 1. That implementation crucially allows directly streaming the JSON access, so long as you're using forward access only. This allows you to keep a minimal memory-footprint. Look into Json.createParser(InputStream)
Since you're creating tasks from your initial task, the ForkJoinPool and the use of ForkJoinTasks is the "correct" model to use here. With this knowledge we can rewrite your program to be significantly more idiomatic and probably quite a bit faster :) This also allows you to not need to think about the termination condition of your operation.


Find maximum length of array where every entries are the same Is the complexity of this code \$O(n^3)$? How can I improve the efficiency and reduce the complexity?

A = [3,2,4,2,4,2,4,5,3]
n= len(A)
def ALG2 (A,i,j):  #to check whether all entries between A[i] and A[j] are the same
    if i==j:
        return True
    for k in range (i,j-1):
        if A[k] != A[k+1]:
            return False
    return True

def  ALG1(A,n):   #find the max length of the arrays that are found in ALG2
    l=0
    for i in range (0,n-1):
        for j in range (i+1,n-1):
            if ALG2(A,i,j) and (j-i)>l:
                l= j-i

    return l

result = ALG1(A,n)

print (result)

You should use better function names ALG1 and ALG2 don't really say what they're performing.
You should keep the creation of A, n and result at the bottom of your code.
You should keep your 'main' code in a main guard block:

if __name__ == '__main__':
    A = [3,2,4,2,4,2,4,5,3]
    n= len(A)
    result = ALG1(A,n)
    print(result)

You should follow PEP 8, so that it's easier for others to read your code.
ALG2 can be simplified by slicing the array from i to j, A[i:j], and then checking if the set has a size of one.

def ALG2(A, i, j):
    return len(set(a[i:j])) == 1

Your entire code can be drastically simplified by using itertools.groupby.

import itertools

def ALG1(array):
    sizes = (
        sum(1 for _ in g)
        for _, g in itertools.groupby(array)
    )
    return max(sizes, default=0)


Using XDocument properly I have a WCF service in which I am reading and adding some records to a .xml file.  I load the .xml document in the constructor and use it in all the methods and save when it's updated.

I want to know if this is the correct way of using it.  I have seen code around where people load the xDocument only when it's required.  If I try that, will it affect performance of individual method calls in cases of big .xml files?

 [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class MyService : IMyService
{
    private readonly string mSchemaPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data",
        "schema_0.1.xsd");
    private readonly string mXmlPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data",
        "MyDataRecords.xml");

    private XDocument mXDocument;

    public MyService()
    {
        try
        {
            //load xml document
            mXDocument = XDocument.Load(mXmlPath);

            if (mXDocument == null)
            {
                throw new Exception("Null returned while reading xml file");
            }
        }
        catch (Exception e)
        {
           //my exception management code
        }
    }

    public List<MyDataRecords> GetAllRecords()
    {
        ////fetch records from xDocument

       mXDocument.Save();
    }
    public void AddRecord(MyRecord record)
    {
        ////add record

       mXDocument.Save();
    }

As you are using a singleton which loads the document once, I would say "Yes you will probably see some degradation in performance to service calls if you only load it on demand".

If your service is the one and only program which modifies the document then your approach is probably viable.

A few notes:

Don't throw Exception. Be as specific as you can.
You mentioned that the file might be big. I don't know what the particular requirements of your application are but be aware that should the service crash at the right moment while saving changes you'll very likely be left with a corrupt xml document because it was only partially saved. Even if it is only a one a million chance it can still be a big problem.
Your service sounds like it's using an xml file as some kind of cheap db backend data store. While there might be scenarios where this is the best/only option forward you might want to consider if it's not better to use an embedded db like SqLite, Sql Server CE or similar ones and have an xml export option instead.


Get the character and its count which has highest occurrence I have this C# method which get the character and its count which has highest occurrence
    public KeyValuePair<char, int> CountCharMax_Dictionary_LINQ(string s)
    {
        char[] chars = s.ToCharArray();

        var result = chars.GroupBy(x => x)
            .OrderByDescending(x => x.Count())
            .ToDictionary(x => x.Key, x => x.Count())
            .FirstOrDefault();

        return result;
    }

It works but is there any better or efficient way to get the same result? Is there any difference if I return it as Tuple vs KeyValuePair?
Test data:

Input: 122. Expected Output: 2,1
Input: 122111. Expected Output: 1,4

As per this answer, it would be wiser to use a tuple in this case. I use lowercase "t"uple as I highly recommend the built-in language support for tuples (char, int) over the explicit Tuple<T1, T2> declaration, etc. Few more points:

What should happen in a tie? Which gets returned? If any is acceptable, it's fine as-is. To be more of a determinate function, secondarily order by the character itself.
Don't need to convert it to a character array as a string already is a character array.
Re-order the OrderByDescending and the Select so that Count only has to be called once.
It can be made static since it doesn't access class instance data.
It can be made an extension method if in a static class.
It can be made into an expression-bodied method.
Maybe consider a better name; one that confers what it does rather than how it does it.

All that said, here's my take:
    public static (char, int) MaxCharacterFrequency(this string s) =>
        s.GroupBy(x => x)
         .Select(x => (x.Key, x.Count()))
         .OrderByDescending(x => x.Item2)
         .ThenBy(x => x.Item1)
         .FirstOrDefault();


Asking for player name and age using OOP I have a text adventure game and I need to use OOP so I've chosen to use it when getting the player's name and age. I need to keep the OOP; but was wondering if there are any ways to clean up the code or simplify it while still getting the overall output.

class Player:
    def __init__(self):
        self.get_name()
        self.verify_age()

    def get_name(self):
        print("If you are ready lets begin!")
        while True:
            print("What is your name?")
            name = input(":> ")
            if not name.istitle():
                print("Please enter a name starting with a capital letter; try again.")
            else:
                self.name = name
                print("Hello " + name + " prepare for battle.")
                break

    def verify_age(self):
        while True:
            print("Before we begin please verify your age. \nWhat is your age?")
            age = input(":> ")
            try:
                if 8 < int(age) <= 110:
                    self.age = age
                    break
                elif int(age) <= 8:
                    print("You are not old enough to play the game! Try again.")
                else:
                    print("You can't be that old, come on! Try again.")
            except:
                print("That is not a valid number! Try again.")

The methods in this class are not really Player methods. They are a combination of game flow, user input and value verification methods.   I'd organize it more like this.
class Game:
  def __init__(self):
    io.show("If ready, let's begin")
    name = self.get_valid_name()
    age = self.get_valid_age()
    self.player = Player(name, age)
    io.show("Hello {}, prepare for battle".format(self.player.get_name()))

The Game object owns the flow of control.  The I/O is encapsulated in an object which can be a simple stdio wrapper for now, but may eventually include non-blocking input or html output or whatever - don't tie the game logic to the display method.  The Player object contains player state.
The get_valid_x methods can basically be what you have now. If you are using that pattern over and over, you could get fancy and write a parameterized validator:
def get_valid_input(prompt, validation_func):
  while True:
    input = io.prompt(prompt)
    guidance = validation_func(input)
    if not guidance:
      return input
    io.show(guidance)

def validate_name(str):
  if not str.istitle():
    return "Please enter name beginning with capital Letter"
  return None

 ...

 name = get_valid_input("What is your name?", validate_name)


jQuery validation code Would like some assistance in improving my jQuery validation code. I have some repeated code, but I am not sure how to write it in a way so that I don't have to keep repeating the same code over and over again for different variable names etc... (such as the if statement part) My goal is to make it so that I can easily apply it to any other form I create.

Here is the jsFiddle

(function($) {

    $('.commentForm').submit(function () {

        var error = 'error';

        var name = $(this).find('.name')
        nameVal = name.attr('value')
        email = $(this).find('.email')
        comment = $(this).find('textarea')
        commentVal = comment.html();

        if (!(name.val() === nameVal || name.val() === '' || name.val().length < 3) &&
            !(comment.val() === commentVal || comment.val() === '' || comment.val().length < 3) &&
            validateEmail(email.val())
           ) {
            console.log('Form is good');
            return true;
        } else {

            (name.val() === nameVal || name.val() === '' || name.val().length < 3) ? name.addClass(error) : name.removeClass(error);
            (comment.val() === commentVal || comment.val() === '' || comment.val().length < 3) ? comment.addClass(error) : comment.removeClass(error);
            (!validateEmail(email.val())) ? email.addClass(error) : email.removeClass(error);

            console.log('Form is BAD');
            return false;

        }

    });

    function validateEmail(email) {
        var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
    }

}) (jQuery);

This confuses me:

name.val() === nameVal

The variable nameVal is equal to the value attribute of name. And, the calling val() on name returns the value attribute of name so of course they are going to be equal.

I may be missing something here, but I think this is unnecessary.

Long chunks of mush like this:

(name.val() === nameVal || name.val() === '' || name.val().length < 3) ? name.addClass(error) : name.removeClass(error);
            (comment.val() === commentVal || comment.val() === '' || comment.val().length < 3) ? comment.addClass(error) : comment.removeClass(error);
            (!validateEmail(email.val())) ? email.addClass(error) : email.removeClass(error);

and this:

!(name.val() === nameVal || name.val() === '' || name.val().length < 3) &&
            !(comment.val() === commentVal || comment.val() === '' || comment.val().length < 3) &&
            validateEmail(email.val())

are in no way whatsoever readable. You need to either

Break this up. Maybe everything here is not necessary.
Split this into variables and check with the variables.

I think you should go with the first option, because these can be simplified:

1:

As I stated above, having

name.val() === nameVal

is unnecessary. You can just remove this.

2:

The value "" is called a falsey value. That means that "" can be treated as though it were false.

So, for example, this here:

name.val() === ''

can be reduced to:

!name.val()

Constantly calling the .val function on these elements in each of your conditionals is inefficient. You should store the result of .val() in a variable, and just use that for the conditionals (I think nameVal should already hold the .val() for name).

Now, for example, one of your conditional chunks becomes:

( !nameVal || nameVal.length < 3) ? name.addClass(error) : name.removeClass(error);

(! commentVal || commentVal.length < 3) ? comment.addClass(error) : comment.removeClass(error);

(!validateEmail(email.val())) ? email.addClass(error) : email.removeClass(error);

Where commentVal is comment.val() and nameVal is name.val()


Check database for item and create it if it doesn't exist Is there a more efficient approach to this code?

// save associated tag
let saveTag question =

    if question.Tag = null then
        ()
        else
            let tagCount =
                query{
                    for row in db.Tags_Tags_Tags do
                    where (row.Tag = question.Tag)
                    select row
                    count
                }

            if tagCount > 0 then
                ()
                else
                    let tagToSave =
                        dbSchema.ServiceTypes.Tags_Tags_Tags(
                            Tag = question.Tag
                        )
                    insertRowIn db.Tags_Tags_Tags tagToSave
                    saveToDb()

You don't need the empty if branches. An if without an else automatically returns unit. So you can simplify it to:

let saveTag question =

    if question.Tag <> null then
        let tagCount =
            query{
                for row in db.Tags_Tags_Tags do
                where (row.Tag = question.Tag)
                select row
                count
            }

        if tagCount = 0 then
            let tagToSave =
                dbSchema.ServiceTypes.Tags_Tags_Tags(
                    Tag = question.Tag
                )
            insertRowIn db.Tags_Tags_Tags tagToSave
            saveToDb()


Generating string primary keys with sequence in SQLAlchemy I need improvement on solution to the following problem:

  Generating random string keys in SQA is relatively simple, something
  like:

request_id = Column(String, default=lambda: uuid.uuid4().hex, primary_key=True)

  However, I need to to get request_id have format like
  DIVISION_ABC_REQUEST_223 (this is because PK is also supposed to be
  good for human consumption -- that key will be sent around in emails,
  copied/pasted, etc, but it also should be usable for regular SQA/SQL
  queries as a typical PK), with integer suffixes ideally following a
  normal (ordinal) sequence.

  (the backend DB is Postgres)

I found a solution, if a bit wasteful:

class WorkPackage(Base):
    __tablename__ = 'work_package'
    int_id = Column(Integer, primary_key=True)
    wp_prefix = Column(Unicode, default=u'DIVISION_ABC_REQUEST_', primary_key=True)
    data = Column(Unicode)

    @hybrid_property
    def wp_id(self):
        return self.wp_prefix + str(self.int_id)

    @wp_id.expression
    def wp_id(cls):
        return cls.wp_prefix.concat(cls.int_id)

wp_id.expression uses concat (a ColumnOperator that produces SQL concatenation operator ||).

It works in the sense of automatic PK creation in desired order and for querying by the wp_id attribute.

However, the silly aspect is that obviously there's a single column filled with the same prefix over and over.

The obvious problem here is that wp_prefix is a column for a single reason: so that I could use its concat method.

I would like to change it in such way that the wp_prefix column is unnecessary (e.g. it could be SQL concatenation of a string and int_id column).

I do not know how to construct SQLAlchemy Core expression that would achieve this without using column method.

literal_column("'DIVISION_ABC_REQUEST'").concat... (note the double quotes, since you want an SQL string expression).

literal_column() essentially means "I hand you this string which is a valid SQL expression and can be used in any column expression-ish context".


Insert into any sorted container The following is my attempt to implement a insert_sorted() C++ function that accepts any sorted STL container and item and inserts it at the right position in the container:
template<template<typename, typename, typename> typename C, typename T1, typename Comp, typename A, typename T2>
inline typename C<std::enable_if_t<std::is_convertible_v<T1, std::remove_reference_t<T2>>, T1>, Comp, A>::iterator
insert_sorted (C<T1, Comp, A> & c, T2 && item)
{
    return c.insert (c.end(), std::forward<T2> (item));
}

template<template<typename, typename> typename C, typename T1, typename A, typename T2, typename Comp = std::less<T1>>
inline typename C<std::enable_if_t<std::is_convertible_v<T1, std::remove_reference_t<T2>>, T1>, A>::iterator
insert_sorted (C<T1, A> & c, T2 && item, Comp comp = Comp{})
{
    return c.insert (std::upper_bound (std::begin (c), std::end (c), static_cast<T1>(item), comp), std::forward<T2> (item));
}

These two compile and work fine; the first overload works for set-like containers, while the second for vector-like containers.
I was wondering if you see any drawbacks to this solution and if there is a more generic way to approach the problem, that is, is it possible to write a single insert_sorted() function that does the same as the above two?
EDIT:
Thanks to the comments, I was able to replace the two template functions above with the following:
template<typename C, typename T, typename Comp = std::less<T>,
         typename = std::enable_if<is_convertible_v<std::remove_reference_t<T>, typename C::value_type>>>
    inline auto insert_sorted (C & c, T && item, Comp comp = Comp{})
{
    return c.insert (std::upper_bound (std::begin (c), std::end (c), item, comp), std::forward<T> (item));
}

Thank you all for your help!

When we use std::begin() and std::end(), we should always consider whether we actually want to use begin() and end() of the type's namespace instead (argument-dependent lookup, aka ADL), with fallback to std:
using std::begin();
using std::end();
return c.insert(std::upper_bound(begin(c), end(c), item, comp),
                std::forward<T>(item));

When we're inserting to a sorted container such as std::set, we probably want to use the container's key_compare as default, rather than std::less<T>.  I suspect that will require splitting back into two functions again.


Bayesian spam filter interface In essence, what I'm looking to do is split a string into one-word and two-word segments, and train classifiers against them. First it lowercasifies the string, then strips all non-alphanumeric characters.

Then, it splits the strings into a list of one-word entries. Afterward, it creates a new *[]string which it fills with all sequential two-word entries.

In particular, I'm concerned about the way I'm creating the two-word *[]string slice, and the way I'm using pointers. The first is an efficiency issue, and the second is a, well, I suppose memory-efficiency issue.

const (
    Spam     bayesian.Class = "Spam"
    Spamlike bayesian.Class = "Spamlike"
    NotSpam  bayesian.Class = "NotSpam"
)

type SpamFilter struct {
    singleWordClassifier *bayesian.Classifier
    doubleWordClassifier *bayesian.Classifier
}

func CreateNewSpamFilter() *SpamFilter {
    v1 := bayesian.NewClassifier(Spam, Spamlike, NotSpam)
    v2 := bayesian.NewClassifier(Spam, Spamlike, NotSpam)
    tmp := SpamFilter{v1, v2}
    return &tmp
}

func LoadSpamFilterFromFile(fileName1 string, fileName2 string) *SpamFilter {
    tmp1, err1 := bayesian.NewClassifierFromFile(fileName1)
    tmp2, err2 := bayesian.NewClassifierFromFile(fileName2)
    switch {
    case err1 != nil:
        panic(err1)
    case err2 != nil:
        panic(err2)
    }
    return &SpamFilter{tmp1, tmp2}
}

func splitStringToSingleWords(input string) *[]string {
    reg, err := regexp.Compile("[^A-Za-z0-9 ]+")
    if err != nil {
        panic(err)
    }

    tmp := reg.ReplaceAllString(input, "")
    split := strings.Fields(tmp)
    return &split
}

func SplitStringToWords(input string) (*[]string, *[]string) {
    splitSingle := splitStringToSingleWords(strings.ToLower(input))
    var splitDouble = make([]string, len(*splitSingle)-1)

    for i := 0; i < len(*splitSingle)-1; i++ {
        splitDouble[i] = (*splitSingle)[i] + " " + (*splitSingle)[i+1]
    }

    return splitSingle, &splitDouble
}

func (filter *SpamFilter) TrainStringsInSpamFilter(trainType bayesian.Class, singleWords *[]string, doubleWords *[]string) *SpamFilter {
    (*filter).singleWordClassifier.Learn(*singleWords, trainType)
    (*filter).doubleWordClassifier.Learn(*doubleWords, trainType)
    return filter
}

func (filter *SpamFilter) TestStringThroughSpamFilter(testString string) (*[]float64, *[]float64) {
    splitSingle, splitDouble := SplitStringToWords(testString)
    p1, _, _ := (*filter).singleWordClassifier.ProbScores(*splitSingle)
    p2, _, _ := (*filter).doubleWordClassifier.ProbScores(*splitDouble)
    return &p1, &p2
}

How does this look, generally-speaking? What should I have done differently?

Also, copied here:

How is my use of pointers (is it, well, correct)?
Am I segmenting the strings in the most efficient possible way? I intend to use this on a rather large dataset.
Will this be threadsafe/goroutine-friendly for large datasets?

You've missed import block, so I will assume, that you are using github.com/jbrukh/bayesian as bayesian in provided snippet.

Passing slices by value

Hm. I see how you've used pointers with slices. Let me tell you a bit about the slice internals.

In Go slice values are backed by a small struct simular to this one in C:

struct Slice {
    Elem *ptr;
    int cap;
    int len;
};

cap and len fields stand for slice capacity and length. ptr holds a pointer for continuous memory of slice elements.

So, when you copy a slice by value, you actually copy it's header, not it's content:

a := []string{"Hello,", "World!"}

// Copying slice by value and changing it
b := a
b[1] = "Code Review!"

fmt.Println(a[0], a[1])

The provided snippet will output Hello, Code Review! because both a's and b's ptr point to the very same memory.

It's totally fine to pass a slice by value. Most standard library code do it like this.

To follow up here is a nice post Go Slices: usage and internals at Golang Blog about slices and arrays internals, I suggest you to take a look. It explains a lot about how they are made and why it is okay to pass them by value.

Tip: if you really need a copy of a slice use copy.

Also, don't dereference struct values like in (*filter).singleWordClassifier.

Use filter.singleWordClassifier directly.