texts:
I have been doing this challenge in which I need to determine and return one's (i.e. alice) rank on a leaderboard by comparing her scores to the others'. I made this work in all but this one case where there are 200000 scores on the board, so I believe my program is not effective at large scale. I am receiving a timeout error. I tried to shorten the program as much as possible but I think loops are still too much of a problem. I would appreciate any suggestions.

#include <bits/stdc++.h>

using namespace std;

vector <int> climbingLeaderboard(vector <int> scores, vector <int> alice) {
    vector<int> result;
    reverse(alice.begin(), alice.end());
    int lastIndex = 0;
    int lastRank = 1;

    for (int i = 0; i < alice.size(); i++) {

        int rank = lastRank;
        for (int j = lastIndex; j < scores.size(); j++) {
            if (alice[i] >= scores[j]) {
                lastIndex = j;
                break;
            }

            else if (alice[i] < scores[j]) {
                rank++;
            }

            if (scores[j] == scores[j+1] && rank != 1) {
                rank--;
            }
        }
        result.push_back(rank);
        lastRank = rank;
    }
    reverse(result.begin(), result.end());

    return result;
}

int main() {
    int n;
    cin >> n;
    vector<int> scores(n);
    for(int scores_i = 0; scores_i < n; scores_i++){
       cin >> scores[scores_i];
    }
    int m;
    cin >> m;
    vector<int> alice(m);
    for(int alice_i = 0; alice_i < m; alice_i++){
       cin >> alice[alice_i];
    }
    vector <int> result = climbingLeaderboard(scores, alice);
    for (ssize_t i = 0; i < result.size(); i++) {
        cout << result[i] << (i != result.size() - 1 ? "\n" : "");
    }
    cout << endl;

    return 0;
}

Sample Input

7
100 100 50 40 40 20 10
4
5 25 50 120

Sample Output

6
4
2
1

Explanation

The second row of input is composed of the scores on the leaderboard and the fourth row contains the scores of Alice. The score she gets during each attempt is compared with other scores on the leaderboard to determine her rank. Dense Ranking is used here. So from the sample input, the first two 100s on the leaderboard rank 1st and then 50 ranks the 2nd, both 40s rank 3rd and so on.


texts: How can I speed up my calculations with loops? Python

texts:
I wrote this code. But it works very slowly.
I'm figuring out how many times I have to run the case generator to find numbers less than or equal to inv, in this case six. I count the number of attempts until a digit <= 6 is generated. I find inv equal to 1 and repeat the loop. Until inv is 0. I will keep trying to generate six digits <= 6.
And I will repeat all this 10 ** 4 degrees again to find the arithmetic mean.
Help me speed up this code. Works extremely slowly. The solution should be without third-party modules. I would be immensely grateful. Thank!
import random

inv = 6

    def math_count(inv):
        n = 10**4
        counter = 0
        while n != 0:
            invers = inv
            count = 0
            while invers > 0:
                count += 1
                random_digit = random.randint(1, 45)
                if random_digit <= invers:
                    invers -= 1
                    counter += count
                    count = 0

            if invers == 0:
                n -= 1
                invers = inv

        return print(counter/10**4)

math_count(inv)


texts:
I just finished Project Euler 37 after a bit of debugging and can't figure out how to make it faster. Whenever I add extra tests that I want to speed the program up, it ends up just slowing it down. My primes test is from here. Please help me optimize!

from primes import test as is_prime
from itertools import product
from timeit import default_timer as timer

def is_trunc(list_num):
    num = ''.join(map(str, list_num)) # turn (1, 2, 3) into 123
    if is_prime(int(num)):
        for k in range(1, len(num)):
            if not is_prime(int(num[k:])) or not is_prime(int(num[:k])):
                return False
        return True
    return False

start = timer()
data = {"count": 0, "length": 2, "sum": 0}

while data["count"] < 11:
    for combo in product([1, 2, 3, 5, 7, 9], repeat = data["length"]):
        if is_trunc(combo):
            data["count"] += 1
            data["sum"] += int(''.join(map(str, list(combo))))
    data["length"] += 1

ans = data["sum"]
elapsed_time = (timer() - start) * 1000 # s --> ms

print "Found %d in %r ms." % (ans, elapsed_time)


texts:
I recently started with object oriented programming in PHP and I am wondering if my database class is on the right track.

Am I doing something wrong? If so, how can I improve it?

Here is the class:

    <?php
    class PDOC extends PDO{
        private $myselhost;
        private $dbname;
        private $myseluser;
        private $mysqlpass;

        public function __construct($mysqlhost, $dbname, $mysqluser, $mysqlpass){
            try{
                parent::__construct("mysql:dbname={$dbname};host={$mysqlhost}", $mysqluser, $mysqlpass);
                $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }catch(PDOException $e){
                return $e->getMessage();
                //die('Something went wrong, please try again.');
            }
        }

        public function queryInsert($tableName, $insertKey, $insertData, $executeData){
            $prepare = parent::prepare("INSERT INTO {$tableName} ({$insertKey}) VALUES ({$insertData})");

            try{
                $prepare->execute(
                    $executeData
                );
            }catch(PDOException $e){
                return $e->getMessage();
            }
        }

        public function queryUpdate($tableName, $insertData, $executeData, $insertWhereKey, $insertWhereValue){
            $prepare = parent::prepare("UPDATE {$tableName} SET {$insertData} WHERE {$insertWhereKey} = {$insertWhereValue}");

            try{
                $prepare->execute(
                    $executeData
                );
            }catch(PDOException $e){
                return $e->getMessage();
            }
        }

        public function queryDelete($tableName, $deleteWhereKey, $deleteWhereValue){
            $prepare = parent::prepare("DELETE FROM {$tableName} WHERE {$deleteWhereKey} = {$deleteWhereValue}");

            try{
                $prepare->execute();
            }catch(PDOException $e){
                return $e->getMessage();
            }
        }

        public function querySelect($tableName, $selectData, $sellectWhereKey = null, $selectWhereValue = null, $orderByKey = null, $orderByValue = null){
            if(isset($selectWhereKey, $selectWhereValue)){
                $prepare = parent::prepare("SELECT {$selectData} FROM {$tableName} WHERE $insertWhere");
            }
            elseif(isset($orderByKey, $orderByValue)){
                $prepare = parent::prepare("SELECT {$selectData} FROM {$tableName} ORDER BY {$orderByKey} {$orderByValue}");
            }
            elseif(isset($selectWhereKey, $selectWhereValue, $orderByKey, $orderByValue)){
                $prepare = parent::prepare("SELECT {$selectData} FROM {$tableName} WHERE {$selectWhereKey} = {$selectWhereValue} ORDER BY {$orderByKey} {$orderByValue}");
            }
            else{
                $prepare = parent::prepare("SELECT {$selectData} FROM {$tableName}");
            }

            try{
                $prepare->execute();
            }catch(PDOException $e){
                return $e->getMessage();
            }
        }
    }
?>


texts: Class and Static practice, IDS and a max instance count

texts:
I was practicing working with classes and the static property included with them and came up with a simple ID counter and max number list. I also added a quick debug error throw if it goes over. Here's what I came up with:

#include <iostream>

// A class that has static variables to save information for the ID's of its instances.
class HoldIdentity{
private:
    static int const maxInstances = 20;
    static int created; // = 0; error
public:
    static int getMax(){
        return maxInstances;
    }
    // A static function that will return an array on the heap of every /possible/ remaining Identity Holder.
    static HoldIdentity* const createAll(){
      int length = maxInstances - created;
      HoldIdentity*JAM = new HoldIdentity[maxInstances - created];
      for (int i = 0; created < maxInstances; JAM[i++]=HoldIdentity());
      return JAM;
    };
private:
    int id;
public:
    HoldIdentity(){
        id = created++;
        if (created > maxInstances){
            created--;
            std::string error = "To many instances!";
            throw (error);
        }
    }
    // Destructor displays the id.
    ~HoldIdentity(){
        displayID();
    }
    void displayID() const{
        std::cout << "my id:" << id << std::endl;
    }
};

//int HoldIdentity::created = 0;
int main(){
    using namespace std;
    HoldIdentity numba1{};
    numba1.displayID();
    HoldIdentity *allInstances = HoldIdentity::createAll();

    // because creating more than the max causes an error.
    // I suppose I should have put all prior code in here as well.
    try{
        HoldIdentity numbaPast{};
        HoldIdentity numbaPast2{};
        HoldIdentity numbaPast3{};
    }
    catch (...){
        // I think I could have used a string to retrieve the message?
        cout << " too many instances! ";

    }

    // free array from the heap.
    delete[] allInstances;
    system("pause");
    return 0;
}

edit: Is there any little bit of code here that could be improved? I've only just started working on C++(again) this week so I'm sure there's many alternatives. But specifically if my own code for determining and handling IDS are bad. Besides that, is my error handling a good practice?


texts:
I use this function to to do some calculations based on 4 select inputs and one number input, I don't have experience in Js, I did some research in w3schools then I ended up with the function below.
The Js function is working exactly as I want, but I feel it is not the perfect syntax and it could be shorter and somehow cleaner, any advice would be appreciated.

