texts:
I have a small gem that I've been maintaining. This gem provides a simple way to do translation using an alternative Google API.

I've been working with Java last year and recently did some refactoring on that gem, but I don't think it's Rubyist enough.

require_relative 'extractor'
require_relative 'requester'
require_relative 'translator'

module FreeGoogle
  ##
  # Responsible for create instance of {FreeGoogle::Translator}
  # It holds all dependencies for this creation
  class Factory
    def self.create
      extractor = FreeGoogle::Extractor.new
      http_requester = FreeGoogle::Requester.new
      FreeGoogle::Translator.new(extractor, http_requester)
    end
  end
end

Source code

Are factories commonly used in Ruby?


texts:
Is this code well protected, and if not, could you tell me how it might be exploited and how to secure it?

if(isset($_POST['vrsta_predmeta']) AND !empty($_POST['vrsta_predmeta']) AND

isset($_POST['res_text']) AND isset($_POST['glavni_dug']) AND isset($_POST['res']) AND isset($_POST['zaklj']) AND isset($_POST['povjerilac']) AND isset($_POST['duznik']) AND isset($_POST['predmet_zaveden'])){

$racunob =  trim($_POST['rac']);
$obrazlozenje = trim($_POST['obr']);
$ob_text = trim($_POST['res_ob']);
$res_text = trim($_POST['res_text']);
$vrsta_pre = trim($_POST['vrsta_predmeta']);
$izvrsenje = trim(strtolower($_POST['res']));
$obrazac = trim($_POST['zaklj']);
$povjerilac = $_POST['povjerilac'];
$duznik = $_POST['duznik'];
$datum= trim($_POST['predmet_zaveden']);
 foreach($povjerilac as $key){
 $lica = $db -> prepare("INSERT INTO p_lica(povjerilac, doc_br, dokument_vlasnik) VALUES('$key', '$dok_broj', '$ses_val')");

}

foreach($duznik as $key1){
 $lica1 = $db -> prepare("INSERT INTO d_lica(duznik,doc_br, dokument_vlasnik) VALUES('$key1', '$dok_broj', '$ses_val')");

}

$insert_dok = $db -> prepare("INSERT INTO document_tbl(dokument_vlasnik,dokument_broj,vrsta_dokumenta,zakljucak, resenje_izvrsenja,datum,resenje_text,obrazlozenje,obtext,racunob) VALUES('$ses_val','$dok_broj', '$vrsta_pre','$obrazac','$izvrsenje','$datum','$res_text','$obrazlozenje','$ob_text','$racunob')");
if($lica -> execute() AND $insert_dok -> execute() AND $lica1 -> execute()){

   $lica -> close();
   $lica1 -> close();
   $insert_dok -> close();

  echo '<script>new Messi(\'Dokument uspjesno dodat.\', {title: \'Obavjestenje\', titleClass: \'success\', buttons: [{id: 0, label: \'Close\', val: \'X\'}]});</script>';
header('location:login.php');
  }else{
   echo '<script>new Messi(\'Dokument uspjesno dodat.\', {title: \'Obavjestenje\', titleClass: \'anim warning\', buttons: [{id: 0, label: \'Close\', val: \'X\'}]});</script>';
}

}


texts:
I'm a bit new to Python and sort of learning on my own. I wrote a small function to help me find the latest file in a directory. Taking a step back, it reads a bit janky and I was curious what steps or what resources I could look into to help me make this more friendly. Should I be returning False? Or 0?
Inside my example/files directory are 3 files which were, for this example, created on the dates specified in the file name:

example/files/randomtext011.201602012.txt
example/files/randomtext011.201602011.txt
example/files/randomtext011.201602013.txt

import os.path
import glob
import datetime

dir = 'example/files'
file_pattern = 'randomtext011.*.txt'

def get_latest_file(file_pattern,path=None):
    if path is None:
        list_of_files = glob.glob('{0}'.format(file_pattern))
        if len(list_of_files)> 0:
            return os.path.split(max(list_of_files, key = os.path.getctime))[1]
    else:
        list_of_files = glob.glob('{0}/{1}'.format(path, file_pattern))
        if len(list_of_files) > 0:
            return os.path.split(max(list_of_files,key=os.path.getctime))[1]
    return False


texts:
I am doing a function that pixelates black and white images. The function must be called pixelate(img, (pixel_width, pixel_height), mode).

The parameter (pixel_width, pixel_height) is a tuple which indicates the size of the resulting pixel values. the function must return a result in any event, even if they are higher than the image dimensions. If the image size is not a multiple of the pixel size,some of the resulting pixels will have a smaller size than (pixel_width, pixel_height). This smaller pixels will be located in the right and bottom edge of the image as shown in the examples below. In other words, the pixels always start from the top left corner of the image.

The parameter mode, is an string, 'min', 'max' or 'mean'. We will write 'mean', if we want to calculate the mean value of the area where a pixel of the new image is going to be. We will write 'max' if we want the brightest value or 'min' for the darkest. If the mean value has decimals, we will only use the integer part.

Now I have the program done, but I want to do it writing the shortest possible code, to use as little CPU memory and time as possible.

from PIL import Image

import numpy as np

def pixelate_mode(mode):
    if mode == 'mean':
        return np.mean
    elif mode == 'min':
        return min
    elif mode == 'max':
        return max

def pixelate(img, (pixel_width, pixel_height), mode):
    width, height = img.size
    W = 0
    while W * pixel_width < width:
        H = 0
        while H * pixel_height < height:
            l = []
            for x in xrange(pixel_width * W, pixel_width * (W + 1)):
                for y in xrange(pixel_height * H, pixel_height * (H + 1)):
                    if x < width and y < height:
                        l.append(img.getpixel((x, y)))
            color = pixelate_mode(mode)(l)
            for x in xrange(pixel_width * W, pixel_width * (W + 1)):
                for y in xrange(pixel_height * H, pixel_height * (H + 1)):
                    if x < width and y < height:
                        img.putpixel((x, y), color)
            H += 1
        W += 1
    return img

And these are some examples applying the program to this image: it has 200×200 pixels, and each square of the image is 10×10 pixels.

pixelate(img, (10, 10), 'mean'), pixelate(img, (5, 5), 'max'),
pixelate(img, (2, 2), 'min') and pixelate(img, (1, 1), 'mean') return the same image.

pixelate(img, (11, 11), 'mean') returns this.


texts: Multiple audio player - arrow keys & space

texts:
I am creating a VueJS component of an audio player.
I am having some difficulties in finding the ideal way to get the arrow keys and space bar to work.
I have found a solution, however I think it is not the best, nor the most effective. I've added an event listener to the DOM in the component, but the problem is that I will have multiple players along the page, so I will have multiple DOM listeners.
Is it a good solution or is there a better one?
    // component code
    ...

     document.addEventListener( 'keydown', event => {
        if ( !state.isPlaying )
            return;

        switch ( event.keyCode ) {
            case 32:
                pause();
                break;
            case 37:
                audio.currentTime -= 2;
                break;
            case 39:
                audio.currentTime += 2;
                break;
            default:
                break;
        }
    });
