texts: Generate the Norwegian equivalent to social security numbers - follow-up

texts:
First of, here is my previous post.

That should explain a fair bit. The reason I'm posting one more time, is I have changed a lot. Using more classes, let them do all the work, and the overall structure.

#include <iostream>

const int DATE_LENGTH = 6;

class Date {
    private:
        char *ans;
    protected:
        int date[DATE_LENGTH];
        int year;
    public:
        Date() {
            askForDate();
        }

        ~Date() {
            if(ans) { delete ans; }
        }

        void askForDate() {
            using namespace std;
            ans = new char[DATE_LENGTH];
            cout << "Date of Birth (DDMMYY): ";         cin.getline(ans, DATE_LENGTH + 1);
            while (!validDate(ans)) {
                cin.getline(ans, DATE_LENGTH + 1);
            }

            for (int i = 0; i < DATE_LENGTH; i++) { date[i] = int(ans[i] - '0'); }
            year = 1900 + date[4] * 10 + date[5];
        }

        bool validDate(const char *d) {
            return strlen(d) == 6;
        }
};

class IndividSiffer : public Date {
    protected:
        int i1, i2, i3;
    public:
        IndividSiffer(int ii1, int ii2, int ii3) : i1(ii1), i2(ii2), i3(ii3) {}

        void individSiffer() {
            static int individ = -1;
            if(year >= 1900 && year <= 1999 ){
                individ++;
                i1 = i2 = i3 = 0;
            }
            i3 = individ % 10;
            if(individ < 100){
                i1 = 0;
                i2 = individ / 10 % 10;
            }else if(individ < 10){
                i1 = i2 = 0;
            }else{
                i1 = individ / 100 % 10;
                i2 = individ / 10 % 10;
            }
        }
};

class KontrollSiffer : public IndividSiffer {
    protected:
        int k1, k2;
    public:
        KontrollSiffer(int kk1 = 0, int kk2 = 0, int i1 = 0, int i2 = 0, int i3 = 0) : IndividSiffer(i1, i2, i3), k1(kk1), k2(kk2) {
            for (int index = 0; index < 500; index++) {
                individSiffer();
                generate();
            }
        }

        void generate() {
            using namespace std;
            k1 = 11 - ((3*date[0] + 7*date[1] + 6*date[2] + 1*date[3] + 8*date[4] + 9*date[5] + 4*i1 + 5*i2 + 2*i3) % 11);
            if(k1 == 11){ k1 = 0; }
            k2 = 11 - ((5*date[0] + 4*date[1] + 3*date[2] + 2*date[3] + 7*date[4] + 6*date[5] + 5*i1 + 4*i2 + 3*i3 + 2*k1) % 11);
            if(k2 == 11){ k2 = 0; }
            if((i3 != 0 && i3 != 2 && i3 !=4 && i3 !=6 && i3 !=8) && (k1 != 10 && k2 !=10)){
                for (int i = 0; i < DATE_LENGTH; i++) { cout << date[i]; }
                cout << i1 << i2 << i3 << k1 << k2 << endl;
            }
        }
};

int main(int argc, char *argv[]) {
    KontrollSiffer k;
    return 0;
}

I'd really like some input on how I structured it, or if things should be done differently.


texts:
I am trying to optimize my code when downloading around 50 pdf files from a website. All of the pdf are big in size (average 25mb). Is there any way to optimize further to download the pdf faster?

for (String pdfUrl : pdfUrls) {
    URLConnection request;
    request = new URL(pdfUrl).openConnection();
    InputStream in = request.getInputStream();
    File downloadedFile = File.createTempFile("download-pdf-" + System.currentTimeMillis(), ".pdf");
    FileOutputStream out = new FileOutputStream(downloadedFile);
    byte[] buffer = new byte[10240];
    int len = 0;
    int bytesBuffered = 0;
    while ((len = in.read(buffer)) != -1) {
        out.write(buffer, 0, len);
        bytesBuffered += len;
        if (bytesBuffered > 1024 * 1024) {
            out.flush();
        }
    }
    in.close();
    out.close();
}


texts: SQL Injection and php performance checking

texts:
I hope this is not a really bad question for a first time here beginner.

This piece of code selects from the left table and will list the content in the right hand table. This is a working code but I would like to see how a professional would protect and make it faster.

Any suggestion (with some code) would be appreciated. Thanks a lot

PS: There is also a little glitch with it: after deleting it lose the selected item on the right list.

<?php include("db_con1.php");?>

<form method="post" action="test.php">

<?php
  $queryl = $pdo->prepare('SELECT id, name FROM test1 ORDER BY name ASC');
  $queryl->execute();