function calculate() {
  var x = parseFloat(document.getElementById("Lang_from").value);
  var y = parseFloat(document.getElementById("Lang_to").value);
  var q = parseFloat(document.getElementById("quantity").value);
  var s = parseFloat(document.getElementById("subject").value);
  var f = parseFloat(document.getElementById("file_type").value);
  var xx = document.getElementById('Lang_from').selectedOptions[0].text;
  var yy = document.getElementById('Lang_to').selectedOptions[0].text;
  var ff = document.getElementById('file_type').selectedOptions[0].text;
  var ss = document.getElementById('subject').selectedOptions[0].text;

  document.getElementById("total_price").innerHTML = (x + y) * q + (s + f);
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

From

        <select id="Lang_from" name="Lang_from" value="" class="form-control pricing_input">
          <option id="en2ar" value="0.025">English</option>
          <option>German</option>
        </select>

To

        <select id="Lang_to" name="Lang_to" value="" class="form-control pricing_input">
          <option value="0.025">German</option>
          <option>English</option>
        </select>

File type

        <select id="file_type" name="file_type" value="" class="form-control pricing_input">
          <option value="0">TXT</option>
          <option value="3">MS word</option>
          <option value="5">PDF (+5$)</option>
          <option value="10">Hand Writing</option>
        </select>

Subject

        <select id="subject" name="subject" value="" class="form-control pricing_input">
          <option value="0">General</option>
          <option value="10">Technical / IT</option>
          <option value="15">Medical</option>
          <option value="5">Press</option>
        </select>

Word count

        <input type="number" id="quantity" name="quantity" min="500" value="1000" class="form-control pricing_input pricing_input_number">

        <button id="calculate" type="button" class="btn btn-primary pricing_btn_calc" onclick="calculate()">Calculate</button>


texts:
I am making a Reddit bot and to prevent my bot from posting to the same comment twice, instead of making a database, I decided I would rather create a temporary list (or "queue") that once appended to, checks to ensure the maximum length of the queue hasn't been exceeded. Once exceeded, however, the queue is cleared.

class TemporaryQueue:
    def __init__(self, max_items=10):
        self._queue = []
        self.max_items = max_items

    def __repr__(self):
        return "<TemporaryQueue max_items={}>".format(self.max_items)

    def __iter__(self):
        yield from self._queue

    def __eq__(self, other):
        return other in self._queue

    def _exceed_check(self):
        if len(self._queue) > self.max_items:
            return True
        return False

    def append(self, value):
        if self._exceed_check():
            self._queue.clear()

        return self._queue.append(value)

Example usage:

for submission in reddit.subreddit("funny").stream.submissions():
    queue = TemporaryQueue()

    if submission.id not in queue:
        if "foo" in title:
            submission.reply("Bar!")
            queue.append(submission.id)


texts: LINQ foreach - error handling and general improvement

texts:
I'm looking for two kinds of feedback:

Is there a better way of doing what I'm attempting to do?
Any obvious weaknesses that could potentially cause problems?

The code in question (I've broken it into lines to prevent horizontal scroll):

items.ForEach(i =>
                i.JobOrderTypeString = Context.JobOrderTypes.Where(x =>
                    x.JobOrderTypeIdentifier == i.JobOrderTypeIdentifier.CodeListItemIdentifier)
                    .FirstOrDefault().Title);

Datatypes:

items is a List of simple ViewModels

My worries:

If FirstOrDefault() returns null (though very unlikely), and I'm "reading" the .Title property, will my code crash?
I'm using Context on each iteration, which I'm suspecting is probably not the best idea.


texts:
I have this ugly age printing method. Can you do better?

def age(birth_date)
  today = Date.today
  years = today.year - birth_date.year
  months = today.month - birth_date.month
  (months -1) if today.day < birth_date.day
  if years == 0 && months == 1
    age =  "#{months} month"
  elsif years == 0 && months > 1
    age =  "#{months} months"
  elsif years > 0 && months > 0
    age = years == 1 ? "1 year, #{months} months" : "#{years} years, #{months} months"
  elsif years > 0 && months < 0
    months = months + 12
    years = years - 1
    age = "#{months} months" if years == 0
    age = "1 year, #{months} months" if years == 1
    age = "#{years} years, #{months} months" if years == 1
  end
  age
end


texts: Counting number of 'if' statements in SAS

texts:
I am writing a C# script to count all the 'if...then' statements present in 4000 lines of SAS code. I am taking the SAS code as a text file and then performing my operation. Here's my C# code:

class Program
{

static void Main(string[] args)
{

    List<String> list = new List<string>();
    list = File.ReadAllLines(@"C:\Users\Dey\Documents\Trucks\file.doc").ToList();
    int count = CountIfs(list);
    Console.ReadKey();
}

static int CountIfs(List<String> list)
{
    int count = 0;
    var index = new List<int>();
    var value = new List<String>();

    for (int i = 0; i < list.Count; i++)
    {
        if (list[i].Contains("if"))
        {
            if (list[i].Contains("then") || list[i + 1].Contains("then"))
            {
                count++;
                index.Add(i);
                String temp = null;

                if(list[i].Contains(";"))
                temp = list[i].Substring(0, list[i].IndexOf(";"));

                if (temp != null)
                {
                    value.Add(temp);
                }
            }

        }
    }
    return count;
}
}

I'm essentially checking for "if" per line and if that is found, i'm checking for "then". And finally I'm also making sure its one line of code by checking for ";" . My logic is that if all these conditions satisfy, then I am indeed able to extract all the if-statements from the code. The list "value" would contain all the "if" statements found in the code. Now I've output "value" to a textfile in notepad and have manually cross-checked about 20 entries. And so far it seems to be working alright. I was hoping someone can proof-read my code and tell me if I can improve it somewhere perhaps? Or is this logic sufficiently accurate?


texts: Printing the most used words from phrases

texts:
I have a collection of phrases in a List. Each phrase is a String Array where each element in the array is a word.

I create a List<Entry<String, Integer>> which holds the words as keys and the times used as value. Everything is sorted by value in descending order.

Then what I do is print the top X words that were used along with how many times they were used. What I want to know is if there is a better/simpler way of doing it and generally anything you want to add to make my code look or perform better.

Here is my code:

public class WordCounting {

    public static void printTopWords(final int numberOfWords, List<String[]> phrases) {
        List<Entry<String, Integer>> wordsMap = entriesSortedByValues(wordCount(phrases));

        Iterator entries = wordsMap.iterator();
        int wordsCounter = 1;
        while (entries.hasNext() && wordsCounter <= numberOfWords) {
            Entry entry = (Entry) entries.next();
            String key = (String) entry.getKey();
            int value = (int) entry.getValue();

            System.out.println(wordsCounter + ": " + key + " - " + value);
            wordsCounter++;
        }
    }

    private static Map<String, Integer> wordCount(List<String[]> phrases) {
        Map<String, Integer> wordCounter = new TreeMap<>();

        for (String[] strings : phrases) {
            for (String string : strings) {
                wordCounter.put(string, wordCounter.get(string) == null
                        ? 1 : wordCounter.get(string) + 1);
            }
        }
        return wordCounter;
    }

    static <K, V extends Comparable<? super V>>
            List<Entry<K, V>> entriesSortedByValues(Map<K, V> map) {

        List<Entry<K, V>> sortedEntries = new ArrayList<>(map.entrySet());

        Collections.sort(sortedEntries,
                new Comparator<Entry<K, V>>() {
                    @Override
                    public int compare(Entry<K, V> e1, Entry<K, V> e2) {
                        return e2.getValue().compareTo(e1.getValue());
                    }
                }
        );

        return sortedEntries;
    }
}


texts: Showing jQuery UI tooltip on focus of text box

texts:
Firstly, here's a link to the fiddle.

Basically my situation is that there is a requirement to show tooltips on textboxes on some forms being created for a website to allow employees to update their personal information (among other things).

The customer likes the idea of the tooltip being displayed to the right of the textbox when the user clicks into it rather than jQuery UI's default of when hovering over it. To that end, I created the following code that shows and hides the tooltip when the user clicks into/out of the textbox:

$(function () {
    $('.tooltip').each(function () {
        var $this,
            id,
            t;

        $this = $(this);
        id = this.id;
        t = $('<span />', {
            title: $this.attr('title')
        }).appendTo($this.parent()).tooltip({
            position: {
                of: '#' + id,
                my: "left+190 center",
                at: "left center",
                collision: "fit"
            }
        });
        // remove the title from the real element.
        $this.attr('title', '');
        $('#' + id).focusin(function () {
            t.tooltip('open');
        }).focusout(function () {
            t.tooltip('close');
        });
    });
});

My question is simple, is there a better way of doing this?

Note that I can rely on the inputs always having a unique Id as this is an ASP.Net application.


texts: Count number of previous elements greater than its element at present index

texts:
Suppose I have a vector containing n elements. I want to find out the number of previous elements greater than its element at present index i. I want to find A[i] > A[j] && i < j for all elements of the vector.

Constraints:

1 <= t <= 1000
1 <= n <= 10^5
1 <= A[i] <=10^5

My code:

#include<bits/stdc++.h>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    cin >> t;

    while(t--) {
        int n,a,i,j;
        cin >> n;

        vector<int>v1;

        for(i=0;i<n;i++) {
            cin >> a;
            v1.push_back(a);
        }
        int cnt=0,sum=0;

        for(i=0;i<n;i++) {
            if( i!=0) {
                for(j=0;j<i;j++) {
                    if(v1[i]<v1[j]) {
                        cnt++;
                    }
                }
            }
            //  cout << cnt << " ";
            sum=sum+cnt;
            cnt=0;
        }

        cout << sum << '\n';
    }
}

This code is running fine for all the test cases except only one. It is showing the Time limit exceeded for one of the test cases. Can anyone help me?


texts:
I am new to C++ and am looking to expand my knowledge. Below is a simple program that I've made. I would like to know how it could be improved, in any way. The introduction of new ways to do things is what I am looking for. These could be anything from improving efficiency to validating input - just whatever you think is most important or beneficial.

float calculate(float x, char y, float z) {
    float answer;

    switch (y) {

        case '+':
            answer = x + z;
            break;

        case '-':
            answer = x - z;
            break;

        case '/':
            answer = x / z;
            break;

        case '*':
            answer = x * z;
            break;

        default:
            return(0);
    }

    cout <<"= "; return answer;
}

int main() {
    float num1;
    float num2;
    char aOp;

    cout << ">> ";
    cin >> num1 >> aOp >> num2;
    cout << calculate(num1, aOp, num2) << endl << endl;
}


texts: Monitoring progress in Parallel.ForEach every minute

texts:
I'm using Parallel.ForEach to download 500K URLs and I want to monitor the number of URLs that have been successfully downloaded each minute.

        int elapsedMinutes = 0, cnt = 0;
        Parallel.ForEach(list, tuple =>
        {
            var currMinutes = (int) ((DateTime.Now - startTime).TotalMinutes);
            lock (Object)
            {
                if (currMinutes > elapsedMinutes)
                {
                    elapsedMinutes = currMinutes;
                    Console.WriteLine("{0}: Extracted {1} urls", DateTime.Now, cnt);
                }
            }

            //download urls ...

            Interlocked.Increment(ref cnt);
        });

It looks fine now but the lock statement part seems a bit ugly to me. Is there a better way to achieve this?


texts: Basic text editor in Python with Tkinter

texts:
I have finished writing my nice and little text editor in Python with Tkinter.
I tried to achieve the best user experience that I could.

I want this code to be 2/3 compatible, I tested it in both versions but if you could test it out again in the 2 versions too it would very knd of you.
I did not use a class on purpose because I think that there is no need for it in such a small project (< 100 lines), do you think I should use classes also in small projects like this?
Is the user going to use this without problems?
Is the code going to be readable if I look back at it after, let's say, a year?
Do I use good names?
I did not use a __name__ guard because this file is not meant to be imported, do you think I should use it anyway?
What other features could I implement?

The code:

try:
    import tkinter as tk
except:
    import Tkinter as tk

try:
    import tkMessageBox as pop_up
except:
    import tkinter.tkMessageBox as pop_up

import time

EMPTY_TITLE_ERROR_MESSAGE_SAVE = "Please write the name of the file you want to save in the given field."
EMPTY_TITLE_ERROR_MESSAGE_OPEN = "Please write the name of the file you want to open in the given field."
FILE_NOT_FOUND_ERROR_MESSAGE = "No file with the given title was found, remember that this text editor can only read files in its directory."
SAVING_SUCCESS_MESSAGE = "Your text is now stored in the {filename} file"
SIGNATURE_TXT_NOT_FOUND_MESSAGE = "Please be sure that the file you want to open exists and that it is in the same folder of this editor."

def _open():
    if not file_title.get():
        pop_up.showerror("Title is empty.",EMPTY_TITLE_ERROR_MESSAGE_OPEN)
        return 1

    if not ".txt" in file_title.get():
        filename = file_title.get() + ".txt"

    try:
        with open(filename) as f:
            main_text.delete("1.0",tk.END)
            main_text.insert(tk.INSERT, f.read(), "a")
    except IOError:
        pop_up.showerror("File not found.",FILE_NOT_FOUND_ERROR_MESSAGE)

def save():
    if not file_title.get():
        pop_up.showerror("No title.",EMPTY_TITLE_ERROR_MESSAGE_SAVE)
        return 1

    if not ".txt" in file_title.get():
        filename = file_title.get() + ".txt"

    with open(filename,"w+") as f:
        f.write(main_text.get(1.0,tk.END))
    pop_up.showinfo("File saved succesfully.",SAVING_SUCCESS_MESSAGE.format(filename=filename))

def add_date():
    full_date = time.localtime()
    day = str(full_date.tm_mday)
    month = str(full_date.tm_mon)
    year = str(full_date.tm_year)
    date = "\n"+day+'/'+month+'/'+year
    main_text.insert(tk.INSERT, date, "a")

def add_signature():
    try:
        with open("signature.txt") as f:
            main_text.insert(tk.INSERT, "\n"+f.read(), "a")
    except IOError:
        MESSAGE = SIGNATURE_TXT_NOT_FOUND_MESSAGE
        pop_up.showerror("\"signature.txt\" not found.",MESSAGE)

root = tk.Tk()

menubar = tk.Menu(root)
menubar.add_command(label="Open", command=_open)
menubar.add_command(label="Save", command=save)
menubar.add_command(label="Add signature",command=add_signature)
menubar.add_command(label="Add date",command=add_date)

root.config(menu=menubar)

top = tk.Frame(root)
temp = tk.Label(root,text="Title:")
temp.pack(in_ = top,side=tk.LEFT)

file_title = tk.Entry(root)
file_title.pack(in_ = top,side=tk.RIGHT)

top.pack()

main_text = tk.Text(root)
main_text.pack()

tk.mainloop()


texts:
Could be useful?

OrdinalIgnoreCase s1 = "a";
OrdinalIgnoreCase s2 = "A";
Assert.AreEqual(s1, s2);

Where:

public class OrdinalIgnoreCase : IEquatable<OrdinalIgnoreCase>
{
    public static StringComparer Comparer { get; } = StringComparer.OrdinalIgnoreCase;

    public static implicit operator OrdinalIgnoreCase(string s) => new OrdinalIgnoreCase(s);
    public static implicit operator string(OrdinalIgnoreCase s) => s.Text;

    public OrdinalIgnoreCase(string text) => Text = text;
    public string Text { get; }

    public override int GetHashCode() => Comparer.GetHashCode(Text);
    public override bool Equals(object obj) => Equals(obj as OrdinalIgnoreCase);
    public virtual bool Equals(OrdinalIgnoreCase other) => Comparer.Equals(Text, other.Text);

    public static bool operator ==(OrdinalIgnoreCase left, OrdinalIgnoreCase right) =>
        Equals(left, right);

    public static bool operator !=(OrdinalIgnoreCase left, OrdinalIgnoreCase right) =>
        !Equals(left, right);

    public override string ToString() => Text;
}


texts: Each element is the sum of itself with the next element of a List: now do this point-free in Haskell

texts:
Here it is the best I can do (I am a noob using Haskell):

map (\(y, z) -> y + z) (zip x (tail x))

I'm looking for a point-free solution.


texts:
This is my final post for my CS1 saga.  Mostly all I had to do was just "class-ify" my past project in this post.  Here are the requirements:

  Make all data members private and use constructors, accessors and
  mutators. Enhancement: Build data verification into the member functions.

I'm mostly concerned with me doing OO programming correctly.  I wasn't very good with it in my Java days way back yonder, and I'm not sure it's that good now either.  Focus in this area would be appreciated.

classyDayOfWeek.cpp:

/**
 * @file classyDayOfWeek.cpp
 * @brief Computes the day of the week given a certain date
 * @author syb0rg
 * @date 12/10/14
 */

#include <cctype>
#include <iostream>
#include <limits>

const std::string weekDays[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

/**
 * The class associated with date values and calculating the day of the week
 */
class Date
{
public:
    int dayOfWeek();
    void getInput();
    bool isLeapYear();
    int getCenturyValue();
    int getYearValue();
    int getMonthValue();
private:
    unsigned day = 0;
    unsigned month = 0;
    unsigned year = 0;
};

/**
 * Makes sure data isn't malicious, and signals user to re-enter proper data if invalid
 */
unsigned getSanitizedNum()
{
    unsigned input = 0;
    while(!(std::cin >> input))
    {
        // clear the error flag that was set so that future I/O operations will work correctly
        std::cin.clear();
        // skips to the next newline
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "Invalid input.  Please enter a positive number: ";
    }
    return input;
}

/**
 * Safetly grabs and returns a lowercase version of the character (if the lowercase exists)
 */
char getSanitizedChar()
{
    // absorb newline character (if existant) from previous input
    if('\n' == std::cin.peek()) std::cin.ignore();
    return std::tolower(std::cin.get());
}

/**
 * Determines if the year stored in the Date instance is a leap year
 */
bool Date::isLeapYear()
{
    return (year >= 1582) && (!(year % 400) || (!(year % 4) && (year % 100)));
}

/**
 * Finds the century, divides by 4, and returns the remainder.
 */
int Date::getCenturyValue()
{
    return (2 * (3 - div(year / 100, 4).rem));
}

/**
 * Computes a value based on the years since the beginning of the century.
 */
int Date::getYearValue()
{
    int mod = year % 100;
    return (mod + div(mod, 4).quot);
}

/**
 * Returns a value based on the given hash tables (requires invoking the isLeapYear function)
 */
int Date::getMonthValue()
{
    const static int NON_LEAP_VALS[] = { 0xDEAD, 0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5 };
    const static int LEAP_VALS[] = { 0xDEAD, 6, 2, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5 };
    return (isLeapYear()) ? LEAP_VALS[month] : NON_LEAP_VALS[month];
}

/**
 * Compute the sum of the date's day plus the values returned by getMonthValue, getYearValue, and getCenturyValue.
 */
int Date::dayOfWeek()
{
    return div(day + getMonthValue() + getYearValue() + getCenturyValue(), 7).rem;
}

/**
 * Get's input safely and stores the input in the instances members
 */
void Date::getInput()
{
    std::cout << "Enter the month (1-12): ";
    month = getSanitizedNum();

    std::cout << "Enter the day (1-31): ";
    day = getSanitizedNum();

    std::cout << "Enter the year: ";
    year = getSanitizedNum();
}

int main()
{
    Date date;
    do
    {
        date.getInput();
        std::cout << "The day of the week is " << weekDays[date.dayOfWeek()] << std::endl;

        std::cout << "Run the program again (y/N): ";  // signify n as default with capital letter
    } while ('y' == getSanitizedChar());
}


texts: Finding unique values in an array with possible nested arrays

texts:
I'm writing a function that receives an array and returns an object with the count of unique values, pretty much like other questions here or in StackExchange. Except that in my case, this array may contain a nested array, like:

var array = [1, 2, 'a', 'b', [3, 'c', 1], 'd', 2, 'b'];

Here is my code:

function findUniques(array, occurrences) {
    if (!occurrences) {
        occurrences = {};
    }

    //checking if parameter passed is an array
    if (Array.isArray(array)) {
        for (let i = 0; i < array.length; i++) {
            //if item is a nested array, call findUniques again
            if (Array.isArray(array[i])) {
                occurrences = findUniques(array[i], occurrences);
            } else {
                //add to/update count in occurrences object
                occurrences[array[i]] = occurrences[array[i]] + 1 || 1;
            }
        }
    }

    return occurrences;
}

It's returning the following object, as it was supposed to:

{
    '1': 2,
    '2': 2,
    '3': 1,
    a: 1,
    b: 2,
    c: 1,
    d: 1
}

My worry is that I'm using recursion.

Is it possible to optimize this function?

(Bear in mind that I must only use vanilla JavaScript)


texts: Why are these functions slower than BigInteger's included methods?

texts:
I tried writing alternative functions to Java's BigInteger.add(BigInteger.ONE), BigInteger.add(BigInteger), and BigInteger.subtract(BigInteger):

 public static BigInteger increment(BigInteger x)
 {
  int i=0;
  while(x.testBit(i))
   x=x.clearBit(i++);
  x=x.setBit(i);
  return x;
 }

 public static BigInteger add(BigInteger x, BigInteger y)
 {
  boolean A, B, carry=false;
  BigInteger sum=BigInteger.ZERO;
  int firstBit=x.or(y).getLowestSetBit(),
      topBit=x.or(y).bitLength();
  for(int i=firstBit;i<=topBit;i++)
  {
   A=x.testBit(i);
   B=y.testBit(i);
   if((A^B)^carry)
    sum=sum.setBit(i);
   carry=(A&&B)||((A^B)&&carry);
  }
  return sum;
 }

 public static BigInteger subtract(BigInteger x, BigInteger y)
 {
  if(x.compareTo(y)==-1)
  return subtract(y,x).negate();
  boolean A, B, borrow=false;
  BigInteger diff=BigInteger.ZERO;
  int firstBit=x.or(y).getLowestSetBit(),
      topBit=x.or(y).bitLength();
  for(int i=firstBit;i<=topBit;i++)
  {
   A=x.testBit(i);
   B=y.testBit(i);
   if((A^B)^borrow)
    diff=diff.setBit(i);
   borrow=(!A&&B)||(!(A^B)&&borrow);
  }
  return diff;
 }

Instead of speeding my program up, they slowed it down. I'm thinking it might be related to the immutability of the Java BigInteger class: every time a new value is computed, a new BigInteger has to be created. Would I have different results if I wrote them as method overrides in a subclass, using MutableBigInteger?


texts:
If you are wondering why I ask, it is because I have numerous different methods all with very similar code (the only difference in the code in each method is what is between the generate resultset comments). I have tried any amount of times to try and shorten this but I am out of ideas. What I have been trying to get is to have the repeating code in the main method (so therefore it won't be repeating), and then to be able to call the resultSet methods from here.

/**
 * This is the Main Method.
 *
 * @param args
 */
public static void main(String[] args) {
// call method resultSet1
resultSet1();
}

/**
 * This Method shows Resultset1.
 */
public static void resultSet1() {
// declare my variables and assign values to them
String url = "jdbc:mysql://lamp.eeecs.qub.ac.uk/mmeaklim01";
Connection connection;

// declare my prepared statement and assign a value to it
PreparedStatement updateSalaries;
String updateSalariesString = "update Staff_Members set salary = ? where idStaff = ?";

// declare two arrays and put values in them
int[] staffSalaries = { 45000, 40000, 35000, 42000, 29000, 29500,
        47000, 34000, 30500, 42000, 44500, 41000, 29500, 29500, 30000,
        34000 };
String[] staffIDs = { "M001", "M002", "M003", "M004", "M005", "M006",
        "M007", "M008", "M009", "M010", "M011", "M012", "M013", "M014",
        "M015", "M016" };

// try catch block to handle exceptions
try {
    // connect to the database
    connection = DriverManager.getConnection(url, "mmeaklim01",
            "xxx");

    // start the update
    updateSalaries = connection.prepareStatement(updateSalariesString);

    // declare my variable and assign a value to it
    int length = staffIDs.length;

    // for loop to take the values from my two arrays and use them to
    // update the Staff_Members table
    for (int loop = 0; loop < length; loop++) {
        updateSalaries.setInt(1, staffSalaries[loop]);
        updateSalaries.setString(2, staffIDs[loop]);
        updateSalaries.executeUpdate();
    }

    // generate resultset1
    ResultSet resultSet1 = updateSalaries
            .executeQuery("SELECT name, position, salary FROM Staff_Members");

    // while loop
    System.out.println("Resultset 1\n");
    System.out.println("Name\t\tPosition\tSalary");
    System.out.println("----------\t----------\t----------");
    while (resultSet1.next()) {
        String name = resultSet1.getString("name");
        String position = resultSet1.getString("position");
        int salary = resultSet1.getInt("salary");

        // print out resultset1
        System.out.println(name + "\t" + position + "\t" + salary
                + "\t");
    } // end of resultset1

    // close the update
    updateSalaries.close();

    // close the connection
    connection.close();

    // add a linebreak
    System.out.println();

    // output a message to the user to indicate that the program has
    // executed correctly
    System.out.println("The Method has executed correctly.");
} catch (SQLException sqlException) {
    // catch block
    System.out.println("Error: " + sqlException.getMessage());
}
}

And all I want the resultSet Methods to have, ideally, would be:

    // generate resultset1
    ResultSet resultSet1 = updateSalaries
            .executeQuery("SELECT name, position, salary FROM Staff_Members");

    // while loop
    System.out.println("Resultset 1\n");
    System.out.println("Name\t\tPosition\tSalary");
    System.out.println("----------\t----------\t----------");
    while (resultSet1.next()) {
        String name = resultSet1.getString("name");
        String position = resultSet1.getString("position");
        int salary = resultSet1.getInt("salary");

        // print out resultset1
        System.out.println(name + "\t" + position + "\t" + salary
                + "\t");
    } // end of resultset1

I'm sure there is probably an easy way around this but I can't seem to figure it out.


texts:
Another challenge from CodeEval that's causing me great pain...

Trying to find out if a sequence if a Jolly Jumper, which is

  A sequence of n > 0 integers is called a jolly jumper if the absolute values of the difference between successive elements take on all the values 1 through n-1.

I ended up adapting this idea into this:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) throws IOException {
        //File file = new File(args[0]);
        File file = new File("test.txt");
        BufferedReader buffer = new BufferedReader(new FileReader(file));
        String line;
        while ((line = buffer.readLine()) != null) {
            line = line.trim();
            String[] numbersString = line.split(" ");
            int[] numbers = new int[numbersString.length];
            for (int i = 0; i < numbers.length; i++){
                numbers[i] = Integer.parseInt(numbersString[i]);
            }
            System.out.println(isJolly(numbers));
        }
        System.exit(0);
    }

    public static String isJolly(int[] array) {
        List listResults = new ArrayList();
        for (int i = 0; i < array.length - 1; i++) {
            int result = Math.abs(array[i] - array[i + 1]);
            if (result == 0) {
                return "Not jolly";
            }
            if (result >= array.length) {
                return "Not jolly";
            }
            if (listResults.contains(result)) {
                return "Not jolly";
            }
            listResults.add(result);
        }
        return "Jolly";
    }
}

I tested it with a few examples locally and it worked, but when I submit the code I don't get any sequence to appear as jolly. What mistakes am I making?


texts: Machine Learning Implementation when dealing with high variance data

texts:
I'm am trying to classify MLB (Baseball) games whose score go over the total based on the total and the number of people who have bet the over. The total is a number set by Vegas and a bettor can either bet the over - meaning both team's combined scores will be greater than the number Vegas set or you can bet the under mean both team's combined scores will be less than the number set by Vegas. The training data coming in is stored in a CSV file a looks like this Team Total Over_Perc Cover i.e. NYY 8.5 0.61 0. I've tested several different models and the highest accuracy achieved was using the RandomForestClassifier. I would like to know if I am implementing this model correctly and if there is anything I can do to tune the parameters to achieve better accuracy?
import pandas as pd
import numpy as np
import json
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score, mean_squared_error
from sklearn.preprocessing import StandardScaler
from sklearn import metrics

training_data = pd.read_csv('/Users/aus10/Desktop/MLB_Data/ML/Data/Training_Data/Training_Data_Total.csv')
df_model = training_data.copy()
scaler = StandardScaler()

features = [['Total', 'Over_Perc' ]]
for feature in features:
    df_model[feature] = scaler.fit_transform(df_model[feature])

test_data = pd.read_csv('/Users/aus10/Desktop/MLB_Data/ML/Data/Test_Data/Test_Data_Total.csv')
X = training_data.iloc[:,1:3]  #independent columns
y = training_data.iloc[:,-1]   #target column

results = []

# fit final model
model = RandomForestClassifier(n_estimators=500, random_state=42) # 0.54

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)