```


texts: Find all of the values in a list that are repeated the most

texts:
I have a list of objects and I would like to see which ones are the most common. It is easy to find the or a most common object using python's Counter, but I haven't found a simple way to find all of the most common objects. The code below is working but I would guess there's a better way to do this.

from collections import Counter

input_lst = [1, 2, 3, 3, 4, 4, 0, 1]

counts = Counter(input_lst)
ranked_counts = counts.most_common().copy()
first_common_obj = ranked_counts.pop(0)
equally_common_objs = [first_common_obj[0]]
while ranked_counts:
    next_obj = ranked_counts.pop(0)
    if first_common_obj[1] == next_obj[1]:
        equally_common_objs.append(next_obj[0])
    else:
        break

print(equally_common_objs)


texts: Listing last 3 items (or all if less than 3) in an ArrayList

texts:
Writing a code to return the last 3 items in a list, if the list has 3 or more elements, otherwise return all list items.

But the code looks really bad.
What is a better way to write the same code?

   public void test_arrayListItems() {
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("item1");
        arrayList.add("item2");
        arrayList.add("item3");
        arrayList.add("item4");
        arrayList.add("item5");
        arrayList.add("item6");
        arrayList.add("item7");
        arrayList.add("item8");

        String items = "";
        int j = 0;
        int k = 0;

        if (arrayList.size() <= 2) {
            j = arrayList.size() - 1;
        } else if (arrayList.size() > 2) {
            j = arrayList.size() - 1;
            k = arrayList.size() - 3;
        }
        for (int i = k; i <= j; i++) {
            items = items + "- " + arrayList.get(i) + " ";
        }
        logger.info(items);
    }

thanks


texts:
Just mucking around with Elixir and bitstrings and wondering if there is a better way to implement the following ( or improve ).  :-

   defmodule Crypto do
      def hexdigit( digit ) do
        case digit do
          d when d >= ?0 and d <= ?9    -> d - ?0
          c when c >= ?a and c <= ?f   -> c - ?a + 10
          c when c >= ?A and c <= ?F   -> c - ?A + 10
          _ -> 0
        end
      end

      def bin(hex) do
        Enum.map(to_char_list(hex), fn x -> <<hexdigit(x)::size(4)>> end) |> :erlang.list_to_bitstring
      end
    end

Note: I'm not looking for a call to a library to do the conversion to binary.


texts: Better way to extract country wise player list from html file using regex

texts:
Problem statement:

Make country wise player list from the following html code

HTML CODE:

        Australia

Steven Smith

David Warner

        Bangladesh

Mashrafe Mortaza

Tamim Iqbal

        England

Eoin Morgan

Jos Buttler

Expected Output:

Australia- Steven Smith, David Warner

Bangladesh- Mashrafe Mortaza, Tamim Iqbal

England- Eoin Morgan, Jos Buttler

My Code:

import re

with open('playerlist.html', 'r') as f:
    text = f.read()

mytext = re.sub(r'[\n\t]', '', text)

pat = r'
(\w+?)

(\w+\s?\w+)

(\w+\s?\w+)
'

cpat = re.compile(pat)

result = cpat.findall(mytext)

for a,b,c in result:
    print('{0}- {1}, {2}'.format(a,b,c))


texts:
I wrote a script to scroll pages when menu buttons are clicked, similar effect like: http://css-tricks.com/examples/SmoothPageScroll

var m1 = document.getElementById('m1'),
    m2 = document.getElementById('m2'),
    m3 = document.getElementById('m3'),
    m4 = document.getElementById('m4'),
    m5 = document.getElementById('m5'),
    m2PositionY = document.getElementById('id2').offsetTop,
    m3PositionY = document.getElementById('id3').offsetTop,
    doneValue = true,
    windowPageYOffset = 0;

function Scroll(ScrollValue1) {
    windowPageYOffset = window.pageYOffset;
    if(windowPageYOffset == ScrollValue1) {
        doneValue = true;
    }
    // scroll up
    else if(windowPageYOffset >= ScrollValue1) {
        window.scrollBy(0, -(1 + ((windowPageYOffset - ScrollValue1) / 10)));
    }
    // scroll down
    else {
        window.scrollBy(0, 1 + ((ScrollValue1 - windowPageYOffset) / 10));
    }
    if(windowPageYOffset != ScrollValue1) {
        var setTimeoutScrollValue1 = setTimeout('Scroll(' + ScrollValue1 + ')', 20);
    }
}

function doneOrNot(doneOrNotValue1) {
    if(doneValue && doneOrNotValue1 != windowPageYOffset) {
        Scroll(doneOrNotValue1);
        doneValue = false;
    }
}
m1.onclick = function () {
    doneOrNot(0); // no need for a id since top is allways 0
}
m2.onclick = function () {
    doneOrNot(m2PositionY);
}
m3.onclick = function () {
    doneOrNot(m3PositionY);
}

I am using a "true or false variable" (doneValue) to determine if previous Scroll is finished before next can start. I wonder if there is any better method to do this in JavaScript?

Please give other feedback if you have any :)


texts: Forming all multiples of 3 using the given digits

texts:
I'm working on this kata from Codewars. The task is:

Given a certain number, how many multiples of three could you obtain with its digits?
Supose that you have the number 362. The numbers that can be generated from it are:
362 → 3, 6, 2, 36, 63, 62, 26, 32, 23, 236, 263, 326, 362, 623, 632

I've written the following recursive function to calculate all possiblities:

const findMult_3 = (num) => {

  const powerset = (set) => {
    const combinations = []
    const combine = (prefix, chars) => {
      for (let i = 0; i < chars.length; i++) {
        const newPrefix = parseInt(prefix + chars[i])
        if (!combinations.includes(newPrefix)) {
          combinations.push(newPrefix)
        } else {
          console.log('encountered duplicate')
        }
        combine(newPrefix, chars.filter((x, ind) => ind !== i))
      }
    }
    combine('', set)
    return combinations.sort((a, b) => a - b)
  }

  const allCombinations = powerset(num.toString().split(''))
  const factorsOfThree = allCombinations.filter(x => x % 3 === 0).filter(x => x !== 0)

  return [factorsOfThree.length, factorsOfThree.pop()]

}

findMult_3(43522283000229)

I noticed early on that I encountered a lot of duplicate cases, hence the console.log('encountered duplicate') flag.
Execution of this algorithm is taking an extremely long time for large numbers, eg 43522283000229.
How can I improve the performance of this code? Or should it be scrapped entirely?


texts: Generic C++ exception catch handler macro

texts:
I have this set of legacy C++ projects with a large number of public functions.  At the start, none of those publicly exposed functions had try..catch insulation inside them.  When a C++ exception fired across that boundary, if the caller wasn't compiled with the same C++ compiler and the same project settings, then it easily caused a crash.

To help insulate against this problem I first went into every public function and wrapped the public function bodies with all-encompassing try...catch blocks, with the catch attempting to log a message about the exception.  Basically just handling the (...) case and logging "Unexpected Exception".

With hundreds of public functions (working up to thousands), this became tedious when I decided to add specialized std::exception handlers to them all, other dev team members update some to do something different, etc.

In the interests of DRY (Don't Repeat Yourself), I chose to make a generic catch block which gets applied in those instances where I wanted something fast to insulate a function from throwing an exception but get as much info as possible into the log.

C++ exceptions being what they are, I couldn't figure out a nice simple portable way to do it without using a macro.  Yes, yes, sad but true, another macro is born, but I am interested to learn about any other options considering it must be portable and fast.  I don't mean to say macros are portable and fast, but this implementation fits the bill...

#define CatchAll( msg ) \
    catch( const Poco::Exception &e )   \
    {   \
        try{ LogCritical( Logs.System(), std::string( e.displayText() ).append( msg ) );}catch(...){assert(0);} \
    }   \
    catch( const std::exception &e )    \
    {   \
        try{LogCritical( Logs.System(), std::string( e.what() ).append( msg ) );}catch(...){assert(0);} \
    }   \
    catch(...)  \
    {   \
        try{ LogCritical( Logs.System(), std::string( "Exception caught in " __FUNCTION__ ". " ).append( msg ) );}catch(...){assert(0);}    \
    }

So there you have it.  The code above gets called like this...

try{
   // statements that can throw
}
CatchAll("*Special extra message about what was attempted in the try block*")

So that's it, that's the magic.  This isn't meant to replace an intelligently coded block of specific exception handling, this is meant to quickly put bare-bones insulation where none existed before, and do it in a DRY, portable, fast and easy to grok way.

Ok, ok, macros are evil, I know, but what else could be done here?

And as goes the way of the macro, they proliferate and multiply.  Here's a secondary macro to set an rc code in addition to logging, so the function can return a failing rc if an exception throws in the insulated function...

/// Catch all generic exceptions and log appropriately.
/// Logger is insulated from throwing, so this is a NO THROW operation.
/// Sets rc (integer parameter) so wrapping function can perform cleanup
/// before returning the error number.
#define CatchAllSetRC( rc, msg )    \
    catch( const Poco::Exception &e )   \
    {   \
        (rc) = -1;  \
        try{ LogCritical( Logs.System(), std::string( e.displayText() ).append( msg ));}catch(...){assert(0);}  \
    }   \
    catch( const std::exception &e )    \
    {   \
        (rc) = -1;  \
        try{ LogCritical( Logs.System(), std::string( e.what() ).append( msg ));}catch(...){ assert(0); }   \
    }   \
    catch(...)  \
    {   \
        (rc) = -1;  \
        try{ LogCritical( Logs.System(), std::string( "Exception caught in " __FUNCTION__ ". " ).append( msg ));}catch(...){ assert(0); }   \
    }

This expanded version gets called with an rc code so the caller can return it...

int rc = 0;
try{
   // statements that can throw
}
CatchAll(rc, "Extra info to append to logged exception message")


texts:
I've compiled a simple Linux pipeline and using my C style and modularization that I will use for my own operating system. Do you have something to say about this code (partly taken from SO)? For example, are all my imports necessary? How can I improve error handling?

#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
struct command
{
    const char **argv;
};

int spawn_proc (int in, int out, struct command *cmd) {
    pid_t pid;
    if ((pid = fork ()) == 0) {
        if (in != 0) {
            dup2 (in, 0);
            close (in);
        }
        if (out != 1) {
            dup2 (out, 1);
            close (out);
        }
        return execvp (cmd->argv [0], (char * const *)cmd->argv);
    }
    return pid;
}

int fork_pipes (int n, struct command *cmd) {
    int i;
    pid_t pid;
    int in, fd [2];
    in = 0;
    for (i = 0; i < n - 1; ++i) {
        pipe (fd);
        spawn_proc (in, fd [1], cmd + i);
        close (fd [1]);
        in = fd [0];
    }
    if (in != 0)
        dup2 (in, 0);
    return execvp (cmd [i].argv [0], (char * const *)cmd [i].argv);
}

int main (int argc, char ** argv) {
    int i;
    if (argc == 1) { /* There were no arguments */
        const char *printenv[] = { "printenv", 0};
        const char *sort[] = { "sort", 0 };
        const char *less[] = { "less", 0 };
        struct command cmd [] = { {printenv}, {sort}, {less} };
        return fork_pipes (3, cmd);
    }
    if (argc > 1) { /* I'd like an argument */
        char *tmp;
        int len = 1;
        for( i=1; i<argc; i++)
        {
            len += strlen(argv[i]) + 2;
        }
        tmp = (char*) malloc(len);
        tmp[0] = '\0';
        int pos = 0;
        for( i=1; i<argc; i++)
        {
            pos += sprintf(tmp+pos, "%s%s", (i==1?"":"|"), argv[i]);
        }
        const char *printenv[] = { "printenv", 0};
        const char *grep[] = { "grep", "-E", tmp, NULL};
        const char *sort[] = { "sort", 0 };
        const char *less[] = { "less", 0 };
        struct command cmd [] = { {printenv}, {grep}, {sort}, {less} };
        return fork_pipes (4, cmd);
        free(tmp);
    }
}

What it does is simply a printenv | sort | less if there are no args and if there are arguments it is taken as parameter list to grep to grep for environment varibles. I'm using it to develop my programming and make my own command-line environment for my own FPGA operating system.


texts: Classifying integers as "weird" or "not weird"

texts:
Problem Statement

  Given an integer N, perform the following conditional actions:

  If N is odd, print Weird
  If N is even and in the inclusive range of 2 to 5, print Not Weird
  If N is even and in the inclusive range of 6 to 20, print Weird
  If N is even and greater than 20, print Not Weird

  Complete the stub code provided in your editor to print whether or not
  N is weird.

  Input Format: A single line containing a positive integer, N.

  Constraints: 1<=N<=100

  Output Format: Print Weird if the number is weird; otherwise, print
  Not Weird.

My Solution

if(N%2!=0)
    System.out.println("Weird");
else{
            if(N>=2&&N<=5||N>20)
            System.out.println("Not Weird");
            else
            System.out.println("Weird");
        }

Another Solution-

if(N%2==1)
            System.out.println("Weird");
        else
            {
            if(N>=2&&N<=5)
                System.out.println("Not Weird");
            else if(N<=20)
                System.out.println("Weird");
                else
                System.out.println("Not Weird");
        }

My question is, does one algorithm have better performance than the other, in other words, is there any advantage to using else if statements rather than logical operators.

P.S- I am new to coding in Java, and was just curious if there is an optimum way to write code that has better performance.


texts: Unit testing for concatenating two int arrays

texts:
Using Java 1.8, I created the following implementation to concat two int arrays:

public static int[] concat(int[] array1, int[] array2) {
    return IntStream.concat(Arrays.stream(array1), Arrays.stream(array2)).toArray();
}

The unit test I created to test this looks like this:

int[] numbers1 = new int[] {1, 4, 3, 10, 2, 11, 15, 8};
int[] numbers2 = new int[] {5, 6, 7, 9, 12, 13, 14};

@Test
public void concat() {
    int[] concatNumbers = ArrayUtils.concat(numbers1, numbers2);

    for (int i = 0; i < numbers1.length; i++) {
        assert(concatNumbers[i] == numbers1[i]);
    }

    for (int i = numbers2.length + 1; i < numbers2.length; i++) {
        assert(concatNumbers[i] - 1 == numbers1[i]);
    }
}

Questions:

Although my unit test works correctly, is there a better way to unit test this method (e.g. in terms of style, cleaner code, etc.)?
How could I change the actual implementation if I were to use varargs?

public static int[] concat(int[] ... args)


texts: Using a Function to emulate F# Match in C#

texts:
So this was inspired by:
this question
But doesn't actually answer it:
What do you think of:

public class Case<TRes>
{
    public Case(bool condition, Func<TRes> result)
    {
        Condition = condition;
        Result = result;
    }
    public bool Condition {get; private set;}
    public Func<TRes> Result { get; private set; }

    public static Case<TRes> Default(Func<TRes> value)
    {
        return new Case<TRes>(true, value);
    }
}

public static class Logic
{
    public static T Match<T> (params Case<T>[] cases)
    {
        return cases.First(c => c.Condition).Result();
    }
}

Which you could invoke:

int i = Logic.Match
(
    new Case<int>(IsCloudy(skyImage), () =>
    {
        ChangeWeatherIcon(Icons.Clouds);
        return 13;
    }),
    new Case<int>(a < b, () => a),
    Case<int>.Default(() => {throw new Exception(); })
);

it's purpose isn't quiet to emulate F#'s Match.
(Because F# match doens't actually take conditions, it is a stuctural/pattern match)
So really its kind of like the trinary operator, meets the nonOrdinal Select statment.

Anyone got any idea's on how to make it work cleaner? Maybe getting a way to get rid of the new's and the brackets


texts:
I would like to receive feedback about my code.  Is there any better way to shorten the code or is it fine?

Demo

var pass_strength;
function IsEnoughLength(str,length){
    if ((str == null) || isNaN(length))
        return false;
    else if (str.length < length)
        return false;
    return true;
}
function HasMixedCase(passwd){
    if(passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))
        if ( passwd.split(/[a-z]/).length >= 3 && passwd.split(/[A-Z]/).length >= 3)
            return true;
        else
            return false;
    else
        return false;
}
function HasNumeral(passwd){
    if(passwd.match(/[0-9]/))
        return true;
    else
        return false;
}
function HasSpecialChars(passwd){
    if(passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/))
        return true;
    else
        return false;
}
function CheckPasswordStrength(pwd)
{
    if (IsEnoughLength(pwd,14) && HasMixedCase(pwd) && HasNumeral(pwd) && HasSpecialChars(pwd))
        pass_strength = "Very strong";
    else if (IsEnoughLength(pwd,10) && HasMixedCase(pwd) && HasNumeral(pwd) && HasSpecialChars(pwd))
        pass_strength = "Strong";
    else if (IsEnoughLength(pwd,10) && HasMixedCase(pwd) && HasNumeral(pwd))
        pass_strength = "Medium";
    else
        pass_strength = "Weak";
    document.getElementById('pwd_strength').innerHTML = "Password strength: " + pass_strength;
}


texts: Implementing Student Record Java program

texts:
Is there a better way to implement my code in Java?  I used to code this in C++ and pretty much worked right off the bat. But in Java, it is different, as it won't let me input data on the string array name.  It seems to skip and move on to ask the user for the age rather than starting on name.

package student;
import java.util.*;

public class Student {

public static void main(String[] args) {
   int i, q, z, c, b;
   int x=0;
   String[] name = new String[30];
   int[] age = new int[30];
   String[] course = new String[30];
   String[] year = new String[30];
   String[] section = new String[30];
   int menuChoice;

   Scanner input = new Scanner (System.in);

   start:
   do{

       System.out.println("\t\t\tStudent Record Menu");
       System.out.println("\t\t1. Add Student\t2. View Students\t3. Search Student\t4. Exit");
       System.out.println("Enter a choice: ");
       menuChoice = input.nextInt();

       if (menuChoice==1)
       {
           for (z=x; z<=29; z++)
           {
               System.out.println("Full name:");
               name [z] = input.nextLine();
               System.out.println("Age:");
               age [z] = input.nextInt();
               System.out.println("Course:");
               course [z] = input.next();
               System.out.println("Year:");
               year [z] = input.next();
               System.out.println("Section:");
               section [z] = input.next();
               x++;
               continue start;
           }
       }
               else if (menuChoice==2)
               {
                   for (i=0; i<x; i++)
                   {
                       System.out.println(name[i] + age [i] + course [i] + year [i] + section [i]);
                   }
               }

   } while (menuChoice<4);

}
}


texts: Converting seconds to hours, minutes and seconds

texts:
The following question was taken from Absolute Java 5th ed. by Walter Savitch:

  Write a program that outputs the number of hours, minutes, and seconds that  corresponds to 50,391 total seconds. The output should be 13 hours, 59 minutes, and 51 seconds. Test your program with a different number of total seconds to ensure that it works for other cases.

This is the code that I have written:

    public class Question7 {

    private static final int MINUTES_IN_AN_HOUR = 60;
    private static final int SECONDS_IN_A_MINUTE = 60;

    public static void main(String[] args) {

        int seconds = 50391;

        System.out.println(timeConversion(seconds));

    }

    private static String timeConversion(int totalSeconds) {
        int hours = totalSeconds / MINUTES_IN_AN_HOUR / SECONDS_IN_A_MINUTE;
        int minutes = (totalSeconds - (hoursToSeconds(hours)))
                / SECONDS_IN_A_MINUTE;
        int seconds = totalSeconds
                - ((hoursToSeconds(hours)) + (minutesToSeconds(minutes)));

        return hours + " hours " + minutes + " minutes " + seconds + " seconds";
    }

    private static int hoursToSeconds(int hours) {
        return hours * MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE;
    }

    private static int minutesToSeconds(int minutes) {
        return minutes * SECONDS_IN_A_MINUTE;
    }
}


texts: Stored procedure to classify policies by sales date

texts:
Currently this is the store procedure I am working on, it is working according to some testing that was done. I feel that it could be improved though, could use some optimization, feedback or recommendations.

What is it supposed to do?  For given policy id passed in, grab all coverages associated with the policy. For each coverage get units that are tied to the coverage. I need to check for 3 conditions for all units for a coverage which is based on Sales_Closing_Date. Depending on the condition update the coverage table with the flag.

DECLARE @Policy_ID BIGINT = 0,
        @CurrCoverageID BIGINT = 0,
        @Year INT = 0
DECLARE @Coverages TABLE(CID INT IDENTITY(1,1),CoverageID BIGINT NOT NULL)
DECLARE @Units TABLE(UID INT IDENTITY(1,1),CoverageID BIGINT NOT NULL,SalesClosing DATE)
DECLARE @CoveragesOut TABLE(CoverageID BIGINT NOT NULL, MultiFlag CHAR(1))

SET @Year = (SELECT p.Reins_Year FROM dbo.Policy p WHERE p.Policy_ID = @Policy_ID)

--INSERT ALL COVERAGES FOR THIS POLICY
INSERT INTO @Coverages(CoverageID)
SELECT Coverage_ID FROM dbo.Coverages c WHERE c.Policy_ID = @Policy_ID

--GO THROUGH COVERAGE AND GET THEIR SALES CLOSING DATE
WHILE (SELECT COUNT(*) FROM @Coverages) > 0
BEGIN
    SET @CurrCoverageID = (SELECT TOP 1 CoverageID FROM @Coverages)
    INSERT INTO @Units(CoverageID,SalesClosing)
    SELECT DISTINCT
        @CurrCoverageID,
        CAST(pu.Sales_Closing_Date AS DATE)
    FROM dbo.Policy_Units pu
    WHERE pu.Coverage_ID = @CurrCoverageID
        AND pu.Sales_Closing_Date IS NOT NULL

    --WE SHOULD HAVE THE SALES CLOSING DATES NOW
    --INSERT INTO OUTPUT TABLE NOW...
    INSERT INTO @CoveragesOut(CoverageID,MultiFlag)
    SELECT DISTINCT
        u.CoverageID,
        CASE (SELECT COUNT(*) FROM @Units)
            WHEN 1 THEN
                CASE
                    --SPRING--
                    WHEN u.SalesClosing BETWEEN CAST('1/1/' + CAST(@Year AS VARCHAR) AS DATE) AND CAST('4/30/' + CAST(@Year AS VARCHAR) AS DATE) OR u.SalesClosing >= CAST('1/1/' + CAST(@Year AS VARCHAR) AS DATE) AND u.SalesClosing < CAST('5/1/' + CAST(@Year AS VARCHAR) AS DATE) THEN 'S'
                    --FALL--
                    WHEN u.SalesClosing BETWEEN CAST('7/1/' + CAST(@Year - 1 AS VARCHAR) AS DATE) AND CAST('12/31/' + CAST(@Year - 1 AS VARCHAR) AS DATE) OR u.SalesClosing >= CAST('7/1/' + CAST(@Year - 1 AS VARCHAR) AS DATE) AND u.SalesClosing < CAST('1/1/' + CAST(@Year AS VARCHAR) AS DATE) THEN 'F'
                END
            WHEN 2 THEN 'B'
            ELSE NULL
        END AS MultiFlag
    FROM @Units u

    --REMOVE THE CURRENT COVERAGE FROM TABLE VAR
    DELETE FROM @Coverages WHERE CoverageID = @CurrCoverageID

    --REMOVE UNITS FROM TABLE VAR
    DELETE FROM @Units

END

--FOR TESTING PURPOSES
SELECT c.Description,c.County_Description, co.*
FROM @CoveragesOut co
INNER JOIN dbo.Coverages c
ON c.Coverage_ID = co.CoverageID

If you need anything else, please let me know. Again, this query is working just fine.


texts:
I did the following exercise:

  Write a C program that does the equivalent of C++ string s; cin>>s;; that is, define an input operation that reads an arbitrarily long sequence of whitespace-terminated characters into a zero terminated array of chars.

I wonder if it's good code. What could be improved?

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

struct String {
    char* signs;
    size_t size;
    size_t capacity;
};

void String_allocate_space(char **c, size_t *capacity)
{
    if (*capacity == 0) {   // allocate the first time
        *capacity = 1;
        *c = malloc(sizeof(**c) * ((*capacity)));
    }
    else {
        *capacity *= 2;     // double the new capacity
        *c = realloc(*c, sizeof(**c) * (*capacity));
    }
    if (*c == NULL)
        exit(-1);
}

void add_character(struct String* string, int ch)
{
    if (string->size == string->capacity) {     // if current letter sz = capacity
        String_allocate_space(&string->signs, &string->capacity);
    }
    string->signs[string->size++] = ch;    // append the sign in the array
}

void String_read(struct String* string)
{
    int ch = ' ';
    while (ch = getc(stdin)) {

        if (!isalpha(ch))
            break;

        add_character(string, ch);
    }
    add_character(string, '\0');
}

void String_print(struct String* string)
{
    printf("%s", string->signs);
}

void String_free(struct String* string)
{
    int i = 0;
    for (i = 0; i < string->capacity; ++i) {
        free(string[i].signs);
        string[i].signs = NULL;
    }
}

int main()
{
    struct String string = { 0 };

    String_read(&string);
    String_print(&string);
    String_free(&string);

    getchar();
    return 0;
}


texts: Scripts loading Scripts Dynamically in Lua

texts:
I have been working with Lua lately and I have discovered that it is capable of doing some very interesting things. I have created a proof of concept that allows one Lua script to load another Lua script and use the loaded script to modify itself by passing itself as an argument to the creation function of the loaded script.  The basic example here is from a simple card game.

In this specific example, I have a Card "object" which is really just a LuaTable. At the top of the Player.lua script I have:

local card = require "Card"

Then I create a card "object" by calling:

function Player:addSpecificCardToDeck(cardSuit, cardType, cardId)
    table.insert(self.deck, card:new(cardSuit, cardType, cardId))
end

The Card.lua script loaded by require contains code that loads another script during its creation.  Here is the Card.lua script.  Please ignore cardSuit in this example as that code is incomplete and I have omitted it.

Card.lua

Card = {} -- the table representing the class, which will double as the metatable for the instances
Card.__index = Card -- failed table lookups on the instances should fallback to the class table, to get methods

local cardList = require "Cardlist"

-- syntax equivalent to "MyClass.new = function..."
function Card:new(cardSuit, cardType, cardId)

    local self = setmetatable({}, Card)

    self.id = cardId
    self.type = cardType

    --this is where another script is loaded
    print(self.id .. " cardID")
    --getAbilityScriptsForId returns the appropriate string
    self.testScript = require (cardList:getAbilityScriptsForId(2)) --2 is the proof of concept script being called
    test = self.testScript:new(self)
    test:increaseCardId()
    print(self.id.. " new cardID") --the cardID will have increased by 1

    return self
end

return Card

Here is the sample script being loaded:

SampleScript02.lua

SampleScript02 = {} -- the table representing the class, which will double as the metatable for the instances
SampleScript02.__index = SampleScript02 -- failed table lookups on the instances should fallback to the class table, to get methods

-- syntax equivalent to "MyClass.new = function..."
function SampleScript02:new(inputCard)

    self.card = inputCard

    return self
end

function SampleScript02:increaseCardId()
    self.card.id = self.card.id + 1
end

return SampleScript02

As stated in the comments, the self.id of the script that loads the sample script will be incremented by 1.  In theory, a script could pass itself into any potential script that modifies it.  When a table is passed as the argument to a function in Lua, changes made to it inside that function apply to the original table.  In contrast, when values such as integer or boolean are passed into a function, a copy is made instead.

What I am looking for is whether I am following the best practices for Lua, and also how to avoid any potential pitfalls that the language presents. Am I using require properly? I am still learning the language, so any tips on syntax are also much appreciated.


texts:
I'm following this

let StringOfLengthConstructor<'c> (input:string, length:int, defaultConstructor:string->'c) =
    match input with
    | null -> None
    | x when x.Length = length -> Some(defaultConstructor(input))
    | _ -> None
type String3 = | String3 of string
let String3 input = StringOfLengthConstructor<String3>(input, 3, String3)
type String4 = | String4 of string
let String4 input= StringOfLengthConstructor<String4>(input, 4, String4)

type String5 = | String5 of string
let String5 input = StringOfLengthConstructor<String5>(input, 5, String5)
type String6 = | String6 of string
let String6 input = StringOfLengthConstructor<String6>(input,6, String6)

and am trying to make more of these with hopefully less repetition. Can this be done without having to repeat type String3 =| String3 of string followed by this?

let String3 input = StringOfLengthConstructor<String3>(input, 3, String3)

See all the repetition?  For the purpose of defining a zip code, a US zip code could be defined as

type ZipCode = | Us of String5

or

type ZipCode = | Us of String5*(String4 option) | Canadian of String3*String3


texts:
I answered the problem of Find common directory path from Rosetta Code.

The problem consists of passing  '/home/user1/tmp/coverage/test',
 '/home/user1/tmp/covert/operator', and '/home/user1/tmp/coven/members' to a function, the resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.

The solution (the working code) is:

import Foundation

func getPrefix(_ text:[String]) -> String? {
    var common:String = text[0]
    for i in text {
        common = i.commonPrefix(with: common)
    }
    return common
}

var test = ["/home/user1/tmp/coverage/test",
 "/home/user1/tmp/covert/operator",
 "/home/user1/tmp/coven/members"]

var output:String = getPrefix(test)!
print(output)

Could the above code be further optimized?


texts:
When an API has a 'next' feature, I use the following pattern to obtain all the results:

/** Obtains a list of channels followed by a user */
function get_follows(username, callback) {
    var channels = [];
    function handler(data) {
        if (!data || data.follows.length == 0) {
            callback(channels);
            return;
        }
        for (var i = 0; i < data.follows.length; i++)
            channels.push(data.follows[i].channel);
        JSON.load(data._links.next, handler);
    }
    var url = "https://api.twitch.tv/kraken/users/"+username+"/follows/channels?limit=75&offset=0&on_site=1";
    JSON.load(url, handler);
}

Is there a better way to go about this?


texts: Find the nearest point of a given set of points

texts:
Suppose there are a set of given points (represented by x and y two dimensional coordinates), and for any given point A, I want to find the nearest distance point among the given set of point.

My current solution is straightforward: just find min among all distances. The issue of my implementation is, if we want to calculate nearest point among the given set of points for another point B, I need to calculate distance again.

My question is, suppose the given set of points are fixed, is there any way to optimize (e.g. pre-process), so that search nearest point is much faster?

import sys
import random
def distance(p1, p2):
    return (p1[0]-p2[0])**2 + (p1[1]-p2[1])**2
def search_point(points, target_point):
    result = sys.maxint
    nearest_point = -1
    for p in points:
        d = distance(p, target_point)
        if d < result:
            result = d
            nearest_point = p
    return nearest_point

if __name__ == "__main__":
    points = []
    for i in range(10):
        points.append((random.randint(0,20),random.randint(0,20)))
    target_point = (random.randint(0,20), random.randint(0,20))
    print 'result', search_point(points, target_point)
    print 'target_point', target_point
    print 'raw points', points
    print 'distances', [distance(p, target_point) for p in points]


texts: Maybe getting a character from a list of strings

texts:
I'm trying to transition from JavaScript to PureScript (a Haskell spinoff that transpiles to JavaScript). For starters I coded this:

getAt :: [String] -> Number -> Number -> String
getAt strings x y = case strings !! y of
    Nothing -> " "
    Just line -> case charAt x line of
        Nothing -> " "
        Just char -> fromChar char

-- getAt ["abc", "def"] 0 1 -- returns "d"

It retrieves a character at position (x, y) from a "grid" of characters given as an arrays of strings. I can't help but think that the same function would be just return strings[y][x] in JavaScript assuming that (x, y) are always within bounds - which is true in my case. I can't get rid of these functions that return Maybe, but can I at least write this in a more concise way?


texts:
I use the following code which is working OK to register and emit event for local storage on the browser. It will be great if you can give me some ideas on how to improve it for production use since I'm fairly new to JS.

"use strict";
    function lsHelper() {
        let status = "available";
        let timeout = 5000;

        //Register a function by its name, itself (callback) and the needed time span for the check cycle
        this.RegisterLocalStorageFunction = function(name, callback) {

            //Set local storage items for function and its result
            resetFunction(name);

            //Setting the event
            window.addEventListener('storage', function(e) {
                //Getting the params or eventually just the status

                //Call the function if params are set and reset all
                if (e.key === name && e.newValue != status) {
                    let result = callback(e.newValue);
                    //Set result
                    localStorage.setItem(name + "Result", result);
                    //Reset call
                    localStorage.setItem(name, status);
                }
            });
        }

        this.CallLocalStorageFunction = function(name, params, callback) {
            //Check if the function is already called
            if (localStorage.getItem(name) == placeholder
                && localStorage.getItem(name + "Result") == status) {

                //Call remote function
                localStorage.setItem(name, params);

                //Define timeout and event for future usage
                let timeout = {};
                let storageEvent = {};

                //Check in interval for result
                storageEvent = function(e) {
                    //Check wheter the result is set
                    if (e.key == name + "Result" && e.newValue != status) {
                        //Call callback with results
                        callback(e.newValue);

                        //Reset result in local storage
                        localStorage.setItem(name + "Result", status);

                        //Dismiss listener and timeout
                        clearTimeout(timeout);
                        window.removeEventListener('storage', storageEvent, false);
                    }
                }

                //Add listener to event
                window.addEventListener('storage', storageEvent);

                //Start timout to cancel listener if no result is set, hence no remote function was called
                timeout = setTimeout(function() {
                    //Dismiss interval
                    clearTimeout(timeout);
                    //Clean up
                    window.removeEventListener('storage', storageEvent, false);
                }, timeout);
            }
        }

        //Reset local storage values
        function resetFunction(name) {
            localStorage.setItem(name, status);
            localStorage.setItem(name + "Result", status);
        }
    };


texts:
I think that my code isn't perfect and I need a help to understand how to optimize it.

In my application I have a main form and several forms for data editing.
The user can:

Add a new item
Edit the selected item
Delete the selected item
Duplicate an item with a new name

You can see an example of my code below. I think that the approach to trigger editing mode isn't good.

An alternative way is to create a new form without parameters and then run methods AddItem(), EditItem(), etc., but I don't think that's a good idea either.

Editor modes:

public enum EditMode { Add, Edit, Delete, Copy };

Main form has several buttons:

    private void AddItemBarButton_ItemClick(object sender, ItemClickEventArgs e)
    {
        ItemForm IF = new ItemForm(EditMode.Add);
        IF.ShowDialog();
        IF.Dispose();
    }

    private void EditItemBarButton_ItemClick(object sender, ItemClickEventArgs e)
    {
        if (ActiveItem != null)
        {
            ItemForm IF = new ItemForm(EditMode.Edit, ActiveItem);
            MIF.ShowDialog();
            MIF.Dispose();
        }
    }

    private void DeleteItemBarButton_ItemClick(object sender, ItemClickEventArgs e)
    {
        if (ActiveItem != null)
        {
            ItemForm IF = new ItemForm(EditMode.Delete, ActiveItem);
            MIF.Dispose();
        }
    }

    private void CopyItemBarButton_ItemClick(object sender, ItemClickEventArgs e)
    {
        if (ActiveItem != null)
        {
            ItemForm IF = new ItemForm(EditMode.Delete, ActiveItem, "somenewname");
            MIF.Dispose();
        }
    }

Editor form:

    private Item T = null;
    private EditMode Mode;

    private ItemForm()
    {
        InitializeComponent();
    }

    public ItemForm(EditMode mode) : this()
    {
        Mode = mode;
        switch (Mode)
        {
            case EditMode.Add:
                T = new Item();
                T.Sort_Order = DateTime.Now;
                break;
        }
    }

    public ItemForm(EditMode mode, Item item) : this()
    {
        Mode = mode;
        T = item;
        switch (Mode)
        {
            case EditMode.Edit:
                NameEdit.Text = T.Name;
                CountEdit.Text = T.Countnum.ToString();
                break;

            case EditMode.Delete:
                cDB.Item.DeleteOnSubmit(T);
                cDB.SubmitChanges();
                break;
        }
    }

    public ItemForm(EditMode mode, Item item, string new_name) : this()
    {
        Mode = mode;
        switch (Mode)
        {
            case EditMode.Copy:
                T = new Item();
                T.Name = new_name;
                T.Countnum = item.Countnum;
                T.Sort_Order = item.Sort_Order;
                cDB.Item.InsertOnSubmit(T);
                cDB.SubmitChanges();
                break;
        }
    }

    private void OKButton_Click(object sender, EventArgs e)
    {
            T.Name = NameEdit.Text;
            T.Countnum = Convert.ToInt(CountEdit.Text);

            if (Mode == EditMode.Add) cDB.Item.InsertOnSubmit(T);
            cDB.SubmitChanges();

            this.Close();
        }
    }


texts:
Here's the code I'm planning to use to power meta description tags for a site in header.php in the template.  Is anything missing / incorrect / could be done better?

<?php
if (is_front_page() || is_home()) {
    $description = get_bloginfo('description');
} else {
    $description = get_post_meta(get_the_ID(), 'description', true);
}
if ($description) {
    ?>
    <meta name="description" content="<?php echo htmlspecialchars($description); ?>" />
    <?php
}
?>

In case anyone's wondering if meta descriptions have any value these days:

  Google will sometimes use the meta description of a page in search
  results snippets, if we think it gives users a more accurate
  description than would be possible purely from the on-page content.
  Accurate meta descriptions can help improve your clickthrough...

Source

EDIT:

A little explanation is I want to make sure there aren't any cases where this breaks something or doesn't print a description when it should or prints the wrong description.  I've tested it and it seems to work pretty well, but you don't know what you don't know.


texts:
public class SudokuChecker{

static int[][] sMatrix={

                    {5,3,4,6,7,8,9,1,2},
                    {6,7,2,1,9,5,3,4,8},
                    {1,9,8,3,4,2,5,6,7},
                    {8,5,9,7,6,1,4,2,3},
                    {4,2,6,8,5,3,7,9,1},
                    {7,1,3,9,2,4,8,5,6},
                    {9,6,1,5,3,7,2,8,4},
                    {2,8,7,4,1,9,6,3,5},
                    {3,4,5,2,8,6,1,7,9}
                };
static int rSum=0;

static int cSum=0;

static int[] rSumArray=new int[9];

static int[] cSumArray=new int[9];

static int[] boxSumArray=new int[9];

static boolean checkArrayStatus(int[] rSumArray,int[] cSumArray,int[] boxSumArray)
{
    int i=0;

    boolean sudukoStatus=true;

    while(i<9){
        if(rSumArray[i]!=45&&cSumArray[i]!=45&&rSumArray[i]!=45)
        {
            sudukoStatus=false;
            break;
        }
        i++;
    }
    return sudukoStatus;
}

    public static void main(String[] args) {
        for(int i=0 ; i<sMatrix.length ; i++){
            for(int j=0 ; j<sMatrix.length ; j++){
                rSum+=sMatrix[i][j];
                cSum+=sMatrix[j][i];
                }
            rSumArray[i]=rSum;
            cSumArray[i]=cSum;
            rSum=0;
            cSum=0;
        }

        for(int i=0 ; i< sMatrix.length ; i++){
            for(int j=0 ; j<sMatrix.length ; j++){
                if(i<=2&&j<=2)
                {
                    boxSumArray[0]+=sMatrix[i][j];
                }
                if(i<=2&&(j>=3&&j<=5))
                {
                    boxSumArray[1]+=sMatrix[i][j];
                }
                if(i<=2&&(j>=6&&j<=8))
                {
                    boxSumArray[2]+=sMatrix[i][j];
                }
                if((i>=3&&i<=5)&&(j<=2))
                {
                    boxSumArray[3]+=sMatrix[i][j];
                }
                if((i>=3&&i<=5)&&(j>=3&&j<=5))
                {
                    boxSumArray[4]+=sMatrix[i][j];
                }
                if((i>=3&&i<=5)&&(j>=6&&j<=8))
                {
                    boxSumArray[5]+=sMatrix[i][j];

                }
                if((i>=6)&&(j<=2))
                {
                    boxSumArray[6]+=sMatrix[i][j];
                }
                if((i>=6)&&(j>=3&&j<=5))
                {
                    boxSumArray[7]+=sMatrix[i][j];
                }
                if((i>=6)&&(j>=6))
                {
                    boxSumArray[8]+=sMatrix[i][j];
                }
            }
        }

        if(checkArrayStatus(rSumArray,cSumArray,boxSumArray))
        {
            System.out.println("The matrix is sudoku compliant");
        }
        else
        {
            System.out.println("The matrix is not sudoku compliant");
        }
    }
}

This a program which verifies if a 2D matrix is a Sudoku or not. The sum of every row, column and 3x3 matrices have to be 45.  Please review the code and provide feedback on best practices and code optimization.


texts: Enabling or disabling a login view based on authentication state

texts:
Is it good to have this:

if(DataHolder.i().getLoginParamInfo().equals(LoginState.stateLoggingIn)) {
    getView().findViewById(R.id.login_button).setEnabled(true);
}
else {
    getView().findViewById(R.id.login_button).setEnabled(false);
}

or this:

getView().findViewById(R.id.login_button).setEnabled(DataHolder.i().getLoginParamInfo().equals(LoginState.stateLoggingIn));


texts:
I have a connection with my database to show all my records on a webpage, and I'm not sure if this code is safe:

define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', null);
define('DB_DATABASE', 'publicacoes');
define('DB_PREFIX', 'bn');
define('DB_CHARSET', 'utf8');

function DBEscape($dados){
    $link = DBConnect();

    if(!is_array($dados))
        $dados = mysqli_real_escape_string($link, $dados);
    else{
        $arr = $dados;

        foreach ($arr as $key => $value) {
            $key = mysqli_real_escape_string($link, $key);
            $value = mysqli_real_escape_string($link, $value);

            $dados[$key] = $value;
        }
    }

    DBclose($link);
    return $dados;
}

function DBclose($link){
    @mysqli_close($link) or die(mysqli_error($link));
}

function DBConnect(){
    $link = @mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die(mysqli_connect_error());
    mysqli_set_charset($link, DB_CHARSET) or die(mysqli_error($link));

    return $link;
}

function DBRead($table, $params = null, $fields = '*'){
    $table  = DB_PREFIX.'_'.$table;
    $params = ($params) ? " {$params}" : null;

    $query  = "SELECT {$fields} FROM {$table}{$params}";
    $result = DBExecute($query);

    if(!mysqli_num_rows($result))
        return false;
    else{
        while ($res = mysqli_fetch_assoc($result)){
            $data[] = $res;
        }
        return $data;
    }
}

function DBExecute($query, $insertId = false){
    $link   = DBConnect();
    $result = @mysqli_query($link, $query) or die(mysqli_error($link));

    if($insertId)
        $result = mysqli_insert_id($link);

    DBClose($link);
    return $result;
}

$dadosIDrow1 = DBRead('publicacao', "ORDER BY id DESC LIMIT 2");

<?php foreach ($dadosUN as $UN): ?>

//some html here to display the records

<?php endforeach; ?

This is the first piece of code that I've written to show the records on my website. At the moment I have 2 connections with my DB. One of them I use PDO prepared statement to a pagination and search box.

I want to know if I should delete this script and make a new one with prepared statements.


texts:
I implemented the solution to the classic Matching Brackets problem:
Given a string containing brackets [], braces {}, parentheses (), or any combination thereof, verify that any pairs are matched and nested correctly.
The code should be correct since it passes several test cases.
I would like to know if:

the usage of the enum Bracket is an idiomatic construct or a useless complexity
the function brackets_are_balanced can be simplified while keeping the enum Bracket
further improvement/suggestions

#![warn(missing_crate_level_docs)]
#![warn(missing_docs)]
//! # Matching Brackets
//!
//! `matching_brackets` is a collection of utilities to solve [this exercise](https://exercism.io/my/solutions/8ecfdc024536471a8c36ac2a3ff4b119).

enum Bracket {
    OPEN(char),
    CLOSE(char),
}

impl Bracket {
    pub fn new(c: char) -> Option<Bracket> {
        match c {
            '{' | '[' | '(' => Some(Bracket::OPEN(c)),
            '}' => Some(Bracket::CLOSE('{')),
            ']' => Some(Bracket::CLOSE('[')),
            ')' => Some(Bracket::CLOSE('(')),
            _ => None,
        }
    }
}

/// Check if the input `string` has balanced brackets.
///
/// # Examples
///
/// ```rust
/// use matching_brackets::brackets_are_balanced;
/// assert!(brackets_are_balanced("(((185 + 223.85) * 15) - 543)/2"));
/// assert!(brackets_are_balanced("([{}({}[])])"));
/// assert!(!brackets_are_balanced("{[)][]}"))
/// ```
pub fn brackets_are_balanced(string: &str) -> bool {
    let mut brackets: Vec<Bracket> = vec![];
    for c in string.chars() {
        match Bracket::new(c) {
            Some(Bracket::OPEN(char_bracket)) => {
                brackets.push(Bracket::OPEN(char_bracket));
            }
            Some(Bracket::CLOSE(char_close_bracket)) => match brackets.pop() {
                Some(Bracket::OPEN(char_open_bracket)) => {
                    if char_close_bracket != char_open_bracket {
                        return false;
                    }
                }
                _ => return false,
            },
            _ => (),
        };
    }
    brackets.is_empty()
}