?>

  <?php foreach ($queryl as $i => $rowl) { ?>

   <?php if ($i) {?>
  <input name="checkbox1_del[]" id="test_<?php echo $i ?>" type="checkbox" value="<? echo $rowl['id']; ?>"/>
  <label for="test_<?php echo $i ?>">
   <a href="test1.php?gid=<?php echo $rowl['id']; ?>"><?php echo $rowl['name']; ?>

  <?php } ?>

<?php
  if(isset($_GET['gid'])) {
   $gid=$_GET['gid'];
   $queryr = $pdo->prepare('SELECT test3.name FROM test1, test2, test3 WHERE test1.id=test2.groupid AND test3.id=test2.peopleid AND test1.id='.$gid.' ORDER BY test3.name ASC');
   $queryr->execute();
  }
?>

  <?php foreach ($queryr as $i => $rowr) { ?>

      <?php if ($i) {?>
      <input name="checkbox2_del[]" id="test_<?php echo $i ?>" type="checkbox" value="<? echo $rowr['id']; ?>"/>
      <label for="test_<?php echo $i ?>"><?php echo $rowr['name']; ?>

  <?php } ?>

<input type="submit" name="del" value="Delete the selected items">
</form>

<?php
if (isset($_POST['del'])) {
echo "Don't delete:)";
  for ($c = 0; $c < count($_POST['checkbox1_del']); $c++){
    $checkbox1_del = $_POST['checkbox1_del'][$c];
    $sql = 'UPDATE test1 SET status=0, log="'.date("Y-m-d").'"WHERE id='.$checkbox1_del;
    echo $sql;
    $query = $pdo->prepare($sql);
    $query->execute();
  }

  for ($c = 0; $c < count($_POST['checkbox2_del']); $c++){
    $checkbox2_del = $_POST['checkbox2_del'][$c];
    $sql = 'UPDATE test2 SET status=0, log="'.date("Y-m-d").'"WHERE id='.$checkbox2_del;
    echo $sql;
    $query = $pdo->prepare($sql);
    $query->execute();
   }

    if($query){
      echo "<meta http-equiv=\"refresh\" content=\"0;URL=test1.php\">";
     }
 }
?>

Revise 1: This is a extracted part of my program, however here is the definition of this function:

Having 3-5000 contact, to send emails them easier to group them to Distribution list.
So this part of the program provide 3 tables:

Distribution list   |    Members of selected group   |   People

you can make group names and can add people into it.

So basic functions that I wrote for this part:

new distribution list can be added
By clicking on any Distribution list you'll get the Members table ($_GET)
Also by clicking on Distribution list should be BOLD (class="bold") as highlighted
Selecting any members in the member list can be deleted (checkbox2_del())
From people list anyone can be added to the list

This is what I tried to write and this test shows that basic steps of it. I just didn't want to overload  anybody to read through the whole script. If anyone would like to see I happy to replace with it. Thanks


texts:
I Needed to parse some positive integers with the following constraints:

If possible use C++ only (no C API)
Needs to be able to process parsed data after each newline
Should be reasonably fast
Memory usage should be kept low  (i.e. don't read the entire file in one go)
CSV file is well formed so error checking can be mostly omitted
Unknown amount of lines in file
Should support both unix (\n) and windows (\r\n) line endings

This code runs fine and is faster than the standard approach of streaming via >>.
On average it takes 290ms to parse 10,000,000 lines whereas the version with >> takes 1.1s which I think is not a bad improvement.

However I have some concerns about this:

Are there any obvious mistakes that make this slower than it should be?
Are there any side effects or undefined behavior?
Is the template part applied correctly or is there a better way to do it?
Does the naming make sense?

Please also point out anything else you notice.

Sample input:

1,22,333
4444,55555,666666

Code:

#include <algorithm>
#include <fstream>
#include <string>
#include <vector>

inline void parse_uints(
        const char* buffer_ptr,
        std::vector<uint_fast16_t>& numbers) {
    bool is_eol = false;
    while (!is_eol) {
        uint_fast16_t parsed_number = 0;
        for (;;) {
            if (*buffer_ptr == ',') {
                break;
            }
            if (*buffer_ptr == '\r' || *buffer_ptr == '\0') {
                is_eol = true;
                break;
            }
            parsed_number = (parsed_number * 10) + (*buffer_ptr++ - '0');
        }
        // skip delimiter
        ++buffer_ptr;
        numbers.emplace_back(parsed_number);
    }
}

template<typename T>
void read_line(
        const std::string& filename,
        const uint_fast8_t& line_length,
        const uint_fast8_t& values_per_line,
        T callback) {
    std::ifstream infile{filename};
    if (!infile.good()) {
        return;
    }

    std::vector<uint_fast16_t> numbers;
    numbers.reserve(values_per_line);

    std::string buffer;
    buffer.reserve(line_length);

    while (infile.good() && std::getline(infile, buffer)) {
        parse_uints(buffer.data(), numbers);
        callback(numbers);
        numbers.clear();
    }
}

int main(int argc, char** argv) {
    constexpr uint_fast8_t line_length = 25;
    constexpr uint_fast8_t values_per_line = 3;
    read_line(argv[1], line_length, values_per_line, [](auto& values) {
        // do something with the values here, for example get the max
        auto max = std::max_element(std::begin(values), std::end(values));
    });
}


texts: Sorting an int[] array using insertion sort algorithm - follow-up

texts:
Previous questions:

Is my implementation of insertion sort is correct?
Sorting an int[] array with an Insertion Sort

I'm currently learning about different sorting algorithms and after reading on the concept of the insertion sort of how it's done I've tried to implement it by myself before seeing how it was implemented in the source from which I'm learning.

This is my implementation:

void insertionSort(int arr[])
{
    for(int i = 1; i < SIZE; i++)
    {
        int value = arr[i];
        int j = i;
        for(; j > 0; j--)
        {
            if (value < arr[j - 1])
            {
                arr[j] = arr[j - 1];
            }
            else
            {
                break;
            }
        }
        arr[j] = value;
    }
}

Now I think I've implemented it correctly (not talking about efficient or anything just the algorithm itself), but when I saw the way it was implemented in the course I'm seeing I had a bit of concerns about my implementation because they're really different and I just wanted to make sure my implementation is really an insertion sort algorithm implementation and I didn't done anything else.

Here's the implementation by the source I'm learning from:

void insertionSort(int arr[])
{
  for(int i = 1;, i < SIZE; i++)
  {
      int value = arr[i];
      int j = i - 1;
      int done = 0;
      do
      {
          if (arr[j] > value)
          {
              arr[j + 1] = arr[j];
              j--;
              if (j < 0)
                  done = 1;
          }
          else
          {
              done = 1;
          }
      } while(!done)
      arr[j + 1] = value;
  }
}

Is my implementation of insertion sort correct ?

Also I would appreciate if you could compare my implementation to the one made by the source I'm learning from, any efficiency differences or any other thing you think would worth mentioning.


texts:
I would love a code review of this LSD radix sort implementation. I've rolled my own, and have implemented counting sort as well. I feel like some of the data structures I've chosen could be improved. My List<List<char[]>>, for instance, is a little gross and makes fiddling with its innards more complex than I think needs to be.

public class LSDSorting {

private static final int DIGIT_RANGE = 5;

public static void main(String[] args) {
    char[][] toSort = new char[][]{"0123".toCharArray(), "1233".toCharArray(), "1212".toCharArray(), "1111".toCharArray(), "4444".toCharArray()};

    int LSD_INDEX = toSort[0].length - 1;
    char[][] sorted = lsdSort(toSort, LSD_INDEX);

    for (char[] str: sorted) {
        System.out.println(String.valueOf(str));
    }
}

private static char[][] lsdSort(char[][] toSort, int d) {
    if (d < 0) {
        return toSort;
    }

    char[][] sortedOnD = runCountingSort(d, toSort, DIGIT_RANGE);
    return lsdSort(sortedOnD, d-1);
}

private static char[][] runCountingSort(int d, char[][] toSort, int range) {
    List<List<char[]>> idx = new ArrayList<>();
    for (int i = 0; i < range; i++) {
        idx.add(i, new ArrayList<char[]>());
    }

    for (int i = 0; i < toSort.length; i++) {
        int currVal = Character.getNumericValue(toSort[i][d]);
        List<char[]> currList = idx.get(currVal);
        if (currList == null) {
            currList = new ArrayList<>();
            idx.add(currVal, currList);
        }
        currList.add(toSort[i]);
    }

    char[][] result = new char[toSort.length][toSort[0].length];
    int currIdx = 0;
    for (int i = 0; i < idx.size(); i++) {
        for (char[] str : idx.get(i)) {
            result[currIdx] = str;
            currIdx++;
        }
    }
    return result;
}
}


texts: Project Euler LCM of 1..20, with some guesswork

texts:
I'm doing a Euler challenge that is stating to find the smallest positive number that is divisible (without a remainder) by all numbers from 1 to 20. So I did it however, I don't like the fact that I have to guess up to which number the while loop have to go (var s.... s < 303000000) and I guess there are too many variables. I'm sure I could get rid of 's'.

var s = 0;
var n = 1;

while (s < 303000000) {
        for (var i=1;i<21;i++) {
                if (n % i != 0) {
                        break;
                }
                if (i == 20) {
                        console.log(n);
                }
        }
        n += 1;
        s += 1;
}


texts:
For a personal programming challenge, I wanted to try writing simple bubble sort and insertion sort functions in Python 3. I haven't looked at the standard pseudo-code, I just read about how they worked. Are these good implementations?

def bubble_sort(array):
    """
    Sorts array using a bubble sort.

    >>> bubble_sort([43, 10, 100, 24, 1, 6, 10, 3])
    [1, 3, 6, 10, 10, 24, 43, 100]
    """
    array2 = array[:] # Save a copy, so that original is not mutated
    last_index = len(array) - 1 # Iterate up to this position
    while last_index > 0:
        for i in range(last_index):
            a, b = array2[i], array2[i + 1] # Consecutive numbers in array
            if a > b:
                array2[i], array2[i + 1] = b, a # Swap positions
        last_index -= 1 # A new number has bubbled up, no need to inspect it again
    return array2

def insertion_sort(array):
    """
    Sorts array using an insertion sort.

    >>> insertion_sort([43, 10, 100, 24, 1, 6, 10, 3])
    [1, 3, 6, 10, 10, 24, 43, 100]
    """
    sorted_array = []
    for a in array:
        # Loop backwards through sorted_array
        for i, b in reversed(list(enumerate(sorted_array))):
            if a > b:
                sorted_array.insert(i + 1, a) # Insert a to the right of b
                break
        else:
            # a is less than all numbers in sorted_array
            sorted_array.insert(0, a) # Add a to beginning of list
    return sorted_array


texts:
The code starts with 128 bits of 0 (size of md5sum checksum) then brute forces to find checksum matching regex (all characters of checksum in hex are digits). I know that there may be collisions and that not all 2^128 possible checksums will come out.

I know that if the code is run, that it will not finish any time soon. I will try to read up on how I can change the for loop into a parallel for loop that uses all CPU cores.

This is one of my first (not very useful) programs in Golang. All constructive feedback welcome.

Output:

0000000000000000000000000092FE92    14275262221639818016075488414463
000000000000000000000000009FF5EA    56052719788687373369347657641554
00000000000000000000000000BA7A1D    25521851964074241922881283516897
00000000000000000000000000E13807    19356247379454983142782955697777
00000000000000000000000000E8C976    64115693827254722796959498140064
00000000000000000000000001037BAD    68461226587668825351060559236884
0000000000000000000000000109658F    87596081213274701373126754303410
...

package main

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
    "regexp"
    "strings"
)

func main() {
    data := []byte("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")

    r, _ := regexp.Compile("^[0-9]{32}$")

    for {
        hash := md5.Sum(data)
        hash_hex_string := hex.EncodeToString(hash[:])

        if (r.MatchString(hash_hex_string)) {
            fmt.Printf("%X    %s\n", data, strings.ToUpper(hash_hex_string))
        }

        if (!increment(data, 15)) {
            break
        }
    }
}

func increment(data []byte, start_pos int) (bool) {
    if (start_pos < 0) {
        return false
    }

    data[start_pos]++

    if (data[start_pos] == 0) {
        return increment(data, start_pos - 1)
    }

    return true
}
```


texts:
I have an array of this fashion:

var arr = ["akira",9248,"padilla",100];

I'm using filter to take the names and the points:

var names = arr.filter(function(e,i){return i%2 == 0});
var points = arr.filter(function(e,i){return i%2 !== 0});

Then I do this to obtain turn it into object:

console.log(JSON.stringify(_.object(names,points)));

What's best in terms of performance/JS quality?


texts:
I am a beginner in coding. I was doing this question today.

  A new movie has been released. Many people are buying tickets which costs 25 dollars. There are many people wanting a ticket but each person has either one of   25 dollar bill, 50 dollar bill or 100 dollar bill.

  People will only come in the order of queue. You initially have no money. Write a program to see if you can sell ticket to everyone or not.

This is my solution

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>

void main()
{  clrscr();
    int queue;
    int bill[100];
    cout<<"Enter number of people in queue:";
    cin>>queue;
    cout<<"\n(Bill value 25/50/100)";
    for (int i=0;i<queue;i++)
    {
        cout<<"Bill person "<<i+1<<" have:";
        cin>>bill[i];
    }
    int bill25=0;
    int bill50=0;
    int bill100=0;
    for(i=0;i<queue;i++)
    {
        if(bill[i]==25)
        {   bill25++;
        }
        else if(bill[i]==50)
        {
            if(bill25>0)
            {
                bill25--;
                bill50++;
            }
            else
            {
                cout<<"No change";
                exit(0);
            }
        }
        else if(bill[i]==100)
        {
            if(bill50>0&&bill25>0)
            {
                bill50--;
                bill25--;
                bill100++;
            }
            else if(bill25>=3)
            {
                bill25-=3;
                bill100++;
            }
            else
            {
                cout<<"No change";
                exit(0);
            }
        }
        else
        {
            cout<<"Wrong bill";
            exit(0);
        }
    }
    cout<<"Tickets sold";
    getch();
}

My testing has found this to be correct (maybe not the best but correct) solution. But I am not sure about it. Are there any possibilities in which this code fails. Also what would be a better solution at my level?


texts:
I have written this class which sorts the array using bubble sort. Please let me know how can I improve it. (I don't like recurrent code in if/else statement)

public class BubbleSort {

public static void numbers(int[] array){
    numbers(array, '<');
}

public static void numbers(int[] array, char direction){
    if(direction == '<'){
        for(int i = 0; i < array.length - 1; i++){
            for(int j = 0; j < array.length - i - 1; j++){

                if(array[j] < array[j + 1]){
                    int tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tmp;
                }
            }
        }
    }
    else{
        for(int i = 0; i < array.length - 1; i++){
            for(int j = 0; j < array.length - i - 1; j++){

                if(array[j] > array[j + 1]){
                    int tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tmp;
                }
            }
        }
    }
}

public static void letters(char[] array){
    letters(array, '<');
}

public static void letters(char[] array, char direction){
    if(direction == '<'){
        for(int i = 0; i < array.length - 1; i++){
            for(int j = 0; j < array.length - i - 1; j++){

                if(array[j] < array[j + 1]){
                    char tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tmp;
                }
            }
        }
    }
    else{
        for(int i = 0; i < array.length - 1; i++){
            for(int j = 0; j < array.length - i - 1; j++){

                if(array[j] > array[j + 1]){
                    char tmp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tmp;
                }
            }
        }
    }
}
}


texts:
I'm trying to get a better grasp on generators in Python because I don't use them enough (I think generators are cool). To do so I wrote a generator for prime numbers:

def primes():
    x = 2
    while True:
        for y in xrange(2, x/2 + 1):
            if x % y == 0:
                break
        else:
            yield x
        x = x + 1

This works as expected but if I use list comprehension to create a list of primes using this generator it's really slow when compared to sieve function that generates the same list:

[prime.next() for i in xrange(1000)] # exectues in 0.212 sec, sieve in 0.001 sec

I'm assuming that this is not the intended purpose of a generator, but I thought I would see if anyone can think of a way to make this faster.


texts: OOP implementation of in-memory file system

texts:
I was working on this problem, where I am constructing a Object Oriented structure of file system where you can have Directories and Files. The Directories could have sub Directories and files.

I have the following layout and I am looking for feedback on improvements or if my approach is wrong.

My OOP design has three different classes Root, Directory and Files

class Root {
    constructor(name, size, writable, parent){
        this.name = name;
        this.size = size;
        this.writable = writable;
        this.parent = parent;
    }

    getName(){
        return this.name;
    };

    setName(val){
        this.name = val;
    }
}

class Directory extends Root{
    constructor(name, size, writable, parent){
        super(name, size, writable, parent);
        this.children = [];
    }

    addContent(obj){
        this.children.push(obj);
    }

    getContent(){
        return this.children;
    }
}

class File extends Root{
    constructor(name, size, writable, parent){
        super(name, size, writable, parent);
    }

    getSize(){
        return this.size;
    }
}

let root = new Root('head', 100, true);
let directory1 = new Directory('sample', 40, true, root);
let file1 = new File('test', 12, true, directory1);
let file2 = new File('test2', 14, true, directory1);
let subDirectory = new Directory('sample2', 40, true, directory1);
directory1.addContent(file1);
directory1.addContent(file2);
directory1.addContent(subDirectory);

console.log(directory1.getContent());


texts: Profitwell API wrapper build as Ruby gem

texts:
I've created my first gem in Profitwell API wrapper https://github.com/eebasadre20/profitwell. I love to get some feedback, comment, or suggestion on the code structure, method implementations, and so on.

I am more concerned in my code structure like how I structured to handle the module and class, the request-response handling, error handling, and parameters handling.

Here is one of the examples of my resource:

module Profitwell
  class Plans
    include Client

    def all
      request(
        "get",
        resource_path("plans")
      )
    end

    def find(plan_id)
      request(
        "get",
        resource_path("plans/#{plan_id}")
      )
    end

    def create(params = {})
      request(
        "post",
        resource_path("plans"),
        options: params
      )
    end

    def update(plan_id, params = {})
      request(
        "put",
        resource_path("plans/#{plan_id}"),
        options: params
      )
    end
  end
end

I would be very pleased if you give me some feedback regarding the code structure and implementation - Profitwell API Wrapper

Everyone is welcome to share your idea and contribute to this simple project.


texts: Using PHP explode() to parse multi-part error messages

texts:
I am dealing with a system which sends any unexpected errors back to me in a string, for example:

Error Type - Database
Error Message - Error Executing Database Something is wrong.
Error Detail - [Macromedia][SQLServer JDBC Driver][SQLServer]Incorrect syntax near '1'.

Now to create a better UI I am expected to deal with these errors, so I thought about using explode(), and found this user's response in the PHP Manual which helped me delimit the results with two delimiters instead of just one:

Then I needed to get a little deeper into the code because I wanted $key => $val pairs, so I came across this answer on StackOverflow.

Then I combined both and came across this solution:

function multiexplode ($delimiters,$string) {

    $ready = str_replace($delimiters, $delimiters[0], $string);

    list($err_typ, $err_typ_cont,
         $err_mess, $err_mess_cont,
         $err_det, $err_det_cont) = explode($delimiters[0], $ready);

    $result[ trim($err_typ) ] = trim($err_typ_cont);
    $result[ trim($err_mess) ] = trim($err_mess_cont);
    $result[ trim($err_det) ] = trim($err_det_cont);
    return  $result;
}

Then I call the function like this:

 multiexplode(array("-", PHP_EOL), $errorMessage)

The response seems to be exactly what I needed:

Array
(
    [Error Type] => Database
    [Error Message] => Error Executing Database Something is wrong.
    [Error Detail] => [Macromedia][SQLServer JDBC Driver][SQLServer]Incorrect syntax near '1'.
)

My question comes with PHP's best practices, and if there would be a more reliable or a more efficient approach I could take into solving this problem?


texts:
Previous question

After applying the suggestions, I wanted to revise the question with the new code because I don't think this is good enough.

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

/* global loop counters */
int i=0, j, k;

/* to find a, b, and c from the input */
float A(const char* in){
    char c[5];
    if(in[0] != 'x'){ /* if first letter isn't x
                      ** eg there is sth in front of x */
        while(in[i] != 'x'){ /* until x in found */
            i++; /* increment i */
        }
        strncpy(c, in, i); /* copy first i characters of in to c */
        return atoi(c); /* make c an int and return */
    }

    if(in[0] == '-' && in[1] == 'x') /* if first two letters are "x" */
        return -1; /* -x = -1 * x */

    return 1; /* if nothing is in front of x, a is 1 */
}

float B(const char* in){
    char c[5];
    int b=1;

    j = i += 3; /* three characters after x (^2+ or ^2-) */
    while(in[j] != 'x') { /* until x is found */
        j++; /*increment j */
    }

    if(in[j-1] != '+' && in[j-1] != '-'){ /* if not -x or +x
                                          ** eg if there is b */
        strncpy(c, in+i, j); /* copy j characters starting from i */
        b = atoi(c); /* make c an int and assign this to b */
    }

    if(in[j-1] == '-') /* if there is a minus sign */
        b = -b; /* negate b */

    return b; /* return b */
}

float C(const char* in){
    char c[5];
    k = j += 1; /* one character after x (+ or -) */
    while(in[k] != '=') { /* until we find a = */
        k++; /* increment k */
    }
    strncpy(c, in+j, k); /* copy k characters starting from j */
    return atoi(c); /* make c an int and return */
}

int main(int argc, char const *argv[]) {
    if(argc == 1){ //if no arguments given
        printf("Usage: %s <quadratic equation>\n", argv[0]);
        return EXIT_FAILURE;
    }

    /* variables for main function */
    float discriminant;
    float a, b, c; /* coefficients */
    float vx, vy; /* vertex */
    char sign; /*positive or negative or zero */

    a=A(argv[1]);
    b=B(argv[1]);
    c=C(argv[1]);

    /*                   b^2 - 4ac     */
    discriminant = pow(b, 2) - 4 * a * c;

    if(discriminant < 0) {
        sign = 'n';
        printf("Parabola doesn't have real roots.\n");
    } else if(discriminant == 0.00f) {
        sign = 'z';
        printf("Parabola has one real root.\n");
    } else if(discriminant > 0) {
        sign = 'p';
        printf("Parabola has two real roots.\n");
    }

    /* vertex points */
    vx = -( b / (2*a) );
    vy = -( discriminant / (4*a) );

    printf("Parabola looks %s\n", a < 0 ? "downwards" : "upwards");
    printf("Vertex: V(%.2f,%.2f)\n", vx, vy);
    printf("Axis of symmetry: %.2f\n", vx);
    printf("y-intercept: %.2f\n", c);

    if(sign=='n'); /* if negative, doesn't have roots */
    else if(sign=='z') /* if zero, root is vertex' abcsissa is root */
        printf("x-intercept: %.2f\n", vx);
    else if(sign=='p'){ /*if positive, roots can be calculated... */
        float x1, x2;
        x1=(-b + sqrt(discriminant)) / (2*a);
        x2=(-b - sqrt(discriminant)) / (2*a);
        printf("x-intercepts: %.2f and %.2f\n", x1, x2);
    }
}


texts: How to approach separation of layers mapping response to model in Angular app?

texts:
I want to organize mapping for my Angular app so that code structure would clear for other developers and I want to have as less code as possible.
I have an api service that is responsible for communicating with API. I create separate data services, which utilize the api service, to get backend data. The same data can be used in different features. I want to provide the data to some feature. But the feature needs a more complex model than backend provides. So, I want to do a complex mapping specific for the particular feature which extends the backend model. But I also do a basic mapping that is required for every feature like property naming ('_name' to 'name') or type converting (string to Date). What is your recommendation on how to approach this?
My current idea is the following. I put the data services in the app/core folder and do the basic mapping on this level. I have feature related models and mapper services in the app/feature folders. It looks OK in terms of separation of concerns. But I have doubts about the number of mapping functions and services. Looks wordy, doesn't it?
app/core/lesson
lesson-dto.model.ts
export interface LessonDto {
    id: string;
    _departmentId: string;
    begin: string;
    end: string;
}

get-lessons-response.model.ts
export interface GetLessonsResponse {
    lessons: LessonDto[];
}

lesson.model.ts
export interface Lesson {
    id: string;
    departmentId: string;
    begin: Date;
    end: Date;
}

lesson-basic-mapping.ts
export function mapLessonDtoToLesson(lessonDto: LessonDto): Lesson {
    return {
        id: lessonDto.id,
        departmentId: lessonDto._departmentId,
        begin: new Date(lessonDto.begin),
        end: new Date(lessonDto.end)
    };
}

lesson.data.service.ts
export class LessonDataService {

    constructor(private readonly apiService: ApiService) { }

    public getLessons(
        departmentId: string
    ): Observable<Lesson[]> {
        const requestUrl = `/departments/${departmentId}/lessons`;

        return this.apiService.get(requestUrl).pipe(
            map((response: GetLessonsResponse) => response.lessons
                .map(mapLessonDtoToLesson))
        );
    }
}

app/features/schedule
schedule-lesson.model.ts
export interface ScheduleLesson {
    id: string;
    name: string;
    begin: Date;
    end: Date;
    description: string;
}

scheduler-mapping.ts
export function mapLessonToScheduleLesson(lesson: Lesson): ScheduleLesson {
    return {
        id: lesson.id,
        name: calculateName(lesson.id, lesson.departmentId),
        begin: new Date(lessonDto.begin),
        end: new Date(lessonDto.end),
        description: doSomeOtherComplexMappingHere(lesson.departmentId)
    };
}

lesson-mapped-data.service.ts
export class LessonMappedDataService {

    constructor(private readonly lessonDataService: LessonDataService) { }

    public getLessons(
        departmentId: string
    ): Observable<ScheduleLesson[]> {
        return this.lessonDataService.get(departmentId).pipe(
            map((lessons: Lesson[]) => lessons
                .map(mapLessonToScheduleLesson))
        );
    }
}

One more thing that concerns me is that the more models I have or the longer they are the more similar code I have. I did some analysis. I like the approach with decorators. It looks similar to Newtonsoft in C# and hides the implementation of basic mapping. But it requires some hacky solutions to align it with TypeScript. And the feature of decorators is still unclear. So, I don't use it.
Do you have any ideas on how to make the code better (more clear and less to read)? And what do you think of the file/folder structure?
Thank you in advance.


texts: RegExp selecting strings surrounded by brackets

texts:
My purpouse is to select every character which is surrounded by { and }, this is easily achievable using this regexp {\w*}.

I've developed an extenstion method for strings:

    public static IEnumerable<string> ObtainTokens(this string originalString)
    {
        Regex expression = new Regex(@"{\w*}");
        foreach (Match element in expression.Matches(originalString))
        {
            //Exclude the brackets from the returned valued
            yield return Regex.Replace(element.Value, @"{*}*", "");
        }
    }

Is there a way to get rid of of Regex.Replace?
Returning the values as IEnumerable is a good choice?


texts: Knapsack problem with duplicate elements

texts:
I solved the knapsack problem where duplicates elements are allowed:

  Given weights and values related to n items and the maximum capacity allowed for these items. What is the maximum value we can achieve if we can pick any weights any number of times for a total allowed weight of W?

  input:

  W = 10

  weight = [2,3,6,4]

  cost = [3,4,6,10]

  output:

  23

I have written this code. Is there any way to improve it?

def knapsack(W, weight, cost):
    #import pdb; pdb.set_trace()
    table = [0] * (W+1)
    for w in xrange(W+1):
        max_so_far = 0
        for i, wt in enumerate(weight):
            if wt <= w:
                cur = cost[i] + table[w-weight[i]]
                if cur > max_so_far:
                    max_so_far = cur
        table[w] = max_so_far
    print table
    return table[W]

weight = [2,3,6,4]
cost = [3,4,6,10]
print knapsack(10,weight,cost)


texts:
Write a program that reads two integers start and end from the user
  and prints the number from start to end inclusive. However, If end was
  less than start than you should print them in descending order.

public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);

    int start = scan.nextInt();
    int end = scan.nextInt();

    if(start < end)
        for(int i = start; i <= end; i++)
            System.out.print(i + " ");

    else if(start > end)
        for(int i = start; i >= end; i--)
            System.out.print(i + " ");
}


texts: Drawing dragon curves using Turtle graphics

texts:
This is exercise 3.2.23. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Write a recursive Turtle client that draws dragon fractal.
The following is the data-type implementation for Turtle graphics from the book which I beautified:
public class Turtle {
    private double x;
    private double y;
    private double angle;

    public Turtle(double x, double y, double angle) {
        this.x = x;
        this.y = y;
        this.angle = angle;
    }
    public void turnLeft(double delta) {
        angle += delta;
    }
    public void goForward(double step) {
        double oldX = x, oldY = y;
        x += step * Math.cos(Math.toRadians(angle));
        y += step * Math.sin(Math.toRadians(angle));
        StdDraw.line(oldX, oldY, x, y);
    }
}

StdDraw is a simple API written by the authors of the book.
Here is my program:
public class Dragon {
    public static void drawDragonCurve(int n, double step, Turtle turtle) {
        if (n == 0) {
            turtle.goForward(step);
            return;
        }
        drawDragonCurve(n - 1, step, turtle);
        turtle.turnLeft(90);
        drawNodragCurve(n - 1, step, turtle);

    }
    public static void drawNodragCurve(int n, double step, Turtle turtle) {
        if (n == 0) {
            turtle.goForward(step);
            return;
        }
        drawDragonCurve(n - 1, step, turtle);
        turtle.turnLeft(-90);
        drawNodragCurve(n - 1, step, turtle);
    }
    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        double step = Double.parseDouble(args[1]);
        Turtle turtle = new Turtle(0.67, 0.5, 0);
        drawDragonCurve(n, step, turtle);
    }
}

I checked my program and it works. Here is one instance of it:
Input: 12 0.007
Output:

Is there any way that I can improve my program?
Thanks for your attention.


texts: Mark a radio element as selected on page load and when clicked

texts:
I have the following javascript that calls a function on page load and on click of an element on my page. Is this the cleanest way to do this?

StyleSelectedPlan();

$(document).on('click', '.select-plan', function () {
    StyleSelectedPlan();
});

function StyleSelectedPlan() {
    $('.radio-wrapper').removeClass('selected');
    $('.select-plan:checked').closest('.radio-wrapper').addClass('selected');
}


texts: Styling navigationController per viewController

texts:
The design of my application consists of multiple viewControllers which all have different styling applied to them. The following code is used in every viewController to style the viewController:

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        self.title = "PROFILE"

        self.navigationController?.view.backgroundColor = .white
        self.navigationController?.navigationBar.tintColor = self.view.tintColor

        navigationController?.navigationBar.barStyle = .default

        tabBarController?.tabBar.isTranslucent = false
        tabBarController?.tabBar.backgroundColor = .white
        tabBarController?.tabBar.tintColor = .black
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        self.navigationController?.navigationBar.tintColor = .white
        self.navigationController?.view.backgroundColor = UIColor.clear
        self.navigationController?.navigationBar.barStyle = .blackTranslucent

        self.navigationController?.navigationBar.shadowImage = UIImage()
    }

Some properties change per VC, for example the backgroundColor of the VC. This code is copy pasted in every VC I make with small changes, which causes a lot of duplicate code etc. Is there a design pattern which allows me to create the styling of every VC more conveniently?


texts: Repetitive unit tests for a programming language

texts:
I've got a recreational regex-based programming language called Retina. Before the next big refactoring of the interpreter, I want to rework how I test the code. The interpreter class works such that it's instantiated once with the program (provided as a list of strings, which usually but not necessarily are all single lines) and can then be run several times on different inputs.

I'd like to make use of this in the new test suite so that I can specify tests by defining a program once and then testing a bunch of input/output pairs on it. Virtually all tests will be written this way, and there will be a lot of them, so I'd like to be able to set this up with as little syntactic overhead as possible which might distract from the programs and I/O pairs. Here's what I'm currently doing. I've got a base class for my test cases:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Retina;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace RetinaTest
{
    [TestClass]
    public class RetinaTestBase
    {
        protected void AssertProgram(List<string> sources, List<(string input, string output)> ioPairs)
        {
            var interpreter = new Interpreter(sources);

            foreach ((var input, var expectedOutput) in ioPairs)
            {
                var actualOutput = new StringWriter();
                interpreter.Execute(input, actualOutput);

                Assert.AreEqual(expectedOutput, actualOutput.ToString());
            }
        }
    }
}

In the derived test classes I can then simply do:

namespace RetinaTest
{
    [TestClass]
    public class ReplaceStageTest : RetinaTestBase
    {
        [TestMethod]
        public void TestBasicReplacement()
        {
            AssertProgram(
                new List<string> {
                    "a",
                    "x"
                },
                new List<(string, string)> {
                    ( "abc", "xbc" ),
                    ( "Hello, World!", "Hello, World!" ),
                    ( "banana", "bxnxnx" )
                }
            );
            /* etc */
        }
    }
}

A List of string tuples seemed like the natural type for the I/O pairs, but I find the constructor is almost too much in terms of overhead. I'm tempted to turn them both into arrays and let the compiler infer the type with new[], or even provide the I/O pairs as an even-length variadic argument list. That seems like bad style to me though because I could easily mess up the pairing if I forget a string somewhere. Not using C# very regularly I'm also not too clear on the exact benefits and shortcomings of the various list types (in this case mainly lists and plain arrays).

Is there a way to set this up which is both idiomatic and requires very little visual overhead beyond specifying a program (as a list of strings) and a list of I/O pairs? I'd be happy about any other criticism of the code as well, of course.


texts:
I wrote this class to use a C++ function as hardware interrupt handler. The idea is to have a single entry point where I can switch stacks, and call a chain of std::function objects to handle the interrupt.

It works... but I think it's a pretty ugly hack. Is there anything I could improve here?

class __attribute__((packed)) interrupt_wrapper
{
    using function_ptr = void(*)(unsigned);
    unsigned int_vector;            // [eax-0x1C]
    selector ds;                    // [eax-0x18]
    selector es;                    // [eax-0x16]
    selector fs;                    // [eax-0x14]
    selector gs;                    // [eax-0x12]
    function_ptr entry_point;       // [eax-0x10]
    std::array<byte, 0x40> code;    // [eax-0x0C]

public:
    interrupt_wrapper(unsigned vec, function_ptr f) : int_vector(vec), entry_point(f)
    {
        byte* start;
        std::size_t size;
        asm volatile (
            ".intel_syntax noprefix;"
            "jmp interrupt_wrapper_end%=;"
            // --- \/\/\/\/\/\/ --- //
            "interrupt_wrapper_begin%=:;"   // On entry, the only known register is CS.
            "push ds; push es; push fs; push gs; pusha;"    // 7 bytes
            "call get_eip%=;"  // call near/relative (E8)   // 5 bytes
            "get_eip%=: pop eax;"           // Pop EIP into EAX and use it to find our variables
            "mov ds, cs:[eax-0x18];"        // Restore segment registers
            "mov es, cs:[eax-0x16];"
            "mov fs, cs:[eax-0x14];"
            "mov gs, cs:[eax-0x12];"
            "push cs:[eax-0x1C];"           // Pass our interrupt number along
            "call cs:[eax-0x10];"           // Call the entry point
            "add esp, 4;"
            "popa; pop gs; pop fs; pop es; pop ds;"
            "sti;"                          // IRET is not guaranteed to set the interrupt flag.
            "iret;"
            "interrupt_wrapper_end%=:;"
            // --- /\/\/\/\/\/\ --- //
            "mov %0, offset interrupt_wrapper_begin%=;"
            "mov %1, offset interrupt_wrapper_end%=;"
            "sub %1, %0;"                   // size = end - begin
            ".att_syntax prefix"
            : "=r" (start)
            , "=r" (size));
        assert(size <= code.size());

        auto* ptr = memory_descriptor(get_cs(), start).get_ptr<byte>(); // Get near pointer to cs:[start]
        std::copy_n(ptr, size, code.data());

        asm volatile (
            ".intel_syntax noprefix;"
            "mov ax, ds;"
            "mov bx, es;"
            "mov cx, fs;"
            "mov dx, gs;"
            ".att_syntax prefix"
            : "=a" (ds)
            , "=b" (es)
            , "=c" (fs)
            , "=d" (gs));
    }

    auto get_ptr(selector cs) { return far_ptr32 { cs, reinterpret_cast<std::size_t>(code.data()) }; }
};


texts: Verifying password strength using JavaScript

texts:
I have a function which verifies the "Password" field and suggests the user to enter a strong password.  I also have a label named "Password Strength", referring to the strength of a password (very weak, weak, medium, etc).

I'm just wondering if there is a better way to re-write this code.

function chkPasswordStrength(txtpass,strenghtMsg,errorMsg)
   {
     var desc = new Array();
     desc[0] = "Very Weak";
     desc[1] = "Weak";
     desc[2] = "Better";
     desc[3] = "Medium";
     desc[4] = "Strong";
     desc[5] = "Strongest";

     errorMsg.innerHTML = ''
     var score   = 0;

     //if txtpass bigger than 6 give 1 point
     if (txtpass.length > 6) score++;

     //if txtpass has both lower and uppercase characters give 1 point
     if ( ( txtpass.match(/[a-z]/) ) && ( txtpass.match(/[A-Z]/) ) ) score++;

     //if txtpass has at least one number give 1 point
     if (txtpass.match(/\d+/)) score++;

     //if txtpass has at least one special caracther give 1 point
     if ( txtpass.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/) ) score++;

     //if txtpass bigger than 12 give another 1 point
     if (txtpass.length > 12) score++;

     strenghtMsg.innerHTML = desc[score];
     strenghtMsg.className = "strength" + score;

  if (txtpass.length < 6)
  {
  errorMsg.innerHTML = "Password Should be Minimum 6 Characters"
  errorMsg.className = "errorclass"
  }

   }

<%= label "Password",:mandatory=>true %>

<input id="user_password" type="password" size="30" name="user[password]"  onkeyup="chkPasswordStrength(this.value,document.getElementById('strendth'),document.getElementById('error'))">

Password Strength


texts:
A simple concept yet I seem to have written it in a complicated way.

I have written some C++ source code that should:

read in a file
parse it
save the data to a class
print out all the saved class data

I am absolutely new to C++ and OOP and Programming and English.

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>

class Person {
private:
    int age;
    std::string name;

public:
    void setAge(int age) {
        this->age = age;
    }

    int getAge() {
        return age;
    }

    void setName(std::string name) {
        this->name = name;
    }

    std::string getName() {
        return name;
    }

    void printInfo() {
        std::cout
            << "Name: " << getName() << '\n'
            << "Age: " << getAge() << '\n';
    }
};

std::istream& operator>> (std::istream& is, Person& person) {
    int age;
    is >> age;

    std::string name;
    is >> name;

    person.setAge(age);
    person.setName(name);

    return is;
}

int main() {
    auto myfilename = "unknown-people.txt";

    std::ofstream myfile(myfilename, std::ios::binary | std::ios::trunc);
    myfile << "3 Baby\n";
    myfile << "48 Linus Torvalds\n";
    myfile << "62 Bill Gates\n";
    myfile << "115 Kane Tanaka\n";
    myfile.close();

    std::ifstream mysamefile(myfilename, std::ios::binary);

    std::string details;
    std::vector<Person> people;

    while (std::getline(mysamefile, details)) {
        Person person;
        std::istringstream personDetails(details);
        personDetails >> person;
        people.push_back(person);
    }

    mysamefile.close();

    for (std::vector<Person>::iterator it = people.begin(); it != people.end(); ++it) {
        it->printInfo();

        if (!(it != people.end() && it == --people.end())) {
            std::cout << "\n\n";
        }
    }
}


texts:
I previously discussed the performance concerns about different GCD algorithms. I wrote a simple Java class that implements the Binary GCD algorithm. It is a really tiny class that has only two easy-to-use methods. See for yourself:

GCD.java

package math;

/**
 * This is a utility class that provides the functionality of calculating the
 * GCD or Greatest Common Divisor (also known as HCF or Highest Common
 * Factor) of two or more integers.
 *

 * It has only two methods:
 *

 *
{@link #of(long, long)}

 *
{@link #of(long, long, long...)}

 *

 * Usage is very simple:
 *

 * ...
 * // assuming a, b, c, d and e are integers (long, int, etc.)
 * long gcd1 = GCD.of(a, b);
 * long gcd2 = GCD.of(a, b, c);
 * long gcd3 = GCD.of(a, b, c, d);
 * long gcd4 = GCD.of(a, b, c, e);
 * ...
 *

 *
 * @author Subhomoy Haldar
 * @version 1.0
 */
public class GCD {

    /**
     * Private constructor to prevent instantiation.
     */
    private GCD() {
        throw new Error("Instantiation not allowed.");
    }

    /**
     * This method computes the GCD of two positive integers using the Binary
     * GCD algorithm.
     *

     * This method does not complain if the integers provided are negative.
     * In such a case, it simply the absolute value and performs the
     * computation. If one of the arguments is zero, the other argument is
     * returned. If both are zero, then zero is returned.
     *
     * @param a The first positive integer.
     * @param b The second positive integer.
     * @return The GCD of two positive integers.
     */
    public static long of(long a, long b) {
        // corner cases
        if (a == 0) return b;
        if (b == 0) return a;
        if (a < 0) a = -a;
        if (b < 0) b = -b;
        // number of tailing zeroes = power of 2 present
        int a0 = Long.numberOfTrailingZeros(a);
        int b0 = Long.numberOfTrailingZeros(b);
        // extract the the number of trailing zeroes common to them
        int commonPower = a0 < b0 ? a0 : b0;
        // make them odd
        a >>>= a0;
        b >>>= b0;
        while (a != b) {
            if (a > b) {
                a -= b;
                a >>>= Long.numberOfTrailingZeros(a);
            } else {
                b -= a;
                b >>>= Long.numberOfTrailingZeros(b);
            }
        }
        return a << commonPower; // multiply back the common power of 2
    }

    /**
     * This method returns the GCD of all the integers provided.
     *

     * This method makes use of the {@link #of(long, long) of(long, long)}
     * method.
     *
     * @param a      The first positive integer.
     * @param b      The second positive integer.
     * @param others The other positive integers.
     * @return The GCD of all the integers provided.
     * @see #of(long, long) Internally used by this method.
     */
    public static long of(long a, long b, long... others) {
        long gcd = of(a, b);
        for (long number : others) {
            gcd = of(gcd, number);
        }
        return gcd;
    }
}

I welcome comments on any aspect of the code. This class will be reused in future questions.


texts:
The program starts at the center of the screen and starts drawing a line in 50ms steps. When the line hits the edge of the terminal it will be reflected and continue drawing. steps takes the number of drawing steps to perform before finishing while until-key finishes on a key press.

Apart from the lack of comments, what would I need to do to make this "good" Forth and how would I change it to fit in one screen (16 lines of 64 chars)?

variable h
variable w
: height h @ ;
: width  w @ ;

variable point-var
cell allot
: point ( offset -- addr ) cells point-var + ;

variable direction-var
cell allot
: dir ( offset -- addr ) cells direction-var + ;

: init ( -- )
    rows h !
    cols w !
    width  2 / 0 point !
    height 2 / 1 point !
    1 0 dir !
    1 1 dir ! ;

: reflect-top ( -- t/f )
    1 point @ 0= dup if 1 1 dir ! then invert ;
: reflect-bot ( -- t/f )
    1 point @ height 1 - = if -1 1 dir ! then ;
: reflect-left ( -- t/f )
    0 point @ width 1 - = if -1 0 dir ! then ;
: reflect-right ( -- t/f )
    0 point @ 0= dup if 1 0 dir ! then invert ;
: reflect ( -- )
    reflect-top if reflect-bot then
    reflect-right if reflect-left then ;

: draw-point ( -- ) [char] # emit ;

: move-x ( -- n ) 0 point @ 0 dir @ + dup 0 point ! ;
: move-y ( -- n ) 1 point @ 1 dir @ + dup 1 point ! ;
: move-xy ( -- ) move-x move-y at-xy ;

: try ;

: step ( -- )
    try reflect
    move-xy draw-point ;

: steps ( n -- )
    init
    page
    0 do step 50 ms loop ;

: until-key ( n -- )
    init
    page
    begin step 50 ms key? until ;


texts:
I have a jQuery code that helps me to scroll to specific sections on mouse scroll. To handle mouse scroll events I am using the jQuery mousewheel plugin.

    function goTo(location) {
        $('html,body').animate({
            scrollTop: $(location).offset().top
        }, 'slow');
         };
    //Mouse Wheel
// My code is repeating consistently below these line
    $('#slides').on('mousewheel', function(event) {
        event.preventDefault();
        if (event.originalEvent.wheelDelta >= 0) {} else {
            //console.log('Scroll down');
            goTo("#rev_slider_2_1");
        }
    });
    $('#rev_slider_2_1').on('mousewheel', function(event) {
        event.preventDefault();
        if (event.originalEvent.wheelDelta >= 0) {
            goTo("#slides");
        } else {
            //console.log('Scroll down');
            goTo("#clients");
        }
    });

    $('#clients').on('mousewheel', function(event) {
        event.preventDefault();
        if (event.originalEvent.wheelDelta >= 0) {
            goTo("#rev_slider_2_1");
        } else {
            //console.log('Scroll down');
            goTo("#slider");
        }
    });

I want to simplify and make this code shorter so that I no longer need to use the same code again and again. I just want to know how I can create a function that helps me to just pass the parameters and then do my required task.


texts: Synesthesia for the rest of us (i.e. algorithm for unique string colorization)

texts:
I'd like to form an algorithmic connections between  a particular string and and a particular color, in such that each unique string is always the same color.

My particular use case is for a kiosk where each user should immediately notice if someone else is logged in, so my strings are employee first names. Reinforcing this visually by assigning each user a different color. And yes I know i could just build a list or add a property to the user object but this is more fun. Here's my current approach:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    float r = 0;
    float g = 0;
    float b = 0;
    var name = value as string;
    if (name.IsNullOrEmpty()) return new SolidColorBrush(Colors.Black);
    var pos = 0;

    foreach (var letter in name)
    {
        var index = letter % 32;
        if (pos == 0) r = (float)index / AlphabetLength;
        if (pos == 1) g = (float)index / AlphabetLength;
        b = (float)index / AlphabetLength;
        pos++;
    }

    return new SolidColorBrush(Color.FromScRgb(1f, r, g, b));
}

private const int AlphabetLength = 26;

Kind of came up with this quickly so there are a bunch of weaknesses. What do you think?


texts: Depth First Search Implementation (iterative)

texts:
Here is my code for Depth First Search and, as far as I know, it is working fine on most cases. It is not very efficient as I have implemented it for the very first time..

Warning: It is only for bi-directional Graphs or Trees.. And it is not searching anything, just traversing. I think searching should be easy if it is traversing correctly..

def DFS(matrix,x):
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            if matrix[i][j]=="farigh" or matrix[i][j]=="hogya":
                matrix[i].pop()

    stack = [x]
    Matrix=matrix
    print(Matrix)
    dimen=len(Matrix)
    rslt = [x]
    while stack:
        current=Matrix[stack[-1]-1]
        for j in range(len(current)):

                if current[j]==1 :
                    a=False
                    if (j+1 not in stack) and (j+1 not in rslt):
                        stack.append(j+1)
                        rslt.append(j+1)
                        print("stack",stack)
                        a= True
                        break
                if j+1== len(current):
                    current.append("farigh")

        if len(Matrix[stack[-1]-1]) == dimen and a == True :
            b=0
            current2= Matrix[stack[-1]-1]

            for e in range(len(current2)):
                if current2[e]==1:
                    b=b+1
            if b==1:
                stack.pop()
                current2.append("Hogya")

        if current[-1]=="farigh":
            stack.pop()

        print(stack,"stack")
    return(rslt,"rslt")

Let me know if you find any bugs.


texts: Is this form submission validator professional?

texts:
I have written some jQuery code for AJAX form submission:

jQuery(function() {
    jQuery('#message').click(function() {
        var btn = jQuery(this)
        var Name = jQuery("#Name").val();
        var Email = jQuery("#Email").val();
        var Sub = jQuery("#Sub").val();
        var Message = jQuery("#Message").val();
        if (Name == "") {
            jQuery('#Name').focus();
            jQuery("#Name").after('');
        }
        else if (Email == "") {
            jQuery("#Email").focus();
            jQuery("#Email").after('');
        }
        else if (Sub == "") {
            jQuery("#Sub").focus();
            jQuery("#Sub").after('');
        }
        else if (Message == "") {
            jQuery("#Message").focus();
            jQuery("#Message").after('');
        }
        else if (!validateEmail(Email)) {
            jQuery("#Email").focus();
        }
        else {
            btn.button('loading')
            $.ajax({
                url: '/application',
                dataType: 'text',
                type: 'post',
                data: {querytype: 'form', name: Name, email: Email, sub: Sub, message: Message},
                success: function(data)
                {
                    jQuery('#success').fadeIn();
                }
            });
        }
    });
});

Is this code good to go? Or it can be improved?  I have seen this where they check the validation after form submission, or this.

Should I check validation before or after submission?

Will my approach be good if I need to handle 10+ input elements?


texts:
The problem of finding the first all zero row in a NxN matrix was featured in a letter to the CACM in 1974 by Frank Rubin who claimed it was a problem for which using a GOTO was better than alternatives.

But many languages have labeled break statements and other features that make the problem trivial. In fact, in JavaScript we need only write:

a.findIndex(row => row.every(x => x === 0))

which gives us the index of the first nonzero row or -1 if no such row exists. I'm interested in implementing this functional approach in C++ 14. As I don't have a huge amount of C++ experience, I came up with:

#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>
using namespace std;

bool isAllZeroRow(const vector<int>& row) {
  return all_of(row.begin(), row.end(), [](int x){return x==0;});
}

int firstAllZeroIndex(const vector<vector<int>>& m) {
  return distance(m.begin(), find_if(m.begin(), m.end(), isAllZeroRow));
}

vector<vector<int>> matrix1 = {{1, 2}, {0, 0}, {1, 1}};
vector<vector<int>> matrix2 = {{0, 0, 1, 2}, {3, 0, 0}, {0, 0, 0}};
vector<vector<int>> matrix3 = {{0, 0, 1, 2}, {3, 0, 0}, {0, 0, 5}};

int main() {
  assert(firstAllZeroIndex(matrix1) == 1);
  assert(firstAllZeroIndex(matrix2) == 2);
  assert(firstAllZeroIndex(matrix3) == 3); // not found
  cout << "ok\n";
}

I'm interested in hearing things like:

whether the lambda is okay, or should it be a named function or a C++ unary predicat
Are distance and find_if best expressed with iterators like I have done here?
Was it right to use the helper function, or is there a way in C++ to make things almost as concise as the JavaScript solution?

I know how to do this function with nested loops with a return in the inner loop, but I'm intrigued by trying out the functional forms and was wondering how I did.


texts:
I am using Python with libtcodpy to build a turn-based strategy game.

In this game each unit has a maximum range which varies from 4-10. This range determines how many "steps" the unit can take and therefore the distance it can move on the game map.

I wish to output all the squares which the unit can move to, based upon its range as well as variable terrain, which increases the number of steps necessary to move over it.

This function is what I have to generate these squares and it works but is intolerably slow (takes about 1-2 seconds for the squares to highlight on the map):

#Gets a list of all the squares the unit can move to (so that they
#can be highlighted later)
def get_total_squares(max_range, playerx, playery, team):

    global coord_in_range   #List where the final coords will be stored
    global T_Map    #Instance of the Map class, i.e the map

    #This iterates through an area of the game map defined by the square
    #created by the player's maximum range (where the player is in the center
    #of the square)
    for x in range((playerx-max_range), (playerx+max_range+1)):
        for y in range ((playery-max_range), (playery+max_range+1)):
            #This creates a path for every square in the above area
            path = libtcod.path_new_using_map(new_map, 0)
            #This computes a path to every square in the above area
            libtcod.path_compute(path, playerx, playery, x, y)
            #This gives the number of steps the unit takes to walk one specific path
            num_steps = libtcod.path_size(path)
            #This is a blank list which will be populated with the coordinates of
            #the tiles of one specific path
            coord_of_path = []

            #This populates the above list
            for i in range(libtcod.path_size(path)):
                coord_of_path.append(libtcod.path_get(path, i))

            #This is a list of all the tiles in the map which can hinder movement
            #henceforth called "terrain_tiles"
            terrain_tiles = [tile for tile in T_Map.tile_array
                                if tile.terrain_name in ('Tall Grass', 'Hills', 'Forest', 'Water')]

            #This iterates through all the "terrain tiles" and
            #if the tile is in the path, adds that tiles movement penalty
            #to the total number of steps to take that path
            for tile in terrain_tiles:
                if (tile.x, tile.y) in coord_of_path:
                    num_steps += tile.move_cost

            #This is what actually determines whether the path is added to the
            #list of walkable paths; if the path's step count, taking into account
            #modifications from terrain, is greater than the unit's range that path is not added
            if num_steps <=max_range:
                for i in range(libtcod.path_size(path)):
                    coord_in_range.append(libtcod.path_get(path, i))

    return coord_in_range

I'm quite certain something in here is acting as a bottleneck and very certain it has something to do with adjusting the paths due to terrain, since if I do it without considering terrain, it runs very fast.

If the full code is necessary (I don't think it should be as, stated above, the problem must lie here) I will post it.


texts: Function to validate parameter and throw exception when invalid

texts:
I've asked a question receiving excessive (in a good sense) feedback. After I've incorporated it into the code, it changed substantially and I felt that I'd need opinion on the new version. Posting revised code is against the rules, so I'm asking a new, follow-up question.

Choice of exception names. Are those informative enough?.
Introduction of tiered exceptions. Are more levels of inner exceptions needed?).
Omission of the values. Should I provide the faulty ones?

Code

private static void Validate(Guid userId, EntityState state, object data)
{
  if (userId == Guid.Empty)
    throw new IdentityNotMappedException("Token unrecognized!",
      new ArgumentException("Can't be Guid.Empty or null!", nameof(userId)));
  if (state == EntityState.Detached)
    throw new InvalidOperationException("Action unrecognized!",
      new ArgumentException("Must follow C_UD!", nameof(state)));
  if (data == null)
    throw new MappingException("Data unrecognized!",
      new ArgumentException("Must be deserializeable!", nameof(data)));
}


texts: Transforming XML as it is being generated on a scanner

texts:
At work I've recently been tasked with creating an XSLT to transform some XML as it is being generated on a scanner. The point being to disregard some pages that we are not interested in for further processing, and this is what I've come up with:

    <?xml version="1.0" encoding="utf-8"?>
       <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
       xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">

     <xsl:output method="xml" indent="yes"/>
     <xsl:strip-space elements="*"/>

    <!-- Do an indentity transform for all root nodes/attributes -->
    <xsl:template match="@* | node()">
      <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
      </xsl:copy>
    </xsl:template>

    <!-- Strip out the sheet with RETURN barcode by replacing it with nothing (blank template) -->
    <xsl:template match="Page[contains(Fields/Barcode, 'RETURN')]" />

    <!-- Check if there is a page containing RETURN in the barcode field.
       If yes append 'return' to all barcodes
       If no just copy everything -->
    <xsl:template match="Barcode">
       <xsl:choose>
         <xsl:when test="count(../../../Page[Fields/Barcode[contains(text(), 'RETURN')]]) > 0">
            <xsl:element name="Barcode">
              <xsl:value-of select="concat(ancestor::Page/Fields/Barcode, 'Return')"/>
            </xsl:element>
          </xsl:when>
        <xsl:otherwise>
         <xsl:copy>
           <xsl:apply-templates select="@* | node()"/>
         </xsl:copy>
       </xsl:otherwise>
     </xsl:choose>
    </xsl:template>
   </xsl:stylesheet>

Running on XML files with the following simplified structure, the actual files have around 100-3000 pages on average with some 40 fields under Fields:

<Data>
  <Batch>
    <Page>
      <Fields>
        <Barcode>|||||||||||</Barcode>
      </Fields>
    </Page>
    <Page>
      <Fields>
        <Barcode>|RETURN|||||||||</Barcode>
      </Fields>
    </Page>
    <Page>
      <Fields>
        <Barcode>||5454|||||||||</Barcode>
      </Fields>
    </Page>
  </Batch>
</Data>

It is working, but I'm a bit worried about the Barcode template running too slow as it must be \$O(n^2)\$. A quick profiling showed my concern to be correct.

Hot path during execution

As this will be running on somewhat limited hardware, does anyone have any suggestions for improvements?


texts: Simple Hangman game - first Python project

texts:
I created a basic Hangman game that uses a text file to select a secret word. Are there any areas for improvement?

import random

secret_word = ['']
user_list = []
number_of_tries = 5
guessed_letters = []
user_tries = 0
user_guess = ''

def select_word():
    global secret_word, user_list
    with open('secret_words.txt', 'r') as f:
        word = f.read()
        word_list = word.split('\n')
        secret_word = word_list[random.randint(1, len(word_list))]
        user_list = ['-'] * len(secret_word)

def game_over():
    if user_tries == number_of_tries or user_list == list(secret_word):
        return True
    else:
        return False

def user_input():
    global user_guess
    user_guess = input('Guess a letter\n')
    check_guess(user_guess)

def repeated(guess):
    global guessed_letters
    if guess in guessed_letters:
        print('You already guessed that letter!\n')
        return True
    else:
        guessed_letters.append(user_guess)
        return False

def check_guess(guess):
    correct_guess = False
    for x in range(len(secret_word)):
        if guess == secret_word[x]:
            user_list[x] = guess
            correct_guess = True
        elif not correct_guess and x == len(secret_word)-1:
            global user_tries
            user_tries += 1
            print('Wrong guess, you lose one try\n'
                  'Remaining tries : {}\n'.format(number_of_tries - user_tries))
    if correct_guess:
        print('Correct guess!')

def valid_input(user_letter):
    valid_letters = 'qwertyuiopasdfghjklzxcvbnm'
    if user_letter.lower() in list(valid_letters):
        return True
    else:
        print('Invalid input')
        return False

# main code:

print('----HANG MAN----')
print('*Welcome, guess the word\n*you have 5 tries.')
select_word()

while not game_over():
    for x in user_list:
        print(x, end='')
    user_guess = input('\nGuess a letter : ')
    if valid_input(user_guess):
        if repeated(user_guess):
            continue
        else:
            check_guess(user_guess)

if user_list != list(secret_word):
    print('Game over, you died!\ncorrect word was {}'.format(secret_word))
else:
    print('Congratulations! you guessed the correct word\n')


texts:
Simple algorithm based HackerRank challenge.

  The Utopian tree goes through 2 cycles of growth every year. The first
  growth cycle of the tree occurs during the monsoon, when it doubles in
  height. The second growth cycle of the tree occurs during the summer,
  when its height increases by 1 meter.  Now, a new Utopian tree sapling
  is planted at the onset of the monsoon. Its height is 1 meter. Can you
  find the height of the tree after N growth cycles?

  Input Format
  The first line contains an integer, T, the number of
  test cases.  T lines follow. Each line contains an integer, N, that
  denotes the number of cycles for that test case.

  Constraints
  1 <= T <= 10  0 <= N <= 60

  Output Format
  For each test case, print the height of the Utopian
  tree after N cycles.

Test Cases can be found at HackerRank

static int[] LifeCycle(int[] input)
{
    int[] output = new int[input.Length];
    for (int i = 0; i < input.Length; i++)
    {
        int lifeCycleCount = Convert.ToInt32(input[i]);
        if (lifeCycleCount == 0)
        {
            output[i] = 1; //no growth
        }
        else
        {
            var treeHeight = 1;
            for (int j = 0; j < input[i]; j ++)
            {
                if (j % 2 == 0)
                {
                    treeHeight = treeHeight + treeHeight; //Monsoon Growth
                }
                else
                {
                    treeHeight++; //Summer Growth
                }
            }
            output[i] = treeHeight;
        }
    }
    return output;
}
static void Main(String[] args) {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */

    int howMany = Convert.ToInt32(Console.ReadLine());
    int[] input = new int[howMany];
    for (int i = 0; i < howMany; i++)
    {
        input[i] = Convert.ToInt32(Console.ReadLine());
    }

    int[] result = LifeCycle(input);
    for (int i = 0; i < result.Length; i++)
    {
        Console.WriteLine(result[i].ToString());
    }
}

Simple enough, but do I really need to use all the if statements and for loops?

I passed all the tests they put the code through (0.08s on each, total of 9 tests)


texts:
I want to create a modular website with no frameworks or CMS nor server-side language.
Also, I am doing simple use of the hashchange event to help the navigation.

The structure would be as follows:

A basic container HTML page with 3 main areas: header, content, footer.
Individual HTML files - one for each page - which would contain only the HTML to be inserted in the content part
a JavaScript file with all the code needed
a CSS file with all the styling

Please bear in mind that all the code below has been cleaned to illustrate the concept: the real code is more complex (e.g. the content of the header and the footer might as well be loaded with AJAX calls, some manipulations might occur to the DOM after the content has been put in place, handling AJAX failures, and so on).

A sample version of the HTML for the container page would be like:

<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Faux SPA</title>
    <link rel="stylesheet" href="styles.css"/>

    <button onclick="setPageHash('Page1')">View 1</button>
    <button onclick="setPageHash('Page2')">View 2</button>

A couple of sample HTML files for the content (obviously, the real-world content would be more complex):

Page1.html:

And Page2.html:

    Some text content

    second line of text content

Finally, the JavaScript code would be like:

var validHashes = ["Page1", "Page2"];
function page(pageName){
    var newPageURI = pageName + ".html";
    var container = "#content";
    $.ajax(newPageURI).done(
        function(content) {
            putContentInContainer(container, content);
            setPageHash(pageName);
        }
    );
}
function putContentInContainer(container, content) {
    $(container).html(content)
}
function loadPageFromHash() {
    var hashValue = window.location.hash || "";
    var hashIsValid;
    hashValue = hashValue.replace('#','');
    hashIsValid = (validHashes.indexOf(hashValue)>=0);
    if (hashIsValid) {
        page(hashValue);
    } else {
        console.error("no valid HASH!");
    }
}
function setPageHash(page) {
    window.location.hash = page;
}
window.onhashchange = loadPageFromHash;
$().ready(function() {
    loadPageFromHash();
});

So, my questions are:

Is there any disadvantage in loading the HTML this way?
I know that the HTML files with the content will not be valid HTML files because of the missing tags (e.g. body, html, etc.): would that represent a problem?
Is there anything else I am missing for the whole hashchange subject?


texts:
I'm making an iOS app which supports multiple languages but not in the built-in localized way. In iOS, for localization to work, the user has to change the device's language. But in the app I'm working on, the user needs to be able to choose the language to effect only this app. So for example, I can have the device's language set to English but the user can choose Spanish to be set as the language within the app.

I took some concepts from iOS localization and added some things on my own. First I created plists to contain strings for each language I support.

English

Spanish

Next I created a singleton which handles the setting on the chosen language and serving the strings based on that selected language. I use a third-party library called SwiftyPlist for easier manipulation of plists.

enum Language: String {
    case english = "en"
    case spanish = "es"
}

class LanguageManager {
    static let shared = LanguageManager()

    private var plist: Plist!

    // Get/Set the language of choice
    var language: Language? {
        set {
            UserDefaults.standard.set(newValue?.rawValue, forKey: "Language")
            reloadPlist()
        }
        get {
            if let code = UserDefaults.standard.object(forKey: "Language") as? String {
                return Language(rawValue: code)
            } else {
                return nil
            }
        }
    }

    private init() {
        reloadPlist()
    }

    // Reload the corresponding plist
    private func reloadPlist() {
        if language == nil || language! == .english {
            let dict = NSDictionary(contentsOfFile: Bundle.main.path(forResource: "English", ofType: "plist")!)
            plist = Plist(plistObject: dict)
        } else if language! == .spanish {
            let dict = NSDictionary(contentsOfFile: Bundle.main.path(forResource: "Spanish", ofType: "plist")!)
            plist = Plist(plistObject: dict)
        }
    }

    var name: String {
        return plist["YOUR_NAME"]!.string!
    }

}

Now I can set the chosen language like this.

LanguageManager.shared.language = .spanish

And I can simply access the strings like so.

LanguageManager.shared.name

I feel like this is a good, scalable approach to my requirement. But I'd like to see if it has room to improvement.

Demo project


texts:
I have implemented a splash screen, to hold/pause the screen for few seconds and then launch the next screen. I am very enthusiastic to know if there is a more basic way to write the code.

public class SplashActivity extends BaseActivity {

    private final int SPLASH_TIME_OUT = 2000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        Thread splashTimerThread = new Thread() {
            public void run() {
                try {
                    Thread.sleep(SPLASH_TIME_OUT);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                } finally {
                    Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
                    startActivity(intent);
                }
            }
        };
        splashTimerThread.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        finish();
    }
}


texts:
I know there must be an easier way to write this but I'm stuck in over-complicating mindset instead of just following the Zen of Python. Please help me simplify this.

  Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and
  a boolean indicating if we are on vacation, return a string of the
  form "7:00" indicating when the alarm clock should ring. Weekdays, the
  alarm should be "7:00" and on the weekend it should be "10:00". Unless
  we are on vacation -- then on weekdays it should be "10:00" and
  weekends it should be "off".

alarm_clock(1, False) → '7:00'
alarm_clock(5, False) → '7:00'
alarm_clock(0, False) → '10:00'

def alarm_clock(day, vacation):

    weekend = "06"
    weekdays = "12345"
    if vacation:
        if str(day) in weekend:
            return "off"
        else:
            return "10:00"
    else:
        if str(day) in weekend:
            return "10:00"
        else:
            return "7:00"


texts:
I have an HTML table and I use jQuery to fade some content for each TD:

Demo

My code works great, but I want to know if my solution can be better.

Inserer un produit

Inserer un nv crédit

    Afficher les produits
    Afficher les crédits courante

jQuery

$( "#first" ).click(function() {
if( $("#Element2" ).show || $("#Element3" ).show || $("#Element4" ).show){
    $("#Element2").hide();
    $("#Element3").hide();
    $("#Element4").hide();
}
$( "#Element1" ).fadeToggle("slow");
});
$( "#second" ).click(function() {
if( $("#Element1" ).show || $("#Element3" ).show || $("#Element4" ).show){
    $("#Element1").hide();
    $("#Element3").hide();
    $("#Element4").hide();
}
$( "#Element2" ).fadeToggle( "slow");
});
$( "#third" ).click(function() {
if( $("#Element1" ).show || $("#Element2" ).show || $("#Element4" ).show){
    $("#Element1").hide();
    $("#Element2").hide();
    $("#Element4").hide();
}
$( "#Element3" ).fadeToggle( "slow");
});
$( "#fourth" ).click(function() {
if( $("#Element1" ).show || $("#Element2" ).show || $("#Element3" ).show){
    $("#Element1").hide();
    $("#Element2").hide();
    $("#Element3").hide();
}
$( "#Element4" ).fadeToggle( "slow");
});


texts: Is this the best approch to combine 2 Interfaces?

texts:
I have a use case where I want to use both HttpRequestInterceptor and HttpResponseInterceptor in one class.

I'm asking if the following would be a good solution and what are the potential problems?

public interface HttpRequestResponseInterceptor extends HttpRequestInterceptor, HttpResponseInterceptor {}

Then I implement this interface:

public class AuthenticatingResponseInterceptor implements HttpRequestResponseInterceptor{

  private static final String TAG = AuthenticatingResponseInterceptor.class.getSimpleName();

  @Inject
  private Authenticator authenticator;
  @Inject
  private CookieStore cookieStore;
  @Inject
  private RequestCache requestCache;

  @Override
  public void process(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException {
    //Implementation
  }

  @Override
  public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    //Implementation
  }
}

The part I am unsure about it is when I pass this into 2 separate methods:

@Inject
private HttpRequestResponseInterceptor interceptor;

httpClient.addResponseInterceptor(interceptor);
httpClient.addRequestInterceptor(interceptor);

I should probably point out that the HttpRequestResponseInterceptor is a singleton. Is this a good solution?


texts:
Hacker News recently released an official API. Unfortunately, it cannot be used to get the newest posts submitted. I wrote a script to provide a faux streaming-api like method (like praw reddit's submission_stream) so that I can simply put it in a loop and do something like make a gtk-notification when title contains the string 'python'.

"""
Usage:

from hn import HNStream

h = HNStream()

for item in h.stream():
    print "Title: ", item.title
    print "By user: ", item.by
"""

from lxml import html as lh
import re
import requests
import threading
import time
import ujson as json

__all__ = ['HNStream']

class Item:

    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

    def __str__(self):
        return "{}: {}".format(self.type, self.title)

    __repr__ = __str__

class HackerNews:

    def __init__(self):
        self.base_url = 'https://hacker-news.firebaseio.com/v0/{api}'

    def get(self, uri):
        response = requests.get(uri)
        if response.status_code == requests.codes.ok:
            return json.loads(response.text)
        else:
            raise Exception('HTTP Error {}'.format(response.status_code))

    def item(self, item_id):
        uri = self.base_url.format(**{'api': 'item/{}.json'.format(item_id)})
        return Item(**self.get(uri))

class SimpleFIFO:

    def __init__(self, length):
        self.length = length
        self.values = length * [None]

    def contains(self, iid):
        return iid in self.values

    def append(self, value):
        assert isinstance(value, str), "Only append strings"
        self.values.append(value)
        while len(self.values) > self.length:
            self.values.pop(0)
        assert len(self.values) == self.length

    def __str__(self):
        return str(self.values)

class HNStream(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def stream(self):

        itembuffer = SimpleFIFO(length=30)
        while True:
            r = requests.get('https://news.ycombinator.com/newest')
            tree = lh.fromstring(r.text)
            # http://stackoverflow.com/a/2756994
            links = tree.xpath("//a[re:match(@href, 'item\?id=\d+')]/@href",
                               namespaces={"re": "http://exslt.org/regular-expressions"})
            links = set(links)
            for link in links:
                iid = re.match(r'item\?id=(\d+)', str(link)).groups()[0]
                if not itembuffer.contains(iid):
                    itembuffer.append(iid)
                    yield HackerNews().item(iid)
            time.sleep(30)


texts:
I have two arrays

dates = ["20161010","20161013"]
values = [5,3]

which represent dates and a view count. To display them in a graph, I also need the values between the dates, which are 0:

["20161010","20161011","20161012","20161013"]
[5,0,0,3]

I came up with a fairly complicated solution:

dates = ["20161010","20161013"]
values = [5,3]
first_date = Date.new(Integer(dates.first[0..3]), Integer(dates.first[4..5]), Integer(dates.first[6..7]))
last_date = Date.new(Integer(dates.last[0..3]), Integer(dates.last[4..5]), Integer(dates.last[6..7]))

# create a continous range
range = (first_date..last_date).to_a.map {|d| d.strftime("%Y%m%d")}
# store the indexes of the original dates inside the new range
date_idxs = dates.map {|d| range.index(d) }

# create a zero filled array with length of our range
filled_values = Array.new(range.length, 0)

values.each_with_index do |value,idx|
  idx_in_filled_values = date_idxs[idx]
  filled_values[idx_in_filled_values] = value
end

puts range # ["20161010", "20161011", "20161012", "20161013"]
puts filled_values # [5, 0, 0, 3]

I think thats not a good solution. Any ideas on how to improve the code? Or a completely different approach?


texts:
Any suggestions on how to improve this code (other than arbitrary call-stack depth)?

#include <iostream>
#include <vector>

template <typename T>
void merge(const std::vector<T>& left, const std::vector<T>& right, std::vector<T>& merged)
{
    auto i = left.begin();
    auto j = right.begin();
    auto k = merged.begin();

    while (i != left.end() && j != right.end())
    {
        *k = (*i < *j) ? *i : *j;
        if (*i < *j) ++i;
        else ++j;
        ++k;
    }
    while (j != right.end())
    {
        *k = *j; ++k; ++j;
    }
    while (i != left.end())
    {
        *k = *i; ++k; ++i;
    }
}

template <typename T>
void merge_sort(std::vector<T>& A)
{
    if (A.size() <= 1) return;
    size_t mid = A.size() / 2;
    std::vector<T> left(A.begin(), A.begin() + mid);
    std::vector<T> right(A.begin() + mid, A.end());
    merge_sort(left);
    merge_sort(right);
    merge(left,right, A);
}

int main()
{
    std::vector<int> input = {19, 14, 17, 16, 12, 9, 15, 1, 2, 11, 7, 3, 10, 14};
    std::vector<int> sorted = {1, 2, 3, 7, 9, 10, 11, 12, 14, 14, 15, 16, 17, 19};
    bool success = true;
    merge_sort(input);
    for (size_t i = 0; i < input.size(); ++i) if ( input[i] != sorted[i] ) success = false;
    std::cout << "Merge sort " << (success ? "passed\n" : "failed\n");
}


texts:
I'm using JDK 11.

This is my code:

public class ReferenceService {

    private final transient Cache<String, Reference> cache;
    private final transient EntityManager entityManager;

    public ReferenceService(
        Cache<String,Reference> cache,
        EntityManager entityManager
    ) {
        this.cache = cache;
        this.entityManager = entityManager;
    }

    public Optional<Reference> get(String id) {
        return Optional.ofNullable(this.cache.get(id))
            .or(() -> Optional.ofNullable(this.entityManager.find(Reference.class, id)));
    }
}

I would like to know to write this code again in order to it's more elegant:

return Optional.ofNullable(this.cache.get(id))
    .or(() -> Optional.ofNullable(this.entityManager.find(Reference.class, id)));

I guess I'm using too much Optional.ofNullable each time I need to get a reference from cache or from persistence layer.

ADITIONAL CODE

private <T> Cache<String, T> getOrCreateCache(String name, Class<T> type) {
    Cache<String, T> cache = cacheManager.getCache(name, String.class, type);

    if (cache == null) {
        CompleteConfiguration<String, T> config =
            new MutableConfiguration<String, T>()
                .setTypes(String.class, type);

        cache = cacheManager.createCache(name, config);
    }

    return cache;
}


texts:
As C# doesn't have generic specialisation like C++ template specialisation and I wanted a way to be able to do it, I came up with a little hack that goes a bit like this:

    public sealed class Specialisation<T>
    {
        private Specialisation() { }
        private static Specialisation<T> instance = new Specialisation<T>();
        public static Specialisation<T> Instance { get { return instance; } }
    }
    public interface ISpecialisable<T>
    {
        T SpecialisedMethod(Specialisation<T> t);
    }
    public class Specialised : ISpecialisable<int>, ISpecialisable<float>
    {
        public double Value;
        public int SpecialisedMethod(Specialisation<int> t) { return (int)Value; }
        public float SpecialisedMethod(Specialisation<float> t) { return (float)Value; }
    }
    public static class Program
    {
        public static void Main()
        {
           Specialised s = new Specialised();
           s.Value = 12.3456789;
           Console.WriteLine(s.SpecialisedMethod(Specialisation<int>.Instance));
           Console.WriteLine(s.SpecialisedMethod(Specialisation<float>.Instance));
           Console.ReadKey();
        }
    }

Other than this not being the 'right way' to do things and being a complete mistreatment of the method overloading system, are there any possible side effects that could happen as a result of this horrible hack?

EDIT:

An applied example of specialisation in such a manner:

    // assume Specialisation is unchanged
    public interface IConvertible<T> // Not to be confused with System.IConvertible
    {
        T Convert(Specialisation<T> t);
    }
    public class ConvertMe : IConvertible<int>, IConvertible<float>
    {
        public double Value;
        public int Convert(Specialisation<int> t) { return (int)Value; }
        public float Convert(Specialisation<float> t) { return (float)Value; }
    }
    public static class Program
    {
        public static void Main()
        {
           ConvertMe c = new ConvertMe();
           c.Value = 12.3456789;
           Console.WriteLine(c.Convert(Specialisation<int>.Instance));
           Console.WriteLine(c.Convert(Specialisation<float>.Instance));
           Console.ReadKey();
        }
    }

EDIT:
Another example I just thought of as an extension of/alternative to the IConvertible<T> example. This technique allows the normal generic method syntax to be used externally, whilst allowing the class developer to internally define specialisations.

public interface IConvertible<T>
{
    T Convert(Specialisation<T> t);
    T Convert<T>();
}
// assume Specialisation<T> is unchanged
public class ConvertMe : IConvertible<int>, IConvertible<float>
{
    public double Value;
    int IConvertible<int>.Convert(Specialisation<int> t) { return (int)Value; }
    float IConvertible<float>.Convert(Specialisation<float> t) { return (float)Value; }
    public T Convert<T>() { return ((IConvertible<T>)this).Convert(Specialisation<T>.Instance); }
}
public static class Program
{
    public static void Main()
    {
        ConvertMe c = new ConvertMe();
        c.Value = 12.3456789;
        Console.WriteLine(c.Convert<int>());
        Console.WriteLine(c.Convert<float>());
        Console.ReadKey();
    }
}

This use of specialisation could be generalised to other applications in order to provide specialised behaviour. I won't add any more examples as the ones provided are long enough as it is, and I'm sure everyone here has the skill and imagination to find other applications of this pattern.


texts:
I wrote some code a few weeks ago, to take a string similar to

  seq[]=8&seq[]=7&seq[]=5&seq[]=1&seq[]=4&seq[]=3&seq[]=6&seq[]=0&seq[]=2

and put it into a gallery, to be ordered by jQuery UI's Sortable, which works all good, however, I'm concerned about the amount of times I .Replace the values in the string.

This code has been bugging me, because I'm employed to rewrite unethical code, and the few times I actually write code from scratch, it looks like this. So, basically, I would love your opinions on this code.

To clarify, the imgMgr is to get the JSON string, and the nodelist is for getting an XML doc of images from the imgMgr.

#region BuildGallery
private void BuildGallery()
{

    StringBuilder sb = new StringBuilder();

    sb.Append("
<button class=\"js-serialize\" style=\"border: 0;height: 25px;background-color: #F4FA58;margin-bottom: 8px;\">Save Layout</button>

");
    int pos = 0;
    string str = "";
    ImageManagerV1 imgMgr = new ImageManagerV1();
    str = imgMgr.galleryOrder(LocalConfig.ImageManagerAuthCode, Convert.ToInt32(hdnListingId.Value), "");
  //  str = "seq[]=8&seq[]=7&seq[]=5&seq[]=1&seq[]=4&seq[]=3&seq[]=6&seq[]=0&seq[]=2";
    str.Replace("seq[]=","-").Split('-');
    XmlNodeList nodelist = xmlDoc.SelectNodes("image");
    str = str.Replace("&", "");
    if (str == "") {
        for (int i = 0; i < nodelist.Count; i++) {
            str += "seq[]=" + i;
        }
    }
    string[] strNew = str.Replace("seq[]=", "-").Split('-');
        str = "";
        for (int i = 0; i < strNew.Length; i++) {
            if (strNew[i] != "") {
                str += "-" + strNew[i];
            }
        }
    if (nodelist.Count > strNew.Length) {
        for (int f = strNew.Length; f < nodelist.Count; f++) {
            str += "-" + f;
        }
    }
    int val2 = 0;
    string[] stringArray = str.Split('-');
    foreach (string num in stringArray) {
        var newNum = num.ToString();
        if (newNum.Length > 0) {
            val2 = Convert.ToInt32(newNum);
            XmlNode image = nodelist[val2];
            string thumbpath = image.Attributes["thumb"].Value;
            string detailpath = image.Attributes["detail"].Value;
            string fileName = detailpath.Substring(detailpath.LastIndexOf(@"/") + 1);
            sb.AppendFormat("
", val2);
            sb.AppendFormat("Make HeroDel", thumbpath, detailpath, listing.ListingName, pos, fileName);
            sb.Append("
");
        }
    }
    sb.Append("

");
        if (sb.Length > 0)
        {
            litGallery.Text = string.Format("
{0}
", sb.ToString());
        }
    }
#endregion


texts:
I need to implement a queue of requests which can be populated from multiple threads. When this queue becomes larger than 1000 completed requests, these requests should be stored into a database.

public class RequestQueue
{
    private static BlockingCollection<VerificationRequest> _queue = new BlockingCollection<VerificationRequest>();
    private static ConcurrentQueue<VerificationRequest> _storageQueue = new ConcurrentQueue<VerificationRequest>();

    private static volatile bool isLoading = false;
    private static object _lock = new object();

    public static void Launch()
    {
        Task.Factory.StartNew(execute);
    }

    public static void Add(VerificationRequest request)
    {
        _queue.Add(request);
    }

    public static void AddRange(List<VerificationRequest> requests)
    {
        Parallel.ForEach(requests, new ParallelOptions() {MaxDegreeOfParallelism = 3},
            (request) => { _queue.Add(request); });
    }

    private static void execute()
    {
        Parallel.ForEach(_queue.GetConsumingEnumerable(), new ParallelOptions {MaxDegreeOfParallelism = 5}, EnqueueSaveRequest );
    }

    private static void EnqueueSaveRequest(VerificationRequest request)
    {
        _storageQueue.Enqueue( new RequestExecuter().ExecuteVerificationRequest( request ) );
        if (_storageQueue.Count > 1000 && !isLoading)
        {
            lock ( _lock )
            {
                if ( _storageQueue.Count > 1000 && !isLoading )
                {
                    isLoading = true;

                    var requestChunck = new List<VerificationRequest>();
                    VerificationRequest req;
                    for (var i = 0; i < 1000; i++)
                    {
                        if( _storageQueue.TryDequeue(out req))
                            requestChunck.Add(req);
                    }
                    new VerificationRequestRepository().InsertRange(requestChunck);

                    isLoading = false;
                }
            }
        }
    }
}

Is there any way to implement this without lock and isLoading?


texts: Is there a way to make this code simplier?

texts:
Program description:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

My solution:
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
  let N = nums.length;
  for(i=0;i<=N-1;i++) {
      for(j=i+1;j<=N;j++) {
          if(nums[i] + nums[j] == target) {
              return [i,j];
          };
      };
  };
};

Test input:
[2,7,11,15]
9

Test output:
[0,1]

Test summary:
Solution accepted.
Runtime: 84ms

Question: is there a way to make this code look more neat using some comprehensions, maybe also improving its runtime? Thank you in advance.