texts:
The Dir() function in VB and VBA can accept wildcard characters (* and ?) but only in the basename of the path.

Dir("path\*.txt")

is a valid request but.

Dir("path\*\*.txt")

will return Error 52 "Bad File Name or Number", because  * is an invalid folder or file name.  I created the ability to use wildcards in the folder names using my
os
module and my
List
 class.

Example Call

It's not a true glob search as you can't search like "*.{cpp,hpp}", but this is far better than nothing.  Example:

Debug.Print Glob("C:\users\ptwales", "????-herp\*\*.txt").ToString
' ["C:\users\ptwales\derp-herp\flerp\merp.txt", ...]

Client code must specify a starting directory.  Current working directory is not implied.

Implementation

Note that os.SubItems and os.SubFolders each now return a List.

Public Function Glob(ByVal root As String, ByVal pattern As String) As List

    Dim pat_list As New List
    pat_list.Extend Split(pattern, os.SEP)

    Set Glob = GlobRecurse(root, pat_list, 1)

End Function
Private Function GlobRecurse(ByVal root As String, ByVal pat_list As List, ByVal index As Integer) As List

    If index = pat_list.Count Then
        Set GlobRecurse = os.SubItems(root, pat_list(index))
    Else

        Set GlobRecurse = New List

        Dim folder As Variant
        For Each folder In os.SubFolders(root, pat_list(index))
            GlobRecurse.Extend GlobRecurse(folder, pat_list, index + 1)
        Next folder

    End If

End Function

It's a bit awkward, particularly that GlobRecurse checks the pat_list.Count each iteration.  It feels too much like scheme and I should be using a for loop instead.


texts:
Is it possible to make this faster? Any suggestions are more than welcome
I have used JavaScript to write this code
PROBLEM

You will get an array of numbers.

Every preceding number is smaller than the one following it.

Some numbers will be missing, for instance:
  [-3,-2,1,5] // missing numbers are: -1,0,2,3,4

Your task is to return an array of those missing numbers:
[-1,0,2,3,4]

SOLUTION
const findTheMissing = (target) => {

    // final result list
    let result = [];

    // array will go from min to max value present in the array
    const min = target[0];
    const max = target[target.length - 1];

    // will maintain the track of index of target array
    // will start from 2nd element of array because we need a no. to subsctract from
    let pivotIndex = 1;

    for (let index = min; index < max; index++) {

        // value to the index
        let pivotValue = target[pivotIndex];

        // dif of the value
        let diff = pivotValue - index;

        // diff means its time to move the pivot to next :P
        if (diff > 0) {
            // not going to current index at exists in the target array
            if (index === target[pivotIndex - 1])
                index++;

            // YO!! WE FOUND HE MISSING
            result.push(index);
        }
        else {
            pivotIndex++;
        }
    }
    return result; // got all missing numbers
}

RESULT
let source = [-5, 0, 2, 5, 7];
console.log(findTheMissing(source));
// [ -4, -3, -2, -1, 2, 3, 4, 6 ]


texts:
First I have two conditions on the number of list elements,then in one of these conditions I have two others conditons to treat it :

My code:

List<StringBuilder> result = ReadResult_WS_Import(NameFile);
 if ((result != null) && (result.Any()))
                {
                    var is_No_Errors_Found_Exist = result[0].ToString().Contains(Properties.Resources.ARGS_RESULT_Is_No_Errors_Found_Exist);
                    var is_Import_Failed_Exist = result[0].ToString().Contains(Properties.Resources.ARGS_RESULT_Is_Import_Failed_Exist);
                    var is_The_Import_Has_Failed_Exist = result[0].ToString().Contains(Properties.Resources.ARGS_RESULT_Is_The_Import_has_Failed_Exist);

                    string[] result_LOG = result[0].ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                    if ((result.Count == 2) && (!is_The_Import_Has_Failed_Exist))
                    {
                        result_REJECT = result[1].ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                        StatusResult = Properties.Resources.ARGS_RESULT_OK_REJECT;
                    }
                    else if (is_No_Errors_Found_Exist)
                    {
                        StatusResult = Properties.Resources.ARGS_RESULT_OK;
                    }
                    else if (is_Import_Failed_Exist)
                    {
                        StatusResult = Properties.Resources.ARGS_RESULT_KO;
                    }

                    if ((is_The_Import_Has_Failed_Exist) && (result.Count == 2))
                    {
                        result_REJECT = result[1].ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                        StatusResult = Properties.Resources.ARGS_RESULT_KO_REJECT;
                    }

                    returnObject = new ReturnObject
                    {
                        CountLines = CountLines,
                        Status = StatusResult,
                        LOG = result_LOG,
                        REJECT = result_REJECT
                    };
                }

It works well, I don't have any problems,
but I want to know if there is other code organization ? or any feedback ?


texts:
I'm just getting into SQL injection and data sanitization and seeking some advice on my script to get started. I have made this simple program which allows the user to enter their name into a form and the information gets saved into the database. There is also a button that lists all the current names in the database.

<?php
require 'db.php';

//If the "name" form was submitted, enter it into the database.
if (isset($_POST['submit'])) {
    $name = $_POST['name'];
    echo $name . ', you submitted it!';

    $con->query("INSERT INTO name (name) VALUES ('$name')");

}

//Delete name from database.
if (isset($_POST['del_submit'])) {
    $con->query("DELETE FROM name WHERE name='$del'");
    echo $del . ' deleted successfully!';
}

?>

<form id="devvo" method="post">

Enter your name:

<input type="text" name="name" />

<input type="submit" value="Submit" />

<input type="hidden" name="submit" />

</form>

<form id="list" method="post">
    <input type="submit" value="List Everyone...">
    <input type="hidden" name="list" />

</form>

<?php

//If the "list" form was submitted, get all names from database and display them to the user.
if (isset($_POST['list'])) {
    $result = $con->query("SELECT * FROM name");

    while ($row = $result->fetch_assoc()) {
        $del = $row['name'];

        echo 'Name:
';
        echo $row['name'];
        echo '<form id="del" method="post"><input type="submit" name="del_submit" value="X" /><input type="hidden" name="del" value="'.$del.'" /></form>';
        echo '
';
    }
}
?>

My knowledge of PHP is very limited (as you can tell from the program) but I'm definitely seeking some best practices and simple ways to improve the security of a simple program such as this. Feel free to tell me all the different ways this program could be exploited!


texts:
I am a first year CS student. We are currently learning Java and my latest assignment was to create this random number game. I am hoping to get some feedback on code style etc so that I know what not to do in the future and so that I can avoid getting into bad habits from the start. I don't know all that much so any explanations/tips at all will be amazing!

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

public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        boolean win = false;
        boolean running = true;
        System.out.println("Please enter the upper limit: ");
        Game game = new Game(scan.nextInt());

        while (running) {

            System.out.println("Please enter a guess ");

            while (!win) {
                if (game.guess(scan.nextInt())) {
                    win = true;

                }
            }
            System.out.println("Would you like to play again y/n?");
            String playAgain = scan.next();
            if (playAgain.equalsIgnoreCase("y")) {
                game.reset();
                running = true;
                win = false;
            } else {
                running = false;
                System.out.println("Game over");
            }
        }
    }
}

Game class:

import java.util.Random;

public class Game {

    private int randomNumber;
    private int tries = 0;
    private int range;

    public Game(int range) {
        this.range = range;
        generateRandomNumber();
    }

    private void generateRandomNumber() {
        Random rand = new Random();
        this.randomNumber = rand.nextInt(range) + 1;
    }

    public boolean guess(int guess) {
        tries++;
        if (guess == randomNumber) {
            if (tries > 1) {
                System.out.println("You got the number in " + tries + " tries.");
                return true;
            } else {
                System.out.println("You got the number in " + tries + " try.");
                return true;
            }
        } else if (guess > randomNumber) {
            System.out.println("Too high try again");
            return false;
        } else if (guess < randomNumber) {
            System.out.println("Too low try again ");
            return false;
        }
        return false;

    }

    public void reset() {
        this.tries = 0;
        generateRandomNumber();

    }

}


texts: Better way to add fields to superclass in Java

texts:
I'm making my first steps in OOP and I'm currently doing some exercises. I've done a simple program with class structure like this (I'll provide only essential parts):

Super class:

public abstract class Employee {
    private String lastName;
    private float salary;

    public Employee(String lastName, float salary) {
        this.lastName = lastName;
        this.salary= salary;
    }
}

And several child classes, all similar to this:

public class Worker extends Employee {
    private float hourRate;

    public Worker (String lastName, float salary, float hourRate) {
        super(lastName, salary);
        this.hourRate = hourRate;
    }
}

My concern is, when I'll decide to add some field to the Employee class that have to be set in constructor, let's say firstName, than I have to add it there and in constructor's arguments of all child classes and where I call super() inside them. It doesn't seem to be the best solution... Is there a better way to do such a thing? Maybe there is some pattern I don't know yet?


texts: Reducing time limit for prime number program

texts:
I have to create a program in which t sets of m and n will be given by the user. For each set, we have to generate all prime numbers between m and n.  This code is successfully executed with the correct output, but I have to reduce the time limit for a large data range.

#include<math.h>
#include<stdio.h>
int isPrime(int k);
int j;
int isPrime(int k)
 {
  for(j=2; j<=(int)sqrt(k); j++)
    {
      if(k%j==0)
      return 0;
    }
  return 1;
}

int main()
{
   int u,i,t,m,n,k;
   scanf("%d", &t);
   while(t--)
       {
         scanf("%d %d", &m, &n);

         for(i=m;i<=n;i++)
             {
                  u = isPrime(i);
                  if (u == 1)
                  printf("%d\n", i);
             }
       }
   return 0;
}


texts: Multiple readers, single writer synchronization

texts:
This is educational purpose "simulation" of multiple readers / single writer server.

No actual work is done, except the synchronization. In current realization, readers have priority over writers.

#include <thread>
#include <mutex>
#include <condition_variable>
#include <shared_mutex>

#include <vector>
#include <cstdio>

#include <chrono>

class Server{
public:
    void read(int const n){
        std::unique_lock<std::mutex> lock(mutex_);

        ++rCount;

        while(status_ == Status::WRITE)
            rQueue_.wait(lock);

        status_ = Status::READ;

        lock.unlock();

        emulate_work_(n);

        lock.lock();

        --rCount;

        if (rCount == 0){
            status_ = Status::IDLE;
            wQueue_.notify_one();
        }
    }

    void write(int const n){
        std::unique_lock<std::mutex> lock(mutex_);

        while(status_ != Status::IDLE)
            wQueue_.wait(lock);

        status_ = Status::WRITE;

        emulate_work_(n);

        status_ = Status::IDLE;

        if (rCount)
            rQueue_.notify_all();
        else
            wQueue_.notify_one();
    }

private:
    void emulate_work_(int const n) const{
        {
            std::lock_guard<std::mutex> lock(mutex_stdout_);

            if (status_ == Status::READ)
                printf("Thread %3d READ  | Readers %3zu\n", n, rCount);
            else
                printf("Thread %3d WRITE |\n", n);

        }

        // working...

        using namespace std::chrono_literals;

        std::this_thread::sleep_for(2ms);
    }

private:
    enum class Status : char{
        IDLE    = '.',
        READ    = 'R',
        WRITE   = 'W'
    };

private:
    mutable
    std::mutex      mutex_stdout_;