texts:
I'm using the Jquery date time picker link here

In the four methods below I am initializing the DT pickers but they are all pretty similar except for the ID in the onChangeDateTime.

Is there a way I can reduce the duplicate code?

$('.jqDatetimeDateOne').datetimepicker({
    defaultTime: '07:00',
    lang: 'en',
    className: 'setTimeClicker',
    step: 30,
    onChangeDateTime: function (current_time, $input) {
        // alert(ct.dateFormat('d/m/Y'))
        $('#emailGenDateOne').removeClass('empty').val(current_time.dateFormat('Y-m-d H:i'));
    },
    inline: true
});

$('.jqDatetimeDateTwo').datetimepicker({
    defaultTime: '07:00',
    lang: 'en',
    className: 'setTimeClicker',
    step: 30,
    onChangeDateTime: function (current_time, $input) {
        // alert(ct.dateFormat('d/m/Y'))
        $('#emailGenDateTwo').removeClass('empty').val(current_time.dateFormat('Y-m-d H:i'));
    },
    inline: true
});

$('.jqDatetimeSearchDateOne').datetimepicker({
    defaultTime: '07:00',
    lang: 'en',
    className: 'setTimeClicker',
    step: 30,
    onChangeDateTime: function (current_time, $input) {
        // alert(ct.dateFormat('d/m/Y'))
        $('#searchGenDateOne').removeClass('empty').val(current_time.dateFormat('Y-m-d H:i'));
    },
    inline: true
});