model.fit(X_train, y_train)

y_train_pred = model.predict(X_train)
y_test_pred = model.predict(X_test)

y_pred = model.predict(X_test)

print("Accuracy:", round(metrics.accuracy_score(y_test, y_pred),2))

# define one new data instance

index = 0
count = 0

while count < len(test_data):
    team = test_data.loc[index].at['Team']
    total = test_data.loc[index].at['Total']
    over_perc = test_data.loc[index].at['Over_Perc']

    Xnew = [[ total, over_perc ]]
    # make a prediction
    ynew = model.predict_proba(Xnew)
    # show the inputs and predicted outputs
    results.append(
        {
            'Team': team,
            'Cover': round(ynew[0][1],2)
        })
    index += 1
    count += 1

sorted_results = sorted(results, key=lambda k: k['Cover'], reverse=True)

df = pd.DataFrame(sorted_results, columns=[
    'Team', 'Cover'])
writer = pd.ExcelWriter('/Users/aus10/Desktop/MLB_Data/ML/Results/Over_Probability.xlsx', engine='xlsxwriter') # pylint: disable=abstract-class-instantiated
df.to_excel(writer, sheet_name='Sheet1', index=False)
df.style.set_properties(**{'text-align': 'center'})
pd.set_option('display.max_colwidth', 100)
pd.set_option('display.width', 1000)
writer.save()


