texts: Getting CSS files based on production or development

texts:
I have the below script which returns CSS files based on production or development environment. The development section is fine; but for production I have to do 2 loops to get the files. Is there a cleaner/better way?

function get_css_files()
{
   $CI =& get_instance();
    $return = array();

    $css_files = array(
        array('path' =>'css/jquery.gritter.css', 'media' => 'all', 'group' => '1.css'),
        array('path' =>'css/jquery-ui.css', 'media' => 'all', 'group' => '1.css'),
        array('path' =>'css/bootstrap-select.css', 'media' => 'all', 'group' => '1.css'),
        array('path' =>'css/select2.css', 'media' => 'all', 'group' => '1.css'),
        array('path' =>'css/font-awesome.min.css', 'media' => 'all', 'group' => '1.css'),
        array('path' =>'css/jquery.loadmask.css', 'media' => 'all', 'group' => '1.css'),
        array('path' =>'css/token-input-facebook.css', 'media' => 'all', 'group' => '1.css'),
        array('path' =>'css/KeyTips.min.css', 'media' => 'all', 'group' => '1.css'),
        array('path' =>'css/bootstrap-colorpicker.min.css', 'media' => 'all', 'group' => '2.css'),
        array('path' =>'css/jquery.ml-keyboard.css', 'media' => 'all', 'group' => '2.css'),
    );
    if(!defined("ENVIRONMENT") or ENVIRONMENT == 'development')
    {
        $return = $css_files;
    }
    else
    {
        $groups = array();

        foreach($css_files as $css)
        {
            $groups[$css['group']] = TRUE;
        }

        foreach(array_keys($groups) as $css_group_file)
        {
            $return[] = array('path' =>"css/$css_group_file", 'media' => 'all');
        }
    }

    if(is_rtl_lang())
    {
        $return[] = array('path' =>'css/rtl.css', 'media' => 'all');
    }
    return $return;
}


texts:
Trying to learn coding in my 30s.

Could anybody review my code and give me some feedback if possible? It works, but I am sure there are better ways to solve this problem.

The problem:

A text is given. Write a program that modifies the casing of letters to uppercase at all places in the text surrounded by <upcase> and </upcase> tags. Tags cannot be nested.

Here is what I've come up with:

namespace Task6Casing
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Text: ");
            string text = Console.ReadLine();

            char[] textNew = new char[text.Length];

            int i = 0, j = 0, k = 0;

            while (i < text.Length)
            {
                if (text.IndexOf("<upcase>", k) < 0)            // check if there is any <upcase> tag
                {                                               // if no, copy everyting
                    while (i < text.Length)
                    {
                        textNew[j++] = text[i++];
                    }
                }
                else
                {
                    while (i < text.IndexOf("<upcase>", k))     // if there is an <upcase> tag, copy letters until the tag
                    {
                        textNew[j++] = text[i++];
                    }

                    i += 8;                                     // move index i to the position right next to the <upcase> tag
                    k = i;
                }

                if (text.IndexOf("</upcase>", k) < 0)           // check if there is any </upcase> tag
                {                                               // if no, copy everyting in CAPITAL letters
                    while (i < text.Length)
                    {
                        textNew[j++] = Char.ToUpper(text[i++]);
                    }
                }
                else
                {
                    while (i < text.IndexOf("</upcase>", k))    // if there is an </upcase> tag, copy letters in CAP letters until the tag
                    {
                        textNew[j++] = Char.ToUpper(text[i++]);
                    }

                    i += 9;                                     // move index i to the position right next to the </upcase> tag
                }
            }

            foreach(char c in textNew)
            {
                Console.Write(c);
            }
            Console.WriteLine();

        }
    }
}


texts:
I'd like to optimize my code and get a better of understanding of how I can perform the task I am doing better. I've only used Perl threads about 3 or 4 times now.

The purpose of my script / code block is to scrape the Pastebin API for every new public paste that appears at regular intervals using a crontab. Then search inside those new pastes for user defined regular expressions such as "google.com." The paste is then saved to a sqlite DB for later viewing and a notification is sent to a listening nodejs bot.

That being said here is my code block I wish to have improved upon:

sub threadCheckKey {
    my ($url, $key, @regexs) = @_;
    my $fullURL = $url.$key;
    my @flaggedRegex = ();
    my $date = strftime "%D", localtime;
    my @data = ();

    my $thread = threads->create(sub {
        my $dbConnection = openDB();
        open(GET_DATA, "-|", "curl -s " . $fullURL . " -k") or die("$!");
        open(WRITE_FILE, ">", $key . ".txt") or die("$!");
        while(my $line = <GET_DATA>) {
            print WRITE_FILE $line;
            foreach my $regex(@regexs) {
                if($line =~ m/$regex/) {
                    if(!(grep(/$regex/, @flaggedRegex))) {
                        push(@flaggedRegex, $regex);
                    }
                }
            }
        }
        close(WRITE_FILE);
        close(GET_DATA);

        my $flaggedSize = @flaggedRegex;
        if($flaggedSize == 0) {
            #Uncomment below for debugging.
            #print "No user defined regex found\n";
            return;
        }

        open(READ_FILE, "<", $key . ".txt") or die("$!");
        while(my $line = <READ_FILE>) {
            push(@data, $line);
        }
        close(READ_FILE);

        my $inputData = join("\r", @data);
        my $flaggedReg = join(" | ", @flaggedRegex);
        my $updateRow = qq(UPDATE $tables[0] set data = ?, date = ?, regex = ? where pastekey = ?);
        my $updateRowPrepare = $dbConnection->prepare($updateRow);
        my $executeRowUpdate = $updateRowPrepare->execute($inputData, $date, $flaggedReg, $key);

        if($executeRowUpdate < 0) {
            print $DBI::errstr;
        }

        my $msg = qq(**Alert:** New paste found! The paste can be viewed via https://pastebin.com/$key - Regex Trigger: $flaggedReg);

       open(SEND_ALERT, "-|", "curl https://localhost:8051/bots/bot_service_id/alert -k --data '{\"text\":\"$msg\"}' -H \"Content-Type: application/json\" -X POST") or die("$!");
        close(SEND_ALERT);

        $dbConnection->disconnect();
    });

    if($thread->is_running()) {
        sleep(2);
    }

    if($thread->is_joinable()) {
        $thread->join();
    }

    unlink $key . ".txt";
    return;
}


texts:
I've decided to write some Linux commands in Python. Below is a list, along with some constraints (if you're unfamiliar with Linux, the top of the program along has a description about each command and what it does):

ls: No constraints, just lists all files/directories in current working directory. No flags.
cd: Can only pass .. or another directory. No flags.
tree: No flags or directories can be passed.
clear: No constraints. No flags.
whatis: Only defined commands can be passed. No flags.
cat: Requires a full path to the file. No flags.

I would like feedback on all the functions embodied by the program below, but whatis in particular. I feel there is a better way than checking each individual function. Any and all recommendations are appreciated.

"""
This is a program to simulate a command line interface

Commands to reimplement:
    - ls ( lists all files and directories in current directory )
    - cd [directory] ( changes directory )
    - tree ( lists all files, directories, sub directories and files from current directory )
    - clear ( clears the console screen )
    - whatis [command] ( gives a description about the command )
    - cat [file] ( outputs the content of the file )
"""

import os

def ls() -> None:
    """
    Lists all files and directories in current directory
    """
    current_directory = os.getcwd()
    for _, directories, files in os.walk(current_directory):
        for file in files:
            print(file)
        for directory in directories:
            print(directory)

def cd(directory: str) -> str:
    """
    Changes directory
    """
    current_directory = os.getcwd()

    if directory == "..":
        current_directory = current_directory.split("/")[:-1]
        current_directory = ''.join(f"{x}/" for x in current_directory)
        return current_directory
    if os.path.isdir(directory):
        return directory
    return "Not a directory"

def tree() -> None:
    """
    Lists all files, directories, sub directories and files from current directory
    """
    current_directory = os.getcwd()
    tab_count = 1
    print(current_directory.split("/")[-1])
    for _, directories, files in os.walk(current_directory):
        for file in files:
            print("|" + ("-" * tab_count) + file)
        for directory in directories:
            print("|" + ("-" * tab_count) + directory)
        tab_count += 1

def clear() -> None:
    """
    Clears the console screen
    """
    print("\n" * 100)

def whatis(command: str) -> None:
    """
    Prints a description about the passed command
    """
    if command == "ls":
        print(ls.__doc__)
    elif command == "cd":
        print(cd.__doc__)
    elif command == "tree":
        print(tree.__doc__)
    elif command == "clear":
        print(clear.__doc__)
    elif command == "whatis":
        print(whatis.__doc__)
    elif command == "cat":
        print(cat.__doc__)
    else:
        print("Not a valid command!")

def cat(file_path: str) -> None:
    """
    Accepts a path to a file, and outputs the contents of that file
    """
    if os.path.exists(file_path):
        with open(file_path, "r") as file:
            print(''.join(line for line in file))
    else:
        print("Not a file!")


texts:
I have the following code, that defines:

A polynomial struct with some useful functions.
The newton Raphson algorithm for polynomials.

and calculates sqrt(2).
What can I improve?

There are some things I am unsure about myself:

Is size_t a good datatype for my purposes? I needed to be very careful when writing the loop condition in the eval function. Is this a good place to switch to signed arithmetics?
Is my definition of my_nan a good way to ensure portability when switching to another floating point type?

Things I am aware of:
I know, that the Newton Raphson for polynomials does not require the explicit construction of a derived polynomial and I am a bit wasteful on the memory.

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

typedef double real;
const real my_nan = ((real) 0.0) / ((real) 0.0);

typedef struct Polynomial {
    real* coeffs;
    size_t capacity;
} Polynomial;

Polynomial* create_poly(size_t capacity)
{
    real* coeffs;

    coeffs = malloc(capacity * sizeof(real));
    if (coeffs == NULL) return NULL;

    Polynomial* poly = malloc(sizeof(Polynomial));

    if (poly == NULL) {
        free(coeffs);
        return NULL;
    }
    poly->coeffs = coeffs;
    poly->capacity = capacity;

    return poly;
}

void delete_poly(Polynomial* p)
{
    free(p->coeffs);
    free(p);
    p = NULL;
}

size_t deg(const Polynomial*const p)
{
    for (size_t i = p->capacity - 1; i > 0; i--) {
/* Here we actually want to compare reals exactly instead of |a - b| < eps */
        if (p->coeffs[i] != 0.0) return i;
    }
    return 0;
}

void print(const Polynomial*const p)
{
    size_t i;
    for (i = 0; i < deg(p); ++i) {
        printf("%f * x^%zu + ", p->coeffs[i], i);
    }
    printf("%f * x^%zu\n", p->coeffs[i], i);
}

real eval(const Polynomial*const p, real x)
{
/* Use Horner Scheme for evaluation */
    size_t i = deg(p);
    real res = p->coeffs[i];

    for (; i-- > 0;) {
        res = res * x + p->coeffs[i];
}
    return res;
}