$('.jqDatetimeSearchDateTwo').datetimepicker({
    defaultTime: '07:00',
    lang: 'en',
    className: 'setTimeClicker',
    step: 30,
    onChangeDateTime: function (current_time, $input) {
        // alert(ct.dateFormat('d/m/Y'))
        $('#searchGenDateTwo').removeClass('empty').val(current_time.dateFormat('Y-m-d H:i'));
    },
    inline: true
});


texts: Checking host status for clients on server

texts:
I run a small server, and to check whether clients are being hosted on my server, I wrote this.  I'm new to object oriented programming. How stratified should my programs really be?  Do I want to have every possible variable and piece in their own function? Also, how am I doing in general?  Any recommendations?

class Domain_check
  def vhost_grab
    return full_domain_path = `ls /etc/httpd/conf.d/vhost_* | grep -v 000_defaults.conf`.chomp.split(' ')
  end

  def vhost_stripper
    prefix =  Domain_check.new.vhost_grab
    vhost_stripped = []
    prefix.each_index do |x|
      vhost_stripped[x] = `echo '#{prefix[x]}' | awk -F'vhost_' '{print $2}' | awk -F'.conf' '{print $1}'`
    end
    return vhost_stripped
  end

  def vhost_display
    puts "\n%s %40s %43s" %["Domain name", "IP Address Listed", "IP Address Currently in Use"]
    final_vhost = vhost_stripper
    final_vhost.each_index { |x|
      padding = 50
      print final_vhost[x].strip
      padding = padding.to_i - final_vhost[x].length
      print "%0#{padding}s" %[`grep '<VirtualHost .*:80>' #{Domain_check.new.vhost_grab[x]} | awk -F'<VirtualHost' '{print $2}'|awk -F':' '{print $1}'`.strip.to_s]
      puts "%40s" %[`dig #{final_vhost[x].strip} +short`]
    }
  end