texts:
I have a Canny Edge Detection Code written in C++. I would like to know how can I make it more robust in terms of detecting all the edges correctly and save it? Is this the best possible edge detection possible? Can the coders find any error in my code? Below is a picture of how the code looks like.

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <stdlib.h>
#include <stdio.h>

using namespace cv;

/// Global variables

Mat src, src_gray;
Mat dst, detected_edges;

int edgeThresh = 1;
int lowThreshold;
int const max_lowThreshold = 100;
int ratio = 3;
int kernel_size = 3;
char* window_name = "Edge Map";

/**
 * @function CannyThreshold
 * @brief Trackbar callback - Canny thresholds input with a ratio 1:3
 */
void CannyThreshold(int, void*)
{
  /// Reduce noise with a kernel 3x3
  blur( src_gray, detected_edges, Size(3,3) );

  /// Canny detector
  Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size );

  /// Using Canny's output as a mask, we display our result
  dst = Scalar::all(0);

  src.copyTo( dst, detected_edges);
  imshow( window_name, dst );
 }

/** @function main */
int main( int argc, char** argv )
{
  /// Load an image
  src = imread( argv[1] );

  if( !src.data )
  { return -1; }

  /// Create a matrix of the same type and size as src (for dst)
  dst.create( src.size(), src.type() );

  /// Convert the image to grayscale
  cvtColor( src, src_gray, CV_BGR2GRAY );

  /// Create a window
  namedWindow( window_name, CV_WINDOW_AUTOSIZE );

  /// Create a Trackbar for user to enter threshold
  createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold );

  /// Show the image
  CannyThreshold(0, 0);

  /// Wait until user exit program by pressing a key
  waitKey(0);

  return 0;
  }


texts: You hate h̶a̶t̶s̶ reputation? Click here to get rid of it

texts:
Soo... I recently read a meta-post about the inherent problems of reputation. It listed some things like:

Confirmation bias.
Demotivating for low-rep users.
Hubris and elitism of high-rep users over low-rep users.
Incorrect representation of competence.
...

So I thought to myself: "How would the network be, just without reputation?"

I grabbed the inspector, checked questions, my profile page and the active page and how reputation is displayed.

Then I quickly hacked together the following small user-script (ECMA6) for Greasemonkey that would hide all reputation from sight:

// ==UserScript==
// @name         Reputation Hider
// @namespace    http://gihub.com/Vogel612/ReputationHider
// @version      0.1
// @description  Hides all reputation displays from StackExchange sites
// @author       Vogel612
// @grant        none
// @include      /https?:\/\/(meta\.)?.*\.stackexchange\.com\/.*/
// @include      /https?:\/\/(stackoverflow|serverfault|superuser|askubuntu)\.com\/.*/
// ==/UserScript==
/* jshint -W097 */
'use strict';

let slice = function(collection) {
  return [].slice.call(collection);
}

let repClasses = [ "rep", "reputation", "reputation-score" ];

let hideRepz = function() {
  repClasses.forEach(clazz =>
    slice(document.getElementsByClassName(clazz))
      .forEach(el => {
        // this results in minor inconsistencies in CSS, but alas
        el.style.visibility = 'hidden';
      })
    );
}

hideRepz();
// add event listener for live-updates
document.addEventListener("DOMNodeInserted", hideRepz);

This has been running for a while now for me and I like to say it's a refreshing change. That aside:

It hides all reputation numbers on the page. If you're curious you can still find them of course. Also it looks funny on /questions when the active timers are outdented differently, but that's just my OCD going mad there.
It also checks for new questions you load over the notification.

What can I do better in that userscript?


texts:
I'm currently building a MongoDB which has collections of 2 types:

A series of "dialog" collections
A collection storing the version numbers of each "dialog"

I'm looking to build an API, where-in I increment the version of the dialogs whenever that particular "dialog" is amended.

Basically I'll be updating multiple collections and I want to ensure that my code is appropriate.

On a given POST route I have something like:

router.post('/:dialogName', function(req,res){

    const dialogName = req.params.dialogName;
    const subId = req.body.subID;
    const newArray = req.body.newArray;
    const collection = db.get().collection(dialogName);

    collection.update({
        "synonyms._id": new ObjectId(subId)
    },
        {
            $set: {"synonyms.$.text": newArray}
        }
    ).then(function(doc){
        return updateVersions(dialogName).then(function(){
            console.log('version updated')
        })
        .catch(function(err){
            console.log('version not saved')
        })
    }).then(function(doc){
        res.status(200).end()
    }).catch(function(err){
        res.status(400).send("Couldnt update question")
    })
})

So once I successfully amend a doc, I invoke a promisified function that does this:

const updateVersions = function(dialog){
    return new Promise(function(resolve,reject){
        const versionCollection = db.get().collection('Version')
        versionCollection.update({
            "dialogs.name": dialog
        },{
            $inc: { "dialogs.$.__v": 1 , "__v": 1}
        }).then(function(response){
            resolve('ok')
        }).catch(function(err){
            console.log('errr : ',err)
            reject('err')
        })
    })
}

Is my approach correct?


texts: Using rotation of proxies within a Python script

texts:
I've written a script in Python using rotation of proxies which is able to fetch different titles from a website traversing different pages. I've tried to write this scraper in such a way so that it will try using proxies randomly until it can get the titles from that webpage, meaning it will use every single proxy cyclically if there is any difficulty getting the valid response.

The proxies and site address I've used within my scraper are just placeholders to let you know how I'm trying to do this.

As I do not have much experience about the usage of rotation of proxies within a scraper, there may be flaws within the design. It is working errorlessly, though.