    std::mutex      mutex_;

    std::condition_variable rQueue_;
    std::condition_variable wQueue_;

    size_t rCount = 0;
//  size_t wCount = 0;

    Status status_ = Status::IDLE;
};

void reader(int const n, Server &server){
    for(int i = 0; i < 100; ++i){
        server.read(n);

        using namespace std::chrono_literals;

        std::this_thread::sleep_for(3ms);
    }
}

void writter(int n, Server &server){
    for(int i = 0; i < 20; ++i){
        server.write(n);

        using namespace std::chrono_literals;

        std::this_thread::sleep_for(1ms);
    }
}

int main(){
    std::vector<std::thread> v;

    Server server;

    for (int n = 0; n < 5; ++n) {
        v.emplace_back(writter, n, std::ref(server));
    }

    for (int n = 0; n < 5; ++n) {
        v.emplace_back(reader, n, std::ref(server));
    }

    for (auto& t : v) {
        t.join();
    }
}


texts: Really fast Knight's Tour using concurrency and Goroutines

texts:
In less that 5 seconds on a normal PC, I found the answer in simple brute-force. Before I met Go, I didn't believe that it will be so easy to use all the power of the PC by using Go Goroutines for concurrency and multithreading.

I tried exactly the same simple algorithm, without concurrency in Haskell and JavaScript. In Go it works more than 10x faster. Feedback is welcome.

package main

import (
    "fmt"
)

const (
    a         = 8
    b         = 8
    maxLevels = 64
)

func main() {
    c := make(chan [a][b]int)
    for x1 := 0; x1 < a; x1++ {
        for y1 := 0; y1 < b; y1++ {
            go func(x1 int, y1 int) {
                var chess [a][b]int
                var current int
                success := tryToMove(&chess, current, x1, y1)
                if success {
                    c <- chess
                }
            }(x1, y1)
        }
    }
    printChess(<-c)
}

func tryToMove(chess *[a][b]int, current int, x int, y int) bool {
    if x >= a || y >= b || x < 0 || y < 0 {
        return false
    }
    if chess[x][y] > 0 {
        return false
    }
    current++
    chess[x][y] = current
    if current == maxLevels {
        return true
    }
    if tryToMove(chess, current, x+2, y+1) {
        return true
    }
    if tryToMove(chess, current, x+2, y-1) {
        return true
    }
    if tryToMove(chess, current, x-2, y+1) {
        return true
    }
    if tryToMove(chess, current, x-2, y-1) {
        return true
    }
    if tryToMove(chess, current, x+1, y+2) {
        return true
    }
    if tryToMove(chess, current, x+1, y-2) {
        return true
    }
    if tryToMove(chess, current, x-1, y+2) {
        return true
    }
    if tryToMove(chess, current, x-1, y-2) {
        return true
    }
    chess[x][y] = 0
    current--
    return false
}

func printChess(chess [a][b]int) {
    for i := 0; i < a; i++ {
        fmt.Println(chess[i])
    }
}

Answer:

[64 53 20 43 22 55 32 29
[41 44 63 54 33 30 23 6]
[52 19 42 21 56 7 28 31]
[45 40 51 62 1 34 5 24]
[18 61 16 57 14 25 8 27]
[39 46 37 50 35 2 11 4]
[60 17 48 15 58 13 26 9]
[47 38 59 36 49 10 3 12]


texts:
I have a jQuery dialog that is opened when the content of a div is clicked.

When the dialog is opened, I am binding a jQuery outside event so when the user clicks anywhere outside of the dialog the dialog is closed.

When the dialog is opened I am modifying the URL path with

history.pushState(state, "new title", urlPath);`

I am also modifying the URL path on the close event.

The only way I have been able to get this to work is by using setTimeout. But I am looking for a better way.

function loadDialog(divID, iframe) {
        // if a dialog has been opened before, emptry it
        $("#dialog").empty();

        $('#dialog').dialog("open");

        // Modify the URL
        var urlPath = "#"+divID;
        var state = {"history" : true};
        history.pushState(state, "new title", urlPath);

        // add stuff to the dialog
        $('#dialog').append(iframe);

        setTimeout(function() {
            // bind the clickoutside event
            $('#dialog').bind( "clickoutside", function(event){
                $('#dialog').dialog('close');
                // modify the URL path
                history.pushState('', document.title, window.location.pathname);
                // unbind the clickoutside event
                $(this).unbind("clickoutside");
            });
        }, 2000);
    }


texts: Terminating a C loop when maximum hardware limit reached

texts:
In response to the SO question C: f>0 vs Perl: $f>0?, the use of overflow to terminate the loop is referred to as "poor programming practice". Paraphrased:

  Your c code is actually exiting because of
  poor programming practice. You're
  relying on fib being a long long int,
  which has an upper limit of 9.22337204
  × 10^18. When you loop around to the
  93rd iteration fib becomes 1.22001604 ×
  10^19, which overflows and becomes
  negative.

Substantially the same code:

cat >fib.c <<EOF
#include <stdio.h>
int main(){
   for (long long int temp, i=1, prev=0, fib=1; fib>0 ; i++, temp=fib, fib+=prev, prev=temp)
      printf("%lli: %lli\n", i, fib);
   }
EOF
gcc -std=c99 -ofib fib.c
./fib

The code was intended to be a one time "throw-away" program which was evidenced by the use of single letter variable names in the original version. The use of the overflow being indicated by fib becoming negate was used to terminate the loop.

Without knowing in advance what the maximum number of iterations the hardware architecture could handle what would be good "programming practice" to terminate the loop knowing that long long int is limited yet desiring as many values as possible?


texts:
I wrote an algorithm to separate a DAG into disjoint sets of vertices. I was hoping to have some comments on algorithmic complexity and efficiency of the Python code. Notably, I don't like the adding and removing of components from the components list.

g = {1: [3, 4], 2: [5], 3:[7], 4:[], 5:[], 6:[1], 7:[]}

vertices = set(g)
components = []
while vertices:
  stack = list((vertices.pop(),))
  comp = set()
  while stack:
    vert = stack.pop()
    comp.add(vert)
    if vert in vertices:
       vertices.remove(vert)
    for e in g[vert]:
        if e in vertices:
            stack.append(e)
        else:
            for component in components:
               if e in component:
                  component.update(comp)
                  comp = component
                  components.remove(comp)
    components.append(comp)

print([c for c in components])

>>> [{2, 5}, {1, 3, 4, 6, 7}]


texts:
I was trying to make my life easier making a class or something that would create HTML tags in a faster way. I ended up with something that I wouldn't consider the best practice. Take a look:

/**
 * Add HTML to the page
 *
 * Add HTML to the page based on arrays with the tag names. It's gonna open and close the tags.
 *
 * @param array tags The name of the tags
 * @param array attributes The attributes of the tags if you want
 * @param array The elements you want inside the tags
 */
function addHtml($tags = null, $attributes = null, $innerHtml = null)
{
    for($i = 0; $i < count($tags); $i++) {
        // Opens the tag
        echo '<' . $tags[$i];

        // If there're attribures, show them and close
        // If not, just closes the tag
        echo !empty($attributes) ? ' ' . $attributes[$i] . '>' : '>';

        // Show something you wanna put inside the tag. Another tag, text, anything
        echo $innerHtml[$i];

        // Closes the tag
        echo '</' . $tags[$i] . '>';
    }
}

Is there someone with a better way of doing it?


texts: Alternative for two sequentially executed loops with identical ranges

texts:
For the moment I'm executing my code as follows:

foreach (int data in dataList)
{
    PreProcess(data);
}
foreach (int data in dataList)
{
    Process(data);
}

First I have to loop over some data (from a list) and to do some pre-processing after which then I do have to loop again over the same data list and do some processing, but those loops have to be run one after another, and cannot be merged as follows...

foreach (int data in dataList)
{
    PreProcess(data);
    Process(data); // Cannot be run in the same loop with PreProcess(data);
}

...because PreProcess(data) and Process(data) are logging a lot of information which could be interlaced in case both are looping together.

The only alternative I've found will be using Linq, but still has the same duplicate ForEach:

dataList.ForEach(data => { PreProcess(data); });
dataList.ForEach(data => { Process(data); });

Is there any way to rewrite this in order to remove the redundancy for two loops with same range, but still looping sequentially first over PreProcess(data) and Process(data) afterwards?


texts: Displaying comments and replies retrieved from a database

texts:
I created an example (for me) of how I must get the comments and replies from the database.

Here is the result for example:

//I am ONLY thinking a query like this
$q = "SELECT * FROM comments_table WHERE post = 'url_code' ORDER BY date DESC";

//An example result (Not used the query above)

$comment = array(
            array(
                'id'            => '7',
                'user'          => 'Jul',
                'post_id'       => '1',
                'comment_id'    => '7',
                'reply_id'      => '1',
                'date'          => 'Jul 2016',
                'message'       => 'hello7'
            ),
            array(
                'id'            => '6',
                'user'          => 'Jun',
                'post_id'       => '1',
                'comment_id'    => '6',
                'reply_id'      => '1',
                'date'          => 'Jun 2016',
                'message'       => 'hello6'
            ),
            array(
                'id'            => '5',
                'user'          => 'May',
                'post_id'       => '1',
                'comment_id'    => '5',
                'reply_id'      => '3',
                'date'          => 'May 2016',
                'message'       => 'hello5'
            ),
            array(
                'id'            => '4',
                'user'          => 'Apr',
                'post_id'       => '1',
                'comment_id'    => '4',
                'reply_id'      => '2',
                'date'          => 'Apr 2016',
                'message'       => 'hello4'
            ),
            array(
                'id'            => '3',
                'user'          => 'Mar',
                'post_id'       => '1',
                'comment_id'    => '3',
                'reply_id'      => '',
                'date'          => 'Mar 2016',
                'message'       => 'hello3'
            ),
            array(
                'id'            => '2',
                'user'          => 'Feb',
                'post_id'       => '1',
                'comment_id'    => '2',
                'reply_id'      => '',
                'date'          => 'Feb 2016',
                'message'       => 'hello2'
            ),
            array(
                'id'            => '1',
                'user'          => 'Jan',
                'post_id'       => '1',
                'comment_id'    => '1',
                'reply_id'      => '',
                'date'          => 'Jan 2016',
                'message'       => 'hello'
            )
        );

Then the code to output it in the page:

foreach ($comment as $key => $value) {
    if(empty($value['reply_id'])) {
        $comments[$value['comment_id']] = array('user' => $value['user'], 'message' => $value['message']);
    } else {
        $replies[] = array('id' => $value['id'], 'reply_id' => $value['reply_id'], 'user' => $value['user'], 'message' => $value['message']);
    }
}

$reply_count = count($replies);
for ($i=0; $i < $reply_count; $i++) {
    $reply_id = $replies[$i]['reply_id'];
    if(isset($comments[$reply_id])) {
        $cc[$reply_id]['comment'] = array('user' => $comments[$reply_id]['user'], 'message' => $comments[$reply_id]['message']);
        $cc[$reply_id][$replies[$i]['id']] = array('user' => $replies[$i]['user'], 'message' => $replies[$i]['message']);
    }
}

foreach ($cc as $kkk => $vvv) {
    $reply = '';
    foreach ($vvv as $kk => $vv) {
        if(is_int($kk)) {
            $reply .= $vv['user'] . ' reply: ' . $vv['message'] . '
';
        } else {
            $comment = $vv['user'] . ' comment: ' . $vv['message'] . '
';
        }
    }
    echo $comment . $reply . '
';
}

The results are okay, but my question is, is this code okay to use?


texts: Display characters remaining next to input/textarea

texts:
I'm not great with JavaScript. I've written a small jQuery function and I've now got it working, but I just wanted to check if the code looks good or if it can be improved.

I wanted a function so that I can easily add the function to any textarea and input so that it counts characters remaining and so I can just change the max count value so I don't have to keep writing out the whole thing for every input/textarea. I want it to show the max count on focus, add a css warn class to it when it is the last 10, and add a css max-reached class to it when the count has exceeded. Here it is:

var jq = jQuery.noConflict();
jQuery( document ).ready( function() {

    jq.fn.cmCharactersLeft = function(options) {

        // defaults
        var defaults = {
            maxLength: 300,
            selector: '#testform .text-count'
        };

        var options = jq.extend(defaults, options);

        jq(this).keyup(function() {

            // character length variable
            var character_length = jq(this).val().length;

            // Characters left
            if( character_length <= options.maxLength ){
               jq( options.selector ).html( options.maxLength - character_length ).removeClass('max-reached count-warn');
            }
            // Characters left last 10
            if ( character_length >= ( options.maxLength - 10 ) ){
                jq( options.selector ).html( options.maxLength - character_length ).addClass('count-warn').removeClass('max-reached');
            }
            // Max characters reached
            if ( character_length > options.maxLength ){
               jq( options.selector ).html( options.maxLength - character_length ).addClass('max-reached').removeClass('count-warn');;
            }
        });

        // show 'characters left' on focus too
        jq(this).focus(function() {

            // character length variable
            var character_length = jq(this).val().length;

            // Characters left
            if( character_length < 1 ){
                jq( options.selector ).html( options.maxLength );
            }
        });

    }

});

Then I can use the above function for any textarea/input:

jQuery( document ).ready( function() {
    jq('#form1 textarea').cmCharactersLeft({
        maxLength: 50,
        selector: '#form1 .text-count'
    });
});

jQuery( document ).ready( function() {
    jq('#form2 textarea').cmCharactersLeft({
        maxLength: 200,
        selector: '#form2 .text-count'
    });
});

Example HTML:

<form id="form1">
<textarea></textarea>

<button type="submit">Submit</button>
</form>

Edit

Or, what would be a better way to write this?


texts: Codility MaxCounters peformance in Python capping out at 77% performance

texts:
My problem is quite similar to the question found here, except I am attempting to answer the question in Python.

  Given an array of N counters, all initialized to 0, and an array A representing a series of operations, find the final state of the counters.  Each entry in A should be interpreted as follows:

  If 1 ≤ A[k] ≤ N, then increase the counter at A[k] by 1.
  If A[k] = N + 1, then set all counters to current maximum value.

def solution(N, A):
    # write your code in Python 2.7
    counters = [0] * N
    max_count = 0
    for x in A:
        if 1 <= x and x <= N:
            counters[x-1] += 1
            if counters[x-1] > max_count:
                max_count += 1
        else:
            counters = [max_count] * N
    return counters

Nothing I can come up with allows me to do this in \$O(N + M)\$ time. I get rid of any max() functions going through the list by keeping track of it, but for the life of me I don't know how one is supposed to update N different variables M times (worst case scenario) without it being \$O(N * M)\$.

I am asking this question because I am uncertain what this question even asks is possible without having N processors to bring the \$O(N)\$ by itself stage of updating the counter array down to \$O(1)\$ through parallelization. Since the other question hasn't been answered, I guess what I want to know is if there is a data structure or some other heuristic that will get this down to \$O(M + N)\$.


texts: autoloader class fine tune to be usable in every project

texts:
I'm open to any advice to help improve this code for general use.

/**
*
* This code was created by Joshua Getner.
* @license http://opensource.org/licenses/bsd-license.php BSD
*
*
*/

namespace Blacksmith;

class Autoloader
{

    // an array that maps classnames to there filepaths
    protected static $classes = array();

   /**
    * register your classnames and class paths to the autoloader.
    * keeps the loading quick and accurate.
    * @param string $class
    * @param string $path
    * @return null
    */
    public static function setClassPath($className, $path)
    {
        static::$classes[$className] = str_replace('\\' , '/' , $path);
    }

   /**
    * register an array of classname with paths to the file
    * keeps the loading quick and accurate.
    * @param array $classes
    * @return null
    */
    public static function setClassPaths(array $classes)
    {
        static::$classes = array_merge($classes, static::$classes);
    }

   /**
    * return the path to the classname registered.
    * @param string $class
    * @return string
    */
    public static function getClassPath($className)
    {
        return((isset(static::$classes[$className]) ?
            static::$classes[$className] : false));
    }

   /**
    * return the array of all the classes registered.
    * @return array
    */
    public static function getClassPaths()
    {
        return static::$classes;
    }

   /**
    * return a formated file path according to the PSR standard
    * @param string $class
    * @return string
    */
    public static function formatPSRClass($class)
    {
        return  str_replace(array('\\', '_'), '/', strtolower($class)) . '.php';
    }

   /**
    * attempt to load the registered class or interface.
    * @param string $class
    * @return bool
    */
    public static function loadClass($class)
    {
        $path = "";

        // check if the class has been mapped
        if(static::getClassPath($class) !== false)
        {
            // set the path as the mapped path
            $path = static::getClassPath($class);
        }

        // so no class mapped, lets try the PSR way
        else
        {
            // get the path from the class name according to PSR-0
            $path = str_replace('\\', '/', dirname(__FILE__)) . '/' . static::formatPSRClass($class);
        }

        // lets attempt to load the file and check if the class or interface exists
        if(file_exists($path))
        {
            @require $path;

            if(class_exists($class, false) || interface_exists($class , false))
            {
                return true;
            }
        }

        // throw an exception no class was loaded.
        else
        {
            throw new \Exception(sprintf('unable to load the requested class: %s at path %s', $class, $path));
        }
    }
}


texts: sorting a numerical list using basic scheme

texts:
I would like some feedback on the appropriate way of ordering a numerical list using the most elementary scheme functions (sorry, i realise that elementary is not well defined).

By way of background: I've been learning a bit of scheme on my ipad, where I have only a basic implementation -- this is a nice challenge as much as a problem, as i have to figure out simple things like sorting a list for myself.

In doing this, i learnt that (append (cdr list) (car list)) is not what you might expect -- which is how i had originally wanted to implement this simple sort.

To hack around it, i discovered list-tail and reverse -- see the else clause below.

(define ra-sort
  (lambda (numList)
    (cond
      ((null? numList) '())
      ((= (car numList) (apply max numList))
       (cons (car numList) (ra-sort (cdr numList))))
      (else (ra-sort (append (list-tail numList (- (length numList) 1))
                             (reverse (list-tail (reverse numList) 1)))))
      )))

(define a '(99 1 6 12 101 2 67 -3))

> (ra-sort a)
(101 99 67 12 6 2 1 -3)

Now this seems to work, but all this repeated calling of reverse seems inefficient -- how should it be done?

Or am i missing something? Is it possible to make things work with the output of (append (cdr a) (car a))?

what does the notation even mean in (1 6 12 101 2 67 -3 . 99)? and how is it useful?


texts: Simple single css node parser written in rust

texts:
I am new to rust and I wrote a little program that takes a part CSS selector and returns the name of the element and two vectors containing its attributes (classes, ids)
Example

div#menu.big.pink => "div", ["menu'], ["big", "pink"]

Because I am new to rust I am looking for improvement to make this code better - more idiomatic faster, etc.
Thanks in advance for any suggestions, have a nice day :)
const LOOK_UP: [char; 2] = ['#', '.'];

fn find(string: &str) -> Option<(usize, usize)> {
    for (index, char) in string.chars().enumerate() {
        match LOOK_UP.iter().position(|&r| r == char) {
            Some(lookup_index) => return Some((index, lookup_index)),
            _ => continue,
        };
    };
    return None;
}

fn get_attributes(node_as_string: &str) -> (&str, [Vec<&str>; 2]) {
    match find(&node_as_string) {
        Some(first) => {
            let mut attributes: [Vec<&str>; 2] = [Vec::new(), Vec::new()];
            let mut current_index = first.0;
            let mut last_type = first.1;

            loop {
                match find(&node_as_string[current_index + 1..]) {
                    Some(next) => {
                        attributes[last_type].push(&node_as_string[current_index + 1..current_index + next.0 + 1]);
                        current_index += next.0 + 1;
                        last_type = next.1;
                        continue;
                    }
                    None => {
                        attributes[last_type].push(&node_as_string[current_index + 1..]);
                        break;
                    }
                }
            }
            return (&node_as_string[..first.0], attributes);
        }
        None => panic!("")
    }
}


texts: Build string by generating random characters step by step

texts:
I'm trying to create a program that will try to build a target string character by character by generating random characters. I have come up with the following Nodejs program with a little bit of Google help:

const args = process.argv.slice(2)

const targetWord = args[0]
let builtWord = ''

function getRandomChar() {
    return String.fromCharCode(Math.floor(Math.random() * (126 - 32 + 1)) + 32)
}

function updateWord() {
    const {length} = builtWord
    const nextChar = getRandomChar()
    process.stdout.write('\r')
    process.stdout.write(builtWord)
    process.stdout.write(nextChar)
    if (targetWord[length] === nextChar) {
        builtWord += nextChar
    }
}

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))

async function main() {
    while (true) {
        updateWord()
        if (builtWord === targetWord) {
            break
        }
        await sleep(1000 / 16)
    }
}

main()

What are your thoughts on it, anything I can improve or do differently? Thanks !


texts: Populating two lists, each from their respective with user input field

texts:
I've simplified this for posting, since there are going to be more than 4 options sets for this function to cycle through:

function redundantSee() {

  var optionSet1 = $('.wrapper:eq(0)'),
      optionSet2 = $('.wrapper:eq(1)');

  optionSet1.find('.options').each(function(){
      var self = $(this),
          input = self.find('input'),
          title = self.find('.title').text(),
          value = input.val(),
          source = self.find('img').attr('src'),
          id = input.attr('id'),
          listItem = $('<li/>', {'value': value, 'id': id }),
          imageElement = $('<img/>', {'src': source, 'title': title});

      $('div.corresponding1').append(nameListItem);
      listItem.append(imageElement);
  });

  optionSet2.find('.options').each(function(){
      var self = $(this),
          input = self.find('input'),
          title = self.find('.title').text(),
          value = input.val(),
          source = self.find('img').attr('src'),
          id = input.attr('id'),
          listItem = $('<li/>', {'value': value, 'id': id }),
          imageElement = $('<img/>', {'src': source, 'title': title});

      $('div.corresponding2').append(listItem);
      listItem.append(imageElement);
  });
}

I'm having a problem figuring out how to turn all of the repetitive code into something much more manageable. But since each option set has its own each loop, the $(this) variable (and all corresponding variables) are specific to the loop that is run on the ('.options') element.

If I do one each loop and use a counter, like this:

$('wrapper').each(function(i){ // ... });

I still run into the problem of needing to re-declare all my new variables specific to that optionSet's turn in the loop.

Can someone help me figure out how I can condense this so that I'm not constantly repeating the same code every time I add a new option set to the function?


texts:
While working with Android GUI my approach to adding Listeners for GUI elements is usually:

Button helpBt = (Button) findViewById(R.id.help_button);
helpBt.setOnClickListener(new View.OnClickListener() {
   /* Code */
});

Currently, I am at learning stage. However, will this approach be maintainence 'friendly' as I get working with more complex apps? If not, then what are suitable alternatives?


texts: Keeping error details out of responses (Restify)

texts:
I'd like to make sure error details are never sent out in responses from my restify-powered API. The best way to achieve that seemed to be via wrapping server.formatters in another function which filtered-out Errors before passing the transformed body on to the relevant formatter. I've probably missed some more obvious way to achieve this, but here's what I came up with. Does this seem reasonable, or is there a simpler solution?

const server = restify.createServer()

// wraps all formatters in a function filtering out Error bodies
Object.keys(server.formatters).forEach((name) => {
  const formatter = server.formatters[ name ]

  server.formatters[ name ] = (req, res, body, next) => {
    // keep possibly sensitive details from going out in error messages
    if (body instanceof Error &&
      !(body instanceof errors.HttpError) &&
      !(body instanceof errors.RestError)
    ) {
      body = new errors.InternalServerError('Internal Server Error')
    }

    return formatter(req, res, body, next)
  }
})


texts:
I maintain a VBA process that prints a large number of PDFs. It was awful when I inherited it and I've been making improvements over time, but I'm a bit stuck on this one. There are at least 4 functions with this exact same code used to check to see if the program has been initialized properly. They could all be called individually, or together depending on circumstances.

I do not want to initialize again if I don't have to. Hence the check in every subroutine, but I just can't figure out how to do it any differently. Thoughts? Is there a design pattern to deal with this kind of thing that I don't know of?

Please try to focus on the pattern and not the supporting intitializer. I know there are a few issues there and intend to deal with them soon. I included it in case it was relevant.

Main code:

Private rootDir As String
Private isInit As Boolean
Private mCycle As String

Public Function printPDF_VoidedNewItems()
    If Not isInit Then
        initialize
    End If
    If rootDir <> "" And mCycle <> "" Then
        If setPrinterToPDF() Then
            ' logic specific to printing this pdf
        End If
    End If
End Function

Public Function printPDF_ComsNotFed()
    If Not isInit Then
        initialize
    End If
    If rootDir <> "" And mCycle <> "" Then
        If setPrinterToPDF() Then
            ' logic specific to printing this pdf
        End If
    End If
End Function

Initializer:

Private Sub initialize()
    rootDir = folderPicker() & "\"
    mCycle = getCycleInput
    isInit = True
End Sub

Private Function folderPicker() As String
'*******************************************
' returns directory path to be printed to
'   does not allow multiple selections,
'   so returning the first item in selected
'   items is sufficient.
'
' returns empty string On Error or if the
'   user cancels
'********************************************
On Error GoTo ErrHandler

    Dim folderChosen As Integer
    Dim fd As Variant
    Set fd = Application.FileDialog(msoFileDialogFolderPicker)
    With fd
        .AllowMultiSelect = False
        .Title = "Choose Directory to Print to"
        .InitialFileName = "\\server\share\"
        .InitialView = msoFileDialogViewSmallIcons
        folderChosen = .Show
        If folderChosen <> -1 Then
            folderPicker = ""
        Else
            folderPicker = .SelectedItems(1)
        End If
    End With
Exit Function

ErrExit:
    folderPicker = ""
    Exit Function
ErrHandler:
    MsgBox "Unexpected Error: " & Err.number & vbCrLf & "Source: " & Err.Source & _
        "Description: " & Err.Description, vbCritical, "ERROR!"
End Function

Private Function getCycleInput() As String
' Displays a form with a combo box to the user.
' Returns an empty string if canceled or errored
'   Otherwise returns 8 character Cycle from dbo.MAM_ISE_SCHEDULE
On Error GoTo ErrHandler

    Dim cpkr As New Form_CyclePicker

    'wait for user input
    Do Until cpkr.Cancel = True Or cpkr.Confirmed = True 'Do Until user clicks "OK" or "Cancel"
        DoEvents 'frees up OS to actually display form and allow user to interact with it
    Loop

    If cpkr.Cancel Or Not cpkr.Confirmed Then ' not confirmed seems redundant, but certainly can't hurt to check.
        ' return
        getCycleInput = ""
        GoTo ExitSub
    Else
        ' return
        getCycleInput = cpkr.CycleNumber
    End If

ExitSub:
    Set cpkr = Nothing
    Exit Function
ErrHandler:
    MsgBox Err.Description, vbCritical, "Runtime Error: " & Err.number
    getCycleInput = ""
    Resume ExitSub
End Function


texts: Keep elements present an odd number of times in an unsorted vector

texts:
From an unsorted vector of integers, I would like to keep only elements that are present an odd number of times and have them sorted. Below is an example of a working code.

#include<vector>
#include <iostream>

using namespace std;

int main()
{
        vector<int> input = { 11, 3, 7, 3, 9, 3, 8, 11, 9, 3, 2, 9 };

        // print  input
        cout << "Input:" << endl;
        for (int i = 0 ; i < input.size() ; i++)
        {
          cout << input[i] << " ";
        }
        cout << endl;

        // sort the input
        sort(input.begin(), input.end());

        // print sorted input
        cout << "Sorted Input:" << endl;
        for (int i = 0 ; i < input.size() ; i++)
        {
          cout << input[i] << " ";
        }
        cout << endl;

        // Keep only elements present an odd number of times
        vector<int> output;
        int nbRepeats = 1;
        for (int i = 1 ; i < input.size() ; i++)
        {
                if (input[i-1] == input[i])  // if the ith element is a repeat
                {
                        nbRepeats++;
                } else
                {
                        if (nbRepeats % 2)  // Given that we have a new element, we will add the previous element to 'output' if the number of repeats of this previous element was odd
                        {
                                output.push_back(input[i-1]);
                        }
                        nbRepeats = 1;      // set nbRepeats back to 1 for the next series of elements.
                }
        }
        if (nbRepeats % 2)  // This is for the last series of elements
        {
                output.push_back(input.back());
        }

        // print the output
        cout << "Output:" << endl;
        for (int i = 0 ; i < output.size() ; i++)
        {
          cout << output[i] << " ";
        }
        cout << endl;
}

it rightly outputs

Input:
11 3 7 3 9 3 8 11 9 3 2 9
Sorted Input:
2 3 3 3 3 7 8 9 9 9 11 11
Output:
2 7 8 9

Question

The process is being a bit too slow for my needs. Is there alternative faster solution?

Typical input

Please note that a typical input is only between 1 and 10 elements long but cases of repeats will be quite common.

Potential ways to improve the code

I don't need to use the input, so I would be happy to directly modify the input rather than having to allocate memory an output vector if you think that would be faster.

It might eventually be more strategic to first remove elements we don't want (and get something like {7 9 8 2}) and sort them afterward but I doubt we can do the first step in better than O(n^2)


texts:
So I made this simple text database system for storing a list of objects because I hate using other database programs. But I was just wondering what you guys think I could do to make this faster and less resource intensive.

package com.gmail.welsar55.WDB;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

public class Managing {

    public static String mime = "wtdb";

    public static boolean addObject(File file, Object object) throws IOException
    {
        if(file.getName().endsWith(mime))
        {
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
            pw.println(object.toString());
            pw.close();
            return true;
        }
        else
        {
            return false;
        }
    }

    public static boolean containsObject(File file, Object object) throws IOException
    {
        if(file.getName().endsWith(mime))
        {
            BufferedReader br = new BufferedReader(new FileReader(file));
            boolean IsGood = false;
            while(br.ready())
            {
                String line = br.readLine();
                if(line.trim().equals(object.toString()))
                {
                    IsGood = true;
                }
            }
            br.close();
            return IsGood;
        }
        else
        {
            return false;
        }
    }

    public static boolean removeObject(File file, Object object) throws IOException
    {
        if(file.getName().endsWith(mime))
        {
            BufferedReader br = new BufferedReader(new FileReader(file));
            boolean IsGood = false;
            ArrayList<String> linestoadd = new ArrayList<String>();
            while(br.ready())
            {
                String line = br.readLine();
                if(!line.trim().equals(object.toString()))
                {
                    linestoadd.add(line.trim());
                }
                else
                {
                    IsGood = true;
                }
            }
            br.close();
            BufferedWriter fileclearer = new BufferedWriter(new FileWriter(file));
            fileclearer.write("");
            fileclearer.close();
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
            for(String linetoadd : linestoadd)
            {
                pw.println(linetoadd);
            }
            pw.close();
            return IsGood;

        }
        else
        {
            return false;
        }
    }

    public static ArrayList<String> getContents(File file) throws IOException
    {
        ArrayList<String> contents = new ArrayList<String>();
        if(file.getName().endsWith(mime))
        {
            BufferedReader br = new BufferedReader(new FileReader(file));
            while(br.ready())
            {
                contents.add(br.readLine());
            }
            br.close();
        }
        return contents;
    }
}


texts: Proper way of deallocating memory in SLL?

texts:
So I'm making my own singly linked list class, with methods that you'd expect such as remove() and insert(). I don't use pointers that much (almost never), so I thought by making a SLL class it would be good practice for me. But I'm not sure if I'm deallocating my memory correctly.
Here's the structure of my SLL:
class singly_linked_list
{
private:
    struct Node
    {
        Node* next;
        int value;
    };

private:
    int _length;
    Node* head;

public:
    ~singly_linked_list();

public:
    void remove(int index);
    void remove_front();
    void remove_back();
};

I'm most concerned about the destructor, and the three remove methods, and those are the ones deallocating memory, and I'm not sure if I'm doing it correctly.
Here's their definitions:
class singly_linked_list
{
private:
    struct Node
    {
        Node* next;
        int value;
    };

private:
    int _length;
    Node* head;

public:
    ~singly_linked_list()
    {
        Node* node_ptr = head;
        for (int a = 0; a < _length; ++a)
        {
            node_ptr = node_ptr->next;

            delete head;
            head = node_ptr;
        }
    }

public:
    void remove(int index)
    {
        if (index < 0 || index >= _length)
            throw "index is out of range";

        if (index == 0)
        {
            this->remove_front();
            return;
        }

        Node* node_ptr = head;
        for (int a = 0; a < index - 1; ++a)
            head = head->next;

        Node* temp = head->next;
        head->next = temp->next;
        delete temp;

        _length -= 1;
    }

    void remove_front()
    {
        if (_length == 1)
        {
            // should I delete head instead?
            head = nullptr; // delete head;
            _length = 0;

            return;
        }

        Node* temp = head;
        head = head->next;
        delete temp;

        _length -= 1;
    }

    void remove_back()
    {
        if (_length == 1)
        {
            head = nullptr;
            _length = 0;

            return;
        }

        Node* node_ptr = head;
        for (int a = 0; a < _length - 2; ++a)
            node_ptr = node_ptr->next;

        Node* temp = node_ptr->next;
        node_ptr->next = nullptr;
        delete temp;

        _length -= 1;
    }
};

I checked a few other questions including this one, but it didn't go too much in depth on memory management.
So a couple questions:

Am I causing any memory leaks, and is there a better, safer way to do things?
In remove_front(), should I set head to nullptr, or should I delete it instead?

Thanks


texts:
The previous version of my function was scalar-valued and employed a WHILE loop to do the comparison, this is SLOW. This new version is tabled-valued and uses a typical tally table in place of the loop. The result is an implementation that is MUCH more efficient while being slightly easier to comprenhend (IMHO).

There is a slight drawback to the new version however: it fails on strings longer than 2GB in size.

create function api.ConstantTimeIsEqual (
    @x varbinary(max) = 0x00
  , @y varbinary(max) = 0x00
)
/*
    What? Compares two variable length binary strings byte by byte in constant time.

    When? Cryptography, Gaming.

    Why? Given the strings 0x1234 and 0x1213: a simple equality comparison will stop processing after
         it hits the first mismatch at byte position 3. An opponent who only knows @x can exploit this
         feature to guess @y by trying thousands of comparisons and gathering statistics on how long
         each one took.

         In other words, assuming that it takes 100 milliseconds to compare a 16 byte string, an
         opponent can rely on the fact that strings that take more than 50 milliseconds to process are
         better guesses than ones that take less than 50 milliseconds. Thus, if a comparison takes 50
         milliseconds then @x is a 50% match of @y (from byte positions 1 through 8).

    How? 1. cache the length of @x into [@xLength] (n)
         2. cache a range of integers from 1 to XLength.n into [Iterator] (n)
         3. bail early if the lengths of @x and @y are not equal
         4. XOR nth byte of @x with nth byte of @y
         5. SUM all XOR results, cast result to bit (0 will stay 0, any other number will become 1)
         6. flip the final bit to retain "IsEqual" semantics
 */
returns table
with schemabinding as
return (
    select Cast(Sum(Substring(@x, [Iterator].n, 1) ^ Cast(Substring(@y, [Iterator].n, 1) as tinyint) /* 4 */) as bit /* 5 */) ^ 1 /* 6 */ as b
    from (values(DataLength(@x))) as [@xLength] (n) /* 1 */
    cross apply math.RangeInt(1, [@xLength].n) as [Iterator] /* 2 */
    where Abs([@xLength].n - DataLength(@y)) = 0 /* 3 */
);


texts:
I need to perform few tasks inside a Windows Service I am writing in parallel. I am using VS2013, .NET 4.5 and this post shows that TPL is the way to go.

I was wondering if anyone can tell me if I have done it correctly.

public partial class FtpLink : ServiceBase
{
    private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
    private readonly ManualResetEvent _runCompleteEvent = new ManualResetEvent(false);

    public FtpLink()
    {
        InitializeComponent();

        // Load configuration
        WebEnvironment.Instance.Initialise();
    }

    protected override void OnStart(string[] args)
    {
        Trace.TraceInformation("DatabaseToFtp is running");

        try
        {
            RunAsync(_cancellationTokenSource.Token).Wait();
        }
        finally
        {
            _runCompleteEvent.Set();
        }
    }

    protected override void OnStop()
    {
        Trace.TraceInformation("DatabaseToFtp is stopping");

        _cancellationTokenSource.Cancel();
        _runCompleteEvent.WaitOne();

        Trace.TraceInformation("DatabaseToFtp has stopped");
    }

    private async Task RunAsync(CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            Trace.TraceInformation("Working");

            // Do the actual work
            var tasks = new List<Task>
            {
                Task.Factory.StartNew(() => new Processor().ProcessMessageFiles(), cancellationToken),
                Task.Factory.StartNew(() => new Processor().ProcessFirmware(), cancellationToken)
            };

            Task.WaitAll(tasks.ToArray(), cancellationToken);

            // Delay the loop for a certain time
            await Task.Delay(WebEnvironment.Instance.DatabasePollInterval, cancellationToken);
        }
    }
}


texts: Count words in a list of titles, with some cleanup

texts:
I have a list of article titles, where I wish to count the number of occurrences for each word (and remove some words and characters). The input is in a .csv file where the titles are in column 'Titles'.

Maybe someone could help me do it more elegantly.

import numpy as np
import pandas as pd
#imports Counter, as we will need it later:
from collections import Counter

df = pd.read_csv("Article_titles.csv")
print (df.head(10))

#Selecting the titles into variable
titles = []
titles = df.Title

remove_words_list = ["at","of","a","and","in","for","the","to","with","on","using","an","after","from","by","use","review","upper","new","system"]
remove_characters_list = ".:,-%()[]?'"

huge_title_list = []
#create a list of all article titles:
for i in range(len(titles)):
  clean_title = titles[i].lower().translate({ord(i): None for i in remove_characters_list})
  huge_title_list.append(clean_title)

total_words_string = " ".join(huge_title_list)
#join all article titles into one huge string

querywords = total_words_string.split()
#split the string into a series of words

resultwords = [word for word in querywords if word not in remove_words_list]
#From stackoverflow

resultwords_as_list = list( Counter(resultwords).items())

#Convert resultwords_list to dataframe, then convert count to numbers and finally sorting.
resultframe = pd.DataFrame(np.array(resultwords_as_list).reshape(-1,2), columns = ("Keyword","Count"))
resultframe.Count = pd.to_numeric(resultframe.Count)
sortedframe = resultframe.sort_values(by='Count',ascending=False).reset_index(drop=True)
print(sortedframe[0:50])

example of Input:

Titles | other_field | other_field2

"Current status of prognostic factors in patients with metastatic renal cell carcinoma." |"asdf"|12
"Sentinel lymph node biopsy in clinically node-negative Merkel cell carcinoma: the Westmead Hospital experience." |"asdf"|15

desired output:

Word | Count

carcinoma | 2

cell | 2

biopsy | 1

clinically | 1

....

...


texts:
This was one of my assignments in which I had to create a backup script that will individually compress all files (of an arbitrary number) of file-types (indicated by their .extension).

Example: backup a b c will take all files ending in .a, .b and .c and compress them using tar, keeping the original file, and naming the new compressed file the same as before except with .tar.gz at the end.

The -t flag can be used to specify the target directory.

The -d flag can be used to specify the destination directory.

Example: backup -t ~/Desktop/stuff -d goesHere gif where goesHere is a directory in your current path and all files ending with .gif come from ~/Desktop/stuff.

$ ls
.  ..  backup  cat.gif  dog.gif  funny_video.mov  media
$ ./backup -d media gif mov
backup: compressed .gif files
backup: compressed .mov files
backup: files saved to "media"
$ cd media
$ ls
.  ..  cat.gif.tar.gz  dog.gif.tar.gz  funny_video.mov.tar.gz
$

Both flags are optional, allowing you to specify either one or both. If you specify both flags you must use the order -t <directory> -d <directory>.

Granted I really don't like the specifications of the assignment, but that is what they are. The fact we're asked to compress all files by their .extension is kind of anti-*nix anyways (everyone knows cat.png could be a plain text file).

#!/bin/bash

list_begin=1 # where the filetype arguments begins
list_end=$ # where the filetype arguments end

target_directory=$(pwd)
destination_directory=$(pwd)

if [[ $# < 1 ]]; then
    echo "backup: not enough arguments"
    exit
fi

# determine if any flags are used and if so update directories and $list_begin
if [[ $1 == "-t" ]]; then # -t
    target_directory=$2
    list_begin=3
    if [[ $3 == "-d" ]]; then # -t, -td
        destination_directory=$4
        list_begin=5
    fi
elif [[ $1 == "-d" ]]; then # -d
    destination_directory=$2
    list_begin=3
fi

# confirm directories are real
if [[ ! -d "${target_directory}" ]]; then # invalid -t
    echo "backup: \"${target_directory}\" is not valid"
    exit
elif [[ ! -d "${destination_directory}" ]]; then # invalid -d
    echo "backup: \"${destination_directory}\" is not valid"
    exit
fi

declare -a filetypes # array to store filetypes

for ((i=${list_begin}, j=0; i<=${list_end}; i++, j++)); do # fetch all filetype arguments and add to array
    eval dir=\${$i}
    filetypes[${j}]=${dir}
done

for i in "${filetypes[@]}"; do # for each filetype
    f_list="${target_directory}/*.${i}" # directory to iterate through
    for file in ${f_list}; do # for each file of that filetype in the target directory
        if [[ -f "${file}" ]]; then
            tar -czf ${destination_directory}/$(basename "$file").tar.gz -P ${file} # compress the file in the destination directory
        fi
    done
    echo "backup: finished .${i} files"
done

echo "backup: files saved to \"${destination_directory}\""


texts:
In short, how do I improve my code? I have a couple of files on Mediafire.com, link to shared folder for the purpose of this question. I would like to get a list of download-links and filenames so I can put them on my website for easy access. The problem is, mediafire doesn't make it easy!

I'd better mention that I own the files I'm working with. I have the mediafire-account the files are in. I could login to mediafire and copy each link, then copy the filename and paste it into a file. But where is the fun in that? And it would take forever to keep track of what files I deleted or added to my account. It's easier to do it this way.

The links I have to my files are in the wrong format so I needed to remake them in order to fit my purpose.

Wrong format:

http://www.mediafire.com/download.php?kt9z2284k2sg8ay

Format I want them in:

http://www.mediafire.com/file/kt9z2284k2sg8ay

Then, from the correct format I need to get the filename. After a lot of trial and error I finally got it working.

But there must be a better way of doing it? When I read the list from file and I have, lets say 50+ links it takes forever and I sometimes get Timeout errors.

I have a local server so I can pretty much do what I want on my end, but PHP is what I "know" (read: manages to find code online that I can rewrite to my needs).

I have tried DomDocument but it kept giving me errors (the manual was no use since it was there I got the code I tried to use). I gave curl a try and it gave me almost what I was looking for but since PHP is what I used to know some 10 years ago, that is what I went back to.

If someone wants to answer this then could you do it in PHP since I can "read" that and understand what is going on.

<?php
ini_set('auto_detect_line_endings', true);

//obviusly this is where I get the incorrect links
//and i have several files with links... thats why i did it this way.
foreach (glob("./mediafire*.txt") as $files) {
    if($files == '.' || $files == '..') continue;

if (($file = fopen("$files", "r")) !== FALSE) {

    // This works and I don't dare to change it ( and this is what one row in "mediafire*.txt
    // looks like http://www.mediafire.com/download.php?kt9z2284k2sg8ay )
    // I get the part after ? to $f1
    while (($line = fgetcsv($file, 500, "\t")) !== false) {
        $f1 = $line[0];
        $f1 = explode('?',$f1);
        $f1 = trim(array_pop($f1));

    //Make the link look like I want it and can use to get the filename-information.
    $var_mediafire = "http://www.mediafire.com/file/";
    $var_full_link = $var_mediafire . $f1;

    //Get the page with the filename information.
    //From this point is where I think there must be a better/faster solution.
    $dllink = file_get_contents("$var_full_link", true);

    $mystring = $dllink;
    $findthis = '<div class="fileName">'; //This is what I'm looking for from the download-page
    $pos = strpos($mystring, $findthis);

    if ($pos === false) {
        echo "The string was not found ";
    } else {
            $foundit = substr(strstr($mystring,$findthis),strlen($findthis),250); //I just take the next 250 chars
            $nextpos = strpos($foundit, '<');

            $myfilename = substr($foundit,0,$nextpos);

    //what should we write to file?
    $writethis = $var_full_link .';'. $myfilename ."\n";
//          echo $writethis;
            $myfile = 'mywonderfullinksandfilenames.txt';
            file_put_contents($myfile, $writethis, FILE_APPEND);
            }
        }
    }
}
// I really would like to get the file size as well, it is in the "$foundit" variable
//but it takes to long to execute already.

?>


texts: Sudoku solutions finder using brute force and backtracking

texts:
I'm calculating all possible solutions for a given Sudoku board with at least 17 values. My approach is a basic backtracking approach and it works.

protected void calculateSolutions(final SudokuBoard input) {

    if (input.getFilledCells() == 81) {
        addSolution(input);
        return;
    }

    for (int grid = 0; grid < 9; grid++) {
        for (int pos = 0; pos < 9; pos++) {
            if (input.getValue(new Position(grid, pos)).isEmpty()) {
                for (int number = 1; number <= 9; number++) {
                    if (isPossibleAtPosition(grid, pos, number)) {

                        SudokuBoard newInput = input.clone();
                        newInput.setValue(new Position(grid, pos), new Value(number));
                        List<SudokuBoard> results = new SudokuBacktrackSolver().solve(newInput);
                        for (SudokuBoard result : results) {
                            addSolution(result);
                        }
                    }
                }
                return;
            }
        }
    }
}

The function isPossibleAtPosition checks whether the number exists in the cell, row or grid. If it is possible, I create a new SudokuBoard, which ends up in a tree structure, where each solution has a depth of 81.

I also thought about creating a matrix containing all possibilities. This would improve the chance of finding a solution fastest but would produce a big overhead, and as I want to find all possible solutions, it would not be an improvement.

Are there any delimitations to improve the algorithm?


texts:
I am trying to implement a greedy zip method in Haskell where it does not drop the elements, instead, it will use some default value. I appreciate any feedback to make it more compact.

zip' [-1] [] r = r
zip' [] [-1] r = r

zip' [] b r  = zip' [-1] b r
zip' a [] r  = zip' a [-1] r

zip' a b r  = (xa, xb) : (zip' xsa xsb r)
  where
    (xa: xsa) = a
    (xb: xsb) = b

main = do
  let l1 = [1, 2, 3]
  let l2 = [3, 4]
  print (zip' l1 l2 [])
  --  expected: [(1,3),(2,4),(3,-1)]


texts: Remove duplication in Ruby map with conditional entries

texts:
I have a nasty (IMO) piece of code for a datatable configuration, how do i best remove the duplication here?

I've tried the obvious things I know (collapsing into one statement and trying inline conditionals) but it isn't working and I can't help thinking there must be a more elegant Ruby way here.

if show_status == "true"
  if show_requested_by == "true"
    records.map do |record|
      {
        warning: as_warning(record),
        updated_at: as_time_ago(record.updated_at),
        status: as_status(record.status),
        user: record.user.nil? ? "" : record.user.formal_name,
        manager: record.manager.nil? ? "" : record.manager.formal_name,
        first_date: as_date(record.first_date),
        last_date: as_date(record.last_date),
        days: as_number(record.total_days),
        hours: as_number(record.total_hours),
        units: as_number(record.total_units),
        value: as_number(record.total_value),
        comment: as_comment(record.comment),
        actions: as_actions(record)
      }
    end
  else
    records.map do |record|
      {
        warning: as_warning(record),
        updated_at: as_time_ago(record.updated_at),
        status: as_status(record.status),
        manager: record.manager.nil? ? "" : record.manager.formal_name,
        first_date: as_date(record.first_date),
        last_date: as_date(record.last_date),
        days: as_number(record.total_days),
        hours: as_number(record.total_hours),
        units: as_number(record.total_units),
        value: as_number(record.total_value),
        comment: as_comment(record.comment),
        actions: as_actions(record)
      }
    end
  end
else
  if show_requested_by == "true"
    records.map do |record|
      {
        warning: as_warning(record),
        updated_at: as_time_ago(record.updated_at),
        user: record.user.nil? ? "" : record.user.formal_name,
        manager: record.manager.nil? ? "" : record.manager.formal_name,
        first_date: as_date(record.first_date),
        last_date: as_date(record.last_date),
        days: as_number(record.total_days),
        hours: as_number(record.total_hours),
        units: as_number(record.total_units),
        value: as_number(record.total_value),
        comment: as_comment(record.comment),
        actions: as_actions(record)
      }
    end
  else
    records.map do |record|
      {
        warning: as_warning(record),
        updated_at: as_time_ago(record.updated_at),
        manager: record.manager.nil? ? "" : record.manager.formal_name,
        first_date: as_date(record.first_date),
        last_date: as_date(record.last_date),
        days: as_number(record.total_days),
        hours: as_number(record.total_hours),
        units: as_number(record.total_units),
        value: as_number(record.total_value),
        comment: as_comment(record.comment),
        actions: as_actions(record)
      }
    end
  end
end


texts:
I have a function that compares bits from a binary representation string and a chunk of memory and returns true if they are equal.

This is the function (which works as expected): I'll explain with comments what some external methods are supposed to do, accept that they work as expected for the sake of this question.

size_t bytes = (check_n_bits + 7) / 8;
size_t bytes_with_skip = (check_n_bits + skip_b_bits + 7) / 8;

//Check if `this` contains the number of bytes we need
if(this->canMoveForward(bytes_with_skip) == false) return false;

//Read the required number if bits. Ignore the skip_b_bits argument.
Bits *data = this->readBits(check_n_bits, skip_b_bits);

unsigned char *bin_string = Utils::removeSpaces(string);
size_t len = strlen((const char *) bin_string);
if(Utils::isValidBinString(bin_string) || len < check_n_bits) return false;

unsigned int last_bits = check_n_bits <= 8 ? check_n_bits : (bytes * 8) - check_n_bits;
last_bits = last_bits == 0 ? 8 : last_bits;

char tmp_bin_repr[9], tmp_bin_repr_2[9];

for(size_t i = 0; i < bytes ; i++) {
    int skip_bits_if_last = i + 1 == bytes ? (8 - last_bits) : 0;
    int bits_to_compare = i + 1 == bytes ? last_bits : 8;

    uint8_t c = data->read_uint8();
    sprintf((char *) &tmp_bin_repr, BYTETOBINARYPATTERN, BYTETOBINARY(c));
    for(int j = 0; j < bits_to_compare; j++) {
        tmp_bin_repr_2[j] = *(&(bin_string[i * 8]) + j);
    }

    if(memcmp((const char *) tmp_bin_repr + skip_bits_if_last, (const char *) tmp_bin_repr_2, bits_to_compare) != 0) {
        match = false;
        break;
    }
}

Helper macro:

#define BYTETOBINARYPATTERN "%d%d%d%d%d%d%d%d"
#define BYTETOBINARY(byte) \
    (byte & 0x80 ? 1 : 0), \
    (byte & 0x40 ? 1 : 0), \
    (byte & 0x20 ? 1 : 0), \
    (byte & 0x10 ? 1 : 0), \
    (byte & 0x08 ? 1 : 0), \
    (byte & 0x04 ? 1 : 0), \
    (byte & 0x02 ? 1 : 0), \
    (byte & 0x01 ? 1 : 0)

Let's call this function:

compareBinary(const char *string, size_t check_n_bits, size_t skip_b_bits)

How is this function used? The function is a method of an object that contains some data. When this method is called, it compares as many bits from a binary string representation of data as we pass it with the data contained in the object.

Example:

mObj->compareBinary("01010101 11110100 00", 18, 0);

This will compare 18 bits in total with the data that is hold in the object. First 8 chars of the passed string will be taken and the first byte of the data hold by the object will be converted to a string (using the helper macro). Then both will be compared. Second 8 chars, the same. Then we'd get the last 00 chars, take the third byte, convert it to a 8 chars binary representation, but only the first two chars will be compared.

This lets me compare a random number of bits with a simple binary representation of the data.

While the function works as expected and it's passing multiple unit tests, I believe it can be refactored and optimized. Can you give me any tips how to do it?


texts: multiple instances of maps and markers using object oriented javascript

texts:
This is my first attempt at object oriented javascript code. I have been writing JavaScript code for few years now but this is first time I am trying to write OO javascript code. I have read about OO javascript, but I am not still very confident about it.

Could you please review it and provide your comments about this implementation of OO javascript?

"use strict";

var maps_1, maps_2, maps_3, maps_4;
var markers_array1 = [], markers_array2 = [], markers_array3 = [], markers_array4 = [];

var google_map = function (x,y,z) {
    this.map = new google.maps.Map(document.getElementById(x), {
        zoom : parseInt(z),
        center : y,
        mapnameId : google.maps.MapnameId.ROADMAP,
        disableDefaultUI : true,
        styles : {
            featurename : "poi",
            elementname : "labels",
            stylers : [{
                    visibility : "off"
                }
            ]
        }
    });
};

var google_marker = function(x,map) {
    var icon_url =  'icons/' + x.dname + '_' + ((x.dname2 === 0) ? '0.png' : '1.png');
    var lat = parseFloat(x.lat), lng = parseFloat(x.lng);

    if(lat*lng > 0) {
        this.marker = new google.maps.Marker({
                icon : icon_url,
                position: {"lat":lat,"lng":lng},
                description : ''+x.name+'
'+x.desc,
                title: x.dname,
                start: x.start,
                map: map
            });

        this.marker.addListener('click', infoWindow);
    }
}

function loadJson() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", "ajax.php", true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.send(data);

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            loadMarkers(JSON.parse(xmlhttp.response));
        }
    }
}

function init() {
    maps_1 = new google_map('maps_1',{"lat" : 32.93,"lng" : 85.06},12);
    maps_2 = new google_map('maps_2',{"lat" : 70.88,"lng" : 45.97},12);
    maps_3 = new google_map('maps_3',{"lat" : 60.49,"lng" : 38.00},12);
    maps_4 = new google_map('maps_4',{"lat" : 85.85,"lng" : 89.63},12);

    loadJson();
}

function loadMarkers(Markers) {

    for(var y in Markers) {
        var x  = Markers[y];
        markers_array1.push(new google_marker (x,maps_1.map));
        markers_array2.push(new google_marker (x,maps_2.map));
        markers_array3.push(new google_marker (x,maps_3.map));
        markers_array4.push(new google_marker (x,maps_4.map));
    }
}
init();


texts:
I recently discover by reading some blog topics on web that 90% of code lines I produced in my career was procedural and not OOP oriented (big slap in the head). So now, I try to lobotomy my brain in order to produce only OOP codes. The problem is that I have a lot of questions about OOP practice.

Here is one :

I got a factory RawLineCollectionFactory that take string lines and create from it a domain entity called RawLineCollection. My question is about argument type pass to the Create method.

Should I pass it the object (IDataSource) that allows me to retrieve the string lines like that :

public class RawLineCollectionFactory : IRawLineCollectionFactory
{
    public IRawLineCollection Create(IDataSource dataSource)
    {
        ICollection<RawLine> lineGroup = new List<RawLine>();

        if (dataSource.GetLines() != null)
        {
            foreach (string line in dataSource.GetLines())
            {
                lineGroup.Add(new RawLine(line));
            }
        }

        return new RawLineCollection(lineGroup);
    }
}

Or call getLines() of the dataSource object on higher abstraction level and pass the result as argument of Create method ?

public class RawLineCollectionFactory : IRawLineCollectionFactory
{
    public IRawLineCollection Create(IEnumerable<string> lines)
    {
        ICollection<RawLine> lineGroup = new List<RawLine>();

        if (lines != null)
        {
            foreach (string line in lines)
            {
                lineGroup.Add(new RawLine(line));
            }
        }

        return new RawLineCollection(lineGroup);
    }
}

Edit :

The context is very close to the application entry point.
RawLine is an object representation of a line in a file that contain data settings for a game creation.

    public class RawLine
{
    private string value;

    public RawLine(string value)
    {
        this.value = value;
    }

    public IEnumerable<string> Split(string separator)
    {
        if (string.IsNullOrEmpty(separator))
        {
            throw new ArgumentException("The separator is required");
        }

        if (!string.IsNullOrEmpty(value))
        {
            return value
                .Replace(" ", "", StringComparison.CurrentCulture)
                .Split(separator)
                .Where(item => !string.IsNullOrEmpty(item));
        }

        return Array.Empty<string>();
    }
}

The behavior of this class is to split an actual representation of his state for the application-specific rules purpose while RawLineCollection is a collection of this entity type.

    public class RawLineCollection : IRawLineCollection
{
    private readonly IEnumerable<RawLine> lines;
    private readonly string separator = "-";

    public RawLineCollection(IEnumerable<RawLine> lines)
    {
        this.lines = lines;
    }

    public SplittedLineCollection Split()
    {
        ICollection<IEnumerable<string>> result = new List<IEnumerable<string>>();

        if (IsValidStringGroup(lines))
        {
            foreach (RawLine line in lines)
            {
                if (line.Split(separator).Any())
                {
                    result.Add(line.Split(separator));
                }
            }
        }

        return new SplittedLineCollection(result);
    }

    private bool IsValidStringGroup(IEnumerable<RawLine> settingsToSplit)
    {
        return settingsToSplit != null && settingsToSplit.Any();
    }
}

The RawLineCollectionFactory is used just one time like DataSource.GetLines() method.


texts: Having a class return a single database instance or list of all database instances

texts:
I'd like the following to happen:

var person = new Person(); // Create instance of new person with Id 0
var person1 = new Person(1); // Creates instance of existing person from database
var list = new Person().List(); // Creates instance of all persons from database

I'm sure there's a better way than what I'm currently doing:

using System.Collections.Generic;
using System.Data;

public class Person
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int GenderId { get; set; }

    public Person()
        : this(0)
    {
    }

    public Person(int id)
    {
        if (id == 0)
        {
            Id = id;
        }
        else
        {
            LoadFromDataBase(id);
        }
    }

    public List<Person> List()
    {
        return LoadFromDataBase(0);
    }

    private List<Person> LoadFromDataBase(int personId)
    {
        var dt = new DataTable();
        // Assume Data acquired from database using personId.
        // A Value of 0 returns all rows

        var list = new List<Person>();

        foreach (DataRow dr in dt.Rows)
        {
            var person = new Person();
            Id = person.Id = (int)dr["Id"];
            Name = person.Name = (string)dr["Name"];
            GenderId = person.GenderId = (int)dr["GenderId"];

            list.Add(person);
        }

        return list;
    }
}


texts:
I am trying to get an Auth ticket from a 3rd party server. I am using FutureTask to perform the task. However, if I don't get response from the server after 10 seconds, I want to timeout the call. At the same time, I want to kill the Thread which was busy in fetching the Auth Ticket from 3rd party, but got stuck because of some issue. Here is the simplified code.

public String getAuthTicket(final String userName) throws Exception{
    String authTicket=null;
    final FutureTask<String> future =
            new FutureTask<String>(new Callable<String>() {
                public String call() throws Exception {
                    log.info("calling server to get trusted ticket.");
                    if(Thread.interrupted()){
                        log.info("Call to server got interrupted.");
                        return "-1";
                    }
                    String authTicket = getTrustedTicket(userName);
                    return authTicket;
                }
            });

    final Thread thread = new Thread(future);
    thread.start();
    String authTicket ="-1";

    try {
        authTicket = future.get(10000, TimeUnit.MILLISECONDS);
        log.info("authTicket: "+ authTicket);
        return authTicket;
    } catch (Exception e){
        log.warning("Timeout occured while waiting to get auth ticket: Reason:"+ e);
        future.cancel(true);
    }

    return authTicket;
}

Could anyone please review my code?


texts:
I'm new to PDO and haven't been coding in a while. Is the following custom session handler industry-acceptable?

class Session {
    protected $sdb;

    function __construct() {
        session_set_save_handler(array($this, '_open'), array($this, '_close'), array($this, '_read'), array($this, '_write'), array($this, '_destroy'), array($this, '_clean'));
        register_shutdown_function('session_write_close');
    }

    function _open() {
        $this->sdb['conn'] = new PDO('mysql:host=' . DBHOST . ';dbname=' . DBNAME . ';charset=utf8', DBUSER, DBPASS);
        $this->sdb['conn']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        return TRUE;
    }

    function _close() {
        $this->sdb['conn'] = NULL;

        return TRUE;
    }

    function _read($sid) {
        try {
            $this->sdb['read']['query'] = $this->sdb['conn']->prepare('SELECT data FROM sessions WHERE sid = :sid LIMIT 1')) {
            $this->sdb['read']['query']->bindParam(':sid', $sid, PDO::PARAM_STR);
            $this->sdb['read']['query']->execute();
            $this->sdb['read']['result'] = $this->sdb['read']['query']->fetch(PDO::FETCH_ASSOC);
        }
        catch( PDOException $exception ) {
            var_export($exception);

            return FALSE;
        }

        $this->sdb['read']['query']->closeCursor();

        return $this->sdb['read']['result']['data'];
    }

    function _write($sid, $data) {
        try {
            $this->sdb['write']['query'] = $this->sdb['conn']->prepare('REPLACE INTO sessions VALUES (:sid, :time, :data)');

            $this->sdb['write']['query']->bindParam(':sid', $sid, PDO::PARAM_STR);
            $this->sdb['write']['query']->bindParam(':time', date('Y-m-d H:i:s'));
            $this->sdb['write']['query']->bindParam(':data', $data, PDO::PARAM_STR);
            $this->sdb['write']['query']->execute();
        }
        catch( PDOException $exception ) {
            var_export($exception);

            return FALSE;
        }

        $this->sdb['write']['query']->closeCursor();

        return TRUE;
    }

    function _destroy($sid) {
        try {
            $this->sdb['destroy']['query'] = $this->sdb['conn']->prepare('DELETE FROM sessions WHERE id = :sid');

            $this->sdb['destroy']['query']->bindParam(':sid', $sid, PDO::PARAM_STR);
            $this->sdb['destroy']['query']->execute();
        }
        catch( PDOException $exception ) {
            var_export($exception);

            return FALSE;
        }

        $this->sdb['destroy']['query']->closeCursor();

        return TRUE;
    }

    function _clean() {
        try {
            $this->sdb['clean']['query'] = $this->sdb['conn']->prepare('DELETE FROM sessions WHERE access < :stale');

            $this->sdb['clean']['query']->bindParam(':stale', date("Y-m-d H:i:s", strtotime("-30 minutes")));
            $this->sdb['clean']['query']->execute();
        }
        catch( PDOException $exception ) {
            var_export($exception);

            return FALSE;
        }

        $this->sdb['clean']['query']->closeCursor();

        return TRUE;
    }
}


texts: Find number of times a property has a truthy value in a nested object

texts:
I have a nested object and I would like to calculate the number of times the property 'error'. I am able to go n levels deep and find the count. Is there a better solution than mine?

const data = {
  "item1": {
    "value": 88,
    "error": false
  },
  "item2": {
    "value": 651,
    "error": false
  },
  "item3": false,
  "item4": [],
  "item5": "",
  "item6": "",
  "item7": false,
  "item8": {
    "error": true
  },
  "item9": {
    "value": [],
    "error": true
  },
  "item10": {
    "value": [],
    "error": true
  },
  "item11": {
    "value": [],
    "error": true
  },
  "item12": false,
  "item13": {
    "subItem1": {
      "name": "Country",
      "groups": {},
      "instances": [],
      "error": true
    },
    "subItem2": {
      "name": "Group",
      "groups": {},
      "instances": [],
      "error": true
    },
    "subItem3": {
      "name": "Product",
      "groups": {},
      "instances": [],
      "error": true
    }
  }
}

function traverseAndFlatten(currentNode, target, flattenedKey) {
  for (var key in currentNode) {
    if (currentNode.hasOwnProperty(key)) {
      var newKey;
      if (flattenedKey === undefined) {
        newKey = key;
      } else {
        newKey = flattenedKey + '.' + key;
      }

      var value = currentNode[key];
      if (typeof value === "object") {
        traverseAndFlatten(value, target, newKey);
      } else {
        target[newKey] = value;
      }
    }
  }
}

function flatten(obj) {
  var flattenedObject = {};
  traverseAndFlatten(obj, flattenedObject);
  return flattenedObject;
}

var flattened = flatten(data);

const keys = _.keys(flattened);

const errorCount = _.map(keys, key => {
  let count = 0;
  if (key.includes('.error') && flattened[key]) {
    count++
  }
  return count
})

console.log(_.sumBy(errorCount))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>


texts: Finding a vertex of a tree such that every subtree rooted at that vertex is of a uniform color

texts:
I'm trying to optimally solve codeforces problem 763A:

  Each New Year Timofey and his friends cut down a tree of n vertices
  and bring it home. After that they paint all the n its vertices, so
  that the i-th vertex gets color ci.

  Now it's time for Timofey birthday, and his mother asked him to remove
  the tree. Timofey removes the tree in the following way: he takes some
  vertex in hands, while all the other vertices move down so that the
  tree becomes rooted at the chosen vertex. After that Timofey brings
  the tree to a trash can.

  Timofey doesn't like it when many colors are mixing together. A
  subtree annoys him if there are vertices of different color in it.
  Timofey wants to find a vertex which he should take in hands so that
  there are no subtrees that annoy him. He doesn't consider the whole
  tree as a subtree since he can't see the color of the root vertex.

  A subtree of some vertex is a subgraph containing that vertex and all
  its descendants.

  Your task is to determine if there is a vertex, taking which in hands
  Timofey wouldn't be annoyed.

  Input
  The first line contains single integer n (2 ≤ n ≤ 10⁵) — the
  number of vertices in the tree.

  Each of the next n - 1 lines contains two integers u and v
  (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u
  and v. It is guaranteed that the given graph is a tree.

  The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 10⁵),
  denoting the colors of the vertices.

  Output
  Print "NO" in a single line, if Timofey can't take the tree in
  such a way that it doesn't annoy him.

  Otherwise print "YES" in the first line. In the second line print the
  index of the vertex which Timofey should take in hands. If there are
  multiple answers, print any of them.

I have come up with a solution that works but times out on large inputs.

from collections import defaultdict

n = int(input())
graph = defaultdict(list)
colors = defaultdict(lambda: -1)
for i in range(n-1):
    (u, v) = [int(i) for i in input().split()]
    graph[u].append(v)
    graph[v].append(u)

c = [int(i) for i in input().strip().split()]
colors = {i+1: v for (i, v) in enumerate(c)}
bad = set()

def start(start):
    nebs = graph[start]
    return all(dfs(n, set([start]), colors[n]) for n in nebs)

def dfs(start, visited, want):
    visited.add(start)
    if colors[start] != want:
        return False
    for neb in graph[start]:
        if neb not in visited:
            if not dfs(neb, visited, want):
                return False
    return True

found = False
ans = -1

for i in range(1, n+1):
    if start(i):
        found = True
        ans = i
        break
    else:
        bad.add(i)

if not found:
    print("NO")
else:
    print("YES")
    print(ans)

I'd love some guidance on how I can make this faster -- thank you!


texts:
My goal was to create a single-line function that produces a deep copy of a javascript object.

Requirements:

Executable on a single line without the use of semicolons (exception: last character of the line)
Nested objects should not be references to the originals

Function:

let copiedObjct = (copy = (obj) => (Object.keys(obj).reduce((v, d) => Object.assign(v, {[d]: (obj[d].constructor === Object) ? copy(obj[d]) : obj[d]}), {})))(obj);

Usage (expanded):

let obj = { /*...*/ }
let copiedObjct = (copy = (obj) => (
  Object.keys(obj).reduce((v, d) => Object.assign(v, {
    [d]: (obj[d].constructor === Object) ? copy(obj[d]) : obj[d]
  }), {})
))(obj);

My questions are:

Is this code efficient?
Are there any reasons this shouldn't be used in the wild?
Is there a way I can make it shorter?


texts:
This is my first attempt to draw using FLTK libraries *:

// Objective: Draw an 8-by-8, red and white checkers board

#include "std_lib_facilities.h"
#include <iostream>
#include "Simple_window.h"

int main(){
try{
    // create a window in the center of the screen wiht size: 600x600
    int wWidth = 660;
    int wHeight = 660;
    Point centerScreen(x_max()/2 - wWidth/2, y_max()/2 - wHeight/2);
    Simple_window sw(centerScreen, 660, 660, "Chapter 12 Exercise 3");

    // starting upper left coordinates of the window + 10 pixels frame
    int tlx = sw.x_max() - 650;
    int tly = sw.y_max() - 650;
    // Point topLeftCheckers(tlx, tly);

    // instantiate all the squares as rectangle objects with: heigth = width
    int numOfColumns = 8;
    int numOfRows = 8;

    // sqrSize == step of drawing
    int sqrSize = 80;

    // vector holding all (pointes to) rectangles
    vector<Graph_lib::Rectangle*> rects;
    int numOfSquares = numOfColumns *  numOfRows;
    rects.reserve(numOfSquares);

    for(size_t i=0; i < numOfColumns; ++i){
        for(size_t j=0; j < numOfRows; ++j){
            // create a 64 conjugate squares with size = 80,
            Graph_lib::Rectangle* r = new Graph_lib::Rectangle(Point(tlx + sqrSize*i, tly + sqrSize*j), sqrSize, sqrSize);
            // fill the consequtive squares with white or red color
            if ((i+j) % 2 == 0) r->set_fill_color(Color::red);
            else r->set_color(Color::white);
            // save object in vector
            rects.push_back(r);
        }
    }
    // attach all the rectangle objects to the window object
    for(size_t k=0; k < rects.size(); ++k) sw.attach(*rects[k]);

    sw.wait_for_button();

}catch(exception& e){
    cerr << e.what() << endl;
    getchar();

}catch(...){
    cerr <<"Default exception!"<< endl;
    getchar();
}
return 0;
}

Questions:

Are there any optimizations (or anything better) that can be done on the above code?
Any useful tips and practices that one should know in the early stages, when using GUI's packages like FLTK?

*as part of B. Stroustrup's "Principles and practice of C++".
All the needed files for compilation are here.
The FLTK could be found here


texts: Are nested foreach loops to compare two multidimensional arrays efficient in PHP?

texts:
I've got the following PHP code, which is taking a search term, and checking if any of the search terms could be or could have a nickname.

$search = $_GET['search-term'];
$indiviudal_terms = explode(" ",$search);
foreach($indiviudal_terms as $term) {
    foreach ($nicknames as $nameset) {//$nicknames is a multidimensional array that contains other arrays featuring sets of names, e.g. array("Abraham","Abe","Abie","Bram")
        foreach ($nameset as $variant_name) {
            if (strtolower($term) == strtolower($variant_name)) { //Checks to see if any of the search terms match any of the variant names in any of the sets of names.
                echo $nameset; //Just prints the set of names for the moment as I'm still writing to code.
            }
        }
    }
}

This works fine, but I worry that all these nested foreach loops may be inefficient. Is there a better way of achieving the same thing?


texts: Swap even and odd bits of unsigned 8-bit integer

texts:
The task:

  Given an unsigned 8-bit integer, swap its even and odd bits. The 1st
  and 2nd bit should be swapped, the 3rd and 4th bit should be swapped,
  and so on.

  For example, 10101010 should be 01010101. 11100010 should be 11010001.

  Bonus: Can you do this in one line?

My solutions:

// imperative:
function swap8BitInteger(bytes){
  let copiedBytes = '';
  for(let i = 0; i < bytes.length; i+=2) {
    copiedBytes+= `${bytes[i+1]}${bytes[i]}`;
  }
  return copiedBytes;
}

console.log(swap8BitInteger('11100010'));

// I don't know wether this qualifies as a one-liner
const swap8BitInteger2 = bytes => bytes.split('').reduce((acc, bit, idx) => {acc[idx % 2 === 0 ? idx + 1 : idx - 1] = bit;return acc;}, []).join('');

console.log(swap8BitInteger2('11100010'));

// Not sure wether this is still readable
const swap8BitInteger3 = bytes => bytes.split('').reduce((acc, _, idx) => idx % 2 ? acc : acc + bytes[idx + 1] + bytes[idx], '');

console.log(swap8BitInteger3('11100010'));

Would be interested to see an even shorter (and/or more readable) solution.


texts:
Here are two implementations I wrote to randomly shuffle cards.

The first method (shuffle) selects a random card, then swaps it to the front.
The second method (shuffle_v2) assumes that if i-1 cards are shuffled well, try to randomly swap card i with any card from 0 to i-1.

Are both methods are good to randomly (uniformly) shuffle cards?

Any ideas to improve time complexity, any code bugs or code style advice are also welcome.

import random
def shuffle(cards):
    write_index = 0 # to write,
    while write_index < len(cards):
        read_index = random.randint(write_index, len(cards)-1)
        cards[read_index], cards[write_index] = cards[write_index], cards[read_index]
        write_index += 1
def shuffle_v2(cards):
    for i in range(1, len(cards)):
        index = random.randint(0, i-1)
        cards[index], cards[i] = cards[i], cards[index]
if __name__ == "__main__":
    cards = []
    for i in range(10):
        cards.append(random.randint(1,52))
    print cards
    shuffle(cards)
    print cards
    shuffle_v2(cards)
    print cards


texts:
I haven't done any research into how you actually write a genetic algorithm, so this is my best guess. What I'm really curious to know is two-fold:

Have I created a genetic algorithm?
If I have, how can I continue to explore the subject more?

I hope this code and docstrings are enough explanation for how the code works.

from random import randint

import time

class Organism(object):

    def __init__(self, r=0, g=0, b=0):
        """Initialize the class with the RGB color values."""
        self.r = r
        self.g = g
        self.b = b

    @property
    def fitness(self):
        """The lower the fitness the better."""
        total = self.r + self.g + self.b
        return abs(765 - total)

    @classmethod
    def spawn(cls, parent):
        """Return a mutated generation of ten members."""
        generation = []
        for number in range(0, 10):
            r = cls.mutate(parent.r)
            g = cls.mutate(parent.g)
            b = cls.mutate(parent.b)
            generation.append(cls(r, g, b))
        return generation

    @staticmethod
    def mutate(value):
        """Mutate the value by 10 points in either direction."""
        min_, max_ = value - 10, value + 10
        return randint(min_, max_)

def breed_and_select_fittest(individual):
    """Return the fittest member of a generation."""
    generation = Organism.spawn(individual)
    fittest = generation[0]
    for member in generation:
        if member.fitness < fittest.fitness:
            fittest = member
    return fittest

if __name__ == '__main__':
    individual = Organism()  # abiogenesis!

    while True:
        individual = breed_and_select_fittest(individual)
        print individual.fitness

        time.sleep(0.2)