end

d1 = Domain_check.new
d1.vhost_display


texts: Do you view this ThrowingFunction interface as "interface abuse"?

texts:
I am currently implementing a fun project involving lambdas and this project makes heavy use of the ability of Java 8 to have default methods in interfaces.

But when does such "heavy use" turn into an outright abuse? Here is one example of an interface which I have defined, and its 4 methods may extend to even more in the future; am I overdoing it?

@FunctionalInterface
public interface ThrowingFunction<T, R>
    extends Function<T, R>
{
    R doApply(T t)
        throws Throwable;

    @Override
    default R apply(T t)
    {
        try {
            return doApply(t);
        } catch (Error | RuntimeException e) {
            throw e;
        } catch (Throwable tooBad) {
            throw new ThrownByLambdaException(tooBad);
        }
    }

    default Function<T, R> orReturn(R defaultValue)
    {
        return t -> {
            try {
                return doApply(t);
            } catch (Error | RuntimeException e) {
                throw e;
            } catch (Throwable ignored) {
                return defaultValue;
            }
        };
    }

    default <E extends RuntimeException> Function<T, R> orThrow(
        Class<E> exceptionClass)
    {
        return t -> {
            try {
                return doApply(t);
            } catch (Error | RuntimeException e) {
                throw e;
            } catch (Throwable tooBad) {
                throw ThrowablesFactory.INSTANCE.get(exceptionClass, tooBad);
            }
        };
    }
}

