texts:
This is my very first Bash script that does something real. I'm here to learn, so please tell me if and how this can be done better.

#!/bin/sh

# Daniele Brugnara
# October - 2013

if [ -k $1 ]; then
        echo "Error! You must pass a repository name!"
        exit 1
fi

SVN_PATH="/var/lib/svn"
currPath=$(pwd)

cd $SVN_PATH
svnadmin create $1
chown -R www-data:www-data $1
cd $currPath

echo "Done! Remember to set valid user permission in authz file."


texts: Rotating color table object (for easy and consistent labeling)

texts:
I wanted to be able to consistently label an arbitrary number of objects on my site. It's pretty simple, but I if there's a more clever way...

// Usage:
// ColorTable.getColor('my link name');
ColorTable = {
  '_colors' : [
    '#F4BB2E',
    '#2DE656',
    '#66CCFF',
    '#6666FF',
    '#CC66FF',
    '#FF6FCF',
    '#FC4048'
   ],
  'tableSize' : function() { return this['_colors'].length; },
  'nextIndex' : function() {
    if (localStorage["ColorTable:_index"]===undefined) {
        localStorage["ColorTable:_index"] = -1;
    }
    rv = (parseInt(localStorage["ColorTable:_index"]) + 1) % this.tableSize();
    localStorage["ColorTable:_index"] = rv;
    return rv;
  },
  'getIndex' : function(key) {
    if (!localStorage["ColorTable:" + key]) {
      localStorage["ColorTable:" + key] = this.nextIndex();
    }
    return localStorage["ColorTable:" + key];
  },
  'setIndex' : function(key, index) {
    if (index >= 0 && index < this.tableLength()) {
      localStorage["ColorTable:" + key] = index;
      return localStorage["ColorTable:" + key];
    } else {
      return false;
    }
  },
  'getColor' : function(key) {
    return this['_colors'][this.getIndex(key)];
  }
};


texts: Project Euler #10 - sum of primes below two million

texts:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

  Find the sum of all the primes below two million.

public class Java {

public static void main(String[] args) {
    long start = System.nanoTime();

    long sum = 0;

    for (int i = 2; i < 2000000; i++) {
        boolean isPrime = true;

        if ((i % 2 == 0 || i % 3 == 0) && (i!=2 || i!=3 || i!=5)) {
            isPrime = false;
        } else {
            for (int j = 5; j <= Math.sqrt(i); j = j + 6) {
                if (i % j == 0 || i % (j + 2) == 0) {
                    isPrime = false;
                    break;
                }
            }
        }

        if (isPrime == true) {
            sum += i;
        }
    }

    System.out.println(sum);
    long end = System.nanoTime();
    System.out.println(end - start);
}

This is probably not efficient since i am using a lot of if-else statements and conditions.


texts:
I have created a "wrapper" for a button that "pulses" until the user presses the button.  The implementation that I came up with is below, but I'm sure there's a better approach.

<UserControl x:Class="Foundation.Common.Controls.Wpf.FoundationGlowButtonWrapper"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Template>
    <ControlTemplate TargetType="UserControl">
        <Border x:Name="AnimatedColorButton" BorderThickness="2" BorderBrush="Gold" Margin="-2,0,0,0">
            <Border.Triggers>
                <EventTrigger RoutedEvent="Border.Loaded">
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation Storyboard.TargetName="AnimatedColorButton"
                                                         Storyboard.TargetProperty="BorderBrush.Opacity"
                                                         RepeatBehavior="Forever"
                                                         AutoReverse="True"
                                                         To="0.0"
                                                         Duration="0:0:0.7" />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
                <EventTrigger RoutedEvent="Button.Click">
                    <BeginStoryboard>
                        <Storyboard>
                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush">
                                <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Brushes.Transparent}" />
                            </ObjectAnimationUsingKeyFrames>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Border.Triggers>
            <ContentPresenter Content="{TemplateBinding Content}" />
        </Border>
    </ControlTemplate>
</UserControl.Template>

XAML

 <wpf:FoundationGlowButtonWrapper>
      <telerik:RadButton />
 </wpf:FoundationGlowButtonWrapper>


texts:
I would really like to get some feedback on how you would improve my code's style, readability, and efficiency. I failed an interview recently and was unable to get any feedback so I thought I would try asking here. I have cleaned up the code a bit already based on advice from friends but would like to have more critical eyes take a look.

My task was to write a function that takes a matrix of 1's and 0's and returns a resulting matrix after one iteration of Conway's Game of Life.

Note: Since the goal was to only return 1 iteration, I was told to not create cell objects and hold references to neighbors. There is not a need to set this up because we only want to run 1 iteration and doing so would waste space.

I would like advice on what you would change in terms of the function organization and how I decided to break down the problem. Specifically, it feels a little awkward how I have to pass the matrix all the way down to the isInBounds function. Is there a way to avoid this?

This or any other readability/optimization advice would be greatly appreciated.

function oneIterationConway(matrix) {
  const height = matrix.length;
  const width = matrix[0].length;
  const resultMatrix = [];

  for (let row = 0; row < height; row++) {
    resultMatrix[row] = [];
    for (let col = 0; col < width; col++) {
      const neighborCount = countNeighbors(row, col, matrix);
      let isAlive = 0;
      if (matrix[row][col]) {
        // current cell is alive
        isAlive = neighborCount > 1 && neighborCount < 4 ? 1 : 0;
      } else {
        // current cell is dead
        isAlive = neighborCount === 3 ? 1 : 0;
      }

      resultMatrix[row][col] = isAlive;
    }
  }

  return resultMatrix;
}

function countNeighbors(row, col, matrix) {
  let neighbors = 0;

  for (let i = -1; i <= 1; i++) {
    for (let j = -1; j <= 1; j++) {
      if (i === 0 && j === 0) continue;
      if (isInBounds(row + i, col + j, matrix) && matrix[row + i][col + j]) {
        neighbors++;
      }
    }
  }

  return neighbors;
}

function isInBounds(row, col, matrix) {
  const height = matrix.length;
  const width = matrix[0].length;
  return row >= 0 && col >= 0 && row < height && col < width;
}

const testMatrix = [
  [1, 0, 0, 0, 0],
  [0, 1, 1, 0, 0],
  [0, 1, 0, 0, 0]
];

const result = oneIterationConway(testMatrix);

for (let row of result) {
  console.log(row);
}


texts:
I'm new when it comes to Java and programming in general, but I feel I have a decent grasp on a lot of the fundamentals.

I've created this "random planet generator" that is virtually useless aside from minimal entertainment, but I've created it to help solidify what I've been learning. I'm not asking for code, but for a direction with as much info as possible.

My random planet generator lists:

name:
temp:
size (circumference):
Density:
Length of Day:
Number of Moons:
Gravity:
If planet has rings:

My problem is, that for the name, it is horribly inefficient. Before I added the name field, I could generate millions of random planets in seconds. Now, I only set it to 50,000 planets and it still takes a minute or two to generate them all.

Here's the method I use to name the planets:

public void setName() throws FileNotFoundException {
    String prefix = "";
    String greek = "";
    int number;
    char suffix;
    Random rand = new Random();

    // randomly pull from list of star names
    int randName = rand.nextInt(300);
    File prefixFile = new File("StarNames.txt");
    Scanner inputFilePrefix = new Scanner(prefixFile);
    for (int i = 0; i <= randName; i++) {
        prefix = inputFilePrefix.nextLine();
    }
    inputFilePrefix.close();

    // randomly pull of list of Greek names
    int randGreek = rand.nextInt(11);
    File greekFile = new File("Greek.txt");
    Scanner inputFileGreek = new Scanner(greekFile);
    for (int i = 0; i <= randGreek; i++) {
        greek = inputFileGreek.nextLine();
    }
    inputFileGreek.close();

    // random number
    int randNum = rand.nextInt(1000);
    number = randNum;

    // random letter
    int randLetter = rand.nextInt(4);
    if (randLetter == 0) {
        suffix = 'a';
    } else if (randLetter == 1) {
        suffix = 'b';
    } else if (randLetter == 2) {
        suffix = 'c';
    } else {
        suffix = 'd';
    }

    // append to class name
    this.name = prefix + " " + greek + "-" + number + "" + suffix;

}

As you can tell, I have 2 text files. One for actual star names, and another for (what I think is) the Greek alphabet. It randomly picks a line to read up to and uses that name.
What could be a faster, more efficient way of doing this?

The name structure would essentially be something like:

 Name: Gemini ALPHA-229c

I have every planet generated added to an ArrayList one by one after all planets fields are created.

Any suggestions?


texts:
I am new in NodeJS and I try to write code based on tutorials I find online. I have a NodeJS app (based on Strapi) and an external API from a Cloud Servers provider. The process I follow is as:

Call the cloud servers provider to authorise and get an access token

Call the Strapi to get the list of servers I have added as content type

For each server, call the cloud server provider to get a list of apps and their disk usage in the server

Iterate in the results and call the Strapi again to update the data fields in another content type called subscriptions.
async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array);
  }
}

const waitFor = (ms) => new Promise(r => setTimeout(r, ms));

await axios.post('https://api.cloudways.com/api/v1/oauth/access_token?email=' + process.env.CLOUDWAYS_EMAIL + '&api_key=' + process.env.CLOUDWAYS_API)
.then((res) => {
  //get access token for cloudways authorization
  const accessToken = res.data.access_token;
  //get all servers from strapi
  strapi.query('server').find({})
    .then((res2) => {
      //call cloudways for each server
      asyncForEach(res2, async (sub) => {
          await axios.get('https://api.cloudways.com/api/v1/server/monitor/summary?server_id=' + sub.ServerID + '&type=db', {
            headers: {
              Authorization: 'Bearer ' + accessToken,
            },
          }).then((res3) => {
            //update subscription disk usage in strapi
            asyncForEach(res3.data.content, async (app) => {
              if ( app.datapoint ) {
                strapi.query('subscription').update({ ApplicationSlug: app.name }, { DiskUsage: Math.ceil(app.datapoint[0]) });
              }
            });
          }).catch((res3) => {
            console.log(res3.response.data);
          });
      });

    });
});

The waitFor is a helper function to wait for X seconds, since Cloud Server provider has a limitation in how many calls you can do per minute. But I wasn't able to integrate it well in my code.


texts: Chess Dictionary Validator (Python) (Automate The Boring Stuff)