Polynomial* derive(const Polynomial*const p)
{
    Polynomial* Dp = create_poly(p->capacity);
    if (Dp == NULL) return NULL;

    for (size_t i = 1; i < p->capacity; ++i) {
        Dp->coeffs[i - 1] = ((real) i) * p->coeffs[i];
    }
    return Dp;
}

real newton_raphson_poly(const Polynomial*const p, real x0, real eps)
{
    Polynomial* Dp = derive(p);
    real x, prev = x0;
    const int max_iter = 100;

    for (int i = 0; i < max_iter; ++i) {
        x = prev - eval(p, prev) / eval(Dp, prev);
        if (fabs(x - prev) < eps) {
            return x;
        } else {
            prev = x;
        }
    }

    return my_nan;
}

int main()
{
    Polynomial* p;
    const real EPS = pow(10, -7);
    p = create_poly(3);

    p->coeffs[0] = -2;
    p->coeffs[1] = 0;
    p->coeffs[2] = 1;

    printf("The result of sqrt(2) is given by the root of\n");
    print(p);
    printf("Its value is: %f \n", newton_raphson_poly(p, 1.0, EPS));

    delete_poly(p);
}
```


texts: Generating a password to save to a .txt file

texts:
Here is my basic password generator which saves your password to a .txt file which you can choose the name of etc.

import random
import string
import os.path
#random numbers section
num1 = random.randrange(100,999)
number_section =  num1
#random letters section
string.letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()'
let1 = random.choice(string.letters)
let2 = random.choice(string.letters)
let3 = random.choice(string.letters)
let4 = random.choice(string.letters)
let5 = random.choice(string.letters)
let6 = random.choice(string.letters)
let7 = random.choice(string.letters)
let8 = random.choice(string.letters)
letters_section = let1 + let2 + let3 + let4 + let5 + let6 + let7 + let8
#letters and numbers combination
password = str(number_section) + letters_section
#input section
password_for = raw_input('This password is for: ')
your_pass =  'Your password for' + ' ' + password_for + ' ' + 'is:' + ' ' + password
print your_pass
#save section
save_path = 'C:\Users\Charles\Desktop\Passes'
name_of_file = raw_input("What is the name of the file: ")
completeName = os.path.join(save_path, name_of_file+".txt")
file1 = open(completeName, "w")
toFile = your_pass
file1.write(toFile)
file1.close()

This will make a .txt file with a line such as:

  Your password for IBM bluemix is: 451juoxQYky

How can I make it 'stronger'? Are there any major holes in it? How can I make it more compact?

This is just a personal project I'm doing to improve my python knowledge.


texts: Implementing faster StringBuilder that only works with ASCII strings

texts:
I wrote a StringBuilder that works only with ASCII strings. the current append performance is almost identical to BCL StringBuilder append performance. I want some tips on how to make it faster, and general tips about the code. I did this for educational purposes.

Implementation:

public sealed class FastStringBuilder
{
    private byte[] chars;

    public int Length { get; private set; }

    public FastStringBuilder(int capacity)
    {
        chars = new byte[capacity];
    }

    public FastStringBuilder()
    {
        chars = new byte[16];
    }

    private void GrowBy(int length)
    {
        var temp = chars;
        chars = new byte[length];
        Array.Copy(temp, 0, chars, 0, Length);
    }

    public unsafe void Append(string str)
    {
        if (str.Length + Length >= chars.Length)
            GrowBy((str.Length + Length) * 4);
        else if(Length == chars.Length)
            GrowBy(chars.Length*2);

        fixed (char* p = str)
        {
            for (int i = 0; i < str.Length; i++)
                chars[Length++] = (byte)(p + i);
        }
    }

    public override string ToString()
    {
        unsafe
        {
            fixed (byte* bp = chars)
            {
                return new string((sbyte*)bp,0,Length);
            }
        }
    }
}

Performance tests spec:

public static void StringBuilderTest()
{
    Stopwatch sw = Stopwatch.StartNew();

    StringBuilder builder = new StringBuilder();

    for (int i = 0; i < 1000000; i++)
    {
        builder.Append("F0000000000000000000000000000000000000000000000000000" );
    }

    var result = builder.ToString();

    Console.WriteLine(sw.Elapsed);
}

Results:

Compiled in release mode.

FastStringBuilder: ~0.36 seconds
StringBuilder: ~0.27 seconds
FasterStringBuilder (ChrisWue's implementation): ~0.17 seconds

EDIT

mjolka spotted that FastStringBuilder had a bug.

this code was causing the bug:

    fixed (char* p = str)
    {
        for (int i = 0; i < str.Length; i++)
            chars[Length++] = (byte)(p + i);
    }

I've fixed it.

public sealed class FastStringBuilder
{
    private byte[] chars;

    public int Length { get; private set; }

    public FastStringBuilder(int capacity)
    {
        chars = new byte[capacity];
    }

    public FastStringBuilder()
    {
        chars = new byte[16];
    }

    private void GrowBy(int length)
    {
        var temp = chars;
        chars = new byte[length];
        Array.Copy(temp, 0, chars, 0, Length);
    }

    public unsafe void Append(string str)
    {
        if (str.Length + Length >= chars.Length)
            GrowBy((str.Length + Length)*4);
        else if (Length == chars.Length)
            GrowBy(chars.Length*2);

        for (int i = 0; i < str.Length; i++)
            chars[Length++] = (byte) str[i];
    }

    public override string ToString()
    {
        unsafe
        {
            fixed (byte* bp = chars)
            {
                return new string((sbyte*) bp, 0, Length);
            }
        }
    }
}


texts: Remove repeated words from a 2D character array

texts:
This code removes repeated words from a word array (2D char array).  I want to optimize this as much possible for speed.

#include "stdio.h"
#include "string.h"

main()
{
    char words[2000][20];

   /*This array is populated by some other module. possible example of this array is given below, but in reality it would far more elements.
        char words[6][20] =
    {
        {"barrack"},
        {"david"},
        {"John"},
        {"david"},
        {"benjamin"},
        {"barrack"}

    };*/

    int names_found = 10;
    char out_words[6][20];
    int i,j;
    int act_names=0;

    for (i = 0; i < names_found; i ++)
    {
        j = i + 1;
        while (j < names_found)
        {
            if (strcmp(words[i], words[j]) == 0)
            {
                memmove(words + j, words + (names_found - 1), sizeof(words[0]));

                -- names_found;
            }
            else
                ++ j;
        }
    }
    for(i=0;i<names_found;i++)
    {
        printf("%s\n",words[i]);
    }

}

How can the 2 for loops for i and j above be optimized?
As you see, the above logic currently outputs to same input buffer (in-place processing).  Can it be optimized further if we allow a second buffer say char out_words[2000][20]?


texts:
I'm trying to create a 2 way communication socket in python. The socket will listen for connections from the client until it gets the data formatted in string like this: 'PHONENUMBER|STATUS'. I will need to split that and convert it to json which will be sent via http request to a web api. When the api receives, it will handle the request and then it will return a status in json format which I will convert to string to return it to the client as string. I would like to have a professional opinion about my code and any additional ideas to what I would like to achieve would be appreciated.

import socket
import json
import requests
import httplib

HOST= '127.0.0.1'
PORT= 80

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Bind to adress

s.bind((HOST,PORT))
print ("Socket bound.")

#Start listening
s.listen(10)
print ("Socket Listening")

conn, addr = s.accept()
url = 'http://www.google.com'
while True:
      data = conn.recv(1024)

      dictionary = dict(item.split("|") for item in data .split(";"))

      json = json.dumps(dictionary, ensure_ascii=False)

      r = requests.get(url, data=json)

 print r.text


texts:
What do you think of this piece of code ? This is an implementation of quick sort in C, but I'm not sure about the quality and correctness.

#include <stdio.h>

void swap(int tab[], int a, int b)
{
  int temp = tab[a];
  tab[a] = tab[b];
  tab[b] = temp;
}

void quickSort(int tab[], int begin, int end)
{
  int left = begin-1;
  int right = end+1;
  const int pivot = tab[begin];

  if(begin >= end)
    return;

  while(1)
    {
      do right--; while(tab[right] > pivot);
      do left++;  while(tab[left] < pivot);

      if(left < right)
        swap(tab, left, right);
      else break;
    }

  quickSort(tab, begin, right);
  quickSort(tab, right+1, end);
}

int main(void)
{
    int tab[5] = {5, 3, 4, 1, 2};
    int i;

    quickSort(tab, 0, 4);

    for(i = 0; i < 5; i++)
    {
        printf("%d ", tab[i]);
    }
    putchar('\n');

    return 0;
}

Is it the standard way of implementing a quick sort in C ?


texts:
If one enters, say, "2, j" then it prints:

j
jj

If there is no second it should be *, so if it's just 2, it's * **.

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

using std::string; using std::cin; using std::cout; using std::endl; using std::ostream; using std::vector;

class tree {
public:
    friend ostream &output(tree &oTree, ostream &os);
    bool makeTree(int, const string&);
private:
    vector<string> Tree;
};

bool tree::makeTree(int newBase, const string &newCont = "*") {
    if (!Tree.empty())
        Tree.clear();
    string tempString;
    for(int tempbase = 0; tempbase != newBase; ++tempbase) {
        tempString += newCont;
        Tree.push_back(tempString);
    }
  return 1;
}

ostream &output(tree &oTree, ostream &os) {
    for (auto c: oTree.Tree) {
        os << c << endl;
    }
    return os;
}

int main() {

}


texts:
I'm working on a LinqEnumerable class (reviewable here), and I'm no Big-O expert and I'm pretty bad with algorithms, so I wonder what the complexity is for what I've implemented here, and whether it could be improved.

Join

Correlates the elements of two sequences based on matching keys.

Private encapsulated As New Collection
Option Explicit

Public Function Join(ByVal inner As LinqEnumerable, _
                     ByVal outerKeySelector As Delegate, _
                     ByVal innerKeySelector As Delegate, _
                     ByVal resultSelector As Delegate) As LinqEnumerable

    Dim result As New LinqEnumerable

    Dim outerValue As Variant
    Dim outerKey As Variant

    Dim innerValue As Variant
    Dim innerKey As Variant

    Dim innerList As System.List
    Set innerList = inner.ToList

    For Each outerValue In encapsulated
        outerKey = outerKeySelector.Execute(outerValue)

        For Each innerValue In innerList
            innerKey = innerKeySelector.Execute(innerValue)
            If outerKey = innerKey Then
                result.Add resultSelector.Execute(outerValue, innerValue)
                innerList.Remove innerValue
            End If
        Next
    Next

    Set Join = result

End Function

I've been told this might be \$O(log(n))\$, but since innerList.Remove is \$O(n)\$ I'm not sure. Could it be?


texts:
var appname = " - simple notepad",
    textarea = document.getElementById("textarea"),
    untitled = "untitled.txt" + appname,
    filename = "*.txt",
    isModified;

document.title = untitled;

textarea.onpaste = textarea.onkeypress = function() {
    isModified = true;
};

function confirmNav() { // Confirm navigation
    if (isModified) {
        var a = window.confirm("You have unsaved changes that will be lost.");
        if (a) {
            isModified = false;
        }
    }
}

function New() { // New
    confirmNav();
    if (!isModified) {
        textarea.value = "";
        document.title = untitled;
    }
    textarea.focus();
}

function Open() { // Open
    confirmNav();
    if (!isModified) {
        document.getElementById("selected_file").click();
    }
}

function loadFileAsText() { // load file as text
    var selected_file = document.getElementById("selected_file").files[0];
    var fileReader = new FileReader();
    fileReader.onloadend = function(e) {
        if (e.target.readyState === FileReader.DONE) {
            filename = selected_file.name;
            document.title = filename + appname;
            textarea.value = e.target.result;
            textarea.focus();
        }
    };
    fileReader.readAsText(selected_file);
}

function rename() { // Rename
    filename = window.prompt("Name this note:", filename);
    if (filename) {
        filename = (filename.lastIndexOf(".txt") === -1) ? filename + ".txt" : filename;
        document.title = filename + appname;
    }
}

function Save() { // Save
    rename();
    if (filename) {
        var blob = new Blob([textarea.value], {
            type: "text/plain;charset=utf-8"
        });
        window.saveAs(blob, filename);
        isModified = false;
    }
    textarea.focus();
}

function Print() { // Print
    var prnt_helper = document.getElementById("prnt_helper");
    prnt_helper.innerHTML = textarea.value;
    window.print();
    prnt_helper.innerHTML = "";
    textarea.focus();
}

function Help() { // Help
    var help = document.getElementById("help_content"),
        overlay = document.getElementById("overlay");

    function closeHelpAndOverlay() {
        help.setAttribute("aria-hidden", "true");
        overlay.setAttribute("aria-hidden", "true");
        textarea.focus();
    }

    if (help["aria-hidden"] === "true") {
        closeHelpAndOverlay();
    } else {
        help.setAttribute("aria-hidden", "false");
        overlay.setAttribute("aria-hidden", "false");
        textarea.blur();
        document.getElementById("overlay").onclick = function() {
            closeHelpAndOverlay();
        };
        // document.onkeydown = function(e) { // esc to close help
        //     if (e.keyCode === 27 || e.which === 27) {
        //         closeHelpAndOverlay();
        //     }
        // };
    }
}

// Confirm close
window.onbeforeunload = function() {
    if (isModified) {
        return "You have unsaved changes that will be lost.";
    }
};

// Keyboard shortcuts
document.onkeydown = function(e) {
    var key = e.keyCode || e.which;
    if (e.ctrlKey) {
        if (e.altKey) {
            if (key === 78) {
                // Ctrl+Alt+N
                New();
            }
        }
        if (key === 79) {
            // Ctrl+O
            e.preventDefault();
            Open();
        }
        if (key === 83) {
            // Ctrl+S
            e.preventDefault();
            Save();
        }
        if (key === 80) {
            // Ctrl+P
            e.preventDefault();
            Print();
        }
        if (key === 191) {
            // Ctrl+/
            e.preventDefault();
            Help();
        }
    }
    if (e.keyCode === 9 || e.which === 9) { // tab
        e.preventDefault();
        var s = textarea.selectionStart;
        textarea.value = textarea.value.substring(0, textarea.selectionStart) + "\t" + textarea.value.substring(textarea.selectionEnd);
        textarea.selectionEnd = s + 1;
    }
};


texts:
This is purely testing my skills; I am not actually coding for a bank.  This is part of a bank account class.

public void withDraw(double amount)
    {
        if(balance - amount >= odLimit)
        {
            balance -= amount;
        }
        else
        {
            Console.WriteLine("Error.  Withdrawing will take you below overdraft limit.  Enter a new amount: ");
            double amount2;
            while (!double.TryParse(Console.ReadLine(), out amount2) || (balance - amount2 < odLimit))
            {
                Console.WriteLine("Enter a valid number: ");
            }

            balance -= amount2;
        }
    }

odLimit is the overdraft limit.  The code checks if the balance - amount is greater than or equal to the odLimit (say -900), and if so, it simply takes that money from the account.  If that's not the case then it keeps asking the user to enter an amount they wish to withdraw, and when they enter a value that won't take the account below the overdraft limit and is a double.

Just checking that this is the most efficient way to do this.  I prefer minimum lines of code.

Also in the main program class.  Would you find it more efficient to create a menu function and call the withDraw function from the menu using a switch statement within the menu, or call a method in the program class from the switch statement that asks the user for their value, and then calls the withDraw function in the bank account class?


texts: Parent implementation different to child implementation

texts:
I have the following interface:

struct IFilter
{
    virtual enterClass(ClassData&, int recursiveLevel) = 0;
    virtual enterStructure(ClassData&, int recursiveLevel) = 0;
    virtual enterVariable(ClassData&, int recursiveLevel) = 0;
    virtual enterFunction(ClassData&, int recursiveLevel) = 0;
};

And here is an example of an implementation:

struct ReadOnlyFilter: public IFilter
{
    virtual enterClass(ClassData& classData, int recursiveLevel)
    {
        if(recursiveLevel==0 || classData->isReadondOnly())
        {
            this.out << "Class " << classData->name() << "\n{";
        }
    }

So items can contain classes, structs, variables and functions. A class or struct can contain items as children and grandchildren and so on. The class ReadOnlyFilter is used by a function which will loop recursively over all of the children and grandchildren etc of an item. The recursiveLevel is incremented as we go deeper and deeper, like this:

Class c (recursiveLevel=0)
{
    Variable v1 (recursiveLevel=1)
    Class cChild (recursiveLevel=1)
    {
       Class cGrandChild (recursiveLevel=2)

All my implementations have one thing in common: they should always write to this.out if the recursiveLevel is zero. This is why I have if(recursiveLevel==0 || in my code. This results in ifs everywhere in my code.

To solve this, I was thinking of doing something like this instead and was wondering if you think this is a good solution:

(I'm using C++98 and Boost)

struct IFilter
{
    virtual enterClass(ClassData&, int recursiveLevel) = 0;
    virtual enterStructure(ClassData&, int recursiveLevel) = 0;
    virtual enterVariable(ClassData&, int recursiveLevel) = 0;
    virtual enterFunction(ClassData&, int recursiveLevel) = 0;

    virtual enterChildClass(ClassData&, int recursiveLevel) = 0;
    virtual enterChildStructure(ClassData&, int recursiveLevel) = 0;
    virtual enterChildVariable(ClassData&, int recursiveLevel) = 0;
    virtual enterChildFunction(ClassData&, int recursiveLevel) = 0;
};

struct BaseFilter: public IStyler
{
    virtual enterClass(ClassData& classData, int recursiveLevel)
    {
        out << "Class " << classData->name() << "\n{";
    }

struct ReadOnlyFilter: public BaseFilter
{
    virtual enterChildClass(ClassData& classData, int recursiveLevel)
    {
        if(classData->isReadondOnly())
        {
            enterClass(classData, recursiveLevel);
        }
    }


texts: Generate all partitions of a set of items

texts:
Here are the items:

    var item = ['a', 'b', 'c', 'd'];

Desired output:

    [
        [ ['a'],['b'],['c'],['d'] ],
        [ ['a'],['b','c'],['d'] ],
        [ ['a'],['b'],['c','d'] ],
        [ ['a'],['b','c','d'] ],
        [ ['a'],['c'],['b','d'] ],....
    ]

The code:

function getCombinations(items) {
   var res = [];
   for (var i = 0; i < items.length; i++) {
      for (var j = i + 1; j <= items.length; j++) {
         var temp = items.slice(i, j);
         var remained = items.slice(0, i).concat(items.slice(j, items.length));
         if (remained.length > 0) {
            var combinations = getCombinations(remained);
            combinations.forEach(combination => {
               res.push([temp].concat(combination));
            });
         } else {
            res.push([temp]);
         }
      }
    }
   return res;
}

var item = ['a', 'b', 'c', 'd'];

console.log(getCombinations(item));


texts: FindUnion data structure used to find the minimum cut of a graph

texts:
I am trying to find the bottleneck in my code for computing the minimum cut of a graph. Currently the program runs in about 40 minutes on the test data set linked below (200 nodes and ~2000 edges). I have tried to make it as fast as possible by removing a dictionary and replacing it with a list (nodeObjs) as well as resetting the values of the objects instead of creating new ones on each iteration.

Neither of these have lead to any real improvement in speed and I lost some of the generality by using a list instead of a dictionary to store my objects. I will likely get rid of the list later to make it more general. The number of trials required is large because the odds of success of an individual trial is approximately \$\frac{1}{n^2}\$ where \$n\$ is the number of nodes.

On the linked data set the solution is found early but I believe this is due to the structure of the graph.

import random
from math import log
from readGraphIn import readGraphIn
from unionfind import UnionFind
from time import clock

def randomMinCut(nodes,edges):

    tries = int( (len(nodes)**2)*log(len(nodes),2))
    minCut = [0]*len(edges)
    tries2 = 1.0/tries
    trialCut = [0]*len(edges)
    nodeObjs = [0] + [ UnionFind(node) for node in nodes ]

    for i in xrange(tries):
        if not i % 100:
            print 'Progress:', i*tries2*100,'Tries:', i, 'MinCut Length', len(minCut)
        #random.shuffle(edges)
        treeIndex = 0
        cutIndex = 0

        # reset object values without creating new values
        for node in nodeObjs[1:]:
            node.__init__(node.vertex)

        for u,v in edges:
            #first build two unconnected forests
            if treeIndex >= len(nodes)-2:
                if nodeObjs[u].find_root() != nodeObjs[v].find_root():
                    trialCut[cutIndex] = [u,v]
                    cutIndex += 1
                if cutIndex > len(minCut):
                    break
            elif nodeObjs[u].find_root() != nodeObjs[v].find_root():
                treeIndex += 1
                UnionFind.union(nodeObjs[u], nodeObjs[v])

        if cutIndex < len(minCut):
            minCut = trialCut[:cutIndex]

    print minCut
    return len(minCut)

nodes, edges = readGraphIn()
t0 = clock()
print randomMinCut(nodes, edges)
t1 = clock()
print 'Run Time: ', t1-t0
#print edgeContraction(edges, tuple(edges[0]))

class UnionFind(object):
    '''
    Used to initialize the set and then holds the required functions to operate on them
    '''

    def __init__(self, vertex):
        self.rank = 0
        self.parent = self
        self.vertex = vertex

    def find_root(self):
        if self != self.parent:
            self.parent = self.parent.find_root()
        return self.parent

    @staticmethod
    def union(x,y):
        xroot = x.find_root()
        yroot = y.find_root()

        if xroot == yroot:
            return

        if xroot.rank > yroot.rank:
            yroot.parent = xroot
        else:
            xroot.parent = yroot
            if xroot.rank == yroot.rank:
                yroot.rank += 1

        return

    def __str__(self):
        return 'Me: %s, Parent: %s, rank: %s ' % ( str(self.vertex), str(self.parent.vertex), str(self.rank))

Test data set location


texts: MySQL Query to check at least one field is greater than zero

texts:
I want to retrieve the row if any of the 3 integer field in a row is greater than zero. All the field has default value of zero.

Which of the following query is better?

-- Query 1
SELECT * FROM my_table WHERE number_A > 0 OR number_B > 0 OR number_C > 0

-- Query 2
SELECT * FROM my_table WHERE (number_A + number_B + number_C) > 0

While checking the execution time both the query gives same numbers and the result data of the query is exactly the same.


texts:
I have a function that accepts a big amount of data as a parameter (sometimes 1 megabyte) I was thinking which would be the fastest way to pass that data, dunno if I got this right, but here is what I think (functionality doesn't matter, all are the same in my app, since data is never used again after this function).

// slow since the data must be copied to another location
// in memory and passed to myfunction
function myfunction(data: string): boolean;

// faster since a pointer to the original data is passed to
// the function and data is never copied
function myfunction(var data: string): boolean;

// no idea ??!!!
function myfunction(const data: string): boolean;


texts:
I use NPOI to copy Excel formula, but can't find an option to do it in a relative way. Therefore, I've written a function to implement it. The task is "easy". When copying a formula A1+B1 of C1 to C2, the result will be A2+B2. But the formula can do more than that. For example:

Left(A1, 3) of B1 to B2 => Left(A2, 3)
(AB1 - AB$1) * $AB1 of AC1 to AD2 => (AC2 - AC$1) * $AB2
A1 & "-B1-C1" of B1 to B2 => A2 & "-B1-C1"

The difficult part is identifying the cell and handling the $.

public string GetCellForumulaRelative(string formula, int columnOffset, int rowOffset)
{
    var cells = formula.Split("+-*/(),:&^>=< ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
        // start w/ A-Z
        .Where(i => (Convert.ToChar(i.Substring(0, 1).ToUpperInvariant()) >= 'A' &&
                     Convert.ToChar(i.Substring(0, 1).ToUpperInvariant()) <= 'Z') ||
                     Convert.ToChar(i.Substring(0, 1).ToUpperInvariant()) == '$')
        // end w/ 0-9
        .Where(i => Convert.ToChar(i.Substring(i.Length - 1, 1)) >= '0' &&
                    Convert.ToChar(i.Substring(i.Length - 1, 1)) <= '9');

    int startIdx = 0;
    foreach (var cell in cells)
    {
        int sepIdx = cell.IndexOfAny("0123456789".ToCharArray());
        if (cell.Substring(sepIdx - 1, 1).Equals("$"))
            sepIdx--;

        string col = cell.Substring(0, sepIdx);
        if (col.StartsWith("$") == false)
            col = GetExcelColumnName(ExcelColumnNameToNumber(col) + columnOffset);

        string row = cell.Substring(sepIdx);
        if (row.StartsWith("$") == false)
            row = (Convert.ToInt32(row) + rowOffset).ToString();

        startIdx = formula.IndexOf(cell, startIdx);
        formula = formula.Substring(0, startIdx) +
                  col + row +
                  formula.Substring(startIdx + cell.Length);
        startIdx += cell.Length;
    }

    return formula;
}

Any suggestions will be appreciated: performance, improvements, one-liners, or bugs.


texts: Parsing mathematical expressions in Reverse Polish Notation

texts:
I've wanted to make a calculator for a long time now, so I wrote one of my first parsers, where the input is in reverse polish notation, \$1 \ 1 +\$ becomes \$2\$.

It supports to following operators; +, -, *, /, // floor division, ^ or ** exponent, and % or mod modulo.

While it's the best calculator I've written, the tokens are limited to only ones that take two operators. And I don't really like the idea of having a separate dictionary for ones that take more or less. This is a shame as now I can't add functions like sqrt or sin, or constants like pi or e, without having to have a different group for each.

Personally I dislike the error you get when you ^C out of the program, and so I silenced it. I also made a new error CalculatorError to not mask unknown errors, to easily exit out of the current equation if more than one function is called, make_pop, and to have a human readable error message.

TOKENS = {
    '+': lambda a, b: a + b,
    '-': lambda a, b: a - b,
    '*': lambda a, b: a * b,
    '/': lambda a, b: a / b,
    '^': lambda a, b: a ** b,
    '**': lambda a, b: a ** b,
    '%': lambda a, b: a % b,
    'mod': lambda a, b: a % b,
    '//': lambda a, b: a // b
}

class CalculatorError(Exception):
    pass

def make_pop(stack):
    def pop():
        try:
            return stack.pop()
        except IndexError:
            raise CalculatorError('Not enough arguments for function')
    return pop

def call():
    stack = []
    pop = make_pop(stack)
    buf = []

    calculation = iter(input('> ') + ' ')

    for char in calculation:
        if char not in ' \t':
            buf.append(char)
            continue

        token = ''.join(buf)
        if not token:
            continue

        if token in TOKENS:
            a = pop()
            b = pop()
            function = TOKENS[token]
            try:
                return_value = function(b, a)
            except ZeroDivisionError:
                raise CalculatorError("Can't devide by zero")
            else:
                stack.append(return_value)
        else:
            try:
                token = float(token)
            except ValueError:
                raise CalculatorError('{!r} is not a number'.format(token))
            stack.append(token)

        buf = []

    if len(stack) > 1 or buf:
        raise CalculatorError('Invalid function, not enough operators.', stack, buf)

    if stack[0] % 1:
        print(stack[0])
    else:
        print(int(stack[0]))

def main():
    while True:
        try:
            call()
        except CalculatorError as e:
            print(e)

if __name__ == '__main__':
    print('Press ^C to exit')
    try:
        main()
    except KeyboardInterrupt:
        pass
    # For some reason my Windows raises EOF on ^C...
    except EOFError:
        print()
    print('Goodbye!')

Some example output is:

Press ^C to exit
> 2 2 + 2 2 - /
Can't devide by zero
> 3 5 * 2 //
7
> 20 mod 11
Not enough arguments for function
> 20 11 mod
9
>
Goodbye!


texts: Reduce a JavaScript array into named objects

texts:
The code below reduces an array into "named" objects (not sure if that's the correct terminology!)

It works, but I'm sure the code could be improved. There is some repetition going on in the reduce.

It checks if a key exists (if (accumulator[name])). If not then initialize the results array, if it does then push onto the results array.

let response = {
  columns: [
    'n'
  ],
  data: [
    {
      graph: {
        nodes: [
          {
            id: '169',
            labels: [
              'Container'
            ],
            properties: {
              reference: 'REF002',
              name: 'Cupboard',
              id: '003'
            }
          }
        ],
        relationships: []
      }
    },
    {
      graph: {
        nodes: [
          {
            id: '170',
            labels: [
              'Container'
            ],
            properties: {
              reference: 'REF003',
              name: 'Cupboard A',
              id: '03a'
            }
          }
        ],
        relationships: []
      }
    },
    {
      graph: {
        nodes: [
          {
            id: '964',
            labels: [
              'Equipment'
            ],
            properties: {
              reference: 'REF004',
              name: 'Cupboard B',
              id: '03b'
            }
          }
        ],
        relationships: []
      }
    }
  ]
}

const result = response.data.reduce(
  (accumulator, currentValue, currentIndex, array) => {
    const name = currentValue.graph.nodes[0].labels[0];

    if (accumulator[name]) {
      accumulator[name].results.push({
        title: currentValue.graph.nodes[0].properties.name,
        description: currentValue.graph.nodes[0].properties.reference
      });
    } else {
      accumulator[name] = {
        name,
        results: [
          {
            title: currentValue.graph.nodes[0].properties.name,
            description: currentValue.graph.nodes[0].properties.reference
          }
        ]
      };
    }

    return accumulator;
  },
  {}
);

console.clear();
console.log(result);

Output Required

{
  Container: {
    name: 'Container',
    results: [
      {
        title: 'Cupboard',
        description: 'REF002'
      },
      {
        title: 'Cupboard A',
        description: 'REF003'
      }
    ]
  },
  Foo: {
    name: 'Foo',
    results: [
      {
        title: 'Cupboard B',
        description: 'REF004'
      }
    ]
  }
}


texts: Find the intervals which have a non-empty intersection with a given interval

texts:
The problem is the following: I have a list intervals which consists of tuples of the form (start, end) [with start <= end]. Each tuple represents an interval (of the real line). We assume that the intervals in intervals are not overlapping each other. Given a new interval (s,e), I would like to write a Python function which checks if (s, e) overlaps any of the intervals in intervals. If (s, e) has a non-empty intersection with at least one of the intervals in intervals, the function should return the indices of these intervals in the list intervals.

Say that the function is called find_intersections. Then, given that intervals = [(1, 3.5), (5.5, 8.7), (10.2, 22.6), (22.7, 23.1)], expected outputs would be:

find_intersection(intervals, (3.2, 5.)) returns array([0])
find_intersection(intervals, (6.1, 7.3)) returns array([1])
find_intersection(intervals, (9.1, 10.2)) returns No intersection.
find_intersection(intervals, (5.8, 22.9)) returns array([1, 2, 3]).

The code for find_intersection I have written is:

import itertools

def find_intersection(intervals, new_interval):
    _times = sorted(list(itertools.chain.from_iterable(intervals)))
    ind = np.searchsorted(_times, np.asarray(new_interval))
    parity = np.mod(ind, 2)
    if (not np.any(parity)) and ind[1] == ind[0]:
        print('No intersection.')
    elif parity[0] == 1:
        ub = ind[1] if parity[1] == 1 else ind[1] - 1
        return np.arange((ind[0] - 1) / 2, (ub - 1) / 2 + 1)
    elif parity[1] == 1:
        lb = ind[0] if parity[0] == 1 else ind[0] + 1
        return np.arange((lb - 1) / 2, (ind[1] - 1) / 2 + 1)
    else:
        lb = ind[0] if parity[0] == 1 else ind[0] + 1
        ub = ind[1] if parity[1] == 1 else ind[1] - 1
        return np.arange((lb - 1) / 2, (ub - 1) / 2 + 1)

I believe that the code does the job.

Is there an easier/smarter way to address this problem?

Edit: this question was cross-posted on stackoverflow.com.


texts: CRC without knowing the data type or size

texts:
I wrote a function to calculate an 8-bit CRC/checksum for unknown data types. The only restriction is the data type must be at most 4bytes/32bits.

uint8_t crc(void* _crc, ssize_t len, uint8_t _crc_seed) {
    void* _crc_cpy = malloc(len);
    memcpy(_crc_cpy, _crc, len);
    uint32_t* _crc_cpy_pointer = static_cast<uint32_t*>(_crc_cpy);
    uint8_t _crc_u[len];
    for(int i = len; i > 0; i--) {
        _crc_u[len-i] = ((*_crc_cpy_pointer)&(0xff << 8*(i-1))) >> (8*(i-1));
    }
    uint8_t crc_seed = _crc_seed;
    uint8_t crc_u;
    for(int i = 0; i < len; i++) {
        crc_u = _crc_u[i] ^= crc_seed;
        for(int i = 0; i < 8; i++) {
            crc_u = (crc_u & 0x80) ? 0x7 ^ (crc_u << 1) : (crc_u << 1);
        }
        crc_seed = crc_u;
    }
    return crc_u;
}

How can I do this better? What are things that I did incorrectly?


texts:
Can anyone please review the following .htaccess file and let me if it is correctly put together?

What I think it does:

So it direct to a custom 404 page
Remove the extensions from the end of the urls (example .php)
Remove /index
I don't really understand what the final rule does, can anyone please explain it if could?

DirectoryIndex index.html index.php
ErrorDocument 404 /404

RewriteEngine On
RewriteBase /

# Remove enter code here.php; use THE_REQUEST to prevent infinite loops
# By puting the L-flag here, the request gets redirected immediately
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301,L]

# Remove /index
# By puting the L-flag here, the request gets redirected immediately
# The trailing slash is removed in a next request, so be efficient and dont put it on there at all
RewriteRule (.*)/index$ $1 [R=301,L]

# Remove slash if not directory
# By puting the L-flag here, the request gets redirected immediately
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /$
RewriteRule (.*)/ $1 [R=301,L]

# Add .php to access file, but don't redirect
# On some hosts RewriteCond %{REQUEST_FILENAME}.php -f will be true, even if
# no such file exists. Be safe and add an extra condition
# There is no point in escaping a dot in a string
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !(/|\.php)$
RewriteRule (.*) $1.php [L]


texts:
To help myself learn macros, I made a custom version of the threading macro that lets you choose which argument the "thread" gets put into.

My main concern is simplifying it, and making it more idiomatic, but anything notable is welcome. If anyone knows of a better implementation for insert-at, I'd love to know that as well!

; Helpers. Other macros use these, or else I'd just inline them
(defn factor? [n m]
  (= (rem n m) 0))

(defn mult-forms? [n forms]
  (factor? (count forms) n))

(defn insert-at
  "Inserts an element at the given index. Returns a list.
  Indices out of range of the collection are treated as either 0 or (dec (count xs))
  Likely very expensive."
  [xs x index]
  (let [[f-half s-half] (split-at index xs)]
    (concat f-half `(~x) s-half)))