I will be very glad if I get any suggestions as to how I can improve this existing script to make it more robust.

import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
from random import choice

ua = UserAgent()

search_urls = ['https://stackoverflow.com/questions?page={}&sort=newest'.format(page) for page in range(1,3)]

def get_proxies():
    proxies = ['128.199.254.244:3128', '95.85.79.54:53281', '128.199.125.54:2468', '178.45.8.113:53281', '206.189.225.30:3128']
    return proxies

def check_proxy(session,proxy):
    session.headers = {'User-Agent', ua.random}
    session.proxies = {'https': 'https://{}'.format(proxy)}
    try:
        response = session.get('https://httpbin.org/ip')
        item = response.json()
        print(item)
        return 0  ##if the proxy is a working one, break out of the function
    except Exception:
        proxy = random_proxy()
        check_proxy(session,proxy)  ##if the earlier one is not working, try moving on to fetch the working one

def random_proxy():
    return choice(get_proxies())

def scrape_page(url):
    proxy = random_proxy()
    session = requests.Session()
    session.headers = {'User-Agent', ua.random}
    session.proxies = {'https': 'https://{}'.format(proxy)}
    check_proxy(session,proxy) ##try validating the proxy before further attempt

    try:
        response = session.get(url)
    except Exception:
        response = None  #preventing "UnboundLocalError:"
        check_proxy(session,proxy) #if try block failed to execute the response, activate it

    soup = BeautifulSoup(response.text, 'lxml')
    for items in soup.select(".question-hyperlink"):
        print(items.text)

if __name__ == '__main__':
    for link in search_urls:
        scrape_page(link)


texts: Minimum steps to 1 to find minimum operations to transform n to 1

texts:
I was doing this JavaScript problem called "Minimum steps to 1." You can find the problem here.

  Given a positive integer - num, Following is a list of possible operations which can be performed on it:

  num / 2, If number is divisible by 2
  num / 3, If number is divisible by 3
  num - 1

  With these 3 available operations, find out the minimum number of steps required to reduce the number to 1.

  For example:

  For num = 1, no. of steps needed - 0
  For num = 2, no. of steps needed - 1 (num/2)
  For num = 6, no. of steps needed - 2 (num/3 followed by num/2)
  For num = 9, no. of steps needed - 2 (num/3 followed by num/3)

function minStepstoOne(n) {
  let steps = [];
  steps[0] = 0;
  steps[1] = 0;

  for(let i = 2; i <= n; i ++) {
    let minChoice = steps[i - 1];

    if(i % 2 == 0) {
      let divideByTwo = steps[i/2]
      minChoice = Math.min(divideByTwo, minChoice);

    }

    if(i % 3 == 0) {
      let divideByThree = steps[i/3]
      minChoice = Math.min(divideByThree, minChoice);

    }

  steps[i] = minChoice + 1;

  }
  return steps[n];
}

//console.log(minStepstoOne(9));


texts: VB.Net interfacing with F# Euclidean Distance Algorithm

texts:
I testing F# code which calculates "nearness" of two N-dimensional points using a least square euclidean distance algorithm.  The class library is written in F# and the calling will be from  VB.NET.  The code will eventually be used for scientific binary data, however I wanted a simple real world test environment.

I choose to create an rgb color table class based upon a list of color names along with their 3 digit rgb value.  The rgb values will be used for the distance algorithm.  The code works, however I'd like to make sure that the distance algorithm in written in an efficient manner.  The code will be called heavily in the final package.

My VB code will create the class instance, adds colors to the color table and finally searches for the nearest match of an unnamed color.  The results is DarkGoldenRod.

Dim GreenYellow() As Double = {173, 255, 47}
Dim Orange() As Double = {255, 127, 0}
Dim Lavender() As Double = {230, 230, 250}
Dim Magenta() As Double = {255, 0, 255}
Dim DarkGoldenRod() As Double = {184, 134, 11}

Dim test() As Double = {122, 122, 122}

Dim objFSColorTable As New MyFSColorTable("GreenYellow", GreenYellow)
objFSColorTable.AddEntry("Lavender", Lavender)
objFSColorTable.AddEntry("Orange", Orange)
objFSColorTable.AddEntry("Magenta", {255, 0, 255})
objFSColorTable.AddEntry("DarkGoldenRod", {184, 134, 11})

Dim name = objFSColorTable.ColorSearch(test)

The F# code contains the color table library which should be self explanatory

type MyColor =
  { Name: string;
    Values: float[];
    }

type MyFSColorTable(name: string, rgb:float[]) = class

  let mutable myHash = Hashtable()
  let mutable CurName = name
  let mutable CurDist = 0.0

  let mutable CurColor =
    { Name = name;
      Values = rgb;
      }

  let mutable CurList = [CurColor]

  member x.AddColor name rgb = CurList <- List.append CurList [{Name = name; Values = rgb}]
  member x.Name   = name

  // Euclidean distance between 2 vectors
  member x.Dist (V1: float[]) V2 =
    Array.zip V1 V2
      |> Array.map(fun (v1, v2) -> (v1 - v2) * (v1 - v2))
      |> Array.sum

  // Loop thru color hash and find the nearest match
  member x.ColorSearch (R1: float[]) =
    let mutable mindist = x.Dist R1 CurList.Head.Values
    let mutable name =  CurList.Head.Name
    for i in (CurList)  do
      let mutable s = 0.0
      s <- x.Dist R1 i.Values
      if s < mindist then
        mindist <- s
        name <- i.Name
    name

  // RGB Hash Table
  member x.RGBHash = myHash
  member x.AddEntry (name:string) (rgb: float[]) = x.AddColor name rgb

end


texts: Make methods shorter when parsing Firebase data

texts:
I have a simple parsing method from firebase. How i can do it smaller?The fact is that after the data is changed I will need to update my View so that the code can be added, which also does not sound cool.

private void createMainHashMapForData() {
    reference = database.getReference().child("OBJ");
    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            try {
               int iterationForMainHashmap = 0;
    mHashmapForData.clear(); // clear

    for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
        //main data
        int iterationForConstructor = 0;
        ArrayList<Product> temp_heshmap = new ArrayList<>();

        for (DataSnapshot messageSnapshot2 : messageSnapshot.child("ITEMS").getChildren()) {
            //progress show its news product // main data
            Product product = messageSnapshot2.getValue(Product.class);
            temp_heshmap.add(iterationForConstructor, product);
            iterationForConstructor += 1;
        }
        Collections.reverse(temp_heshmap);

        //main data
        String mNumberOfProduct = messageSnapshot.child("NUMBER_OF_PRODUCTS").getValue().toString();
        String nameOfBlock = messageSnapshot.child("TITLE").getValue().toString();
        Boolean mShowCoins = Boolean.parseBoolean(messageSnapshot.child("SHOW_COINS").getValue().toString());

        //put to main hashmap
        mHashmapForData.put(iterationForMainHashmap,
                new ContainerForData(mShowCoins, nameOfBlock, mNumberOfProduct, temp_heshmap));
        iterationForMainHashmap += 1;
                createViews();
            } catch (Exception e) {
                Log.d("Exception getProducts", e.getMessage());
                FirebaseCrash.report(new Exception(e.getMessage()));
            }
            ;
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            FirebaseCrash.report(new Exception(databaseError.getMessage()));
        }
    });
}

As I said, my question is how to make modal methods less and more productive? Do you have any ideas??


texts:
I wrote my very first login/register PDO system today.  I know there is still a lot of flaws, but I was wondering what tips and advice you have to help me improve this. I know that PDO is much more secure than MySQl, so would you say my code is secure?  If so, to what extent, since I'm using PDO?  Any tips and advice would be much appreciated!

login.php

Login

<form method="POST">
    <input type="text" name="username">

    <input type="password" name="password">

    <input type="submit">
</form>

<?php
session_start();
    if(isset($_POST['username'], $_POST['password'])){
        require 'core/connect.php';

        $query = dbConnect()->prepare("SELECT username, password FROM users WHERE username=:username AND password=:password");
        $query->bindParam(':username', $_POST['username']);
        $query->bindParam(':password', $_POST['password']);
        $query->execute();

        if($row = $query->fetch()){
            $_SESSION['username'] = $row['username'];
            header("Location: index.php");
        }
    }
?>

register.php

Register

<form method="POST">
    <input type="text" name="username">

    <input type="password" name="password">

    <input type="submit">
</form>

<?php
session_start();

    if(isset($_POST['username'], $_POST['password'])){
        require 'core/connect.php';

        $query = dbConnect()->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
        $query->bindParam(':username', $_POST['username']);
        $query->bindParam(':password', $_POST['password']);

        if($query->execute()){
            header("Location: index.php");
        } else{
            echo 'ERROR';
        }
    }
?>

index.php

<?php
session_start();

if(isset($_SESSION['username'])){
    echo 'Welcome!', 'Logout';
} else {
    echo 'Login

    Register';
}
?>

core/connect.php

<?php
    function dbConnect(){
        try{
            $username = 'root';
            $password = '';
            $conn = new pdo("mysql:host=localhost;dbname=test;", $username, $password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $conn;

        }   catch(PDOException $e){
            echo 'ERROR', $e->getMessage();
        }
    }
?>


texts: Simple c# MemoryCache mechanism to reduce number of db calls

texts:
I have some legacy code which gets a list of Students and their corresponding School. It's LinqToSql and there is no lazy loading:

public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public School AttendedSchool { get; set; }

    public Student(int studentId) {
        // code to get the student from the database goes here, this
        // gets FirstName, LastName and SchoolId from the db.
        FirstName = dbResult.FirstName;
        LastName = dbResult.LastName;
        AttendedSchool = new School(dbResult.SchoolId);
    }
}

public class School
{
    public string SchooolName { get; set; }
    public School(int schoolId) {
        // go to database and call 'GetDbSchool' using schoolId
        SchoolName = resultFromDatabase.SchoolName;
    }
}

There are thousands of students but only a handful of schools. Because of the way the code is built we see a GetDbSchool call to the database every time a Student is created but this clearly isn't required, it's getting the same school details again and again. I want a simple cache of schools to prevent so many db calls. The cache doesn't need a mechanism to empty or update and if there is a race condition and the school is fetched from the database twice that's not a problem. This is the caching code I've written:

public static class SchoolCache
{
    public static School GetSchool(int schoolId)
    {
        if (MemoryCache.Default["school_" + schoolId] != null)
        {
            return (School)MemoryCache.Default["school_" + schoolId.ToString()];
        }

        var cachePolicy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromSeconds(100) };
        var schoolFromDb = // go to database to get the school details
        MemoryCache.Default.Add("school_" + schoolId, schoolFromDb, cachePolicy);
        return schoolFromDb;
    }
}

Then in the School class I can use the cache and we get one db call per school:

public School(int schoolId) {
    SchoolName = SchoolCache.GetSchool(schoolId).SchoolName;
}

It works as expected but I don't see many caches this simple, most examples and implementations are more complicated. Are there any obvious problems with this simple implementation?


texts:
I'm very new to haskell (I never used Monads, Functors and other things) and FP in general. I decided to write the simplest parser I possibly can with some expansion possibilities. (I have a general interest in programming languages, so this is why I chose to do this...).
I have a simple parser type:
type Parser a = String -> (Maybe a, String)
-- (Nothing, ErrorMessage)
-- (Just a, Leftovers)