(Not that this is relevant, but the source for ThrowablesFactory can be viewed here.)


texts: Recreating binary counter for arbitrary length arrays

texts:
After weeks of slaving over FIPS-197, I finally have my own working C/C# implementation of AES-128 which I'm quite happy about.

The next thing I'm looking to do is implement a nonce counter block of configurable length (either 8 or 16 bytes) to convert this block cipher into a stream cipher (CTR mode), according to NIST 800-38a recommendation.

So to do this, the idea I had was to create from scratch a sort of BigNumber implementation that basically reflects how we increment the bits in a byte, starting with the least significant bit:

0000
0001
0010
0011
0100
0101
0110
0111
1000
...

The concept is come up with the same counting system, incrementing each element in the array (starting with the last element), resetting the LSE ("least significant element") when it's at max and incrementing the previous element.

Here's what I came up with:

// Re-invent the byte using arbitrary length array (i.e. BigNumber)
// to increment 16-byte nonce

// Benchmark: 273,839 inc/s { 00, 04, 2D, AF } on ATmega328
void incBytes(byte *state, int i)
{
  if (state[i] < 0xff)
  {
    state[i]++;
    return;
  }

  state[i] = 0x00;

  if (i == 0)
    return;

  i--;
  incBytes(state, i);
}

void printBytes(byte *state, int len)
{
  int i;
  for (i = 0; i < len; i++)
  {
    printf("%02X ", state[i]);
  }

  printf("\n");
}

void test()
{
  long t, count;
  byte nonce[16];

  fillBytes(nonce, 0, sizeof(nonce));
  count = 0;
  t = millis();
  while (millis() - t < 1000)
  {
    // cipher(plaintext, expandedKey);
    // cipherCtr(plaintext, expandedKey, nonce);
    incBytes(nonce, sizeof(nonce) - 1);
    count++;
  }

  Serial.print(count);
  Serial.println(" inc/s (incBytes)");
  dumpBytes(nonce, sizeof(nonce));
}

And here is a link to it in action at Ideone.

So I'd just like to get some feedback, not so much on the purpose of all of this or other alternatives out there, but if there are ways to improve it or if this is pretty much it :)

It will then provide me with a way to ensure that the Nonce block for AES-128 in CTR mode gets incremented properly (hence unique) using any arbitrary length byte array.

Note: This is for an Atmega328 so I would like to avoid using long long (64-bit integers) altogether.


texts: Finding the type of number entered by the user

texts:
I am making a fractions calculator that can calculate fractions, whole numbers and mixed fractions.
So there is a String fraction, which is the input.
Also, the user will enter the fraction in a specified format which is:

For normal fraction, "a/b" (a and b are integers)
For whole numbers, "c" (c is an integer)
For mixed fraction, "c a/b" (c is integer, a/b is the fraction separated by a space)

I want the program to check and find out which type of fraction the user has entered and then proceed. I'm using If-Else If-Else for this.
fun fractionalize(fraction: String): List<Int>{
        //Finds type of number (input) and converts to List<Int> with [numerator, denominator, whole number]
        var result: List<Int> = listOf(0,1,0)
        var numerator: Int = 0
        var denominator:Int = 1
        var whole_number:Int = 0
        try {
            if ((fraction.contains('/') && fraction.indexOf('/') == fraction.lastIndexOf('/')) && !fraction.contains(" ")) {
                //input is a regular fraction
                var fraction_string = fraction.split("/")
                numerator = fraction_string[0].toInt()
                denominator = fraction_string[1].toInt()
                result = listOf(numerator, denominator, 0)
            } else if (fraction.isDigitsOnly()) {
                //input is a whole number
                result = listOf(fraction.toInt(), 1, 0)
            } else if ((fraction.contains('/') && fraction.indexOf('/') == fraction.lastIndexOf('/')) && (fraction.contains(" ") && fraction.indexOf(' ') == fraction.lastIndexOf(' '))) {
                //input is mixed fraction
                var wholeNumber_split = fraction.split(" ")
                whole_number = wholeNumber_split[0].toInt()
                numerator = wholeNumber_split[1].split("/")[0].toInt()
                numerator += whole_number * denominator
                denominator = wholeNumber_split[1].split("/")[1].toInt()
                result = listOf(numerator, denominator, 0)
            }
            else {
                Toast.makeText(applicationContext,
                "The number you entered is not in a valid format.",
                Toast.LENGTH_LONG).show()
            }
            //simplifying input
            if (result[2] != 0){
                numerator += whole_number * denominator
                result = listOf(numerator, denominator, 0)
            }
            return result
        }
        catch (e: Exception){
            Toast.makeText(applicationContext,
                "The number you entered is not in a valid format.",
                Toast.LENGTH_LONG).show()
            return result
        }
    }

Is this the best way I can do that or is there cleaner and more efficient code I can make (personally I think this is too messy and can be made more efficient)?


texts:
I'm implementing a file upload using NodeJS. I've got fully functional code, however, it feels overly complicated and I'm hoping there would be an easier way to implement the same thing?

In particular what I want to achieve is:

Write the request to a file
Send upload progress information
Send final MD5 hash
Send final size (position)
Properly propagate errors
Have no resource leaks

app.post('/file', (req, res, next) => {

  // ...

  const progress$ = Observable
    .create(o => {
      const fileStream = fs.createWriteStream(filePath, { flags: 'wx' })
      const hasher = crypto.createHash('md5')

      req.on('data', buf => {
        hasher.update(buf)
        o.next({
          position: fileStream.bytesWritten
        })
        if (!fileStream.write(buf)) {
          req.pause()
        }
      })
      req.on('error', err => {
        fileStream.destroy()
        o.error(err)
      })
      req.on('end', ::fileStream.end)
      req.on('close', () => {
        fileStream.destroy()
        o.error(new Error('upload cancelled'))
      })
      fileStream.on('drain', ::req.resume)
      fileStream.on('error', ::o.error)
      fileStream.on('close', () => {
        o.next({
          md5: hasher.digest('hex'),
          position: fileStream.bytesWritten
        })
        o.complete()
      })
    })

 // ...

})


texts:
I am trying to write a method that can find the child item in a menu. The below code works but is not exactly elegant or scaleable. Is there another way to find the path to child menu item that could be used?

public class Item
{
    public string Name { get; set; }
    public string Parent { get; set; }
}

public void OpenMenuItem(string name)
{
    var items = new List<Item>
    {
        new Item  { Name = "Test", Parent = null },
        new Item  { Name = "TestChild1", Parent = "Test" },
        new Item  { Name = "TestChild2", Parent = "Test" },
        new Item  { Name = "TestGranChild1", Parent = "TestChild1" },
        new Item  { Name = "TestGranChild2", Parent = "TestChild1" },
        new Item  { Name = "TestGranChild3", Parent = "TestChild2" },
        new Item  { Name = "TestGranChild4", Parent = "TestChild2" }
    };
    var menuItem = items.Where(x => x.Name == name);
    if (menuItem.FirstOrDefault().Parent != null)
    {
        var parent1 = items.Where(x => x.Name == menuItem.FirstOrDefault().Parent);
        if (parent1.FirstOrDefault().Parent != null)
        {
            var parent2 = items.Where(x => x.Name == parent1.FirstOrDefault().Parent);
            app.Tap(x => x.Marked(parent2.FirstOrDefault().Name));
        }
        app.Tap(x => x.Marked(parent1.FirstOrDefault().Name));
    }
    app.Tap(x => x.Marked(menuItem.FirstOrDefault().Name));
}


texts: Reading from and writing to a file without passing around filename

texts:
I was looking for a way to write to and then read from a file in different parts of my code, without passing the filename around and without consumers needing to know it was coming from a file.

I came up with this FilePipe based on io.Pipe:

package pipe

import (
    "io"
    "os"
)

func FilePipe(name string) (*io.PipeReader, *io.PipeWriter) {
    inr, inw := io.Pipe()
    outr, outw := io.Pipe()

    go func() {
        // Open the file for writing
        f, err := os.Create(name)
        if err != nil {
            outw.CloseWithError(err)
            return
        }

        // Copy the input to the file
        _, err = io.Copy(f, inr)
        f.Close()
        if err != nil {
            outw.CloseWithError(err)
            return
        }

        // Open the file for reading
        f, err = os.Open(name)
        if err != nil {
            outw.CloseWithError(err)
            return
        }

        // Copy the file to the output
        _, err = io.Copy(outw, f)
        f.Close()
        if err != nil {
            outw.CloseWithError(err)
            return
        }
        outw.Close()
    }()

    return outr, inw
}

What do you think? Is there a better way to do this?


texts: Service status checker... Is there a more efficient way?

texts:
I've been working on a website status checker.. However this array that I use has around 30 sites within it, I've noticed it's taking around 6-7 seconds to load it.

I was wondering if there's any kind of way of doing below, but more efficiently.

I have thought of doing the below in a cron, and fetching the stored results from a database.

<?php

function Visit($url){
   $agent = "S3 (SF Service status)";
   $ch=curl_init();
   curl_setopt ($ch, CURLOPT_URL,$url );
   curl_setopt($ch, CURLOPT_USERAGENT, $agent);
   curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt ($ch,CURLOPT_VERBOSE,false);
   curl_setopt($ch, CURLOPT_TIMEOUT, 5);
   curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
   curl_setopt($ch,CURLOPT_SSLVERSION,3);
   curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
   $page=curl_exec($ch);
   #curl_error($ch);
   #
   #http header response code
   global $httpcode;
   $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

   curl_close($ch);
   if($httpcode>=200 && $httpcode<=308) return true;
   else return false;
}

$sites = array(
"Name of site" => "URL",
);
?>

    <title>Service Status</title>
    <link href="static/css/main/main.css" rel="stylesheet" type="css/stylesheet">

service status

        <?php
        foreach ($sites as $key => $value) {
            echo '
';
            if (Visit($value)) {
                echo "$key ($value)	Available ($httpcode)	";
            } else {
                echo "$key ($value)	Unavailable ($httpcode)	";
            }
            echo '
';
        }
        ?>

Any recommendations on how parts of this could be done better would be greatly appreciated :)