(defmacro n->
  "Expects a value to be threaded, and pairs of indices and forms.
  The indices indicate which index the value should be inserted at in the following form.
  Example:
      (n-> 1
          1 (+ 2)
          0 (+ 3))
  Expands to: (+ (+ 2 1) 3)"
  [val & forms]
  (if (and (not (empty? forms))
           (mult-forms? 2 forms))
    (let [[thread-n form & rest-forms] forms
          threaded  (insert-at form val (inc thread-n))]
      `(n-> ~threaded ~@rest-forms))
    val))

Note, I'm not claiming this is a useful macro; it will likely lead to confusing to read code. This was just an exercise.

Example:

(n-> "Hello"
  0 (str "0" "1" "2" "3")
  1 (str "0" "1" "2" "3")
  2 (str "0" "1" "2" "3"))

Expands to:

(clojure.core/str "0" "1"
    (clojure.core/str "0"
        (clojure.core/str "Hello" "0" "1" "2" "3") "1" "2" "3") "2" "3")

Which evaluates to:

"010Hello012312323"


texts:
I've constructed a simple class whose entire purpose is to hash passwords securely and simply.

The catch is the PHP version is probably going to be 5.2.x. This means:

No CRYPT_BLOWFISH
Obviously no password_hash().

The question is, is the following secure? Can it be improved?

/**
 * Class Hasher
 *
 * @package Dependencies\Hasher
 *
 * Defines hashing mechanism for password saving.
 */
class Hasher {

    /**
     * @param string $string String for hashing
     * @param string $salt   Unique salt. The salt is best kept as a very long, very random string.
     * @param int    $cost   Cost parameter. 2^$cost iterations over the hashing algorithm.
     *
     * @return string
     */
    public function algo($string, $salt, $cost) {
        $iterations = pow(2, $cost);
        $result     = "";

        for ($i = 0; $i < $iterations; $i++) {
            $result = sha1($result . $salt . $string);
        }

        return $result;
    }

    /**
     * Pass a password through the hashing algorithm. And return the result.
     *
     * @param string $password
     * @param string $salt
     * @param int    $cost
     *
     * @return string
     */
    public final function hash($password, $salt, $cost = 10) {
        return $this->algo($password, $salt, $cost);
    }

    /**
     * Match password through the hashing algorithm against an existing hash to make sure there's a match.
     *
     * @param string $hash
     * @param string $password
     * @param string $salt
     * @param int    $cost
     *
     * @return bool
     */
    public final function verify($hash, $password, $salt, $cost = 10) {
        return $this->algo($password, $salt, $cost) == $hash;
    }

}


texts: Calculating price after sales commission and discount

texts:
The code already works, but I just want tips for improving.

import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class Calculator
{
    public static void main(String[] args)
    {
        double initialPrice = 0.00;
        double commissionRate = 0;
        double discountRate = 0;
        initialPrice = Double.parseDouble(JOptionPane.showInputDialog(null, "What is the initial price total of the sale?"));
        commissionRate = Double.parseDouble(JOptionPane.showInputDialog(null, "What is the percentage amount of the sales commission? \nFor example for 20%, type 20."));
        discountRate = Double.parseDouble(JOptionPane.showInputDialog(null, "What is the customer's discount rate? \nFor example for a 15% discount, type 15."));
        JOptionPane.showMessageDialog(null, "The final cost to the customer is \n$" + computeFinalPrice(initialPrice, commissionRate, discountRate) + ".");
    }
    public static String computeFinalPrice (double initialPrice, double commissionRate, double discountRate)
    {
        double finalPrice;
        DecimalFormat d = new DecimalFormat("0.00");
        finalPrice = (initialPrice*(commissionRate+100)*.01)*((100-discountRate)*.01);
        return (d.format(finalPrice));
    }


texts:
I have a list of dictionaries and I want to group them by a specific value
let's say this is the list:
lst = [{'name':'john','course':'geography','grade':'80'},
       {'name':'Mary','course':'geography','grade':'70'},
       {'name':'John','course':'calculus','grade':'70'},
       {'name':'Mary','course':'calculus','grade':'70'}]

I will want all the dictionaries with the same value of "name" to be in a sublist, like this :
lst_new = [[{'name':'John','course':'geography','grade':'80'},
            {'name':'Mary','course':'geography','grade':'70'}],
           {'name':'John','course':'calculus','grade':'70'},
           {'name':'Mary','course':'calculus','grade':'70'}]

so I am doing it this way :
lst_new = [[elt for elt in lst if elt['name']==n] for n in np.unique(np.array([elt['name'] for elt in lst]))]

but I am feeling there are too much iterations, is there a better way to do it?


texts:
I was given this coding challenge when a applying for a summer internship but didn't get selected for the next round and I was curious if it could be improved.

The problem says:

  Given a number in base "-2" divide it by 2.

  For example:

  Given [1, 0, 0, 1, 1, 1] (-23) the output is [1, 0, 1, 0, 1, 1] (-11)

  Given [0, 0, 1, 0, 1, 1] (-12) the output is [0, 1, 1, 1] (-6)

  Note the array is read from left to right. [1, 0, 0, 1, 1, 1] = 1*(-2)^0 + 0*(-2)^1 + 0*(-2)^2 + 1*(-2)^3 + 1*(-2)^4 + 1 * (-2)^5 = 1
  + 0 + 0 + (-8) + 16 + (-32) = -23

The easiest solution that I found was to convert the number to an integer, divide it by two and then convert it back to base -2.

Thanks in advance for your input.

My code in Python:

import math

# Main function
def solution(A):
    value = math.ceil(calculate_number(A) / 2)
    p = convert_number_to_binary(value)
    return p

# This function calculates the value of the list
def calculate_number(A):
    total = 0
    for i in range(0, len(A)):
        total += A[i] * (-2) ** i
    return total

# This function converts a number to base -2
def convert_number_to_binary(number):
    binary = []
    if number == 0:
        return binary

    while number != 0:
        number, remainder = divmod(number, -2)
        if remainder < 0:
            number += 1
            remainder -= -2
        binary.append(remainder)
    return binary

print(solution([1, 0, 0, 1, 1, 1]))


texts: Testing after_save hooks in Rails 4.2 with MiniTest

texts:
I've recently started working on a new application in Rails 4.2.0-beta2. I've been using this as an opportunity to learn more about MiniTest, with a stretch goal of being as strict with myself with testing as possible.

My general problem: How do I test the after_save action for an ActiveRecord model in such a way that I can be confident that an ActiveRecord callback will not cause my code to break?

Here's what I've got so far (gist or inline code below).

How would you (re)write these files to detect if the NotificationMailer called in the after_save hook prevented a TeamMembership from being persisted?

Note that not included here are the relevant test fixtures. You may safely assume that fixtures users(:carol) and teams(:alpha) are not associated with each other.

app/models/team_membership.rb

class TeamMembership < ActiveRecord::Base
  # A proc that will enqueue `NotificationMailer.team_invitation`
  DEFAULT_NOTIFIER = proc do |user, team|
    NotificationMailer.team_invitation(team, user).deliver_later
  end

  class << self
    # This is a class level attribute that is mainly used for testing.
    # Defaults to {TeamMembership::DEFAULT_NOTIFIER}
    attr_accessor :notifier
  end
  self.notifier = DEFAULT_NOTIFIER

  belongs_to :team
  belongs_to :user

  after_create :invite_user_to_team!

  private

  # ActiveRecord callback used to equeue team invitation emails
  # @return void
  def invite_user_to_team!
    self.class.notifier.call(team, user)
    nil
  end
end

tests/models/team_membership_test.rb

require 'test_helper'

class TeamMemberTest < ActiveSupport::TestCase
  test 'callbacks' do
    # setup
    test_notifier = Minitest::Mock.new
    test_notifier.expect(:call, nil, [teams(:alpha), users(:carol)])
    TeamMembership.notifier = test_notifier

    # test
    TeamMembership.create(user_id: users(:carol).id, team_id: teams(:alpha).id)
    assert test_notifier.verify

    # teardown
    TeamMembership.notifier = TeamMembership::DEFAULT_NOTIFIER
  end
end


texts:
I have a WCF service that itself uses another third party WCF service. It's basically a proxy. So I'm getting a request to my own one and I have just to "forward" it to the third party one.

I would like then to map from my flattened request (that's the way it's been decided to be coded) to the slightly more complex request the other service needs.

Although quite a few of the properties in each request are a naming match my issues are the following

There are properties flattened in my request in relation to theirs
There's a huge load of my properties that should go into theirs "generic" Data[] ApplicationDetails property being both as follows:

public class ApplicationDetails
{
    public Data[] Data { get; set; }
}

public class Data
{
    public string category { get; set; }

    public string attribute { get; set; }

    public string Value { get; set; }
}

And those will come from my request as a property named as the attribute should be, i.e. my request will have a property named AIM and I should put that as an the attribute of one of the elements of the Data array, it's value as the element's value and hardcode the category (there are 3 of them).

I couldn't see many advantages (apart for the equally named properties) for using Automapper (or any other it could be) and ended up with a massive static Mapper class that looks this way

public static class Mapper
{
    public static Request FromDecisionRequestToZRequest(DecisionRequest request)
    {
        var applicationDetails = new Data[]
        {
            new Data {category = "ID", attribute = "PubID", Value = request.PubID},
            new Data {category = "ID", attribute = "AID", Value = request.AID},
            new Data {category = "APP", attribute = "NID", Value = request.NID},
            new Data {category = "BOOK", attribute = "DupeApps90", Value = request.DupeApps90},
            new Data {category = "BOOK", attribute = "DupeApps30", Value = request.DupeApps30},

            //And many others of each of the three categories

        };

        var address = new Address[]
        {   new Address{
                City = request.City,
                Country = request.Country,
                HouseNumber = request.HouseNumber,
                HouseNumberExtension = request.HouseNumberExtension,
                Street = request.Street,
                ZIP = request.ZIP,
                kind = "MAIN"
            }
        };

        var ret = new Request()
        {
            UserName = request.UserName,
            RequestDateTime = Convert.ToDateTime(request.RequestDateTime),
            CompanyRegistrationID = request.CompanyRegistrationID,

            //And many others "direct" mappings

            Addresses = new Addresses { Address = address },
            Phone1 = new Phone1 { type = "1", Value = request.Phone1 },
            Phone2 = new Phone2 { type = "2", Value = request.Phone2 },
            Phone3 = new Phone3 { type = "3", Value = request.Phone3 },
            Email = request.Email,
            Amount = new Amount { Value = request.Amount },

            ApplicationDetails = new ApplicationDetails { Data = applicationDetails }
        };

        return ret;
    }
}

How would you tackle this?  To me this static class looks horrible (taking into account that the full one has more than 150 lines but not sure how I could improve it).


texts: Retrieving information about a vendor using MySQL

texts:
I am loading some information about the selected vendor using mysql query. I made a method with a List as return type, then created another method to assign values coming from a list. I am wondering if there is a better way of doing things.

P.S. The vendorCrud object is a database helper.

 private List<string> GetVendorInformation(string vendorId)
    {
        crud vendorCrud = new crud();
        List<string> columnData = new List<string>();

        string query = String.Format("SELECT tin, email_add, fax_no, tel_no, contact.contact_person FROM lib_inv_vendor vendor " +
           "LEFT JOIN lib_inv_vendor_contact_person contact ON vendor.vendor_id = contact.vendor_id " +
           "WHERE vendor.vendor_id = {0} ORDER BY contact_default DESC LIMIT 1", vendorId);

        vendorCrud.load_data(query, Modules.connection.filesetupDB1, CommandType.Text);

        foreach (DataRow item in vendorCrud.table.Rows)
        {
            columnData.Add(item["tin"].ToString());
            columnData.Add(item["email_add"].ToString());
            columnData.Add(item["fax_no"].ToString());
            columnData.Add(item["tel_no"].ToString());
            columnData.Add(item["contact_person"].ToString());
        }

        return columnData;
    }

    private void SetVendorInformation(List<string> colData)
    {
        txtVendorTin.EditValue = colData[0];
        txtEmail.EditValue = colData[1];
        txtFaxNo.EditValue = colData[2];
        txtTelNo.EditValue = colData[3];
        txtAttention.EditValue = colData[4];
    }

    private void txtSupplier_EditValueChanged(object sender, EventArgs e)
    {
        SetVendorInformation(GetVendorInformation(txtSupplier.EditValue.ToString()));
    }


texts: Conditionally replacing a placeholder in a form

texts:
Given this code

if account_id:
    form = form.replace("<<ACCOUNT_ID>>", "<accountId>"+account_id+"</accountId>")
else:
    form = form.replace("<<ACCOUNT_ID>>", "")

I was wondering if I could remove the else tag to make the code simpler:

account_id_tag = ""
if account_id:
    account_id_tag = "<accountId>" + account_id + "</accountId>"
form = form.replace("<<ACCOUNT_ID>>", account_id_tag)

Or even using a ternary operator:

account_id_tag = "<accountId>" + account_id + "</accountId>" if account_id else ""
form = form.replace("<<ACCOUNT_ID>>", account_id_tag)

But even the last one uses less lines, I have the sensation that the original option (with else) is easy to read and to understand, and this is very important for my point of view.


texts: Determine if Array has an Increasing Sequence

texts:
I wrote a function in JavaScript that expects an array of integers (negative or positive) and determines if that array has an increasing sequence.

For the sake of better time performance I made the function return out of the loop with false as soon as i+1 - i did not equal 1 or -1. I used continue to do this. Here is the function:

const increasingSequence = (arr) => {
    for (let i = 0; i < arr.length - 1; i ++) {
      if (arr[i+1] - arr[i] === 1 || arr[i+1] - arr[i] === -1) {
        continue;
      } else {
        return false;
      }
    }
    return true;
  }

Seems to be producing the desired output:

var arr1 = [1, 2, 3, 4];
var arr2 = [1, 2, 4, 5];
var arr3 = [-4, -3, -2, -1];
var arr4 = [-4, -3, -1, 0];

increasingSequence(arr1); // true
increasingSequence(arr2); // false
increasingSequence(arr3); // true
increasingSequence(arr4); // false

This is actually a helper function to a bigger problem I'm trying to solve, so time complexity is important. Feedback about improving time complexity or any missing edge cases would be greatly appreciated.


texts: Array partition 1 to group the array into pairs and make sum of minimum of pairs as maximum

texts:
Challenge from LeetCode: Array Partition I

  Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

  Example 1:

  Input: [1,4,3,2]

  Output: 4

  Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).

My approach:

import java.util.*;

class Solution {
    public int arrayPairSum(int[] nums) {
       //Sorting the array in least time
        Arrays.sort(nums);

        int sum = 0;
        for( int i = 0; i < nums.length; i = i + 2 )
            sum += nums[i];

        return sum;

    }
}

1) Is there a better way to solve this question?

2) Can I still decrease the time and space complexity?

Reference


texts: Print 10 × 10 square of X and O characters, split diagonally

texts:
I'm going through a beginners exercise for writing a small program in Java. My task is to print out (i.e. find an algorithm) the following output:

XOOOOOOOOO
XXOOOOOOOO
XXXOOOOOOO
XXXXOOOOOO
XXXXXOOOOO
XXXXXXOOOO
XXXXXXXOOO
XXXXXXXXOO
XXXXXXXXXO
XXXXXXXXXX

I have figured out how to do it but the code I wrote seems repetitive and tedious. How can I shorten my code?

package helloWorld;

public class HelloWorld {

public static void main(String[] args)
{
    // Output

    // Algorithm 1

    boolean ft = true;

    String s = new String();
    for(int i = 0; i < 10; i++)
    {
        s  += "X";
        for(int j = 0; j < 9; j++)
        {
            if(i == 0)
            {

                s += "O";
            }

            if(i == 1)
            {

                if(ft == true)
                {
                    s+="X";
                    ft = false;
                }
                if(j == 8)
                {
                    continue;
                }
                s += "O";
            }

            if(i == 2)
            {

                if(ft == true)
                {
                    s+= "XX";
                    ft = false;

                }

                if(j == 7)
                {

                    break;
                }
                s += "O";

            }

            if(i == 3)
            {

                if(ft == true)
                {
                    s+= "XXX";
                    ft = false;

                }

                if(j == 6)
                {

                    break;
                }
                s += "O";
            }

            if( i == 4)
            {
                if(ft == true)
                {
                    s+= "XXXX";
                    ft = false;

                }

                if(j == 5)
                {

                    break;
                }
                s += "O";
            }

            if( i == 5)
            {
                if(ft == true)
                {
                    s+= "XXXXX";
                    ft = false;

                }

                if(j == 4)
                {

                    break;
                }
                s += "O";
            }

            if( i == 6)
            {
                if(ft == true)
                {
                    s+= "XXXXXX";
                    ft = false;

                }

                if(j == 3)
                {

                    break;
                }
                s += "O";
            }

            if( i == 7)
            {
                if(ft == true)
                {
                    s+= "XXXXXXX";
                    ft = false;

                }

                if(j == 2)
                {

                    break;
                }
                s += "O";
            }

            if( i == 8)
            {
                if(ft == true)
                {
                    s+= "XXXXXXXX";
                    ft = false;

                }

                if(j == 1)
                {

                    break;
                }
                s += "O";
            }

            if( i == 9)
            {
                if(ft == true)
                {
                    s+= "XXXXXXXXX";
                    ft = false;

                }

                if(j == 0)
                {

                    break;
                }
                s += "O";
            }

        }
        System.out.println(s);
        s = "";
        ft = true;

    }
}

}


texts: has extra blank 's and I have no idea why. please help me get them out

texts:
This is the result of the code it has extra option tags no idea why.

I have no idea why It produces the extra option box.

Below is the result of the query. Correct number of rows correct response...

     ParentID   Parent
    1   Pipe
    2   Valve
    3   Control Valve
    4   Pump
    5   Chamber
    6   Meter
    7   Check
    8   Distribution Pipe

This is some php that makes the dropdown:

$qry = "select distinct ParentID, Parent from tbl
    where ChildID = '0' and Parent is not null";

$parentRslt = mysql_query($qry);

$count = mysql_num_rows($parentRslt);

$opt7 = null;

for($m=0;$m<$count;$m++)
    {
        $var = mysql_result($parentRslt,$m,'ParentID');
        $name = mysql_result($parentRslt,$m,'Parent');

        $var = trim($var);
        $name = trim($name);

        $opt7.="<option value='$var'>$m $name<option>";
    }

$form = "
    <form method='post'>

    Network Action: <input type='text' name='child' />
    <select name='parentID'>
            $opt7
    </select>

    <input type='submit' name='submit' value='submit' /></form>";

return $form;


texts:
I have method which checks period and return schedules:

public IEnumerable<EventSchedule> GetSchedulesForPeriod(PeriodEvent period, string tab = "")
        {
            switch (period)
            {
                case PeriodEvent.Today:
                    return GetTodaySchedules(tab);

                case PeriodEvent.Tomorrow:
                    return GetTomorrowSchedules(tab);

                case PeriodEvent.Week:
                    return GetWeekSchedules(tab);

                case PeriodEvent.FewWeek:
                    return GetFewWeekSchedules(tab);

                case PeriodEvent.Month:
                    return GetMonthSchedules(tab);
                case PeriodEvent.All:
                    return GetAllFromTodaySchedules(tab);

                default:
                    return GetTodaySchedules(tab);
            }
        }

Consider the GetTodaySchedules and GetTomorrowSchedules:

    private IEnumerable<EventSchedule> GetTodaySchedules(string tab)
{
    var today = DateTime.Now.Date;

    var result = Database.EventSchedules.Where(s => s.RecurrenceStart.Value.Date <= today &&
         s.RecurrenceEnd.Value.Date >= today &&
         s.BaseEvent.IsApproved.Value && !s.IsRemoved.Value &&
         s.BaseEvent.EventsCategories.Any(
         c => c.EventCategory.Name == tab)).ToList();

    return result.Where(s => Evaluator.CheckDate(s, today)).ToList();
}
private IEnumerable<EventSchedule> GetTomorrowSchedules(string tab)
{
    var today = DateTime.Now.AddDays(1).Date;
    var result = Database.EventSchedules.Where(s => s.RecurrenceStart.Value.Date <= today &&
         s.RecurrenceEnd.Value.Date >= today &&
         s.BaseEvent.IsApproved.Value && !s.IsRemoved.Value &&
         s.BaseEvent.EventsCategories.Any(
         c => c.EventCategory.Name == tab)).ToList();

    return result.Where(s => Evaluator.CheckDate(s, today)).ToList();
}

The similar code have all methods above. How to rewrite it? May be, there is  some pattern for this?
And, the second, now I want that tab checks only if it filled and introduce new var called placeName (also check if filled):

private IEnumerable<EventSchedule> GetTodaySchedules(string tab, string placeName)
    {
        var today = DateTime.Now.Date;

        var result = Database.EventSchedules.Where(s => s.RecurrenceStart.Value.Date <= today &&
             s.RecurrenceEnd.Value.Date >= today &&
             s.BaseEvent.IsApproved.Value && !s.IsRemoved.Value &&
             s.BaseEvent.EventsCategories.Any(
             c => c.EventCategory.Name == tab) && s.BasePlace.Name).ToList();

        return result.Where(s => Evaluator.CheckDate(s, today)).ToList();
    }

I don't want to create separate methods for this. What is best way to do this?

Thanks.


texts: Reducing Inventory Quantity When Order Is Being Processed

texts:
I've got a method which removes quantity from inventory when an order is completed. If there is not enough inventory quantity available, the order completion fails and the sql transaction is rolled back. Otherwise, transaction is commited.
I'm using Dapper for MySQL database access
        public async Task<(bool, string)> CompleteInvoice(Invoice invoice, List<InvoiceLineItem> lineItems)
        {
            bool success = true;
            string errorProductNumber = null;

            if (!await UpdateInvoiceLineItemsAsync(lineItems))
                return (false, "Error saving line items. Please try again.");
            //Check to see if there is available quantity
            using (var conn = _InvoiceRepository.DbConnection)
            {
                conn.Open();

                // create the transaction
                using (var trans = conn.BeginTransaction(System.Data.IsolationLevel.RepeatableRead))
                {
                    try
                    {
                        var selectProductSQL = "SELECT InventoryNumber,Quantity FROM Product WHERE Id = @productId";
                        var updateProductSQL = "UPDATE Product SET Quantity = @NewQuantity WHERE Id = @productId";
                        DynamicParameters productParameters;
                        foreach (var lineItem in lineItems)
                        {
                            productParameters = new();
                            productParameters.Add("productId", lineItem.ProductId, System.Data.DbType.String);
                            var cprod = await conn.QueryFirstOrDefaultAsync<Product>(selectProductSQL, productParameters, trans);

                            if (cprod.Quantity >= lineItem.Quantity)
                            {
                                productParameters.Add("NewQuantity", cprod.Quantity - lineItem.Quantity, System.Data.DbType.Int32);
                                if (await conn.ExecuteAsync(updateProductSQL, productParameters, trans) != 1)
                                {
                                    success = false;
                                }
                            }
                            else
                            {
                                errorProductNumber = cprod.InventoryNumber;
                                success = false;
                            }
                            if (!success)
                                break;
                        }
                        if (success)
                        {
                            invoice.InvoiceStatus = "COMPLETE";
                            if (!await UpdateInvoiceAsync(invoice))
                            {
                                success = false;
                                errorProductNumber = "Error saving invoice";
                            }
                        }
                        // if it was successful, commit the transaction
                        if (success)
                            trans.Commit();
                        else
                        {
                            trans.Rollback();
                        }
                    }
                    catch (Exception ex)
                    {
                        // roll the transaction back
                        trans.Rollback();

                        // handle the error however you need to.
                        //throw;
                    }
                }
            }
            return (success, errorProductNumber);
        }

I'm open and any General feedback.
Am I correctly using the SQL Transaction mechanism?(Also with Dapper?)


texts: Calculate square of a number without multiplication

texts:
I wrote these two methods to calculate the square of a number:

static int sqr(int val)
{
    int valSqr = 0;

    for (int i = 0; i < val; i++)
        valSqr += val;

    return valSqr;
}

static int sqr(int val)
{
    int valSqr = 0;

    for (int i = 0, j = 1; i < val; i++, j += 2)
        valSqr += j;

    return valSqr;
}

The first one simply adds the given number to a value until it has been added number times.  The second one uses the 1+3+5... sequence.  I tried to profile this on Visual Studio, but the report was taking a really long time (over two hours) to be generated after the data collection was done.  I am particularly interested in which of these methods will run faster, and which is less resource intensive (would the second one be slightly more resource intensive because there are more variables?).


texts:
I have this jQuery handled buttons. But I think I overdid it with the if else statements.

I am wondering if the code can be more efficient in some way than what I have. It's mainly voting up and down. So what is does is toggle buttons and inserts HTML.

function handleVote(commentid, voted, type){
    $.ajax({
      url: endpoint + commentid + "/update/",
      method: "PATCH",
      data: { commentid: commentid, voted: voted,  type: type},
      success: function(data){
        console.log(data)
        if(type === 'down' && voted === 'True'){
          $('.comment-item .down-vote .i-down-'+commentid+'').toggleClass('active-color');
          $('.comment-item .down-vote .i-down-'+commentid+'').toggleClass('opacity-initial');
          $('.comment-item .down-vote .i-down-'+commentid+'').css('opacity', '0.2')
        } else if(type === 'down' && voted === 'False'){
          $('.comment-item .down-vote .i-down-'+commentid+'').toggleClass('active-color');
          $('.comment-item .down-vote .i-down-'+commentid+'').toggleClass('opacity-initial');
        } else if(type === 'up' && voted === 'True'){
          $('.comment-item .up-vote .i-up-'+commentid+'').toggleClass('primary-color');
          $('.comment-item .up-vote .i-up-'+commentid+'').toggleClass('opacity-initial');
          $('.comment-item .up-vote .i-up-'+commentid+'').css('opacity', '0.2')
        } else if(type === 'up' && voted === 'False'){
          $('.comment-item .down-vote .i-up-'+commentid+'').toggleClass('primary-color');
          $('.comment-item .down-vote .i-up-'+commentid+'').toggleClass('opacity-initial');
        }

        $(".comment-vote-down .vote-count-down-" + commentid +"").html(`-${data.num_vote_down}`);
        $(".comment-vote-up .vote-count-up-" + commentid +"").html(`+${data.num_vote_up}`);
      },
      error: function(data){
        var msg = formatErrorMsg(data.responseJSON)
        $("[data-id='" + commentid + "']").closest('div .comment-wrapper').after(msg);
      }
    })
  }


texts:
I have created a brute-force algorithm class in C# and I was wondering if I could speed up the process of creating a new string. There are two methods inside the class: one returns the brute-force string and one returns the number of strings created.

public class BruteForce
{
    int IntPasswordsGenerated = 0;
    public char[] CharList = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    public List<int> IntList = new List<int> { 0 };

    public string GenerateString()
    {
        int Number = IntList.Count - 1;

        IntPasswordsGenerated++;
        if (IntPasswordsGenerated == 1) return CharList[0].ToString();

        do
        {
            IntList[Number]++;
            if (IntList[Number] == CharList.Length && Number == 0)
            {
                IntList[Number] = 0;
                IntList.Add(0);
                break;
            }
            else if (IntList[Number] == CharList.Length)
            {
                IntList[Number] = 0;
                Number--;
                continue;
            }
            else
            {
                break;
            }
        } while (true);

        string BruteForceString = "";

        foreach (int CurrentInt in IntList)
            BruteForceString += CharList[CurrentInt];

        return BruteForceString;
    }
    public int PasswordsGenerated()
    {
        return IntPasswordsGenerated;
    }
}


texts: A random relative prime number based on the modulus

texts:
I am implementing RSA in java using BigInteger and I have a method to return a random relative prime number based on the modulus m.

The method looks like this:

BigInteger prime = new BigInteger(m.bitLength(),rnd);

    while (prime.compareTo(BigInteger.ZERO) <= 0 || !prime.gcd(m).equals(BigInteger.ONE) )
    {
        prime = new BigInteger(m.bitLength(),rnd);
    }

Is there anyway to make this more efficient? I dont know if recreating an object like this is bad or not.


texts: Generate xyz coordinates of a tube made of multiple rings

texts:
In this code, I generate the coordinates of a tube made of multiple rings. Finally, I write those x,y,z coordinates in a .csv file. I want to simplify this code (maybe using a for loop?).

import numpy as np
import matplotlib.pyplot as plt

bLength=1.6
numPoints=10
radius = bLength*numPoints / (2 * np.pi)
theta = np.linspace(0,2*np.pi,numPoints,endpoint=False)
dtheta=theta[1]-theta[0]

#creating the x, y coordinates of the first ring
x0,y0=(radius * np.cos(theta)), (radius * np.sin(theta))
#creating the x, y coordinates of the second ring
x1,y1=(radius * np.cos(theta+dtheta/2)) , (radius * np.sin(theta+dtheta/2))
#above first ring and second ring will come alternatively to form a tube.
#plt.plot(x0,y0)
#plt.show()
#plt.plot(x1,y1)
#plt.show()
#now generating the z-coordinate of the first ring, second ring, third ring, etc.
cons0=np.ones(x0.shape)*0
cons1=np.ones(x1.shape)*2
cons2=np.ones(x0.shape)*4
cons3=np.ones(x1.shape)*6
cons4=np.ones(x0.shape)*8
cons5=np.ones(x1.shape)*10
cons6=np.ones(x0.shape)*12
cons7=np.ones(x1.shape)*14
cons8=np.ones(x0.shape)*16
cons9=np.ones(x1.shape)*18

###Now saving the x, y, z coordinates in csv files.

np.savetxt('cooRing00.csv',np.c_[x0,y0,cons0],delimiter=' ',fmt='%10f')
np.savetxt('cooRing01.csv',np.c_[x1,y1,cons1],delimiter=' ',fmt='%10f')
np.savetxt('cooRing02.csv',np.c_[x0,y0,cons2],delimiter=' ',fmt='%10f')
np.savetxt('cooRing03.csv',np.c_[x1,y1,cons3],delimiter=' ',fmt='%10f')
np.savetxt('cooRing04.csv',np.c_[x0,y0,cons4],delimiter=' ',fmt='%10f')
np.savetxt('cooRing05.csv',np.c_[x1,y1,cons5],delimiter=' ',fmt='%10f')
np.savetxt('cooRing06.csv',np.c_[x0,y0,cons6],delimiter=' ',fmt='%10f')
np.savetxt('cooRing07.csv',np.c_[x1,y1,cons7],delimiter=' ',fmt='%10f')
np.savetxt('cooRing08.csv',np.c_[x0,y0,cons8],delimiter=' ',fmt='%10f')
np.savetxt('cooRing09.csv',np.c_[x1,y1,cons9],delimiter=' ',fmt='%10f')

###Now, I have the x, y, z coordinates in many files (based on the length of the tube I want.


texts: What is the best way to pass an argument from one subcomponent to other subcomponent?

texts:
Hi I was just asked by stackoverflow to move this question into this forum (https://stackoverflow.com/questions/67685433/how-to-design-the-react-component-properly).
Hi I am pretty new to react and I want to achieve something that turns out to be real pain for me and I am not sure what the best solution might be.
I got an application that handles a single keystore as application keystore and the admin is allowed to upload new keystores and merge the entries of these keystores into the application keystore. This results in the following class definition:
export default class ApplicationKeystore extends React.Component
{

    constructor(props)
    {
        super(props);
        this.scimResourcePath = "/scim/v2/Keystore";
        this.state = {};
        this.setAliasSelectionResponse = this.setAliasSelectionResponse.bind(this);
        this.onAliasSelectionSuccess = this.onAliasSelectionSuccess.bind(this);
    }

    setAliasSelectionResponse(resource)
    {
        let copiedResource = JSON.parse(JSON.stringify(resource));
        this.setState({aliasSelectionResponse: copiedResource})
    }

    onAliasSelectionSuccess(resource)
    {
        this.setState({newAlias: resource[ScimConstants.CERT_URI].alias})
    }

    render()
    {
        return (
            <React.Fragment>
                <KeystoreUpload scimResourcePath={this.scimResourcePath}
                                setAliasSelectionResponse={this.setAliasSelectionResponse} />
                <AliasSelection scimResourcePath={this.scimResourcePath}
                                aliasSelectionResponse={this.state.aliasSelectionResponse}
                                onCreateSuccess={this.onAliasSelectionSuccess} />
                <KeystoreEntryList scimResourcePath={this.scimResourcePath}
                                   newAlias={this.state.newAlias} />
            </React.Fragment>
        )
    }
}

My problem now occurs on the last component KeystoreEntryList. The upload succeeds and the selection of entries to be merged works also correctly (just one at a time not several). But if I successfully merge an entry I get a response with the alias of the keystore entry that should now be added to the state of KeystoreEntryList. How do I do this in a clean way. I found several workarounds but all of them are dirty and make the code hard to read...
the important part of the KeystoreEntryListcan be found here:
class KeystoreEntryList extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state = {aliases: []};
        this.setState = this.setState.bind(this);
        this.scimClient = new ScimClient(this.props.scimResourcePath, this.setState);
        this.onDeleteSuccess = this.onDeleteSuccess.bind(this);
    }

    async componentDidMount()
    {
        let response = await this.scimClient.listResources();
        if (response.success)
        {
            response.resource.then(listResponse =>
            {
                this.setState({
                    aliases: new Optional(listResponse.Resources[0]).map(val => val.aliases)
                                                                    .orElse([])
                })
            })
        }
    }

    componentDidUpdate(prevProps, prevState, snapshot)
    {
        // TODO if we delete an alias and add the same again the following if condition prevents adding it again
        if (prevProps.newAlias !== this.props.newAlias && this.props.newAlias !== undefined)
        {
            let aliases = this.state.aliases;
            aliases.push(this.props.newAlias);
            aliases.sort();
            this.setState({aliases: aliases, aliasDeleted: undefined});
        }
    }
   ...
}

my first idea was to do it on the componentDidUpdate method  but this results in the problem stated out by the TODO. Is there any good way how I might be able to smoothly add the new alias into this component?


texts: Different selects in one form with same name attribute?

texts:
I have the following scenario:

    class Product < ActiveRecord::Base
        belongs_to :categories
    end

    class Category < ActiveRecord::Base
        has_many :products
    end

Categories table has 2 level nesting, for example.
Main category is 'Men', sub-category is 'Accessories' and sub-sub-category is 'Watches'.

Now when user creates new product he must choose category(only main category is required, but he can also chose sub and sub-sub category optional).

My idea is this: I created 3 different select boxes with same name "product[category_id]", so only the last selected value will be sent to the server through params[:product][:category_id].

     Main category? required
    <%= f.select :category_id,
            Category.where('category_id IS ?', nil).collect {|c| [c.name, c.id]},
            { include_blank: "Select category..." },
            id: 'main-category', class: 'form-control' %>

     What type? optional
    <%= f.select :category_id, {}, {}, class: 'form-control' %>

     What type? optional
    <%= f.select :category_id, {}, {}, class: 'form-control' %>

2nd(sub-categories) and 3rd(sub-sub-categories) are initial empty ({}, {}) and hidden through CSS(display: none) and will be populated through Ajax call.

$('#main-category, .category-level-1 > select').change(function() {
    var selectBox = this.id;
    var selectedValue = $(this).val();
    var url = '/categories/' + selectedValue + '/subcategories';

    $.get(url, function(data) { createSelect(data, selectBox); });
});

function createSelect(data, selectBox) {
  var $currentSelect = null;

  if (selectBox == 'main-category') {
    $('.category-level-1').show();
    $('.category-level-2').hide();
    $('.category-level-1 > select').find('option').remove();

    $currentSelect = $('.category-level-1 > select');
  }
  else {
    $('.category-level-2').show();
    $('.category-level-2 > select').find('option').remove();

    $currentSelect = $('.category-level-2 > select');
  }

  $currentSelect.append('<option selected disabled>Select Category...</option>');
  for(var i=0; i<data.length; i++) {
    $currentSelect.append('<option value="' + data[i].id + '">' + data[i].name +
                          '</option>');
  }
}

Where Ajax call is sent to following route (categories controller)

def subcategories
    id = params[:id]
    @subcategories = Category.where('category_id = ?', id)
    render json: @subcategories
end

So for final result i have following:

First of all, is it normal to have different inputs in one form with same names created manually like I did in this example?  For some reason, it seem like 'code-smell' to me. I'm relatively new to Rails, so I wanted to ask if I am violating some good practices with this code.  Can you suggest better ways of achieving the same results?


texts:
The Problem

  In the January 1984 issue of Scientific American, an interesting sequence of numbers known as a hailstone series was described. The series is formed by generating the next number based on the number just prior to it. If the previous number was even, the next number in the series is half of it. If the previous number was odd, the next number is three times it plus one. Although the series goes up and down, it eventually settles into a steady state of 4, 2, 1, 4, 2, 1, … For example, starting at 21, the hailstone series is: 21, 64, 32, 16, 8, 4, 2, 1, 4, 2, 1, … For 21, it required five steps before the steady state was reached.

  Write a program that computes how many steps will be necessary before the steady state is reached in the hailstone series beginning at a given number.

  Sample Input

  Your program must take its input from the ASCII text file hail.in. The file contains a sequence of one or more integer values, one per line. Sample contents of the file could appear as:

  21
10

  Sample Output

  Your program must direct its output to the screen and must tell the number of steps required to reach the hailstone steady state for each integer recorded in the input file. Your program must format its output exactly as that shown below which is the output corresponding to the sample input above.

  5 steps were necessary for 21.
4 steps were necessary for 10.

hail.py

with open('hail.in') as f:
    l = f.readline()
    while l:
        n, a, b, i = int(l[:-1]), [], { 4, 2, 1 }, 0
        while set(a) & b != b:
            if i == 0:
                a.append(n)
            else:
                a.append(a[i-1]/2 if a[i-1] % 2 == 0 else a[i-1]*3+1)
            i += 1
        print(i - len(b), 'steps were necessary for', str(n) + '.')
        l = f.readline()

Any advice on performance enhancement and solution simplification or that is topical is appreciated!


texts:
The Mongo-Scala Driver (v2.6) currently only supports asynchronous operations, although my use cases often seem to lend themselves well to synchronous reads. This may be to block downstream code execution, or to save off the result-set of documents for later use. I'm guessing there may be a way to do this with Futures, but my current implementation doesn't utilize them.

At the moment, I use the following function to perform "synchronous" reads and return a list of documents. It serves my needs of blocking downstream code execution and returning a reusable list of documents, but it doesn't feel like the cleanest way to approach the problem - the use of var in Scala, and while() loops with a Thread.sleep() just feel like bandaids for a better solution. Is there a better way to do this?

// This is the code I'm looking for feedback on

import org.mongodb.scala._
import org.mongodb.scala.bson.Document
import org.mongodb.scala.model.Filters
import scala.collection.mutable.ListBuffer

/* This function optionally takes filters if you do not wish to return the entire collection.
 * Future implementation may include optional {Sorts, Projections, Aggregates}
 */
def getDocsSync(db: MongoDatabase, collectionName: String, filters: Option[conversions.Bson]): ListBuffer[Document] = {
    val docs = scala.collection.mutable.ListBuffer[Document]()
    var processing = true
    val query = if (filters.isDefined) { // conditionally apply filters
        db.getCollection(collectionName).find(filters.get)
    } else {
        db.getCollection(collectionName).find()
    }
    query.subscribe(
        (doc: Document) => docs.append(doc), // add doc to mutable list
        (e: Throwable) => throw e, // handle errors here
        () => processing = false // deontes that we've reached the end of the collection
    )
    while (processing) {
        Thread.sleep(100) // wait here until all docs have been returned
    }
    docs
}

// sample usage of 'synchronous' query
val client: MongoClient = MongoClient(uriString)
val db: MongoDatabase = client.getDatabase(dbName)
val allDocs = getDocsSync(db, "myCollection", Option.empty)
val someDocs = getDocsSync(db, "myCollection", Option(Filters.eq("fieldName", "foo")))

For reference, I'll include a typical asynchronous usage pattern for the Mongo-Scala Driver. As a quick note, I'd like to point out that I use this pattern whenever possible since it doesn't require the entire collection to be loaded into memory, which makes async a must for large collections.

// typical asynchronous usage pattern
db.getCollection(collectionName).find().subscribe(
    (doc: org.mongodb.scala.bson.Document) => {
        // operate on an individual document here
    },
    (e: Throwable) => {
        // do something with errors here, if desired
    },
    () => {
        // deontes that we've reached the end of the collection
    }
)


texts:
I got the original problem from Leetcode for top k frequent elements,  But I decide to simplify the problem just top 2 elements to make it simpler to solve.

// Given an array, return an array of the top 2 most elements.
// Input: [1, 2, 3, 4, 5, 3, 4] | Output: [3, 4]
// Input: [2, 2, 3, 2, 4, 3, 4] | Output: [2,4]

const topTwoElement = nums => {
  const arr = [];
  nums.forEach(num => {
    arr[num] ? arr[num][1]++ : arr[num] = [num, 1];
  });

  arr.sort((a, b) => b[1] - a[1]);
  return [arr[0][0], arr[1][0]];
};

console.log(topTwoElement([3, 2, 3, 4, 5, 3, 4])); //[3,4]
console.log(topTwoElement([2, 2, 3, 2, 4, 3, 4])); //[2,4]


texts:
This is a function that reads until EOF and reallocs as it goes.

char *
read_to_end(int fd, int *bread)
{
    ssize_t size, nread, rc;
    char *buf, *tmp;

    nread = 0;
    size = MINLEN;
    buf = malloc(size);

    while ((rc = read(fd, buf + nread, size - nread))) {
        if (rc < 0) {
            if (errno == EINTR)
                continue;

            goto error;
        }

        nread += rc;

        /* See if we need to expand. */
        if (size - nread < MINLEN) {
            size *= 2;

            /* Make sure realloc doesn't fail. */
            if (!(tmp = realloc(buf, size)))
                goto error;

            buf = tmp;
        }
    }

    /* Shrink if necessary. */
    if (size != nread && !(tmp = realloc(buf, nread)))
        goto error;

    buf = tmp;
    *bread = nread;
    return buf;

error:
    free(buf);
    return NULL;
}

Do you have any improvement suggestions?