I can parse any character and return an error if there are none:
eatParser :: Parser Char
eatParser []     = (Nothing, "Unexpected EOF")
eatParser (x:xs) = (Just x, xs)

I can parse a specific character:
charParser :: Char -> Parser Char
charParser c s = case eatParser s of
    (Nothing, e) -> (Nothing, e)
    (Just x, xs) | x == c -> (Just x, xs)
    (Just x, _) | x /= c ->
        (Nothing,
        "Expected " ++ [c] ++ ", but got " ++ [x] ++ " instead.")

Also, a specific string:
stringParser :: String -> Parser String
stringParser [] s = (Just "", s)
stringParser u s = case charParser (head u) s of
    (Nothing, e) -> (Nothing, e)
    (Just x, xs) -> case stringParser (tail u) xs of
        (Nothing, e) -> (Nothing, e)
        (Just x', xs') -> (Just $ x : x', xs')

And any word:
varParser :: Parser String
varParser s = case eatParser s of
    (Nothing, _) -> (Just [], [])
    (Just x, xs) | not $ isLetter x -> (Just [], xs)
    (Just x, xs) | isLetter x ->
        case varParser xs of
            (Nothing, e') -> (Nothing, e')
            (Just [], _) -> (Just [x], xs)
            (Just x', xs') ->
                (Just $ x : x', xs')

And finally, the expression parser
data Expr = Open Expr | Value String deriving (Show)
exprParser :: Parser Expr
exprParser s = case charParser '(' s of
    (Nothing, _) -> case varParser s of
        (Nothing, e) -> (Nothing, e)
        (Just x, xs) -> (Just $ Value x, xs)
    (Just _, xs) -> case exprParser xs of
        (Nothing, e)  -> (Nothing, e)
        (Just q, xs') -> case charParser ')' xs' of
            (Nothing, e)   -> (Nothing, e)
            (Just _, xs'') -> (Just $ Open q, xs'')

Here are some examples of what the code does:

*Test2> eatParser "abc"
(Just 'a',"bc")
*Test2> charParser 'a' "abc"
(Just 'a',"bc")
*Test2> charParser 'b' "abc"
(Nothing,"Expected b, but got a instead.")
*Test2> stringParser "abc" "abce"
(Just "abc","e")
*Test2> stringParser "abc" "abc"
(Just "abc","")
*Test2> stringParser "abc" "axbc"
(Nothing,"Expected b, but got x instead.")
*Test2> varParser "abc"
(Just "abc","")
*Test2> varParser "abc2"
(Just "abc","2")
*Test2> varParser "abc abc2"
(Just "abc"," abc2")
*Test2> exprParser "((aa))bc"
(Just (Open (Open (Value "aa"))),"bc")
*Test2> exprParser "((aa)b)bc)"
(Nothing,"Expected ), but got b instead.")

I know that there is a way to simplify all of the
case ... s of (Nothing, e) -> (Nothing, e) (Just x, xs) -> ...
And not use parserSequence...
Can you tell what I can improve? Thanks in advance :D


texts:
From this Stack Overflow answer, I learned that C++17 will have __has_include, which can

  [make] migrating from experimental to std almost seamless

This still leaves the question of how to do it. Doing something like namespace std { using namespace std::experimental; } is undefined behaviour, so I came up with this method:

optional.h demonstration on coliru

#pragma once

#if __has_include(<optional>)
#   include <optional>
#   define HAS_STD_OPTIONAL
#elif __has_include(<experimental/optional>)
#   include <experimental/optional>
#   define HAS_STD_EXPERIMENTAL_OPTIONAL
#else
#   error Must have an optional type, either from <optional> or if not supported from <experimental/optional>.
#endif

#if defined HAS_STD_OPTIONAL

namespace opt {
    template<class T>
    using optional = std::optional<T>;
    using bad_optional_access = std::bad_optional_access;
    using nullopt_t = std::nullopt_t;
    using in_place_t = std::in_place_t;

    constexpr auto nullopt = std::nullopt;
    constexpr auto in_place = std::in_place;

    template<class T>
    constexpr auto make_optional(T && value)
    {
        return std::make_optional(std::forward<T>(value));
    }
}

#elif defined HAS_STD_EXPERIMENTAL_OPTIONAL

namespace opt {
    template<class T>
    using optional = std::experimental::optional<T>;
    using bad_optional_access = std::experimental::bad_optional_access;
    using nullopt_t = std::experimental::nullopt_t;
    using in_place_t = std::experimental::in_place_t;

    constexpr auto nullopt = std::experimental::nullopt;
    constexpr auto in_place = std::experimental::in_place;

    template<class T>
    constexpr auto make_optional(T && value)
    {
        return std::experimental::make_optional(std::forward<T>(value));
    }
}

#endif


texts: Initializing BufferedReader and DataOutputStream in infinite loop

texts:
Is it a good practice to initialize the BufferedReader and DataOutputStream in infinite loop?

        ServerSocket welcomeSocket = new ServerSocket(8080);
        Socket connectionSocket = welcomeSocket.accept();

        while (true) {
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); //close it
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); //close it
            //... Do read/write stuff
        }

Connection establishes successfully and communication happens normally. Just want to know that whether it is a good practice or not? It is a Java code.

Thanks.


texts: Higher-order Prolog predicates combine/3 and reduce/3


texts:
I just rewrote this:

if (budgetRemaining != 0 || totalOpenInvoices != 0)
{
}

Like this:

if (new[] { budgetRemaining, totalOpenInvoices }.Any(c => c != 0))
{
}

If I had seen that before I ramped up on Linq, it would have confused me.  Now that I've been learning functional programming and using Linq, it seems natural, but is it sacrificing simplicity?


texts:
Several hours ago I posted this question about Generating character permutations in Python.

User rolfl said that my main problem was not using the right tool for the job, as Python is interpreted it will be much slower than a compiled solution. So I tried to write this in C.

Objective

Generate a file containing all fixed length l permutations of a given set of chars, in this case upper-case alphabet.

i.e.: With l = 5 the output file should look like:

AAAAA
AAAAB
AAAAC
...
ZZZZZ

My solution

I used a recursive for loop. It's my first program in C (after a hello world) so I don't know what it's worth. It runs in about 2.621s on my 2.9 GHz Intel Core i7

#include <stdio.h>

FILE *fp;

char alphabet[26] = { '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'};
int len = 5;

void recloop(char *pwd, int repeat) {
  int i;
  for (i = 0; i < 26; i++) {
    pwd[len-repeat] = alphabet[i];

    if (repeat == 1) {
      fprintf(fp, "%s\n", pwd);
    }
    else {
      recloop(pwd, repeat - 1);
    }
  }
}

int main(void) {
  char pwd[len];
  fp = fopen("output", "w");
  recloop(pwd, len);
}


texts: Too many for-loops and conditional operators

texts:
Not please with this outcome, function works as is, but would love to simplify and prettify it. Use of one for-loop would be great and limit the use of the conditional operator.