texts:
This is an exercise in the Automate The Boring Stuff book. I am supposed to create a function  that takes a dictionary argument that represents a chess board (ex: {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', etc.}) and returns True or False depending on if the board is valid.
A valid board will have (A) exactly one black king and exactly one white king. (B) Each player can only have at most 16 pieces, (C) at most 8 pawns, and (D) all pieces must be on a valid space from '1a' to '8h'; that is, a piece can’t be on space '9z'. (E) The piece names begin with either a 'w' or 'b' to represent white or black, followed by 'pawn', 'knight', 'bishop', 'rook', 'queen', or 'king'. This function should detect when a bug has resulted in an improper chess board.
#Example dictionary of coordinates (keys) and pieces (values)
#my_board = {"1a":"wking", "2a":"bking", "8b":"wpawn", "3a":"wpawn"}

def isValidChessBoard(board):
    #Creating a dictionary of pieces (keys) and the number of pieces (values)
    num_pieces = {}
    list_pieces = ["bpawn", "bking", "bqueen", "brook", "bbishop", "bknight", "wpawn", "wking", "wqueen", "wrook", "wbishop", "wknight"]
    for v in board.values():
        num_pieces.setdefault(v, 0)
        num_pieces[v] = num_pieces[v] + 1
    for i in list_pieces:
        if i not in num_pieces:
            num_pieces.setdefault(i, 0)
    #Making sure there is exactly one king on each side
    if (num_pieces["wking"] != 1) or (num_pieces["bking"] != 1):
        return False
    #Making sure there are no more than 8 pawns on each side
    if ("bpawn" or "wpawn" in num_pieces) and (num_pieces["bpawn"] or num_pieces["wpawn"]) > 8:
        return False
    #Making sure every piece is apprpriately named (b/w + king/queen/rook/pawn/knight/bishop)
    for j in num_pieces:
        if j not in list_pieces:
            return False
    #Making sure there are no more than 16 pieces on each side
    if num_pieces["bpawn"] + num_pieces["bking"]  + num_pieces["bqueen"] +  num_pieces["brook"] +  num_pieces["bbishop"]  + num_pieces["bknight"] > 16:
        return False
    if num_pieces["wpawn"] + num_pieces["wking"]  + num_pieces["wqueen"] +  num_pieces["wrook"] +  num_pieces["wbishop"]  + num_pieces["wknight"] > 16:
        return False
    #Making sure that the board coordinates are all between (a-h, and 1-8)
    in_range = 0
    possible_coordinates = []
    for i in range(1, 9):
        for j in ["a", "b", "c", "d", "e", "f", "g", "h"]:
            possible_coordinates.append(str(i)+str(j))
    for k in board.keys():
        if k in possible_coordinates:
            in_range = in_range + 1
    if len(board) != in_range:
        return False
    return True

if isValidChessBoard(my_board) == True:
    print("Valid Board")
else:
    print("Invalid Board")

I know that the code works, but I was wondering if there were any faux-pas that I am implementing, or if there is anything I could obviously do to make it cleaner. Thanks!


texts:
How can I improve the performance of this method or is it already good?

private static void LoadAssembliesWithInjectorModule(IEnumerable<FileInfo> files)
{
    var moduleType = typeof (InjectorModule);

    foreach (var file in files)
    {
        try
        {
            var assembly = Assembly.LoadFrom(file.FullName);

            var moduleTypes = from assemblyType in assembly.GetTypes()
                              where moduleType.IsAssignableFrom(assemblyType) && !assemblyType.IsAbstract
                              select assemblyType;

            if (!moduleTypes.Any()) continue;

            foreach (var instance in moduleTypes.Select(type => Activator.CreateInstance(type) as InjectorModule))
            {
                instance.Load();
            }
        }
        catch (BadImageFormatException)
        {
            //Files that aren't class libraries will throw this exception, just eat it and move on.
        }
        catch (ReflectionTypeLoadException e)
        {
            throw new AppDomainUnloadedException(string.Format("Error loading {0} exception {1} loading errors {2}", file.FullName, e.Message, e.LoaderExceptions), e);
        }
    }
}


texts:
This is a simple program to convert a number, from 0 up to 99999999, to English words.

Example:

If the input is:

1234

The output would be:

  one thousand two hundred thirty four

I would like to get feedback regarding this small program.

#include <iostream>
#include <vector>
#include <string>

const std::vector<std::string> words[] =
{
    {
        "",
        "one",
        "two",
        "three",
        "four",
        "five",
        "six",
        "seven",
        "eight",
        "nine",
        "ten",
        "eleven",
        "twelve",
        "thirteen",
        "fourteen",
        "fifteen",
        "sixteen",
        "seventeen",
        "eighteen",
        "nineteen"
    },
    {
         "-",
         "-",
         "twenty -",
         "thirty -",
         "forty -",
         "fifty -",
         "sixty -",
         "seventy -",
         "eighty -",
         "ninety -"
    },
    {
         "million",
         "hundred",
         "thousand",
         "hundred",
         ""
    },
};

class NumberConvertor
{
public:
    NumberConvertor(std::size_t number);

    friend std::ostream& operator<< (std::ostream& out, const NumberConvertor& nc);

private:
    void convert(std::size_t unit, const std::string& units);

    std::size_t mNumber;
    std::string mResult;
    std::size_t mIterator;
    std::size_t mSwap;
};

NumberConvertor::NumberConvertor(std::size_t number)
    : mNumber(number), mIterator(0), mSwap(0)
{
    if (mNumber == 0)
    {
        mResult = "zero";
    }
    else
    {
        convert( 1000000,  words[2][0]);
    }
}

void NumberConvertor::convert(std::size_t unit, const std::string& units)
{
    std::size_t index = mNumber / (unit * 10);
    std::size_t sub   = (index > 1 ? index * unit * 10 : 0);

    std::string word = words[1][index];

    if (word[word.size() - 1] == '-')
    {
        word.erase(word.size() - 1);
        index   = (mNumber-sub) / unit;
        word.append(words[0][index]);
    }

    if (word != "")
    {
        std::size_t x = mNumber / 1000;

        switch(x)
        {
            case 100:
            case 200:
            case 300:
            case 400:
            case 500:
            case 600:
            case 700:
            case 800:
            case 900:
            {
                mResult.append( word + ' ' + units + ' ' + words[2][mIterator + 1] + ' ');
                break;
            }
            default:
            {
                mResult.append( word + ' ' + units + ' ');
            }
        };
    }

    mNumber -= mNumber / unit * unit;

    if( ++mIterator < words[2].size())
    {
        mSwap ^= 1;

        if(unit == 1)
        {
            convert( 1, words[2][0]);
        }

        convert( unit / (mSwap == 0 ? 100 : 10), words[2][mIterator]);
    }
}

std::ostream& operator<< (std::ostream& out, const NumberConvertor& nc)
{
    return out << nc.mResult;
}

int readInput(const std::string& prompt)
{
    int answer;
    while((std::cout << prompt) && (!(std::cin >> answer) || answer < 0 || answer > 99999999))
    {
        std::cout << "Enter a positive number between 0 - 99999999\n";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    return answer;
}

int main()
{
    while(1) // (ctrl c) to exit
    {
        std::cout << NumberConvertor(readInput("Enter the number: ")) << '\n';
    }
}


texts: Parsing error messages using regular expressions in Java 8

texts:
I have a below method in Java 8 which checks for message pattern and finds the line number from the message.

 private LawfirmInvoice getInvoiceForErrormessage(InvoiceParcel parcel, String message) {
    if (parcel.getInvoices() != null) {
        if (parcel.getInvoices().size() == 1)
            return parcel.getInvoices().get(0);
        else {
            String regex1 = "^Line\\s+\\:\\s+\\d.+";
            String regex2 = "^Line\\s\\d\\s\\:\\s+.+";
            Pattern p = Pattern.compile("\\d+");
            Matcher m;
            int lineNumber = -1;
            if (message.matches(regex1)) {
                m = p.matcher(message);
                if (m.find()) {
                    lineNumber = Integer.parseInt(m.group());
                } else if (message.matches(regex2)) {
                    m = p.matcher(message);
                    if (m.find()) {
                        lineNumber = Integer.parseInt(m.group()) - 2;
                    }
                }

            }
            if (lineNumber != -1)
                return parcel.getInvoices().get(lineNumber);
        }

    }
    return null;
}

Example : message can be of below types
msg1 = "Line : 1 Invoice does not foot Reported"
msg2 = "Line 3 : Could not parse ADJUSTMENT_AMOUNT value"

The above method finds the line number from the message and returns the instance of invoice from the arraylist.

Since Java 8 has some new features am wondering whether my code can be optimized further.


texts:
Please take a look at my code below and tell me if I'm doing the right thing here. My wishes:

Username

The username must be at least 6 characters long
The username can't contain any special symbols

Password:

The password must be at least 8 characters
The password must contain at least 1 upper- and lowercase letter
The password must contain at least 1 number
The password can't contain any special symbols

As you can see I am also using a hash function for the password. It is supposed to be hashed like this for the purpose I'm using it for. Does this affect my code at all?

//password hash function
function l2j_hash($password) {
    return base64_encode(pack("H*", sha1(utf8_encode($password))));
}

$pass = mysqli_real_escape_string($db_link, $_POST['password']);
$repass = mysqli_real_escape_string($db_link, $_POST['repeat_password']);
$user = mysqli_real_escape_string($db_link, $_POST['name']);

$uppercase = preg_match('@[A-Z]@', $pass);
$lowercase = preg_match('@[a-z]@', $pass);
$number    = preg_match('@[0-9]@', $pass);

if(!$uppercase || !$lowercase || !$number || !ctype_alnum($password) || strlen($password) < 8) {

    echo "The password must contain at least 1 lowercase letter, 1 uppercase letter and 1 number.";
    echo "The password can't contain special symbols.";

} else if ($pass != $repass) {
    echo "Passwords do not match";
} else if ($user == '' && strlen($user) < 6 && !ctype_alnum($user)) {
    echo "The User ID must be at least 6 characters long and can't contain special symbols.";
} else {
    $pass_hash =  l2j_hash($pass);
    $db_add = mysqli_query( "INSERT INTO `accounts` VALUES ('$user', '$pass_hash', '0', '0', '')" ) or die( 'Error: '.mysqli_error() );
    echo 'Account created';
}


texts: Returning all possible English dictionary words that can be formed out of a string

texts:
I am using an external library named enchant here. My problem is that I guess my program is not returning all possible English words and is slow as well for large string input.

I am using both en_US and en_UK here:

import enchant
import itertools
uk = enchant.Dict("en_UK")
us=enchant.Dict("en_US")
a=[] # stores all possible string combinations
ent=input('enter the word: ')
ent=ent.rstrip('\r\n')
i=3 # minimum length of words
while i<=len(ent):
  it=itertools.permutations(ent,i)
  for y in it:
    a.append("".join(y))
  i+=1
a.sort(key=len,reverse=True)
possible_words=[]
for x in a:
  if uk.check(x) and x not in possible_words :
    possible_words.append(x)

for x in a :
  if us.check(x) and x not in possible_words:
    possible_words.append(x)

possible_words.sort(key=len,reverse=True)
for x in possible_words:
  print(x)

Example :

enter the word: wsadfgh
wash
wads
wags
swag
shag
dash
fads
fags
gash
gads
haws
hags
shaw
shad
was
wad
wag
saw
sad
sag
ash
ads
fwd
fas
fad
fag
gas
gad
haw
has
had
hag


texts: Pattern matching and fmt::Display on recursive Rc in Rust

texts:
This works, and does what I want, but it feels ugly and clunky to me. How can I make it better?

It's just constructing a basic Lisp-style list and pretty-printing it.

// simple example of pattern matching on Rc<enum>

use std::rc::Rc;
use std::fmt;

type Cell = Rc<RawCell>;

#[derive(Debug, Clone)]
enum RawCell { Nil, Item(i32), Cons(Cell, Cell) }
use RawCell::*;

fn cell(x:RawCell)->Cell { Cell::new(x) }
fn item(x:i32)-> Cell { cell(Item(x)) }
fn cons(a:Cell, b:Cell)-> Cell { cell(Cons(a,b)) }

impl fmt::Display for RawCell {
  fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result {

    // !! is there any way to get rid of these & in the
    match self {

      &Nil => write!(f, "()"),                              // should only happen if we directly display nil.

      &Item(x) => write!(f, "{}", x),                       // single item. easy.

      &Cons(ref x, ref y) => {                              // walk through and display the entire list:

        // always show '(x'
        write!(f, "({}", x).unwrap();                       // !! how to detect and propagate the errors correctly?

        // intermediate values are space-separated:
        let mut tail = y;
        while let &Cons(ref h, ref t) = tail.as_ref() {
          write!(f, " {}", h).unwrap();                     // !!same question.
          tail = t
        }

        // final value at end of list is either ')' (normal list) or '. y)' for "dotted pair"
        match tail.as_ref() {
          &Nil => write!(f, ")"),
          &Item(n) => write!(f, ". {})", n),

                                                            // !! not sure how i'm supposed to handle errors here:
          xxx => { eprintln!("got to end of list and found something weird: {:?}", xxx); Err(fmt::Error) }
        }
      }
    }
  }
}

fn main() {
  let nil = cell(Nil);
  let ls1 = cons(item(1), cons(item(2), nil.clone()));
  let ls2 = cons(item(3), nil.clone());
  println!("refcount for nil (before): {}", Rc::strong_count(&nil));
  let pretty = format!("{}", cons(ls1.clone(), cons(ls1, ls2)));
  assert_eq!("((1 2) (1 2) 3)", pretty);
  println!("refcount for nil (after): {}", Rc::strong_count(&nil));
}


texts: OpenGL forward-compatible context creation on Windows

texts:
Is this the proper method for creating an OpenGL 3.3+ forward-compatible context?

// Create window
WNDCLASSEX wc;
ZeroMemory( &wc, sizeof( wc ) );
wc.cbSize = sizeof( wc );
wc.lpfnWndProc = _eventHandler;
wc.hInstance = GetModuleHandle( NULL );
wc.hIcon = LoadIcon( NULL, IDI_APPLICATION );
wc.hIconSm = LoadIcon( NULL, IDI_APPLICATION );
wc.hCursor  = LoadCursor( NULL, IDC_ARROW );
wc.lpszClassName = "OpenGL 3.3";
if ( !RegisterClassEx( &wc ) ) Error( "Failed to register window class!" );
if ( !( _window = CreateWindowEx( WS_EX_CLIENTEDGE, "OpenGL 3.3", "OpenGL 3.3", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 800, 600, NULL, NULL, GetModuleHandle( NULL ), NULL ) ) )
    Error( "Failed to create the window!" );
if ( !( _hdc = GetDC( _window ) ) ) Error( "Failed to retrieve device context!" );

// Choose pixel format
int pixelFormat;
PIXELFORMATDESCRIPTOR pfd;
ZeroMemory( &pfd, sizeof( pfd ) );
pfd.nSize = sizeof( pfd );
pfd.nVersion = 1;
pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
if ( !( pixelFormat = ChoosePixelFormat( _hdc, &pfd ) ) ) Error( "Failed to find suitable pixel format!" );
if ( !SetPixelFormat( _hdc, pixelFormat, &pfd ) ) Error( "Failed to set pixel format!" );

// Create temporary context and make sure we have support
HGLRC tempContext = wglCreateContext( _hdc );
if ( !tempContext ) Error( "Failed to create temporary context!" );
if ( !wglMakeCurrent( _hdc, tempContext ) ) Error( "Failed to activate temporary context!" );

int major, minor; glGetIntegerv( GL_MAJOR_VERSION, &major ); glGetIntegerv( GL_MINOR_VERSION, &minor );
if ( major < 3 || minor < 2 ) Error( "OpenGL 3.2 is not supported!" );

// Create forward compatible context
int attribs[] =
{
    WGL_CONTEXT_MAJOR_VERSION_ARB, major,
    WGL_CONTEXT_MINOR_VERSION_ARB, minor,
    WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
    WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
    0
};
PFNWGLCREATEBUFFERREGIONARBPROC wglCreateContextAttribsARB = (PFNWGLCREATEBUFFERREGIONARBPROC)wglGetProcAddress( "wglCreateContextAttribsARB" );
if ( !wglCreateContextAttribsARB ) Error( "Failed to find pointer to wglCreateContextAttribsARB function!" );
if ( !( _context = wglCreateContextAttribsARB( _hdc, 0, (UINT)attribs ) ) ) Error( "Failed to create forward compatible context!" );

// Remove temporary context and activate forward compatible context
wglMakeCurrent( NULL, NULL );
wglDeleteContext( tempContext );
if ( !wglMakeCurrent( _hdc, (HGLRC)_context ) ) Error( "Failed to activate forward compatible context!" );

// Show window
ShowWindow( _window, SW_SHOW );
UpdateWindow( _window );

It seems to work (gives GL_INVALID_OPERATION when using glBegin), but I just want to make sure this is the right way to go about it.


texts:
I am just wondering if my code can still be simplified. I intend to make it reusable in all update statements.

Public Sub updateRecord(ByRef procedure As String, ByRef parameters As String, ByRef obj As String, ByRef LastName As String, ByRef FirstName As String, ByRef MiddleInitial As String, ByRef Age As String, ByRef Address As String)
Dim CS As String = ConfigurationManager.ConnectionStrings("DBCS").ConnectionString
Try
    Using con As New SqlConnection(CS)
        Dim cmd As SqlCommand = New SqlCommand(procedure, con)
        cmd.CommandType = System.Data.CommandType.StoredProcedure
        cmd.Parameters.AddWithValue(parameters, obj)
        cmd.Parameters.AddWithValue("@LastName", LastName)
        cmd.Parameters.AddWithValue("@FirstName", FirstName)
        cmd.Parameters.AddWithValue("@MiddleInitial", MiddleInitial)
        cmd.Parameters.AddWithValue("@Age", Age)
        cmd.Parameters.AddWithValue("@Address", Address)
        cmd.Connection = con
        con.Open()
        Dim TotalRows As Int32 = cmd.ExecuteNonQuery()
    End Using
Catch ex As Exception
    MessageBox.Show(ex.ToString, "Annual Procurement Plan", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End Sub


texts: Matrix struct with random values allocation and deallocation

texts:
I've written this code in 2013 or 2014, I think. I've rediscovered it today in one of my folders, made some changes and now I'm left (and my 2013/2014 me as well) wondering how good it looks for other C programmers.

It's a simple dummy program that reads N and M from stdin, then creates a matrix with those values as rows and columns with dynamic memory allocation, prints them, and then frees the memory. A rollback is made if malloc fails.

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

#define ERROR -1
#define SUCCESS 0

char welcome[] = "\tThis program \
    gets the size of a matrix from stdin, messes around \
    with it and then frees it.\n";

struct Matrix
{
    int N;
    int M;
    int **values;
};

/**
* allocates memory for the matrix
*/
int allocateMatrix(struct Matrix *matrix, int n, int m)
{
    printf("Allocating memory for matrix... (%d x %d)\n", n, m);
    int i, j;

    /* allocate rows */
    matrix->values = malloc(n * sizeof(int*));

    if (detectError(matrix->values)) {
        return ERROR;
    }

    /* allocate columns */
    for(i = 0; i < matrix->N; i++)
    {
        matrix->values[i] = malloc(m * sizeof(int));
        /* handles errors */
        if (detectError(matrix->values[i])) {
              /* frees already allocated memory */
            j = i-1;
            for(; j >= 0; j--)
            {
                free(matrix->values[i]);
            }
            free(matrix->values);
            return ERROR;
        }
    }
    printf("%lu bytes of memory allocated! \n", (n * m * sizeof(int)));
}

/**
* gets the properties of the matrix
*/
int getMatrixProps(struct Matrix *matrix)
{
    int n, m;
    printf("\nWhat will be the size of our matrix? (N x M)\n");
    scanf("%d %d", &n, &m);
    matrix->N = n;
    matrix->M = m;
    return allocateMatrix(&(*matrix), n, m);
}

/**
* frees the memory requested
*/
void freeMatrixMem(struct Matrix *myMatrix)
{
    int i;
    for(i = 0; i < myMatrix->N; i++)
    {
        free(myMatrix->values[i]);
    }
    free(myMatrix->values);
}

/**
* populates and prints the matrix
*/
void dummyHandleMatrix(struct Matrix *myMatrix)
{
    srand(time(NULL)); /* seeds random function */
    int n, m;
    printf("Populating matrix with random data... ");
    for(n = 0; n < myMatrix->N; n++)
    {
        for(m = 0; m < myMatrix->M; m++)
        {
            int value = rand() % 50;
            printf("%d ", value);
            myMatrix->values[n][m] = value;
        }
    }
    printf("\n");
    printf("Matrix populated. Values are:\n[");
    for(n = 0; n < myMatrix->N; n++)
    {
        for(m = 0; m < myMatrix->M; m++)
        {
            printf("%d, ", myMatrix->values[n][m]);
        }
        printf("\n");
    }
    printf("]\n");
}

int detectError(void *ptr) {
     if (ptr == NULL)
    {
            printf("operation failed\n");
            printf("%s\n", strerror(errno));
            return ERROR;
    }
    return SUCCESS;
}

int main(int argc, char *argv[])
{
    printf("%s", welcome);
    struct Matrix myMatrix;

    /* get size of the matrix and allocate memory for it */
    if (getMatrixProps(&myMatrix) == ERROR) {
        return ERROR;
    }

    /* populates it with random data and print to the screen */
    dummyHandleMatrix(&myMatrix);

    /* frees allocated memory */
    printf("Freeing matrix memory!\n");
    freeMatrixMem(&myMatrix);
    printf("Memory freed.\n");
}


texts: Sequential Thread Execution using wait() and notifyAll()

texts:
Problem Statement:

  T1, T2 to Tn threads prints numbers up to N such that each threads
  prints number in circular sequential fashion. T1 prints 1, T2 prints
  2, T3 prints 3 and T1 prints 4 again following strict ordering. This
  implementation would allow us to control any number of threads to do
  sequential ordered execution. It uses wait() and notifyAll() methods
  to signal threads. I am using HashMap to store sequence I would like
  to achieve and this can allow me to add N threads as long as I can
  control turns for each threads.

Please suggest any improvements.

class SignalThread implements Runnable {

    volatile Integer i = 1;

    volatile String turn = "1";

    Map<String, String> sequence = new HashMap<String, String>();

    WaitNotifySignal waitNotifySignal;

    public SignalThread(WaitNotifySignal waitNotifySignal) {
        this.waitNotifySignal = waitNotifySignal;
    }

    @Override
    public void run() {
        while (i.intValue() <= 10) {
            if (Thread.currentThread().getName().equalsIgnoreCase(turn)) {
                System.out.println("Thread: "
                        + Thread.currentThread().getName() + " --- " + i);
                i++;
                turn = getNextTurn(turn);
                waitNotifySignal.doNotifyAll();
                waitNotifySignal.doWait();
            }
        }
    }

    public void setTurnSequence(Map<String, String> sequence) {
        this.sequence = sequence;
    }

    private String getNextTurn(String currentTurn) {
        return sequence.get(currentTurn);
    }
}

And:

/**
 * Common Wait Notify Signal class
 *
 * @author manishdevraj
 *
 */

 class WaitNotifySignal {

    Object monitorObject = new Object();

    boolean wasSignalled = false;

    public void doWait() {
        synchronized (monitorObject) {
            while (!wasSignalled) {
                try {
                    monitorObject.wait();
                } catch (InterruptedException e) {
                }
            }
            // clear signal and continue running.
            wasSignalled = false;
        }
    }

    public void doNotifyAll() {
        synchronized (monitorObject) {
            wasSignalled = true;
            monitorObject.notify();
        }
    }
}

public class LinearCircularSignalT {

    public static void main(String[] args) {

        SignalThread signalThread = new SignalThread(new WaitNotifySignal());
        Thread t1 = new Thread(signalThread);
        t1.setName("1");
        Thread t2 = new Thread(signalThread);
        t2.setName("2");
        Thread t3 = new Thread(signalThread);
        t3.setName("3");
        Map<String, String> sequence = new HashMap<String, String>();
        sequence.put("1", "2");
        sequence.put("2", "3");
        sequence.put("3", "1");
        signalThread.setTurnSequence(sequence);
        t1.start();
        t2.start();
        t3.start();

    }
}


texts:
A Binary Tree Sort is an algorithm that builds a binary search tree from the elements to be sorted, and then traverses the tree (in-order) so that the elements come out in sorted order.

Average Case Time Complexity : O(N log N) adding one element to a Binary Search Tree on average takes O(log N) time (height of a tree). Therefore, adding n elements will take O(N log N) time.

Worst Case Time Complexity : O(N^2). The worst case can be improved by using a self-balancing binary search tree, which will take O(N log N) time to sort the array in worst case.

Just for practicing, I've implemented the Binary Tree Sort algorithm, and if you'd like to review the code and provide any change/improvement recommendations, please do so, and I appreciate that.

Code

"""
This module creates a Binary Sort Tree ascendingly using In Order Tree Traverse;
Stable Sort;
Worst Case Time Complexity (For if the tree would be a chain Tree): O(N^2)
Average Case Time Complexity: O(N^Log N)
Memory Complexity: Not in place O(N)
"""

import random
from typing import List, TypeVar

T = TypeVar('T')

# Not sure how to design and handle the exceptions here yet
class ExceptionHandling(Exception):
    pass

class Node(object):
    def __init__(self, node_value: int) -> None:
        """
        Initializes a node with three attributes;
        `node_value` (Node Value): Must be an integer/float;
        `right_child` (Right Child): Initializes to `None`; Its value must be larger than the Root Node;
        `left_child` (Left Child): Initializes to `None`; Its value must be smaller than the Root Node;
        """
        self.node_value = node_value
        self.right_child = None
        self.left_child = None

class BinarySearchTree(object):
    def __init__(self) -> None:
        """
        Initializes the Root Node of the Binary Tree to None;
        """
        self.root = None

    def is_empty(self) -> bool:
        """
        Returns True if the tree doesn't have a node;
        """
        return self.root == None

    def insert(self, new_node: int) -> None:
        """
        Inserts an integer-value Node in the Tree;
        """
        self.root = self._insert(self.root, new_node)

    def _insert(self, parent: int, new_node: int) -> int:
        """
        Inserts an integer value in the left or right Node;
        Returns the parent Node;
        """
        # If tree is empty
        if parent is None:
            parent = Node(new_node)
        # If the new Node value is smaller than its parent Node value
        elif new_node < parent.node_value:
            parent.left_child = self._insert(parent.left_child, new_node)
        # If the new Node value is bigger than its parent Node value
        else:
            parent.right_child = self._insert(parent.right_child, new_node)

        return parent

    def inorder(self) -> None:
        """
        Calls the _inorder traversing method;
        """
        self._inorder(self.root)

    def _inorder(self, parent: int) -> None:
        """
        Traverses the tree inorder (Left Node, Root Node, Right Node)
        """
        if parent is None:
            return
        self._inorder(parent.left_child)
        print(f'{parent.node_value}')
        self._inorder(parent.right_child)

if __name__ == '__main__':

    tree = BinarySearchTree()

    for i in range(random.randint(20, 30)):
        tree.insert(random.uniform(-10, 10))

    tree.inorder()

Sources

Tree Sort - Wiki
Tree Sort - Geeks for Geeks


texts: Pattern match on type in Clojure spec conformer

texts:
I am using Clojure spec to conform (coerce) a 1 or 2 value of a number type or string into a 1, 2 or :clojure.spec/invalid.

(require [[clojure.spec :as s]
          [clojure.core.match :as m]])

(defn parse-number [n]
  "Parses a string or number in a safe way."
  (m/match [n]
    [_ :guard number?] n
    [_] (Integer/parseInt (re-find #"\A\d+" n))))

(defn one-or-two? [n]
  (try
    (let [parsed-n (parse-number n)]
      (m/match [parsed-n]
        [1] 1
        [2] 2
        [_] :clojure.spec/invalid))
    (catch Exception _
      :clojure.spec/invalid)))

(s/def ::one-or-two (s/conformer one-or-two?))

Now we can conform and validate values like this:

(s/valid? ::one-or-two 1))   ; => true
(s/valid? ::one-or-two 2)    ; => true
(s/valid? ::one-or-two 3)    ; => false
(s/conform ::one-or-two "1") ; => 1
(s/conform ::one-or-two "2") ; => 2
(s/conform ::one-or-two :2)   ; => :clojure.spec/invalid

I have a feeling that the parse-number and one-or-two method can be combined into one, but I do not see how. Can it be done, and if so how?


texts:
I'm pretty new to asp and c# and I have a couple of concerns with the security of the code I have written (shown below).  Basically all it does is allow you to enter a quantity before you add the item to your cart using a razor form.

Every example I see uses validation on input fields, like:

[Required]
[DataType(DataType.EmailAddress)]

Is that sort of validation (or any other) necessary in this case, or is my form secure enough because the controller requires the input of the product id and the quantity, both of which are limited to integers? Also, is there anything else that I should be concerned about with this form, like Javascript injection?

Thanks for your help!

The view has a razor input form:

@using ( Html.BeginForm( "AddToCart", "Cart" ) )
{
    @Html.HiddenFor(_ => item .ProductID)
    @Html.TextBoxFor(_=> item.Quantity)
    <input type="submit" value="+ Add to cart" />
}

The form is posted to the AddToCart action of the CartController:

[HttpPost]
public ActionResult AddToCart(int id, int quantity)
{
    // Retriebe the product from the database
     var addedProduct = storeDB.Products
         .Single(product => product.ProductId == id);

    // Add it to the shopping cart
    var cart = ShoppingCart.GetCart(this.HttpContext);

    cart.AddToCart(addedProduct, quantity);

    //Go back to the main store page for more shopping
    return RedirectToAction("Index");
}

And here is the AddToCart method:

public void AddToCart(Product product, int quantity)
{
    //Get the matching cart and album instances
    var cartItem = storeDB.Carts.SingleOrDefault(
        c => c.CartId == ShoppingCartId
            && c.ProductId == product.ProductId);

    if (cartItem == null)
    {
        // Create a new cart item if no cart exists
        cartItem = new Cart
        {
            ProductId = product.ProductId,
            CartId = ShoppingCartId,
            Count = quantity,
            DateCreated = DateTime.Now
        };
        storeDB.Carts.Add(cartItem);
    }
    else
    {
        // If the item does exist in the car,
        // than add one to the quantity
        var newCount = cartItem.Count + quantity;
        cartItem.Count = newCount;
    }
    // Save changes
    storeDB.SaveChanges();
}

Thanks again for your help!


texts:
How do I make these line of codes more scala-ish (shorter?). I still get the Java feeling in it (which I want to stay away from).

import scala.collection.mutable
val outstandingUserIds: mutable.LinkedHashSet[String] = mutable.LinkedHashSet[String]()

val tweetJson = JacksMapper.readValue[Map[String, AnyRef]](body)
val userObj = tweetJson.get("user")
tweetJson.get("user").foreach(userObj => {
  userObj.asInstanceOf[Map[String, AnyRef]].get("id_str").foreach(idStrObj => {
    if (outstandingUserIds.exists(outstandingIdStr => outstandingIdStr.equals(idStrObj))) {
      outstandingUserIds.remove(idStrObj.asInstanceOf[String])
    }
  })
})


texts: Converting IActionResult to something that can be mapped in JS

texts:
I have the following ReactJS unordered list which is generated from answers:

{this.state.answers.map((v,i) =>

 {v}
) }

I get answers the following way:

handleSubmit(event) {
    const url = "api/" + this.state.actionWith + this.state.button + this.state.value;
    fetch(url, {
        method: this.state.method
    })
       .then(response => response.json())
       .then(data => {
            this.setState({answers: data, input: false, actionWith: "", method: "", button: "", placeholder: "", value: ""})
       })
}

Controller looks like this:

[HttpGet]
public IActionResult ListTargets()
{
    var answer = _tlConnection.ListTargets();
    return Ok(answer);
}

And it works well, when _tlConnection methods return something like IEnumerable.

The problem is, that some of the methods return UInt for example. Then this.state.answers is not something that can be mapped. I solve this the following way:

[HttpGet("{targetName}")]
public IActionResult getTargetID(string targetName)
{
    var answer = new List<string>() { _tlConnection.getTargetID(targetName).ToString() };
    return Ok(answer);
}

But it feels quite hacky. Is there a more eloquent solution?

Is this a correct way to approach JSON response in ReactJS in general?


texts: Enforce exclusive order of four processes using semaphores

texts:
I am on the learning curve of C and its capabilities. Below I have tried to create 4 individual programs where the execution is always in order (program 0,1,2,3).

About the program
Program #0 is always executed (called) first, it also creates semid's
Program #1 can ONLY be executed if Program #0 has ran
Program #2 can ONLY be executed if Program #1 has ran
Program #3 can ONLY be executed if Program #2 has ran

What Do I Need?
Since, I am a beginner I thought an expert's knowledge on creating a better design or code structuring would help me.

Program Call
./prog0 && ./prog1 && ./prog2 && ./prog3

Program #0

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

int
main ( )
{
    int semid;
    key_t key;
    union semun arg;

    key = ftok("program0.c", 'a');
    semid = semget(key, 3, 0666 | IPC_CREAT);
    if ( semid < 0 )
    {
        perror("Could Not Created The Requested Semaphore");
        exit(1);
    }
    arg.val = 1;
    semctl(semid, 0, SETVAL, arg);
    arg.val = 0;
    semctl(semid, 1, SETVAL, arg);
    semctl(semid, 2, SETVAL, arg);
    printf("Executing process #0.\n");
    return 0;
}

Program #1

int
main ( )
{
    int semid, key;
    union semun arg;
    key = ftok("program0.c", 'a');
    semid = semget(key, 3, 0666 | IPC_CREAT);
    if ( semid < 0 )
    {
        perror("Could Not Created The Requested Semaphore");
        exit(1);
    }
    if ( semctl(semid, 0, GETVAL, 0) != 1 )
    {
        semctl(semid, 0, IPC_RMID);
        exit(1);
    }
    printf("Executing process #1.\n");
    arg.val = 0;
    semctl(semid, 0, SETVAL, arg);
    arg.val++;
    semctl(semid, 1, SETVAL, arg);
    return 0;
}

Program #2

int
main ( )
{
    int semid, key;
    union semun arg;
    key = ftok("program0.c", 'a');
    semid = semget(key, 3, 0666 | IPC_CREAT);
    if ( semid < 0 )
    {
        perror("Could Not Created The Requested Semaphore");
        exit(1);
    }
    if ( semctl(semid, 1, GETVAL, 0) != 1 )
    {
        semctl(semid, 0, IPC_RMID);
        exit(1);
    }
    printf("Executing process #2.\n");
    arg.val = 0;
    semctl(semid, 1, SETVAL, arg);
    arg.val++;
    semctl(semid, 2, SETVAL, arg);
    return 0;
}

Program #3

int
main ( )
{
    int semid, key;
    key = ftok("program0.c", 'a');
    semid = semget(key, 3, 0666 | IPC_CREAT);
    if ( semid < 0 )
    {
        perror("Could Not Created The Requested Semaphore");
        exit(1);
    }
    if ( semctl(semid, 2, GETVAL, 0) != 1 )
    {
        semctl(semid, 0, IPC_RMID);
        exit(1);
    }
    printf("Executing process #3.\n");
    semctl(semid, 0, IPC_RMID);
    return 0;
}


texts: MVC - Control Class - Architecture / Design - Structure Review - PHP

texts:
The client side version in JavaScript is here

This is the server side version of my control module.  How does the structure look.

PostScript

Because this is a small prototype/app I have preferences or things I will consider when I will have a working prototype, they are - testing, try/catch/throw handling of errors, advanced abstractions / design patterns, defensive coding against programmer error / malicious users. Auto-Loading, optimization  Will add these later if the project matures.

<?php
function __autoload( $class_name ) { include 'class.' . $class_name . '.php'; }
$object_c = new CMachine();
$object_c->invoke();

class CMachine
{
    public function invoke()
    {
        $pipe = $this->getPipe();
        switch( $pipe['model'] )
        {
            case 'MUserNew': case 'MUserExist':
                $model_object = new $pipe['model']( new SDB(), new SUniversals() , new SText( $pipe['page'] ), new SMessage() );
                $this->send( $model_object->invoke( $pipe['args'] ) );
                break;
            case 'MUserTry':
                $model_object = new $pipe['model']( new SDB(), new SText( $pipe['page'] ) );
                $test = $model_object->invoke( $pipe['args'] );
                $this->send( $test );
                break;
            case 'MUserAny': case 'MOrb':
                $model_object = new $pipe['model']( new SDB() );
                $this->send( $model_object->invoke( $pipe['args'] ) );
                break;
            default:
                echo " -> Undefined Module Requested";
        }
    }
    private function send( $string_send )
    {
        echo "|A|" . $string_send;
    }
    private function getPipe()
    {
        return json_decode( $_POST['pipe'], true );
    }
}


texts: How to write a cleaner code for this piece of php snippet?

texts:
I would like to know if there is a better/shorter/cleaner/resource saving method for this snippet of php code with codeigniter? Thanks.

$code = $this->uri->segment(3);

if (!$code) {
    // validation
    $this->form_validation->set_rules('code', 'PassCode', 'required|trim|max_length[100]|xss_clean');

    // run validation to check if validation rules are satifised
    if ($this->form_validation->run() == true) {
        $code = $this->input->post('code');
        $user_id = $this->user_model->getUserId($code);
        if (empty($user_id)) {
            $data['errorMessage'] = 'Your code is not valid.';
        } else {
            redirect('user/profile');
        }
    }
} else {
    $user_id = $this->user_model->getUserId($code);
    if (empty($user_id)) {
        $data['errorMessage'] = 'Your code is not valid.';
    } else {
        redirect('user/profile');
    }
}


texts:
I'm writing a chat application.  I would like to know if there are problems in this code.

This function sends message:

function sendMessage()
{
    var text = $('#messageBox').val();
    $('#messageBox').val('');
    if($('.context').scrollTop() + $('.context').innerHeight() >= $('.context')[0].scrollHeight)
    {
        $(".context").animate({ scrollTop: $('.context')[0].scrollHeight}, 1000);
    }
    $('.context').append('
'+ text +'
');
    if(text != '')
    {
        $('#send').attr('disabled', 'disabled');
        $.ajax({
            url: 'http://localhost/chat/display',
            async: true,
            type: "POST",
            data: 'text=' + text,
            cache: false,
            //dataType: 'json',
            success: function (msg) {
                if (msg == 1)
                {
                    $('#send').removeAttr('disabled');
                }
            },
            error: function (msg) {
                alert('app has an error!');
            }
        });
    }
}

When the user sends a message, the message is written on the page before saving.

This code comes before the AJAX call.  Is it right?

$('.context').append('
'+ text +'
');

This function shows messages:

$(document).ready(function () {
    $(window).load(displayMessage(lastTimestamp));
});

function displayMessage(time)
{
    $.ajax({
        url: 'http://localhost/chat/display',
        async: true,
        type: "POST",
        data: 'time=' + time,
        cache: false,
        dataType: 'json',
        success: function (msg) {
            if(msg)
            {
                if($('.context').scrollTop() + $('.context').innerHeight() >= $('.context')[0].scrollHeight)
                {
                    $(".context").animate({ scrollTop: $('.context')[0].scrollHeight}, 1000);
                }
                $('.context').append(msg[0]);
                time = msg[1];
            }
            setTimeout(displayMessage, 2000, time);
        },
        error: function (msg) {
            displayMessage(time);
        }
    });
}

After the page loads, this function will be run to send data to be displayed.

Display method:

public function display()
    {
        if(isset($_POST['text']))
        {
            $text = DB::Escape($_POST['text']);
            $time = time();
            DB::Query("INSERT INTO `messages` (`user_id`, `to_message_id`, `text`, `timestamp`) VALUES ('{$_SESSION['id']}', '1', '{$text}', '{$time}')");
            if(DB::AffectedRows() > 0)
            {
                return 1;
            }
            else
            {
                return DB::LastError();
            }
        }

        if(isset($_POST['time']))
        {
            $time = intval($_POST['time']);
            $current = time();
            while (time() - $current < 10)
            {
                $result = self::findAll("WHERE (`timestamp` > '{$time}' AND `user_id` != '{$_SESSION['id']}')");
                if(count($result) > 0)
                {
                    $html = '';
                    foreach ($result as $obj)
                    {
                        $html .= '
'. $obj->text .'
';
                    }
                    return json_encode(array($html, $obj->timestamp));
                }
                else
                {
                    sleep(3);
                }
            }
        }
    }

Note this section:

while (time() - $current < 10)

This code slows sending and receiving messages so it takes several seconds to send and insert a message when I press Enter or click the sending button.

I'm using last timestamp for selecting messages from database. Is there a problem as the same time in timestamp column? I'd like to fix this apparent performance problem.


texts:
I tried using recursion for this.
Here is the code
  public static string ReverseWords(string str)
  {
    var splitArr = str.Split(" ");
    if(splitArr.Length == 1)
      return splitArr[0];

    return splitArr[splitArr.Length - 1] + " " + ReverseWords(String.Join(" ", splitArr.Take(splitArr.Length - 1));
  }


texts: Processing files in directories with multithreading

texts:
I am processing files in directories. I want to use multi-threading in two ways:

10 threads to process files/folders concurrently
10 threads to process all lines in each file concurrently

In this code, FolderProcessor implements (1), and DocProcessor implements (2). Is there any flaw in this implementation? My testing seems to show that (2) works and reduces time a lot, but (1) doesn't really reduce the processing time.

class FolderProcessor{
      ...
 void processFolder(String inputPath, String outputPath){

            File inputFolder = new File(inputPath);
            String[] filenames = inputFolder.list();

            ExecutorService pool = Executors.newFixedThreadPool(10);

            for (String filename : filenames) {
                String filePath = inputPath + filename;
                File inputfile = new File(filePath);
                if (inputfile.isDirectory()) {
                    processFolder(filePath, outputPath + filename);
                } else {
                    pool.execute(new Runnable() {
                        public void run() {
                            log.info("Start processing " + filePath);
                            Writer.write(filePath, outputPath);
                        }
                    });
                }
            }
            pool.shutdown();
            try {
                pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
}

class DocumentWriter{
    ...
 public static void write(String inputFile, String outputFile) {
        try {

            File test_output = new File(outputFile);
            test_output.getParentFile().mkdirs();
            test_output.createNewFile();
            FileWriter write_test_output = new FileWriter(outputFile);

            List<Document> docs = DocPrecessor.processDocs(inputFile);
            for (Document doc : docs) {
               ...
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class DocPrecessor{
    ......
    public static List<Document> processDocs(String filePath) {

    BufferedReader br = null;
    ExecutorService pool = Executors.newFixedThreadPool(10);
    List<Document> processedDocs = new ArrayList<>();
    try {
        ...
        String line = null;
        int docNo = 0;
        List<Future<Document>> tasks = new ArrayList<>();
        while ((line = br.readLine()) != null) {
            Callable<Document> callable = new TextThread(line, ++docNo);
            tasks.add(pool.submit(callable));
        }
        for (Future<Document> task : tasks) {
            try {
                processedDocs.add(task.get());
            } catch (InterruptedException e) {
                log.error("InterruptedException Failure: " + line);
            } catch (ExecutionException e) {
                log.error("Thread ExecutionException e: " + line);
                e.printStackTrace();
            }
        }
        pool.shutdown();
        try {
            pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)
                br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return processedDocs;
}


texts:
(...as I still learning Kotlin) I found this "problem":

  You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

  Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

  Output: 7 -> 0 -> 8

This is my solution so far:

fun add(a: IntArray, b: IntArray): Iterable<Int> {
  val result: MutableList<Int> = mutableListOf()
  var remainder = 0
  for (i in 0..Math.max(a.size, b.size) - 1) {
    val sum = a.elementAtOrElse(i, { 0 }) + b.elementAtOrElse(i, { 0 }) + remainder
    remainder = if (sum >= 10) 1 else 0
    result.add(if (remainder >= 1) sum - 10 else sum)
  }
  if (remainder > 0) result.add(remainder)
  return result
}

...test cases:

import org.assertj.core.api.Assertions.assertThat
import org.junit.Test

class AddTwoNumbersTest {
  @Test
  fun test_Add() {
    assertThat(add(intArrayOf(9, 6, 9, 5, 9), intArrayOf(1, 5, 1, 6, 1))).isEqualTo(listOf(0, 2, 1, 2, 1, 1))
    assertThat(add(intArrayOf(4, 1, 8, 7, 2), intArrayOf(9, 4, 1, 0, 3))).isEqualTo(listOf(3, 6, 9, 7, 5))
    assertThat(add(intArrayOf(2, 2, 3, 3), intArrayOf(4, 5, 6, 7))).isEqualTo(listOf(6, 7, 9, 0, 1))
    assertThat(add(intArrayOf(4, 1, 0, 8), intArrayOf(2, 2, 7, 6))).isEqualTo(listOf(6, 3, 7, 4, 1))
    assertThat(add(intArrayOf(2, 7, 1, 0), intArrayOf(0, 0, 8, 1))).isEqualTo(listOf(2, 7, 9, 1))
    assertThat(add(intArrayOf(9, 9, 9), intArrayOf(9, 9, 9))).isEqualTo(listOf(8, 9, 9, 1))
    assertThat(add(intArrayOf(9, 3, 7), intArrayOf(8, 7, 8))).isEqualTo(listOf(7, 1, 6, 1))
    assertThat(add(intArrayOf(6, 6, 6), intArrayOf(7, 8, 9))).isEqualTo(listOf(3, 5, 6, 1))
    assertThat(add(intArrayOf(0, 0, 0), intArrayOf(0, 0, 0))).isEqualTo(listOf(0, 0, 0))
    assertThat(add(intArrayOf(2, 4, 3), intArrayOf(5, 6, 4))).isEqualTo(listOf(7, 0, 8))
    assertThat(add(intArrayOf(0, 1), intArrayOf(0, 1, 2))).isEqualTo(listOf(0, 2, 2))
    assertThat(add(intArrayOf(4, 6), intArrayOf(6, 4))).isEqualTo(listOf(0, 1, 1))
    assertThat(add(intArrayOf(1), intArrayOf(9, 9))).isEqualTo(listOf(0, 0, 1))
    assertThat(add(intArrayOf(), intArrayOf(0, 1))).isEqualTo(listOf(0, 1))
    assertThat(add(intArrayOf(), intArrayOf())).isEmpty()
  }
}

It works so far...so I'm wondering if you can improve this one, or have a better approach. Notice I use everything the language offer.


texts:
I have one application in c++ and i'm using the C++ Mysql Connector (https://dev.mysql.com/downloads/connector/cpp/)

I need to save some logs inside one table.Depending on the times I may have large amounts of data on the order of thousands (for example, 80,000).

I already implement a function that iterate my std::vector and save the std::string to my database.

For example:

std::vector<std::string> lines = explode(filedata, '\n');
for (int i = 0; i < lines.size(); i++)
{
   std::vector<std::string> elements = explode(lines[i], ';');
   ui64 timestamp = strtol(elements.at(0).c_str(), 0, 10);
   std::string pointId = elements.at(6);
   std::string pointName = elements.at(5);
   std::string data = elements.at(3);

   database->SetLogs(timestamp, pointId, pointName, data);
}

The logs come from csv file, i save all fields to my vector. After this i parse the vector (with explode) and get only the fields that i need to save.

But i have a problem. If i have e.g 80,000 i'm calling my function to save in database 80,000. It works and save correctly all data but it takes a lot of time.

Exists some way to save all data only calling one time the function to save without calling e.g 80,000 and thus optimize the time?


texts:
I want to execute a number of tasks that may enqueue other tasks, and do all that in parallel, ending only once all tasks are finished.
For example, some sort of crawler that starts with node A, discovers B, C, and D, then visits each of those and discovers other adjacent nodes.
If one task has an error, that error should be raised on the main thread.
My primary concerns are correctness and simplicity.
AFAIK, this is simplest way to do that, even with the new standard libraries like concurrent.futures.
import queue
import threading

class WorkerRunner:
    """
    Runner

    :param int parallelism: Number of workers to run in parallel
    :param handler: Handler that receives work and optionally yields other work
    """

    def __init__(self, parallelism: int, handler):
        self._handler = handler
        self._parallelism = parallelism

    def run(self, items):
        queue_ = queue.Queue()
        threads = []
        for _ in range(self._parallelism):
            thread = WorkerThread(queue_, self._handler)
            thread.start()
            threads.append(thread)
        for item in items:
            queue_.put(WorkItem(item))
        queue_.join()
        for _ in range(self._parallelism):
            queue_.put(END_ITEM)
        for thread in threads:
            thread.result()

"""
End item
"""
END_ITEM = None

class WorkItem:
    def __init__(self, value):
        self.value = value

class WorkerThread(threading.Thread):
    def __init__(self, queue: queue.Queue, handler):
        super().__init__()

        self._queue = queue
        self._exception = None
        self._handler = handler

    def run(self):
        try:
            self._work()
        except Exception as e:
            self._exception = e
            while True:
                try:
                    self._queue.get(False)
                except queue.Empty:
                    break
                else:
                    self._queue.task_done()
            print("here")

    def result(self):
        self.join()
        if self._exception is not None:
            raise self._exception

    def _work(self):
        while True:
            item = self._queue.get()
            try:
                if item is END_ITEM:
                    break
                result = self._handler(item.value)
                if result is not None:
                    for item in result:
                        self._queue.put(WorkItem(item))
            finally:
                self._queue.task_done()

Example
def work(x: int):
    print(x)
    while 0 < x:
        x -= 1
        yield x

runner = WorkerRunner(2, work)
runner.run([3])

# 3
# 2
# 1
# 0
# 0
# 1
# 0
# 0


texts: Producer / Consumer implementation for Parallel Processing in the TPL

texts:
I've stripped this down to its bare bones removing stopping/cancellation logic etc... to keep it simple.

The Producer is a very simple class containing a timer. At regular intervals  the TimerOnElapsed will let the host now that it has another batch of items available. The onus is on the host to pull that next batch using GetNextBatch().

public class Producer
{
    public event EventHandler BatchAvailable;
    private readonly Timer timer;
    private int i;

    public Producer()
    {
        i = 1;
        timer = new Timer(5000);
        timer.Elapsed += TimerOnElapsed;
    }

    public void Start()
    {
        timer.Enabled = true;
        timer.Start();
    }

    private void TimerOnElapsed(object sender, ElapsedEventArgs e)
    {
        if (BatchAvailable != null)
            BatchAvailable(sender , e);
    }

    public IEnumerable<int> GetNextBatch()
    {
        var range = Enumerable.Range(i, i + 50).ToList();
        i = i + 50;
        return range;
    }
}

The Consumer class uses a Concurrent.BlockingCollection<T> to pass objects to a Parallel ForEach loop. The Consumer is READY for the next batch each time it empties the blocking collection of the existing batch.

public class Consumer
{
    private TaskFactory _factory;
    private readonly BlockingCollection<int> _entries;

    public Consumer()
    {
        _entries = new BlockingCollection<int>();
    }

    public void Start()
    {

        _factory = new TaskFactory();

        try
        {
            _factory.StartNew(() =>
            {
                Parallel.ForEach(
                    _entries.GetConsumingEnumerable(),
                    new ParallelOptions() { MaxDegreeOfParallelism = 5 },
                    ProcessEntry
                    );
            });
        }
        catch (OperationCanceledException oce) { }
    }

    public void Add(int entry)
    {
        _entries.Add(entry);
    }

    public bool Ready
    {
        get { return (_entries.Count == 0); }
    }

    private void ProcessEntry(int entry)
    {
        Console.WriteLine("Processing {0}", entry);
        Thread.Sleep(3000);
    }
}

The Host is a class containing each of the above. It orchestrates communication between the two. Each time the Producer says it has another batch available, the host checks to see if the Consumer is ready, and if so, retrieves the batch and passes it on.

public class Host
{
    private Producer _producer;
    private Consumer _consumer;

    public Host()
    {
        _producer = new Producer();
        _producer.BatchAvailable += (s,e) => ProducerOnBatchAvailable();
        _consumer = new Consumer();
    }

    public void Start()
    {
        _producer.Start();
        _consumer.Start();
    }

    private void ProducerOnBatchAvailable()
    {
        if (!_consumer.Ready) return;
        Console.WriteLine("Producer is ready for another Batch...");
        var batch = _producer.GetNextBatch().ToList();
        batch.ForEach(_consumer.Add);
    }
}

I've tested this a couple of times and it behaves as I'd expect. The throttling of batch sizes and the max parallelism in the P-ForEach loop also works. And in my larger example I have a number of other Players that hand entry along to the next step in the pipeline by way of more events and blocking collections.

However, I'm a bit irked by the fact that I never need to call the BlockCollection<T>.CompletedAdding(). Is this bad practice? Do I have any potential problems leaving the blocking collection in the WAIT state for long periods of time?

In the real example the producer will be querying a DB queue which could potentially have no work in it, so the BlockingCollection could sit there for hours overnight.


texts:
I was interviewed for one position and had the following task.

The goal is to design system according step 1, then adapt it to additional requirements in step 2.

Step 1: Shopping cart

You are building a checkout system for a shop which only sells apples and oranges.
Apples cost 60p and oranges cost 25p.
Build a checkout system which takes a list of items scanned at the till and outputs the total cost
For example: [ Apple, Apple, Orange, Apple ] => £2.05
Make reasonable assumptions about the inputs to your solution; for example, many candidates take a list of strings as input

Step 2: Simple offers

The shop decides to introduce two new offers:

buy one, get one free on Apples
3 for the price of 2 on Oranges

Update your checkout functions accordingly

Please find my implementation below and let me know about weak points and what would you do differently or improve.

Checkout.java

import java.util.*;

public class Checkout {

private Set<CheckoutStrategy> strategies = new HashSet<>();

public static Map<String, Double> PRICE_MAP = new HashMap<>();

static {
    PRICE_MAP.put("Orange", 0.25);
    PRICE_MAP.put("Apple", 0.6);
}

public Checkout() {
    this.strategies.add(new SummingStrategy());
}

public Checkout(CheckoutStrategy discountStrategy) {
    this();
    this.strategies.add(discountStrategy);
}

public double calculateTotal(List<String> strings) {
    double[] result = new double[1];

    for (CheckoutStrategy strategy : strategies) {
        strategy.calculateTotal(strings, result);
    }

    return result[0];
}

}

CheckoutStrategy.java

import java.util.List;

public interface CheckoutStrategy {
    void calculateTotal(List<String> strings, double[] result);
}

SummingStrategy.java

import java.util.List;
import static Checkout.PRICE_MAP;

public class SummingStrategy implements CheckoutStrategy {

@Override
public void calculateTotal(List<String> items, double[] result) {
    result[0] = items.stream().mapToDouble(PRICE_MAP::get).sum();
  }

}

DiscountStrategy.java

import Checkout;
import java.util.List;

public class DiscountStrategy implements CheckoutStrategy {

@Override
public void calculateTotal(List<String> items, double[] result) {
    ItemCounter counter = items.stream().collect(ItemCounter::new, ItemCounter::accept, ItemCounter::combine);

    double appleDiscount = (counter.counts[ItemCounter.APPLE_INDEX] / 2) * Checkout.PRICE_MAP.get("Apple");
    double orangeDiscount = (counter.counts[ItemCounter.ORANGE_INDEX] / 3) * Checkout.PRICE_MAP.get("Orange");

    result[0] -= orangeDiscount;
    result[0] -= appleDiscount;
}

class ItemCounter {
    static final int APPLE_INDEX = 0;
    static final int ORANGE_INDEX = 1;
    private int[] counts = new int[2];

    public void accept(String item) {
        switch (item) {
            case "Apple":
                counts[APPLE_INDEX]++;
                break;

            case "Orange":
                counts[ORANGE_INDEX]++;
                break;
        }
    }

    public void combine(ItemCounter other) {
        this.counts[APPLE_INDEX] += other.getCounts()[APPLE_INDEX];
        this.counts[APPLE_INDEX] += other.getCounts()[ORANGE_INDEX];
    }

    public int[] getCounts() {
        return counts;
    }
    }

 }


texts: Convert big collection into simple array

texts:
Is there a better way to do this?

const data = [{id: 1, name: 'item1'}, {id: 2, name: 'item2'}]
const a = []
data.forEach(x => { a[x.id] = x.name })
return a // ['1': 'item1', '2': 'item2']


texts:
I'm looking for a review of the Javascript code which has this specifications:

  Given two objects, the function "extend" adds properties from the 2nd object to the 1st object.

Notes:

Add any keys that are not in the 1st object.
If the 1st object already has a given key, ignore it (do not overwrite the property value).
Do not modify the 2nd object at all.

A runnable version can be found on repl.it.

function extend(obj1, obj2) {
  for (var key in obj2) {
    if (!obj1.hasOwnProperty(key)) {
      obj1[key] = obj2[key];
    }
  }
}
var obj1 = {
  a: 1,
  b: 2
};
var obj2 = {
  b: 4,
  c: 3
};

extend(obj1, obj2);

console.log(obj1); // --> {a: 1, b: 2, c: 3}
console.log(obj2); // --> {b: 4, c: 3}


texts: What do you think of my Recursive FizzBuzz?

texts:
I wanted to see if I fully understood recursion so I attempted the FizzBuzz challenge and applied recursion to it.

Did I do it correctly? Is this good code? Is there a more efficient way of doing it? How can I improve?

//---------------------------------------------------------------------------------------
//[RecurFizzBuzz]
//  FizzBuzz using recursion
//---------------------------------------------------------------------------------------
// Author : Jimmy
//---------------------------------------------------------------------------------------

public class RecurFizzBuzz {

 // Specify a range to recurse, starts at int a, ends at int b
 public static void recurse(int a, int b){

  if(a <= b){
   if(a % 3 == 0 && a % 5 == 0){
    System.out.println("FizzBuzz");
   } else if(a % 3 == 0){
    System.out.println("Fizz");
   } else if(a % 5 == 0){
    System.out.println("Buzz");
   } else {
    System.out.println(a);
   }
   recurse(++a, b);
  } else {
   System.exit(0);
  }
 }

 public static void main(String[]args) {
  recurse(1, 100);
 }
}


texts: Wipe sensitive information from memory in Python

texts:
I have come up with the following method to remove sensitive information with the help of the garbage collector:

def wipe_sensitive_info(d, keys):
    """
    In Python we are not able to overwrite memory areas. What we do is:
    - remove references to the specified objects, in this case keys in a dictionary
    - immediately call garbage collection
    """
    # TODO: the following points are pending
    #   - this relies on the gc to remove the objects from memory (de-allocate memory).
    #   - the memory itself is not guaranteed to be overwritten.
    #   - this will only deallocate objects which are not being referred somewhere else (ref count 0 after del)
    for key in keys:
        del d[key]
    logger.info('Garbage collected {} objects'.format(gc.collect()))

This would be called from a django app as follows:

wipe_sensitive_info(request.data, ['password'])

Any ideas or comments on how to improve this implementation?


texts:
Check out the fiddle here.  This JavaScript will take the row that a user clicks on and make an object with the key coming from the thead element in the table and the value coming from the data in the text in the table cell value.  I'm looking for a more professional/succint way of doing this:

JS

$(document).ready(function () {
            $('tr').click(function () {
                var tableData = $(this).children('td').map(function () {
                    return $(this).text();
                }).get();
                var props = $('thead > tr th');
                var array = [];
                props.each(function () { array.push($(this).text()) });
                //keys
                console.log(array);
                //values
                console.log(tableData);

                var obj = {};
                for (var i = 0; i < tableData.length; i++) {
                    obj[array[i]] = tableData[i];
                }
                console.log(obj);
            });

        });

HTML

                PersonId	FirstName	LastName

                1	John	Doe

                2	Jane	Doe

                3	Time	Smith


texts:
I am studying Python, so it is very easy task. I want to get best and most elegant way to solve each simple task.
The task is:

  Write a program that reads the integers from the console one number per line.
  For each entered number check:

  if the number is less than 10, skip that number;
  if the number is greater than 100, stop to read the numbers;

  Print all numbers that does not satisfy those two conditions.

lst = []
num = 0
while num <=100:
    num = int(input())
    if num > 100:
        break
    if num >= 10:
        lst.append(num)

print('\n'.join(str(value) for value in lst))


texts: Determine Collatz sequence length for given starting values

texts:
I am trying to get into the habit of solving programming puzzles in my spare time but am stuck on the first one (which I know can be for a large number of reasons, hence my posting for help). Shown below is my code that is meant to solve the 3n+1 Challenge:

from sys import stdin

def main():
    curr_Line=stdin.readline()
    while curr_Line!=None:
        curr_Line=curr_Line.split()
        min_num=int(curr_Line[0])
        max_num=int(curr_Line[1])
        maxCycleLength =0
        for curr_num in range(min_num,max_num+1):
            currCycleLength =1
            while curr_num!=1:
                currCycleLength +=1
                if curr_num%2==0:
                    curr_num=curr_num/2
                else:
                    curr_num=3*curr_num+1
            maxCycleLength=max(currCycleLength,maxCycleLength)
        print(min_num,max_num,maxCycleLength,sep=" ")
        curr_Line=stdin.readline()
    return
main()

When I run this, the UVA online judge says that I've exceeded the 3 second time limit.

I've tried the following:

changing the the while loop to for line in stdin:

Any suggestions would be much appreciated.


texts:
Below script is used to generate passphrases for gpg (or anything really).

Do you see any blatant security mistakes in it?

I wrote it by myself, because I couldn't find any passphrase generator that doesn't use external services and uses /dev/urandom.

Note: I run it with ./generator.bash 4 > x && vim x so stdout is not printed to the terminal, but I'm not sure if this is neccessary. I'm thinking that somewhere terminal history could be stored.

#!/bin/bash
# Usage: ./passphrase_gen.bash 4 > x && vim x
# We redirect to file and print via vim so no history is saved anywhere.
# Repeat after you get passphrase you like. Memorize it/write it down
# and remove x afterwards.
set -eo pipefail

words=/usr/share/dict/words

# https://serverfault.com/a/214620/216850
sudo rngd -r /dev/urandom

n=$1

# print $n randomly chosen words from $words file
for i in $(seq 1 $n); do
  # https://unix.stackexchange.com/a/268960
  random=$(od -vAn -N4 -tu4 < /dev/urandom)

  lines=$(cat $words | wc -l)

  line=$((random % lines))
  awk "NR==$line" $words
done

Gist link: https://gist.github.com/jan-swiecki/9974501047c79bad12a3c87cfe846cd6


texts: Checking for any character common to two strings — Go is 50× slower than Python

texts:
I decided to learn Go, knowing Python. My approach is by solving easy problems like this one:

  You are given two strings, A and B. Find if there is a substring that
  appears in both A and B. Several test cases will be given to you in a
  single file. The first line of the input will contain a single integer
  T, the number of test cases.

  Then there will be T descriptions of the test cases. Each description
  contains two lines. The first line contains the string A and the
  second line contains the string B.
  For each test case, display YES (in a newline), if there is a common substring. Otherwise, display NO.

The problem is straightforward: check if two sets intersect.

The real problem is that for the biggest testcase (20 strings of length 105 each) my Go code takes 2.6 seconds, which is unacceptable, knowing that my Python code solves the problem in 0.08 seconds. Based on the fact that Go is claimed to be near C speed, I assume that I am doing something super inefficiently.

package main
import "fmt"

func subst(s1 string, s2 string) bool {
    m := map[uint8]bool{}

    for i := 0; i < len(s1); i++ {
        m[s1[i]] = true
    }

    for i := 0; i < len(s2); i++ {
        if m[s2[i]] {
            return true
        }
    }
    return false
}

func main() {
    var n int
    var s1, s2 string

    fmt.Scanf("%d", &n)
    for i := 0; i < n; i++ {
        fmt.Scanf("%s", &s1)
        fmt.Scanf("%s", &s2)
        if subst(s1, s2) {
            fmt.Println("YES")
        } else {
            fmt.Println("NO")
        }
    }
}

Python implementation:

def twoStrings(a, b):
    if len(set(a) & set(b)):
        print 'YES'
    else:
        print 'NO'

for i in xrange(input()):
    twoStrings(raw_input(), raw_input())

Nonetheless, two snippets look really different, they are actually doing similar things. In go I create a hash-map and put boolean value for each character from the first string (this is how sets are implemented in a lot of languages) and then for each character from the second string I am checking whether it is in a map and if no - exiting. It's obvious in the Python code.


texts:
I've just written some code in an online compiler, and since I'm very new to C#, I wanted to ask what could be improved about the code.

The task of the program is simply to add up the numbers the user entered before and then calculate the average.

public static void Main()

{
    int input;
    int sum = 0;
    bool error = false;
    int[] numbers = new int[5];

    for(int i = 0; i < numbers.Length; i++)
    {

        if (!error)
            Console.WriteLine("Please write a number:");

        if(Int32.TryParse(Console.ReadLine(), out input))
        {
            numbers[i] = input;
            sum += numbers[i];
            error = false;
        }
        else
        {
            Console.WriteLine("An error occured, please try again:");
            error = true;
            i--;
            continue;
        }
    }

    Console.WriteLine("");
    Console.WriteLine("Your typed in values:");
    for(int i = 0; i < numbers.Length; i++)
    {
        Console.WriteLine(numbers[i]);
    }

    Console.WriteLine("");

    Console.WriteLine("The result of your numbers:");
    Console.WriteLine(sum);

    Console.WriteLine("The average of your numbers:");
    Console.WriteLine((double)sum / (double)numbers.Length);
}

The code works fine, but maybe I could do some things more effectively.
Would be glad to get some help :)

Just to sum things up here is the console-output:

Please write a number:
> 4
Please write a number:
> 2
Please write a number:
> a
An error occured, please try again:
> 6
Please write a number:
> 4
Please write a number:
> 8

Your typed in values:
4
2
6
4
8

The sum of your numbers:
24
The average of your numbers:
4.8

('>' = User input)


texts: Tell GUI to update itself by passing self to module?

texts:
I hope this is the right spot to ask this, if not tell me and I will delete the post.
I need my GUI/program to update whenever the active_bots variable is changed, to display the contents of this variable.
Is this the correct way to speak to the GUI instance? Pass the instance in the module-call and then set the active_bots-variable by calling the GUI-setter from the module. Or is this bad practice/is there a better way?
Cutting out a lot my code looks like this:
import curses
import modules.bots.quote_bot as quoteBot

class GUI:

    def __init__(self, stdscr):

        self.active_bots = [] #This variable is the one that needs to be watched

        #All kinds of preparation etc.

        self.run() # This would normally call run and start the program

    def run(self):

        while True:
            key = self.screen.getch()
            if key == ord('e'):
                #End program
                break
            elif (key == ord('q')):
                # Start bot
                quoteBot.start(self)
            else:
                #do nothing
                continue

        #Revert terminal settings and end
        self.screen.clear()
        curses.endwin()

    def active_bots_setter(self, operator, botname):
        if (operator == '-'):
            self.active_bots.remove(botname)
        elif (operator == '+'):
            self.active_bots.append(botname)
        else:
            raise ValueError
        self.init_user_window() #Refresh user-window

#Start program.
#Use wrapper to restore original terminal settings even if exception raised
curses.wrapper(GUI)

quote_bot.py
def start(GUI_instance):
    #Check whether QuoteBot is already running
    thread_list = [] #List of alive threads
    for thread in threading.enumerate():
        thread_list.append(thread.getName())
    if "QuoteBot-Thread" in thread_list:
        logger.info("QuoteBot: Shutting down...")
        stop()
    else:
        logger.info("QuoteBot: Starting up...")
        GUI_instance.active_bots_setter('+', "QuoteBot")
        if (check_connection() == True):
            t = threading.Thread(target=tweet_quote)
            t.name = 'QuoteBot-Thread'
            t.daemon = True
            t.start()
        else:
            logger.error("Quotebot: Quote API Connection Test - Failed to connect! /nCancelling start up.")


texts:
This is a minimal little utility that I've found useful while reorganizing my music and book libraries. Any issues you can see? Anything I could be doing better or more elegantly? Anyone wanna take a crack at the equivalent in Python/Perl?

Take 2:

#!/usr/bin/ruby

require 'optparse'
require 'pp'
require 'fileutils'

$options = {:sub => "", :downcase => nil}
OptionParser.new do |opts|
  opts.on('-r', '--regex REGEX', String,
          'Specify the regular expression to replace') {|reg| $options[:regex] = Regexp.new(reg)}
  opts.on('-s', '--sub SUBSTITUTE', String,
          'Specify what to replace the match with. By default, the empty string (so matches are stripped).') {|$options[:sub]|}
  opts.on('-d', '--downcase', 'If passed, all filenames will be downcased.'){|$options[:downcase]|}
end.parse!

usage unless ARGV.length > 0

def rename(str)
  ($options[:downcase] ?
   str.downcase : str).gsub($options[:regex], $options[:sub])
end

ARGV.each do |target|
  File.rename(target, rename(target))
end


texts:
So my app needed a cookie store that persists over the app closing, device reboot etc. I decided to use the sharedPreferences for this. The class works pretty well, in both my tests and on the device. However there are couple of things I think can be improved. First is error handling. The problem is I cannot throw the errors further up in the app as the cookiestore interface doesn't not allow it. Secondly I have made a persistantcookie so I have a concrete class to serialise. I then convert that to the cookie interface. It seems an ugly way to do it. So any pointers would be very much appreciated.

public class BetterPersistantCookieStore implements CookieStore {

    private static final String TAG = BetterPersistantCookieStore.class.getSimpleName();
    private SharedPreferences sharedPreferences;
    private ObjectMapper objectMapper = new ObjectMapper();//TODO pass serializer and deserialiser into constructor
    private static final String COOKIES_KEY = "cookiesKey";

    @Inject
    public BetterPersistantCookieStore(SharedPreferences sharedPreferences) {
        this.sharedPreferences = sharedPreferences;
    }

    @Override
    public void addCookie(Cookie cookie) {
        List<PersistantCookie> cookieList = getPersistantCookies();
        int len = cookieList.size();
        for (int i = 0; i < len; ++i) {
            Cookie tempCookie = cookieList.get(i);
            if (cookie.getName().equals(tempCookie.getName())) {
                cookieList.remove(i);
            }
        }
        cookieList.add(new PersistantCookie(cookie));
        sharedPreferences.edit().putString(COOKIES_KEY, listToString(cookieList)).commit();
    }

    @Override
    public List<Cookie> getCookies() {
            return convertPersistantCookiesToCookies(getPersistantCookies());
    }

    @Override
    public boolean clearExpired(Date date) {
        List<PersistantCookie> cookieList = getPersistantCookies();
        int len = cookieList.size();
        boolean returnValue = false;
        for (int i = 0; i < len; ++i) {
            Cookie cookie = cookieList.get(i);
            if (cookie.isExpired(date)) {
                cookieList.remove(i);
                returnValue = true;
            }
        }
        sharedPreferences.edit().putString(COOKIES_KEY, listToString(cookieList)).commit();
        return returnValue;
    }

    @Override
    public void clear() {
        sharedPreferences.edit().remove(COOKIES_KEY).commit();
    }

    private List<PersistantCookie> getPersistantCookies()  {
            return stringToList(sharedPreferences.getString(COOKIES_KEY, ""));
    }

    private List<PersistantCookie> stringToList(String value) {
        try {
            return objectMapper.readValue(value, TypeFactory.collectionType(ArrayList.class, PersistantCookie.class));
        } catch (IOException e) {
            e.printStackTrace();
            return new ArrayList<PersistantCookie>(0);
        }
    }

    private String listToString(List<PersistantCookie> cookies)  {
        try {
            return objectMapper.writeValueAsString(cookies);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    private List<Cookie> convertPersistantCookiesToCookies(List<PersistantCookie> persistantCookies) {
        List<Cookie> cookies = new ArrayList<Cookie>();
        for (Cookie cookie : persistantCookies) {
            cookies.add(cookie);
        }
        return cookies;
    }

}


texts:
I am learning programming online and currently watching CS50 lectures, in third lecture, professor introduces us to merge_sort though only through pseudo code, so I wanted someone to review my implementation and tell me where I can improve and what I possibly missed.

#include <algorithm>
#include <assert.h>
#include <cmath>
#include <iostream>
#include <vector>

template <typename T> void merge_sort(T m_array[], const size_t size) {
    using namespace std;
    if (size < 2)
        return;
    else if (size == 2) {
        if (m_array[0] > m_array[1])
            std::swap(m_array[0], m_array[1]); // no need for a new array
        return;
    }
    merge_sort(m_array, size / 2);
    merge_sort(m_array + size / 2,
               std::ceil(static_cast<double>(size) /
                         2) // for odd size, divison will have truncated value
                            // and recursion will left the the last array value
                            // for sorting, size%2==0?size/2:size/2+1
    );

    T *new_array = new T[size];
    size_t na_pos = 0;

    const T *array1 = m_array, *array2 = m_array + size / 2;

    const T *const array1end = m_array + size / 2, *const array2end =
                                                       m_array + size;

    while (1) {
        if (array1 == array1end)
            break;
        if (array2 == array2end)
            break;

        if (*array1 < *array2)
            new_array[na_pos++] = *array1++;
        else if (*array2 < *array1)
            new_array[na_pos++] = *array2++;
        else if (*array1 == *array2) {
            new_array[na_pos++] = *array1++;
            new_array[na_pos++] = *array2++;
        }
    }

    assert(array1 == array1end || array2 == array2end);

    while (array1 != array1end)
        new_array[na_pos++] = *array1++;
    while (array2 != array2end)
        new_array[na_pos++] = *array2++;
    assert(na_pos == size);

    for (na_pos = 0; na_pos < size; na_pos++)
        m_array[na_pos] = new_array[na_pos];

    delete[] new_array;
}

int main() {
    using namespace std;

    auto limit = 10000;
    const auto size = 21;
    while (limit--) {
        vector<int> a;
        a.reserve(size);
        while (a.size() < size)
            a.push_back(rand() % 10000);
        merge_sort(a.data(), a.size());
        assert(std::is_sorted(a.begin(), a.end()));
    }

    return 0;
}


texts:
I have some sample code where I used string.Format but after reading about benchmark performances by other people I believe that it may be better to do multiple appends by a StringBuilder

Here is the scenario:

In my gridView, I have a function called before a databind. The function looks like such:

public string getColumnText(String myParam)
{
    StringBuilder sb = new StringBuilder();
    return sb.Append(string.Format("{1}", myParam).ToString();
}

Is this a better alternative?

StringBuilder sb = new StringBuilder();
sb.Append("<a href = 'javascript:Global.someFunction(\"");
sb.Append(myParam"); etc...

Let's assume that this function will be called 10,000 times.


texts:
Any tips on how to improve this simple recursion program?

#include <iostream>
#include <cstdlib>

using namespace std;

int findSum(int*, const int, int, int);

int main()
{
    int length = 5, sum = 0, n = 0;
    int list[length];

    for (n; n < length ; n++ )
    {
     list[n] = n + 1; //initializes array elements to 1,2,3,4,5
    }

    n = 0;

    cout << findSum(list, length, n, sum) << endl;

    system("pause");
    return 0;
}

int findSum(int list[], const int length, int n, int sum)
{
    if (n == length) //if end of list has been reached, stop recursion
    {
        return sum;
    }
    else
    {
        sum += list[n]; //adds list elements
        n++;            //increments list
        return findSum(list, length, n, sum);
    }
}


texts: Safe init using failable guarded initializer

texts:
I am wondering if that is a safe and proper init, with one failable init guarded and an init.

Are the force-unwrap correct in the self.init as I know they are those types ?

struct Item: Equatable {

            let id: NSNumber
            let displayName: String
            let amount: NSNumber

            init(id:NSNumber, displayName:String, amount:NSNumber) {
                self.id = id
                self.displayName = displayName
                self.amount = amount
            }

            init?(dictionnary:NSDictionary) {

                guard let id = dictionnary["id"] , id is NSNumber else  {
                    return nil
                }

                guard let displayName = dictionnary["display_name"] , displayName is String else {
                    return nil
                }

                guard let amount = dictionnary["amount"] , amount is NSNumber else  {
                    return nil
                }

                    self.init(id:id as! NSNumber, displayName: displayName as! String, amount: amount as! NSNumber)
                }

}

func ==(lhs: Item, rhs: Item) -> Bool {
        return lhs.id == rhs.id
}


texts: Binary expression tree node with two possible states

texts:
I am building out a binary expression tree and shown below is an implementation of the tree's node.

The node can be either a leaf or non-leaf, with leaves having Integer type values and non-leaves having ExpressionTreeNodeOperands type values. Leaves may have neither left nor right child nodes, and non-leaves must have both left and right child nodes.

I feel like this could be solved more appropriately using inheritance but can't seem to wrap my head around the generic Object member.

public class ExpressionTreeNode {

    private Object value;
    private ExpressionTreeNode leftNode;
    private ExpressionTreeNode rightNode;

    public ExpressionTreeNode(Object value) {
        this(value, null, null);
    }

    public ExpressionTreeNode(Object value, ExpressionTreeNode leftNode, ExpressionTreeNode rightNode) {

        if (value == null || (!(value instanceof Integer) && !(value instanceof ExpressionTreeNodeOperands))) {
            throw new IllegalArgumentException("Illegal argument: value must be non-null with a type of Integer or ExpressionTreeNodeOperand");
        }

        if (leftNode == null && rightNode != null || leftNode != null && rightNode == null) {
            throw new IllegalStateException("Illegal state: leftNode and rightNode should both be null or non-null alike");
        }

        if ((value instanceof Integer) && (leftNode != null && rightNode != null)) {
            throw new IllegalStateException("Illegal state: non-operand non-leaf node");
        }

        if (!(value instanceof Integer) && leftNode == null && rightNode == null) {
            throw new IllegalStateException("Illegal state: non-integer leaf node");
        }

        this.value = value;
        this.leftNode = leftNode;
        this.rightNode = rightNode;
    }

    public boolean isLeafNode() {
        return (leftNode == null) && (rightNode == null);
    }

    public Object getValue() {
        return value;
    }

    public ExpressionTreeNode getLeftNode() {
        return leftNode;
    }

    public ExpressionTreeNode getRightNode() {
        return rightNode;
    }
}