texts:
I'm creating a function that converts a title, to a URL slug. I'm not all to familiar with regular expressions, but I've done my best. Can you see any problems or improvements with the following function below?

The only thing allowed in the slug is letters, numbers and - charchaters.

function slugify($input) {
    // Convert multiple spaces to single spaces
    $slug = preg_replace("/[[:blank:]]+/",' ', $input);
    // Convert to lower case
    $slug = strtolower($slug);
    // Remove anything that's not a number, letter or space
    $slug = preg_replace('/[^a-z0-9\s]+/', '', $slug);
    // Trim, and replace spaces with hyphens
    $slug = preg_replace('/\s/', '-', trim($slug));

    return $slug;
}


texts:
I'm following a tutorial into pygame. I realized the example code was written for the sake of being easy to understand. I wondered if I could 'improve' the code, with a focus on keeping the exact same functionality. I tried, but I'm not really sure if this is an improvement.

This is the original code from the instructions:

import pygame, sys
from pygame.locals import *

pygame.init()

FPS = 30 # frames per second setting
fpsClock = pygame.time.Clock()

# set up the window
DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption('Animation')

WHITE = (255, 255, 255)
catImg = pygame.image.load('cat.png') # hosted at https://inventwithpython.com/cat.png
catx = 10
caty = 10
direction = 'right'

while True: # the main game loop
    DISPLAYSURF.fill(WHITE)

    if direction == 'right':
        catx += 5
        if catx == 280:
            direction = 'down'
    elif direction == 'down':
        caty += 5
        if caty == 220:
            direction = 'left'
    elif direction == 'left':
        catx -= 5
        if catx == 10:
            direction = 'up'
    elif direction == 'up':
        caty -= 5
        if caty == 10:
            direction = 'right'

    DISPLAYSURF.blit(catImg, (catx, caty))

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()
    fpsClock.tick(FPS)

This is my 'improved' code. Two questions. In general, how can my version be improved and why is that improvement better then my code? And, how could the original be improved?

import pygame, sys
from pygame.locals import *

pygame.init()

FPS = 30
fps_clock = pygame.time.Clock()

window_size = (400,300)
DISPLAYSURF = pygame.display.set_mode(window_size,0,32)
pygame.display.set_caption("Animation test!")

WHITE = (255,255,255)
cat = pygame.image.load('assests/cat.png') # hosted at https://inventwithpython.com/cat.png
direction = 'right'
x_,y_ = 10,10

def listenToQuit():
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

def detectCollision(cat,x,y,window_size):
    return cat.get_size()[0] + x >= window_size[0] or \
        cat.get_size()[1] + y  >= window_size[1] or \
            x <= 0 or y <= 0

def getDirection(direction):
    directions = ['right','down','left','up']
    idx = directions.index(direction)
    idx = 0 if idx + 1 == len(directions) else idx + 1
    return directions[idx]

def getMovement(x,y,direction):
    if direction == 'right':
        return x+5,y
    elif direction == 'down':
        return x , y+5
    elif direction == 'left':
        return x - 5 , y
    elif direction == 'up':
        return x , y - 5

i = 0
while 1:
    DISPLAYSURF.fill(WHITE)

    x,y = getMovement(x_,y_,direction)
    while detectCollision(cat,x,y,window_size):  # if there would be a collision, change direction
        direction = getDirection(direction)
        x,y = getMovement(x_,y_,direction) # re-calculate movement, now avoiding collision

    x_,y_ = x,y

    DISPLAYSURF.blit(cat,(x,y))
    listenToQuit()

    pygame.display.update()
    fps_clock.tick(FPS)

I specifically chose not to make the animated object a class. I will try to do so as my next exercise towards myself.


texts:
I am learning dynamic programming and I have written down some code for longest increasing subsequence. I would like to know if there is any case or any area of improvement in the terms of optimization/programming style.

/**
 * LIS = Longest increasing subsequence.
 * Input = [10, 22, 9, 33, 21, 50, 41, 60, 80]
 * Output = [10, 22, 33, 50, 60, 80]
 * Created by gaurav on 1/7/15.
 */

function findSubsequence(arr){
    var allSubsequence = [],
        longestSubsequence = null,
        longestSubsequenceLength = -1;

    for(var i=0;i<arr.length;i++){          //i=1
        var subsequenceForCurrent = [arr[i]],
            current = arr[i],
            lastElementAdded = -1;
        for(var j=i;j<arr.length;j++){
            var subsequent = arr[j];
            if((subsequent > current) && (lastElementAdded<subsequent)){
                subsequenceForCurrent.push(subsequent);
                lastElementAdded = subsequent;
            }
        }
        allSubsequence.push(subsequenceForCurrent);
    }
    for(var i in allSubsequence){
        var subs = allSubsequence[i];
        if(subs.length>longestSubsequenceLength){
            longestSubsequenceLength = subs.length;
            longestSubsequence = subs;
        }
    }
    return longestSubsequence;
}

(function driver(){
    var sample = [87,88,91, 10, 22, 9,92, 94, 33, 21, 50, 41, 60, 80];
    console.log(findSubsequence(sample));
})();


texts:
The Problem

I'm asking to see if there are methodically better solutions to this problem. The situation is as follows, I am receiving an array of events, they are marked by timestamp and there is a designated order of events. That is, that after every event of type a, there should always be a corresponding event b.

Due to how the server batches events, there is a chance that other event types with the same timestamp can corrupt this sequence. I would like to restore it.

The data structure is as follows,

[ { type: string, timestamp: number }, ]

As mentioned beforehand, I would like to ensure that every event of type 'a' is followed immediately by a type 'b' event.

const events = [
  { type: 'a', timestamp: 1 },
  { type: 'c', timestamp: 1 },
  { type: 'b', timestamp: 1 },
  { type: 'a', timestamp: 2 },
  { type: 'a', timestamp: 2 },
  { type: 'c', timestamp: 2 },
  { type: 'b', timestamp: 2 },
  { type: 'b', timestamp: 2 },
];

The target sequence would be as follows:

const sortedEvents = [
  { type: 'a', timestamp: 1 },
  { type: 'b', timestamp: 1 },
  { type: 'c', timestamp: 1 },
  { type: 'a', timestamp: 2 },
  { type: 'b', timestamp: 2 },
  { type: 'a', timestamp: 2 },
  { type: 'b', timestamp: 2 },
  { type: 'c', timestamp: 2 },
];

My Solution

My immediate approach to this is the following:

// Check if the next event for this item is of correct type
const nextIsCorrect = (arr, idx) => (arr[idx].type === 'a') && (arr[idx+1] && arr[idx+1].type === 'b');

// Build list of partnered events
const indices = events.reduce((prev, event, idx, arr) => {
  if (nextIsCorrect(arr, idx)) {
    return prev;
  }

  if (event.type === 'a') {
    prev.push([() => arr.indexOf(event)]);
  }

  if (event.type === 'b') {
    const precedingEvent = prev.find(el => {
      return (el[0] && !el[1]);
    });

    precedingEvent && precedingEvent.push(() => arr.indexOf(event));
  }

  return prev;
}, []);

// Rearrange
indices.forEach(set => {
  const from = set[1]();
  const target = set[0]() + 1;

  events.splice(target, 0, events.splice(from, 1)[0]);
});

I think this is an okay solution, but I can't help feel there is a much better approach eluding me.


texts:
Is this a better way to validate a text box for mobile number only?

Validation:

allow only numbers
will not allow to paste string including characters
allow copy from the box
length is set to 10 without country code
allow back space

Suggest some methods to help me improve my function.

Public Sub mob_validation(ByVal e As System.Windows.Forms.KeyPressEventArgs, ByVal mob As TextBox)
        If e.KeyChar = Chr(22) Then
            Dim output As String = New String((From c As Char In Clipboard.GetText.ToString Select c Where Char.IsLetter(c)).ToArray())
            If output = "" And Len(mob.Text) = 10 Then
                mob.ForeColor = Color.Green
            Else
                mob.ForeColor = Color.Red
                Clipboard.Clear()
            End If
        Else
            If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
                If Asc(e.KeyChar) <> 8 Then
                    If Asc(e.KeyChar) <> 3 Then
                        e.Handled = True
                        mob.ForeColor = Color.Red
                    End If
                End If
            Else
                mob.ForeColor = Color.Green
            End If
        End If
    End Sub


texts: Propagating table cell border colors to adjoining cells

texts:
I have a JavaScript function (which uses the jQuery library but that should not be relevant here) that takes as input an ID (integer), a color, and a side (all, top, right, bottom, or left). For each side, a computation is run in an if-clause. For instance, of borderSide == "top" and anId >= width, do something.

Even though it's not important for the problem, it might help to understand what is going on: the idea is that in a table with a width and height of cells, a user can "color" a cell's border. However, in HTML/CSS it might be necessary to also color another cell's border to make the effect visible. E.g. if you want to color a cell's top border, you may need to paint the cell right above it in the same color as well.

"all" is a special case, as that means all sides of a cell need to be painted, and with respect to its neighbours all surrounding cells need to undergo modification as well (top's bottom border, right's left, bottom's top, left's right). The disjunction between the case with all and all others makes me use a lot of duplicate code, however I feel that the only way I could minimise this is by using separate if's (instead of if...else if's). However, that would mean that every if is evaluated and needs computation, even though in the cases without all there can only be one if active at any given time. So my question is, how can I re-write the following and getting rid off duplication, without evaluating each if-clause if borderSide is not all?

function paintConnectedBorder(cellId, selectedBorderColor, selectedBorderSide) {
  const width = $("#pixels").data("defaultGrid").grid.width,
    totalCells = width * $("#pixels").data("defaultGrid").grid.height;

  let changedCells = [];

  if (selectedBorderSide === "all") {
    if (cellId >= width) {
      $("#cell-" + (cellId - width)).css("borderBottomColor", selectedBorderColor);
      changedCells.push("cell-" + cellId - width);
    }
    if (cellId % width - 1 !== 0) {
      $("#cell-" + (cellId + 1)).css("borderLeftColor", selectedBorderColor);
      changedCells.push("cell-" + cellId + 1);
    }
    if (cellId < totalCells - width - 1) {
      $("#cell-" + (cellId + width)).css("borderTopColor", selectedBorderColor);
      changedCells.push("cell-" + cellId + width);
    }
    if (cellId % width !== 0) {
      $("#cell-" + (cellId - 1)).css("borderRightColor", selectedBorderColor);
      changedCells.push("cell-" + cellId - 1);
    }
  } else {
    if (selectedBorderSide === "top" && cellId >= width) {
      $("#cell-" + (cellId - width)).css("borderBottomColor", selectedBorderColor);
      changedCells.push("cell-" + cellId - width);
    } else if (selectedBorderSide === "right" && (cellId % width - 1 !== 0)) {
      $("#cell-" + (cellId + 1)).css("borderLeftColor", selectedBorderColor);
      changedCells.push("cell-" + cellId + 1);
    } else if (selectedBorderSide === "bottom" && cellId < totalCells - width - 1) {
      $("#cell-" + (cellId + width)).css("borderTopColor", selectedBorderColor);
      changedCells.push("cell-" + cellId + width);
    } else if (selectedBorderSide === "left" && (cellId % width !== 0)) {
      $("#cell-" + (cellId - 1)).css("borderRightColor", selectedBorderColor);
      changedCells.push("cell-" + cellId - 1);
    }
  }
  return changedCells;
}