private void checkForOverage(List<GoogleUsageMapping> records) {
    Long sumOfAllocatedSize = 0L;
    Long sumOfLogicalSize = 0L;
    for (GoogleUsageMapping record : records) {
        // initially all records are set to GoogleTrackingState.UNPROCESSED
        if (record.getUsage().getMeasuredType() == MeasuredType.ALLOCATED_SIZE) {
            sumOfAllocatedSize += record.getUsage().getQuantity().longValue();
        } else if (record.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {
            sumOfLogicalSize += record.getUsage().getQuantity().longValue();
        }
    }

    for (GoogleUsageMapping record : records) {
        if (sumOfAllocatedSize >= sumOfLogicalSize && record.getUsage().getMeasuredType() == MeasuredType.LOGICAL_SIZE) {
            record.setState(GoogleTrackingState.IGNORED_OVERAGE);
        } else if (sumOfLogicalSize > sumOfAllocatedSize && record.getUsage().getMeasuredType() == MeasuredType.ALLOCATED_SIZE) {
            record.setState(GoogleTrackingState.IGNORED_OVERAGE);
        }
    }
}


texts:
I've written a Caesar Cipher in python (a more in-depth explanation is provided in the docstring at the top of the program). At first, it was supposed to just be the cipher, but I expanded it to have the user guess the original string, given the encoded string. I would like feedback on the caesar algorithm, and any other nitpicks you can find in my program. Any and all feedback is appreciated and considered!

Link to github prompt

cipher.py

""" Import Statements """
import random

"""
Caesar cipher - Implement a Caesar cipher, both encoding and decoding.

The key is an integer from 1 to 25. This cipher rotates the letters of the alphabet
(A to Z). The encoding replaces each letter with the 1st to 25th next letter in the
alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI"
to "BC". This simple "monoalphabetic substitution cipher" provides almost no security,
because an attacker who has the encoded message can either use frequency analysis to
guess the key, or just try all 25 keys.

Input is all lowercase, so using ord() should use 97-122 a-z
"""

WORDS = [
    "thisisarandomstring", "hellomynameisben", "whatisyourname", "thiswaswrittenonamac",
    "macsarethebestcomputer", "thisprogramisinpython", "thisonlyhasletters", "andeveryother",
    "stringinthislist", "isonlyusingletters", "becausethatshowitworks", "andifyoudontlikeit",
    "thenyoucangetyour", "naysayerselfoutofhere", "thatshowiroll"
]

CHART = {
    97: 'a', 98: 'b', 99: 'c', 100: 'd', 101: 'e', 102: 'f', 103: 'g',
    104: 'h', 105: 'i', 106: 'j', 107: 'k', 108: 'l', 109: 'm', 110: 'n',
    111: 'o', 112: 'p', 113: 'q', 114: 'r', 115: 's', 116: 't', 117: 'u',
    118: 'v', 119: 'w', 120: 'x', 121: 'y', 122: 'z'
}

def encode(text, rotations):
    """ Encodes the passed text, rotating `rotations` times """
    encoded_text = ""
    for index in range(len(text)):
        new_position = ord(text[index]) + (rotations % 26)
        if new_position > 122:
            new_position = 97 + (new_position - 122)
        encoded_text += CHART[new_position]
    return encoded_text

def decode(text, rotations):
    """ Decodes the passed text, with the passed rotations """
    decoded_text = ""
    for index in range(len(text)):
        new_position = ord(text[index]) - (rotations % 26)
        if new_position < 97:
            diff = 97 - new_position
            new_position = 122 - diff
        decoded_text += CHART[new_position]
    return decoded_text

def check_guess(guess):
    """ Checks how close the guess is to the original string """
    if len(guess) != len(DECODED):
        return "Guess must be same length to check guess!"
    response = ""
    for i in range(len(guess)):
        if guess[i] == DECODED[i]:
            response += guess[i]
        else:
            response += " "
    return response

if __name__ == '__main__':

    ROTATIONS = random.randint(3, 26)
    ENCODED = encode(random.choice(WORDS), ROTATIONS)
    DECODED = decode(ENCODED, ROTATIONS)
    print(f"""
        Encoded: {ENCODED}
        Length: {len(ENCODED)}
    """)

    print(f"What is the original string?")
    GUESS = input(">>> ")
    GUESSES = 1
    while GUESS != DECODED:
        print(f">>> {check_guess(GUESS)}")
        GUESS = input(">>> ")
        GUESSES += 1

    print("Correct!")

    print(f"""
        Encoded: {ENCODED}
        Original: {DECODED}
        Guesses: {GUESSES}
    """)


texts: Custom Scala implementation of generic Future.sequence

texts:
I'm trying to make sure I understand how to write clean and robust idiomatic Scala, so I wrote a custom generic implementation sequence of type A[B[C]] => B[A[C]] (instead of TraversableOnce[Future[A]] => Future[TraversableOnce[A]] -- I know something like this exists in scalaz).

Is the following code a reasonable and idiomatic way of writing sequence? Are there existing traits in the core Scala library that would be easy to substitute for Liftable, Monoid, and Traversable that would keep this implementation of sequence relatively intact? What are the most significant improvements that can be made to this code?

import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import java.util.concurrent.Executors
import scala.util.Success
import scala.util.Failure

object TestMain {

  implicit val ec = ExecutionContext
    .fromExecutorService(Executors.newSingleThreadExecutor)

  trait Liftable[A[_], B[_]] {
    def lift[C](bc: B[C]): B[A[C]]
  }

  trait Monoid[A] {
    def mappend(a1: A, a2: A): A
    def mzero: A
  }

  trait Traversable[T[_]] {
    def head[A](t: T[A]): Option[A]
    def next[A](t: T[A]): T[A]
  }

  implicit val listOfFutureLiftable = new Liftable[List, Future] {
    def lift[C](fc: Future[C]) = fc.map(c => List(c))
  }

  implicit def listMonoid[A] = new Monoid[List[A]] {
    def mappend(a1: List[A], a2: List[A]) = a1 ++ a2
    def mzero = Nil
  }

  implicit def futureMonoid[A: Monoid] = new Monoid[Future[A]] {
    def mappend(a1: Future[A], a2: Future[A]) = {
      for {
        v1 <- a1
        v2 <- a2
      } yield implicitly[Monoid[A]].mappend(v1, v2)
    }
    def mzero = Future.successful(implicitly[Monoid[A]].mzero)
  }

  implicit val listTraversable = new Traversable[List] {
    def head[A](l: List[A]) = l match {
      case Nil => None
      case x :: _ => Some(x)
    }

    def next[A](l: List[A]) = l.tail
  }

  def sequence[A[_], B[_], C](lf: A[B[C]])(
    implicit ta: Traversable[A],
    lab: Liftable[A, B],
    mb: Monoid[B[A[C]]]): B[A[C]] = {
    val obc: Option[B[C]] = ta.head(lf)
    obc match {
      case Some(bc) => {
        val first: B[A[C]] = lab.lift(bc)
        val tail: A[B[C]] = ta.next(lf)
        val rest: B[A[C]] = sequence(tail)
        mb.mappend(first, rest)
      }
      case None => mb.mzero
    }
  }

  def main(args: Array[String]) {
    val lfi: List[Future[Int]] = List(Future(1), Future(2))
    val fli: Future[List[Int]] = sequence(lfi)
    fli andThen {
      case Success(li) => println(li)
      case Failure(e) => println("fail: " + e)
    } andThen {
      case _ => ec.shutdown
    }
  }
}


texts: PHP - hacker rank - ransom check - extra space at the end of the string

texts:
Not sure if I can ask this question here -

I am working on a problem statement of hacker rank, the idea is that a kidnapper want to recreate a ransom note using a magazine, the input format is as below -

  6 4
  give me one grand today night
  give one grand today

6 and 4 are the counts of words in magazine and ransom respectively, so I just need to check and return "Yes" if the ransom note can be re-created using the words in magazine, otherwise return "No".

My code is working fine as expected, but during two test cases the output is being printed wrong, and that is because of an extra space at the end of a key.

I am first taking the counts of the array values into another array, and checking the value by comparing the keys of ransom with magazine.

I've downloaded the test case and when I test it locally the result is No, that is because the last word in the magazine array is having an extra white space character.

Here's the search where you can see there is an extra space at the end of the string, and because of that the string is not getting matched and is returning output as "No". I've observed that is that last string in the array after counting the values.

Beneath that you have links to the inputs and expected output.

Test case 1:
I/P - https://hr-testcases-us-east-1.s3.amazonaws.com/24432/input16.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1513762294&Signature=GoW9OnUfaKo3gwmM2X4L%2FpjQndM%3D&response-content-type=text%2Fplain

Expected O/P: Yes

<?php

$handle = fopen ("php://stdin","r");
fscanf($handle,"%d %d",$m,$n);
$magazine_temp = fgets($handle);
$magazine = explode(" ",$magazine_temp);
$ransom_temp = fgets($handle);
$ransom = explode(" ",$ransom_temp);

    $countRan = array_count_values($ransom);
    $countMag = array_count_values($magazine);

    if(count($countRan) > count($countMag)) {
        print "No";
        return;
    }

    foreach ($countRan as $key => $value){
        // exit if key not exists in $countMag array
        // or exit if value in $countRan[$key] greater than $countMag[$key]
        if (!array_key_exists($key, $countMag) || $value > $countMag[$key]) {
            print "No";
            return;
        }
    }
    print "Yes";
?>


texts:
Problem statement
After 10 sec of execution of a program, start reading the property descriptors of each property of an object and continue reading all remaining properties each, every 3 seconds until done.

Solution
function Timer(obj, startTime, interval) {
    var PDO ={
        obj:{value: obj, enumerable: true, writable:false, configurable:false},
        startTime: {value:startTime, enumerable:true, writable:false, configurable:false},
        interval: {value:interval, enumerable:true, writable:false, configurable:false}
    };
    Object.defineProperties(this, PDO);
}

Timer.prototype.readProperties = function(){
    var props = Object.getOwnPropertyNames(this.obj);
    var self = this;
    function readPDO(){
        console.log(Object.getOwnPropertyDescriptor(self.obj, props[0]));
        props.shift();
        if (props.length === 0) {
            clearInterval(self.clearID);
        }
    }
    setTimeout(function(){
        self.clearID = setInterval(function(){
                                        readPDO();
                                    },
                                    self.interval
                                  );
                        },
                        self.startTime
              );
}

var t = new Timer({x:1, y:2}, 10000, 3000);
t.readProperties();

Can we improve the solution?
Are the naming conventions looking fine?


texts: Computing pairwise bitwise OR in a list of bit-strings

texts:
I am trying to solve this problem using Clojure:

  You are given a list of \$N\$ people who are attending ACM-ICPC World
  Finals. Each of them are either well versed in a topic or they are
  not. Find out the maximum number of topics a 2-person team can know.
  And also find out how many teams can know that maximum number of
  topics.

  Input Format:

  The first line contains two integers \$N\$ and \$M\$ separated by a single
  space, where \$N\$ represents the number of people, and M represents the
  number of topics. \$N\$ lines follow. Each line contains a binary string
  of length \$M\$. In this string, 1 indicates that the ith person knows a
  particular topic, and 0 indicates that the ith person does not know
  the topic.

  Output Format:

  On the first line, print the maximum number of topics a 2-people team
  can know.  On the second line, print the number of 2-person teams that
  can know the maximum number of topics.

  Constraints:

  \$2 ≤ N ≤ 500\$

  \$1 ≤ M ≤ 500\$

  Sample Input:

4 5

10101

11100

11010

00101

  Sample Output:

5

2

However, my implementation is too slow to pass all the test cases. What are some suggestions to optimize this implementation? Basically, I have a list of bit-strings, and I am trying to find a faster way to bitwise-OR every pair of strings, and find the maximum number of set bits that could be obtained from ORing a pair.

(let [[N _] (clojure.string/split (read-line) #" ")
      N (Integer/parseInt N)
      strings (vec (repeatedly N read-line))
      known
      (for [i (range N) j (range (inc i) N)
            :let [s1 (strings i)
                  s2 (strings j)]]
        (apply + (map #(if (or (= %1 \1)
                               (= %2 \1))
                         1
                         0)
                      s1
                      s2)))
      maximum (apply max known)]
  (println maximum)
  (println (count (filterv #(= % maximum) known))))


texts:
I wish to ask if the code written below has any holes (probably it will be useful for someone else). This code checks, by IP and by userid, if more than 5 attempts within the last 5 minutes were made to login. Every attempt to log in is stored in the history table (MySQL).

The history table is needed only for the purpose of CAPTCHA displaying. ENGINE=InnoDB is chosen for history table.

No indexes were put on Time or userid or remote_addr.

Any suggestions about optimization?

$query1="SELECT id FROM history
    WHERE (Time>date_sub(now(), interval 5 minute))
        AND remote_addr='" . ip2long($_SERVER['REMOTE_ADDR']) . "' limit 6";
//limit 6 is for performance, 6+ means 6, we only care if it less than 5
$result1=mysql_query($query1);
//so we know mysql_num_rows($result1)

$query2="SELECT id FROM history
    WHERE (Time>date_sub(now(), interval 5 minute))
        AND userid='" . $userid . "' limit 6";
//limit 6 is for performance, 6+ means 6, we only care if it less than 5
$result2=mysql_query($query2);
//so we know mysql_num_rows($result2)

$attempts=0; // we want to set up $attempts=maximum of
             // (mysql_num_rows($result1), mysql_num_rows($result2))
if($result1) {
    $attempts=mysql_num_rows($result1);
}
if($result2 && $attempts<mysql_num_rows($result2)) {
    $attempts=mysql_num_rows($result2);
}

// if $attempts is more than 5, then CAPTCHA should be displayed,
// if less then it should not


texts:
I'm working on an API for getting System Information easily in C#, albeit I'm pretty sure that one already exists, but I like creating my own stuff. I'm coming from JavaScript and Java, so I don't really know if my approach for certain things in the API is good or not so much. What do you think?

// Dict for storing the needed ManagementObjectSearchers for easy access
    private Dictionary<string, ManagementObjectSearcher> wmiSearchers;

    public SystemMonitor() {

        this.wmiSearchers = new Dictionary<string, ManagementObjectSearcher>();

        string[] wmiClasses = {
            "Win32_Processor",
            "Win32_DiskDrive",
            "Win32_PhysicalMemoryArray"
        };

        foreach (string wmiClass in wmiClasses) {
            this.wmiSearchers.Add(wmiClass, new ManagementObjectSearcher(String.Format("SELECT * FROM {0}", wmiClass)));
        }

    }

    // Utility method for getting the ManagementObjectCollection results as a List
    static List<ManagementBaseObject> _searcherAsList(ManagementObjectSearcher s)
    {
        List<ManagementBaseObject> tmp = new List<ManagementBaseObject>();
        foreach (var obj in s.Get()) {
            tmp.Add(obj);
        }
        return tmp;
    }

    // Utility method for getting a property name from a wmiClass (for the given index)
    private string getValueFrom(string wmiClass, string propName, int itemIndex = 0)
    {
        return _searcherAsList(this.wmiSearchers[wmiClass])[itemIndex][propName].ToString();
    }

    #region CPU_INFORMATION

    // Get the number of available cpus
    public int getNumberOfCpus()
    {
        return _searcherAsList(this.wmiSearchers["Win32_Processor"]).Count;
    }

    // Get the OVERALL cpu usage for the given cpu.
    public double getOverallCpuUsage(int cpuIndex = 0) {
        return Double.Parse(this.getValueFrom("Win32_Processor", "LoadPercentage"));
    }

    // Get the number of physical cores for the given cpu.
    public double getCpuPhysicalCoreCount(int cpuIndex = 0)
    {
        return int.Parse(this.getValueFrom("Win32_Processor", "NumberOfCores", cpuIndex));
    }

    // Get the number of logical cores for the given cpu
    public double getCpuLogicalCoreCount(int cpuIndex = 0)
    {
        return int.Parse(this.getValueFrom("Win32_Processor", "NumberOfLogicalProcessors", cpuIndex));
    }


texts:
I'm working on an experiment to parse speech out of an emote in a text roleplaying game (MUD) so that if you can't hear it correctly, or if it's in a different language, you won't understand it. This works correctly, but I was just wanting to make sure it was as clear and efficient as possible.

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

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

        System.out.print("Enter an emote: ");
        String emote = scanner.nextLine();

        System.out.println("Original emote:\n" + emote);
        System.out.println("\nParsed emote:\n" + jumbleEmoteSpeech(emote));
    }

    public static String jumbleEmoteSpeech(String emote) {
        StringBuilder out = new StringBuilder();
        int quote1Location = emote.indexOf('"');

        if (quote1Location == -1) {
            out.append(emote);
        }
        else {
            int quote2Location;
            int currentIndex = 0;
            boolean found = true;
            do {
                quote2Location = emote.indexOf('"', quote1Location + 1);
                if (quote2Location == -1 || quote2Location < currentIndex) {
                    out.append(emote.substring(currentIndex));
                    found = false;
                }
                else {
                    out.append(emote.substring(currentIndex, quote1Location + 1));
                    out.append(jumble(emote.substring(quote1Location + 1, quote2Location)));
                    currentIndex = quote2Location;

                    quote1Location = emote.indexOf('"', currentIndex + 1);
                }
            } while (found);
        }

        return out.toString();
    }

    public static String jumble(String text) {
        StringBuilder out = new StringBuilder();
        Random generator = new Random();

        for (int i = 0; i < text.length(); i++) {
            char ch = text.charAt(i);
            if (Character.isLetter(ch)) {
                if (Character.isUpperCase(ch)) {
                    out.append((char)('A' + generator.nextInt(26)));
                }
                else {
                    out.append((char)('a' + generator.nextInt(26)));
                }
            }
            else if (Character.isDigit(ch)) {
                out.append((char)('0' + generator.nextInt(10)));
            }
            else {
                out.append(text.charAt(i));
            }
        }

        return out.toString();
    }
}

Also, is there any real benefit to using '"' vs "\""? I think '"' is more readable, and any performance difference is probably optimized out anyway.


texts: Lambda@Edge function for handling redirects and rewrites

texts:
We're converting the City of Philadelphia's website to be served as static files. In order to support redirects and rewrites (URL masking), we decided to use a Lambda@edge function, which modifies (or responds to) the inbound request. I expect this will be maintained by other people so readability is very important. I would love your feedback on how this could be easier to understand and maintain.

const { URL } = require('url')
const { inspect } = require('util')
const TRAILING_SLASH = /\/$/
let compiledRegexes = {}

exports.handler = createHandler(require('../rules.json')) // expose to lambda
exports.createHandler = createHandler // expose for testing

function createHandler (rules) {
  return async function (event) {
    const request = event.Records[0].cf.request
    const cleanPath = request.uri.toLowerCase().replace(TRAILING_SLASH, '')
    log(event)

    for (const rule of rules) {
      let newPath = null

      if (rule.regex) {
        if (!compiledRegexes.hasOwnProperty(rule.pattern)) {
          compiledRegexes[rule.pattern] = new RegExp(rule.pattern)
        }

        const regex = compiledRegexes[rule.pattern]
        if (regex.test(cleanPath)) {
          newPath = cleanPath.replace(regex, rule.replacement)
        }
      } else if (cleanPath === rule.pattern) {
        newPath = rule.replacement
      }

      if (newPath !== null) {
        if (rule.type === 'rewrite') {
          request.uri = newPath || '/'
          if (rule.origin) setOrigin(request, rule.origin)
          log(request)
          return request
        } else {
          const response = createRedirect(newPath)
          log(response)
          return response
        }
      }
    }

    // If no matches, return unmodified request
    log('no match')
    return request
  }
}

// Mutates request object
function setOrigin (request, origin) {
  const url = new URL(origin)
  const protocol = url.protocol.slice(0, -1) // remove trailing colon
  const path = url.pathname.replace(TRAILING_SLASH, '')

  request.origin = {
    custom: {
      domainName: url.hostname,
      protocol,
      port: (protocol === 'https') ? 443 : 80,
      path,
      sslProtocols: ['TLSv1.2', 'TLSv1.1'],
      readTimeout: 5,
      keepaliveTimeout: 5,
      customHeaders: {}
    }
  }
  request.headers.host = [
    { key: 'host', value: url.hostname }
  ]
}

function createRedirect (newUri) {
  return {
    status: '301',
    statusDescription: 'Moved Permanently',
    headers: {
      location: [
        { key: 'Location', value: newUri }
      ]
    }
  }
}

function log (data) {
  if (process.env.NODE_ENV === 'test') return
  // use util.inspect so objects aren't collapsed
  console.log(inspect(data, false, 10))
}

A few example rules from rules.json:

redirects

{
  "pattern": "/old",
  "replacement": "https://example.com/new",
  "type": "redirect"
}

rewrites

{
  "pattern": "/old(/.+)?",
  "regex": true,
  "replacement": "$1",
  "origin": "https://example.com/new",
  "type": "rewrite"
}

(I definitely don't love the "API" of how these rules are configured, and I think they could be simplified or merged. Would love any ideas here too!)

Thanks so much for your time.


texts: Validate if the user is associated with the organization then it must have any valid timezone

texts:
def validate_time_zone
  if time_zone.present? && org.present? && !org.country.states.map(&:time_zone).uniq.include?(time_zone)
    errors.add(:time_zone, :invalid)
  end
end

I have a user model with the following relations:

User can optionally belong to Org
Org belongs to a Country
A Country has some timezones (not unique as two states may have the same timezone).

So I validate that if the user is associated with an organization then it must have a valid timezone. Valid timezone means any time zone that comes under organization country. Ex Organization is ABC, Country is USA and Timezones are CET, Pacific, and Other US Time Zone. Then the user must use a timezone within the above three only.

I have filtered the condition but I am not sure breaking down will improve quality or further performance.

Can we used scope here too in country or organization or user module as it help in DRY not just validation.


texts: First attempt incorporating backbone.js in my code

texts:
I have a feeling I might be doing it wrong, what major things would you improve in this code?

The code is basically handling a tour on first login, showing it only for first login users (activated externally via calling activate) and preventing the step to apear again if the user has already seen it.

I intentionally used only the basic building blocks of backbone.js to a bare minimum, e.g. I didn't use templates as the DOM at this moment is given as is, and the HTML elements are not "backbone" friendly

var tourModel, tourView;

(function($){
    var VISITED = "visited";
    function cookieName(step){
        return "tour_step" + step;
    }
    function isStepVisited(step){
        return $.cookie(cookieName(step)) === VISITED;
    }
    function setStepVisited(step){
        $.cookie(cookieName(step.number),VISITED);
    }
    var TourModel = Backbone.Model.extend({
        active: false, //private flag
        defaults: {
            step: {
                number:1,
                display:false
            }
        },
        activate:function(){
            this.active = true;
        },
        close:function(){
            this.toggleStep(this.get("step").number, false);
        },
        toggleStep: function(step, show){
            //if this is active (e.g. first time login) and the user haven't seen this step yet (e.g. cookie isn't set) or if this is closing the step (!show) then continue, else ignore
            if(!show || this.active && !isStepVisited(step)){
                this.set("step",{number:step, display:show});
            }
        },
        initialize: function(){
            this.on("change:step",function(model,step){
                if(step.display){
                    setStepVisited(step);
                }
            });
        }
    });

    tourModel = new TourModel();
})(jQuery);

(function($){

    var closeStepOne = function(){
        $("#step1").hide();
        $("#rss, #gorss, #mySitesTab").glowToggle(false);
    };
    var closeStepTwo = function(){
        $("#step2").hide();
        $(".help-text-drag, #gallery").glowToggle(false);
    };

    var stepFunctions = {
            1:function (show){
                if(show) {
                    $("#step1").show();
                    $("#rss, #gorss, #mySitesTab").glowToggle(true);
                    $("#rssInputs, #mySitesTab").expose({
                        closeOnEscape : true,
                        closeOnClick : false,
                        close:function(){
                            closeStepOne();
                        }
                    });
                } else {
                    closeStepOne();
                    $("#mySitesTab").expose("remove");
                }
            },
            2:function (show){
                if(show) {

                    $("#step2").show();
                    $(".help-text-drag, #gallery").glowToggle(true);

                    $(".help-text-drag, #step2, #gallery").expose({
                        closeOnEscape : true,
                        closeOnClick : false,
                        close:function(){
                            closeStepTwo();
                            //$("#rss, #gorss, #mySitesTab").glowToggle(false);
                        }
                    });
                    $("#step2").css("z-index","1003");
                } else {
                    closeStepTwo();
                     $("#gallery").expose("remove");
                }
            }
         };

    var TourView = Backbone.View.extend({

        model: tourModel,
        initialize: function() {
            this.model.on( 'change:step', this.render, this );
        },
        render: function(model,step) {
            //alert(JSON.stringify(step,4));
            stepFunctions[step.number](step.display);
        }
    });

    tourView = new TourView();
    //view private functions

})(jQuery);

$(function(){

    $(".tourCloseButton").click(function(){
       tourModel.close();
    });

});


texts:
I promise that I've done my reading on this topic.  I've seen many suggestions and critiques, but I haven't seen the argument below critiqued.  I'm not trying to beat a dead horse, but I don't think anyone's offered this one up yet:

x ||= y
is functionally equivalent to
x = y unless x

The code below has been through 5 years of feature additions; hence the difference in coding style.  An evaluation is a survey questionnaire.  To determine which questions to present, first see if an evaluation ID is specified in the URL, then fall back on the evaluation the user should see (if any), then fall back on the evaluation configured for this site (if any).

evaluation = Evaluation.find(params[:evaluation_id]) if params[:evaluation_id]
evaluation ||= Evaluation.find(@user.id_of_required_evaluation)
evaluation = Evaluation.find(@site.id_of_required_evaluation) unless evaluation

This doesn't flow well visually.  I'm at the point where I can use ||= or unless and don't believe there to be any difference between the two.

Therefore, my question is:  Is there any reason to choose one of the below blocks over the other?

Option 1

evaluation = Evaluation.find(params[:evaluation_id]) if params[:evaluation_id]
evaluation ||= Evaluation.find(@user.id_of_required_evaluation)
evaluation ||= Evaluation.find(@site.id_of_required_evaluation)

Option 2

evaluation = Evaluation.find(params[:evaluation_id]) if params[:evaluation_id]
evaluation = Evaluation.find(@user.id_of_required_evaluation) unless evaluation
evaluation = Evaluation.find(@site.id_of_required_evaluation) unless evaluation

My apologies to the dead horse who again finds himself being beaten and to those who have to watch.  If this is a stupid question, please consider the horse and beat me instead.