So if borderSide === "all", all conditions after the &&'s should be evaluated. However, if it's not all, there can only be one at a time (hence the use of else if). So when it's not "all", I do not want to evaluate all if-clauses. So when borderSide === "top" there is no chance that any of the following if-clauses will be true, so I don't want to evaluate them and thus save computations.


texts:
I have written the following code for finding out the prime numbers less than or equal to n. When I enter the input n = 10^7, my program crashes. So I was wondering whether my code can be further optimised.

def sieve(n):
    array = []
    for i in range(1, n):
        array.append(True)
    for i in range(0, n-1):
        for j in range(2*i+4, n+1, i+2):
            if array[j-2] != False:
                if j % (i+2) == 0:
                    array[j-2] = False
    final = []
    for i in range(0, n-1):
        if array[i] == True:
            final.append(i+2)
    return final


texts: Painting Fences - optimize for faster performance

texts:
I am attempting this problem at Codeforces. I'm stuck as it gives a time limit exceeded error for large inputs though the logic I followed is similar to that of the editorial.

I'd be grateful for any pointers that can be useful in improving my logic and/or code performance.

import sys

count = 0

def count_and_split(p):
    h = min(p)
    n = len(p)
    global count
    if h<n:
        count += h
    else:
        count += n
    p = [i-h for i in p]
    e = []
    for i in p:
        if i == 0:
            k = p[:p.index(i)]
            if k:
                e.append(k)
            p = p[(p.index(i)+1):]
    if p:
        e.append(p)
    return e

def main():
    n = int(sys.stdin.readline())
    a = [map(int, sys.stdin.readline().split())]

    for part in a:
        e = count_and_split(part)
        if count>n:
            print n
            exit()
        for new_part in e:
            a.append(new_part)
    print count

if __name__ == '__main__':
    main()


texts: Solving the rod-cutting problem using dynamic programming

texts:
I've written what I believe is a valid dynamic programming solution to a variation of the rod cutting problem. In this problem, the goal is to make as few cuts as possible on a rod of length n.

I have two questions:

Is this a valid dynamic programming solution?
How can it be improved?

(This is not a school assignment. I simply want to understand dynamic programming better)

public class RodCutting {

    RodCutting(int[] cuts, int length) {
        List<Integer> cutLengths = new ArrayList<Integer>();
        for (int i = 0; i < cuts.length; i++) {
            cutLengths.add(cuts[i]);
        }
        Collections.sort(cutLengths);
        List<List<Integer>> optimalCuts = new ArrayList<List<Integer>>();

        // initialize list
        for (int i = 0; i <= length; i++) {
            optimalCuts.add(new ArrayList<Integer>());
        }

        for (int i = 1; i <= length; i++) {
            // assume 1 is always a valid cut length
            if (cutLengths.contains(i)) {
                for (int j = 0; j < cutLengths.size(); j++) {
                    if (i == cutLengths.get(j)) {
                        optimalCuts.get(i).add(cutLengths.get(j));
                        // nothing larger than the current cut
                    }
                }
            } else {
                for (int j = 0; j < cutLengths.size(); j++) {
                    if (i > cutLengths.get(j)) {
                        List<Integer> newCuts = union(
                                optimalCuts.get(i - cutLengths.get(j)),
                                cutLengths.get(j));
                        if (optimalCuts.get(i).size() == 0
                                || newCuts.size() < optimalCuts.get(i).size()) {
                            optimalCuts.remove(i);
                            optimalCuts.add(i, newCuts);
                        }
                    }
                }
            }
        }

        for (int i = 0; i < optimalCuts.size(); i++) {
            System.out.println(i + ": " + optimalCuts.get(i));
        }

    }

    List<Integer> union(List<Integer> listOfCuts, int additionalCut) {
        List<Integer> returnList = new ArrayList<Integer>(listOfCuts);
        returnList.add(additionalCut);
        return returnList;
    }

    public static void main(String[] args) {
        int[] cuts = { 1, 3, 4, 7 };
        int rodLength = 100;
        RodCutting cut = new RodCutting(cuts, rodLength);
    }
}


texts: Shorten and optimize php custom code for wordpress page template and use shortcodes

texts:
I'm pretty new to php coding, but i know wordpress for a long time. Also experimenting with bootstrap. I created a new Page Template and modified it a bit. What I'm looking for is to optimize this php code:

    <?php
        global $post;
        $post = get_post(56);
        setup_postdata($post);
        get_template_part( 'template-parts/content', 'page', get_post_format() );
    ?>

    <?php
        global $post;
        $post = get_post(1);
        setup_postdata($post);
        get_template_part( 'template-parts/content', 'page', get_post_format() );
    ?>

    <?php
        global $post;
        $post = get_post(3);
        setup_postdata($post);
        get_template_part( 'template-parts/content', 'page', get_post_format() );
    ?>

    <?php
        global $post;
        $post = get_post(2);
        setup_postdata($post);
        get_template_part( 'template-parts/content', 'page', get_post_format() );
    ?>

As you can see, it's calling for 4 specific post IDs, since i want them to appear on my homepage in a bootsrap grid. I guess this could be done better by using an array?
Any suggestion is very much appreciated! Stay healthy!


texts:
I'm a complete amateur at python.  Other than hello world programs, this is the first thing I've ever done in Python.

I cannot find a good way to make os.walk function the way I want it to so I worked on my own function for it.

I'm curious which would be the best way to do something.

import os
def atDirList(startDir, maxDepth=0, minDepth=0, curDepth=0):
    output = []
    curDir = []
    curDir = os.listdir(startDir)
    if curDepth >= minDepth:
        for item in curDir:
            fullItem = os.path.join(startDir,item)
            if os.path.isfile(fullItem):
                output.append(fullItem)
    if curDepth+1 <= maxDepth:
        for item in curDir:
            fullItem = os.path.join(startDir,item)
            if os.path.isdir(fullItem):
                output = output+atDirList(fullItem,maxDepth,minDepth,curDepth+1)
    return output

print(atDirList('/music/main'))

or

import os
def atDirList(startDir, maxDepth=0, minDepth=0, curDepth=0):
    output = []
    curDir = []
    curDir = os.listdir(startDir)
    if curDepth >= minDepth:
        for item in curDir:
            fullItem = os.path.join(startDir,item)
            if os.path.isfile(fullItem) and curDepth >= minDepth:
                output.append(fullItem)
            elif os.path.isdir(fullItem) and curDepth+1 <= maxDepth:
                output = output+atDirList(fullItem,maxDepth,minDepth,curDepth+1)
    return output

print(atDirList('/music/main'))

Basically of those, is checking the if once, and traversing the list twice best or is traversing the list once, but checking the if on each entry best?


texts:
Problem Statement:

Watson gives Sherlock an array \$A_1\$, \$A_2\$ ... \$A_N\$.
He asks him to find an integer \$M\$ between \$P\$ and \$Q\$ (both inclusive), such that, \$\min \{|A_i-M|, 1 \le i \le N\}\$ is maximised. If there are multiple solutions, print the smallest one.

Input Format:

The first line contains \$N\$. The next line contains space separated N integers, and denote the array \$A\$. The third line contains two space separated integers denoting \$P\$ and \$Q\$.

Constraints:

\$1 \le N \le 10^2\$
\$1 \le A_i \le 10^9\$
\$1 \le P \le Q \le 10^9\$

My code:

#include <bits/stdc++.h>
int main()
{   int size,print,dist=INT_MIN,answer,start,end,diff;
    std::vector <int> arr;
    std::cin>>size;
    for(int i=0;i<size;i++)
    {   int templ
        std::cin>>temp;
        arr.push_back(temp);
    }
    std::sort(arr.begin(),arr.end());
    std::cin>>start>>end;
    for(int i=start;i<=end;i++)
    {
        dist=INT_MAX;
        for(int j=0;j<size;j++)
        {
            diff=fabs(i-arr[j]);
            if(diff>dist)
                break;
            dist=std::min(dist,diff);

        }
        if(dist>answer)
        {
            answer=dist;
            print=i;
        }
    }
    std::cout<<print;
    return 0;
}

My code is producing the output that I'm expecting, however it is failing with the hackerrank judge telling me that the time limit has been exceeded.

According to me its running time is O(n(p-q)).
Then it should clear all the test cases in less than 2s (assuming computer can compute 10^9 problems in a second, I remember reading somewhere that that's how most online judges work). At most my program will work on 10^11 problems (n*p-q= 10^2 *10^11).

Do my timing predictions make sense?

How can I improve my code, particularly the performance so that it is able to pass this judge?


texts: Implementing 3Blue1Brown's description of Fourier transform in Python+numpy

texts:
I have implemented the 3Blue1Brown's description of Fourier transform in Python+numpy for irregular and unsorted data, as described here.

import numpy as np
import matplotlib.pyplot as plt

def polarToRectangular(radii, angles):
    return radii * np.exp(1j * angles)

def frequencyGenerator(time, steps = 100):
     = time.max() - time.min()
    M = np.arange(1, steps + 1)[:, np.newaxis]
    return M /

def easyFourierTransform(time, values, frequency = None, steps = 100):
    if frequency is None:
        ft = frequencyGenerator(time, steps)
        frequency = ft.reshape(ft.shape[0])
    else:
        ft = frequency[:, np.newaxis]

    # sorting the inputs
    order = np.argsort(time)
    ts = np.array(time)[order]
    Xs = np.array(values)[order]

     = (ts - time.min()) * 2 * np.pi * ft
    Y = polarToRectangular(Xs, )[:, :-1] * np.diff(ts)
    amplitude = np.abs(Y.sum(axis=1))
    return frequency, amplitude

I'm thinking maybe I can suggest this to be added to numpy/scypy. However, I'm not sure if this small piece of code is qualified to be added upstream. I was wondering if you could help me know:

Is this code correct? Does it actually return the Fourier transform? I want to be sure there are no logical errors.
Is this a performant code or there is any way to improve performance?
Is the formating good enough? Should I comply with PEP8 standard or numpy/scipy require different best practices?
Is this novel or it has been done before? (not necessarily relevant to this forum but still my question)

Keywords: nonuniform, uniformly, unevenly, sampled, distributed

P.S. Updated version of the code plus examples in this Jupyter notebook.


texts:
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

Please review for performance.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ArrayQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/trapping-rain-water/
    /// </summary>
    [TestClass]
    public class TrappingRainWater
    {
        [TestMethod]
        public void TestMethod1()
        {
            int[] height = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
            Assert.AreEqual(6, Trap(height));
        }

        public int Trap(int[] height)
        {
            int left = 0;
            int right = height.Length - 1;
            int ans = 0;
            int leftMax = 0;
            int rightMax = 0;
            while (left < right)
            {
                if (height[left] < height[right])
                {
                    //if height left < left max that means we can trap water
                    if (height[left] < leftMax)
                    {
                        ans += leftMax - height[left];
                    }
                    else // otherwise left max needs to be updated
                    {
                        leftMax = height[left];
                    }
                    left++;
                }
                else
                {
                    if (height[right] < rightMax)
                    {
                        ans += rightMax - height[right];
                    }
                    else
                    {
                        rightMax = height[right];
                    }

                    right--;
                }
            }
            return ans;
        }
    }
}