texts:
I'm very new to Angular, and trying to get my head around whether or not I'm doing it the Right Way (tm).

I want to filter a set of results by their properties, where if none of the filters are checked, all the results are displayed, but if one or more filters are checked, all results which match the checked properties are displayed.

I've setup a simple demo with the colours of fruit. The JSFiddle is available at http://jsfiddle.net/mattdwen/u5eBH/2/

The HTML has a series of checkboxs and a repeating list for the set results:

        <input type="checkbox" ng-click="includeColour('Red')"/> Red

        <input type="checkbox" ng-click="includeColour('Orange')"/> Orange

        <input type="checkbox" ng-click="includeColour('Yellow')"/> Yellow

                {{f.name}}

        Filter dump: {{colourIncludes}}

And the JS adds the checked properties to a scope array, and the filter checks if the fruit colour is in that array:

'use strict'

angular.module('fruit', []);

function FruitCtrl($scope) {
    $scope.fruit = [
        {'name': 'Apple', 'colour': 'Red'},
        {'name': 'Orange', 'colour': 'Orange'},
        {'name': 'Banana', 'colour': 'Yellow'}];

    $scope.colourIncludes = [];

    $scope.includeColour = function(colour) {
        var i = $.inArray(colour, $scope.colourIncludes);
        if (i > -1) {
            $scope.colourIncludes.splice(i, 1);
        } else {
            $scope.colourIncludes.push(colour);
        }
    }

    $scope.colourFilter = function(fruit) {
        if ($scope.colourIncludes.length > 0) {
            if ($.inArray(fruit.colour, $scope.colourIncludes) < 0)
                return;
        }

        return fruit;
    }
}

It doesn't really feel 'Angular' enough to be the correct way to achieve this?


texts: How should I efficiently delete elements from a PHP array?

texts:
In this case I have an array that is parsed from a JSON file. Normally I use all the elements in the array, but for AJAX crawling I only show the parts the search engine asked for:

<?php $fitstyles = json_decode(file_get_contents(DATA_FILE), true); ?>
…
<?php
if ($base == "fits" || $base == "gallery") {
    /* For fragment handler, delete out the parts of the fits array that aren't needed. */
    $keep_fit = $fragments[1];
    $keep_style = $fragments[2];
    foreach ($fitstyles as $fit => $styles) {
        if ($fit != $keep_fit) {
            unset($fitstyles[$fit]);
            continue;
        }
        foreach ($styles as $style => $styleinfo) {
            if ($style != $keep_style) {
                unset($fitstyles[$fit][$style]);
                continue;
            }
        }
    }
} ?>

Here, $fragments looks like:

(
    [0] => fits
    [1] => straight
    [2] => utility
)

and $fitstyles takes the following form:

Array
(
    [straight] => Array
        (
            [utility] => Array
                ( … )
        )
    [anotherfit] => Array
        (
            [anotherstyle] => ( … )
        )
)

The approach appears to work; however, please give me feedback as to the effectiveness, efficiency and readability of this approach.


texts: Country, city, and address tables for a customer

texts:
I need to create a customer and I have foreign keys for each table. Below is an image displaying the relationships of the tables when I want to insert a new customer. Then below the diagram I list out 3 methods that I would like to know any suggestions on how to best remove all the duplication. The main obstacle I encounter is that each method has a different amount of PrepareStatement and params to set (i.e. setString, setLong, etc). I want to use this example to learn how to do it to clean up the rest of my code. Please note that I am not allowed to use any external libraries or frameworks for this project outside of the standard java libraries.

private void handleSaveButton() throws SQLException {
    countryId = getCountryId();
    cityId = getCityId();
    addressId = getAddressId();
}

/**
 *
 * @return @throws SQLException
 */
private long getCountryId() throws SQLException {
    getConnection();
    param = toTitleCase(countryTextField.getText());
    System.out.println("country param: " + param);
    String query = "insert into country (country) values (?)";
    ps = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
    ps.setString(1, param);
    try {
        ps.executeUpdate();
        rs = ps.getGeneratedKeys();
        rs.next();
        primaryKey = rs.getLong(1);
        System.out.println("inserted country id: " + primaryKey);
    } catch (SQLIntegrityConstraintViolationException e) {
        ps = con.prepareStatement("select countryId from country where country = ?");
        ps.setString(1, param);
        rs = ps.executeQuery();
        rs.next();
        primaryKey = (long) rs.getInt(1);
        System.out.println("existing country id: " + primaryKey);
    } finally {
        closeConnection(ps);
    }
    return primaryKey;
}

/**
 *
 * @return @throws SQLException
 */
private long getCityId() throws SQLException {
    getConnection();
    param = toTitleCase(cityTextField.getText());
    System.out.println("city param: " + param);
    String query = "insert into city (city, countryId) values (?, ?)";
    ps = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
    ps.setString(1, param);
    ps.setLong(2, countryId);
    try {
        ps.executeUpdate();
        rs = ps.getGeneratedKeys();
        rs.next();
        primaryKey = rs.getLong(1);
        System.out.println("inserted city id: " + primaryKey);
    } catch (SQLIntegrityConstraintViolationException e) {
        ps = con.prepareStatement("select cityId from city where city = ?");
        ps.setString(1, param);
        rs = ps.executeQuery();
        rs.next();
        primaryKey = (long) rs.getInt(1);
        System.out.println("existing city id: " + primaryKey);
    } finally {
        closeConnection(ps);
    }
    return primaryKey;
}

/**
 *
 * @return @throws SQLException
 */
private long getAddressId() throws SQLException {
    getConnection();
    param = toTitleCase(addressTextField.getText());
    System.out.println("address param: " + param);
    String query = "insert into address (address, cityId, postalCode, phone) values (?,?,?,?)";
    ps = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
    ps.setString(1, param);
    ps.setLong(2, cityId);
    ps.setString(3, postalTextField.getText());
    ps.setString(4, phoneTextField.getText());
    try {
        ps.executeUpdate();
        rs = ps.getGeneratedKeys();
        rs.next();
        primaryKey = rs.getLong(1);
        System.out.println("inserted address id: " + primaryKey);
    } catch (SQLIntegrityConstraintViolationException e) {
        ps = con.prepareStatement("select addressId from address where address = ? and cityId = ?");
        ps.setString(1, param);
        ps.setLong(2, cityId);
        rs = ps.executeQuery();
        rs.next();
        primaryKey = (long) rs.getInt(1);
        System.out.println("existing address id: " + primaryKey);
    } finally {
        closeConnection(ps);
    }
    return primaryKey;
}


texts: Building a string from multiple inputs with some variations

texts:
I am accepting a form from the user with a bunch of inputs and I am constructing a string from those inputs.  I am trimming each input and 2 of the inputs (GID & Clone) are not required fields so I'm doing null checks before building the string to avoid null object errors.

I wrote this method and it works, but I was wondering if there is a less repetitive way of doing this.

private string ConstructSeedReference(SeedViewModel model)
{
    string SeedRefId;

    if (!String.IsNullOrEmpty(model.Seed.GID) && !String.IsNullOrEmpty(model.Seed.Clone))
    {
        SeedRefId = String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}",
        model.Customer.CustomerCode.TrimEnd(), model.Seed.CollectionCodeId.TrimEnd(), model.Seed.SpeciesId.TrimEnd(),
        model.Seed.Zone.TrimEnd(), model.Seed.Elevation.TrimEnd(), model.Seed.ColYear.TrimEnd(), model.Seed.OrchardId, model.Seed.GID.TrimEnd(), model.Seed.Clone.TrimEnd());
        return SeedRefId;
    }
    else if (!String.IsNullOrEmpty(model.Seed.GID) && String.IsNullOrEmpty(model.Seed.Clone))
    {
        SeedRefId = String.Format("{0}{1}{2}{3}{4}{5}{6}{7}",
        model.Customer.CustomerCode.TrimEnd(), model.Seed.CollectionCodeId.TrimEnd(), model.Seed.SpeciesId.TrimEnd(),
        model.Seed.Zone.TrimEnd(), model.Seed.Elevation.TrimEnd(), model.Seed.ColYear.TrimEnd(), model.Seed.OrchardId, model.Seed.GID.TrimEnd());
        return SeedRefId;
    }
    else if (String.IsNullOrEmpty(model.Seed.GID) && !String.IsNullOrEmpty(model.Seed.Clone))
    {
        SeedRefId = String.Format("{0}{1}{2}{3}{4}{5}{6}{7}",
        model.Customer.CustomerCode.TrimEnd(), model.Seed.CollectionCodeId.TrimEnd(), model.Seed.SpeciesId.TrimEnd(),
        model.Seed.Zone.TrimEnd(), model.Seed.Elevation.TrimEnd(), model.Seed.ColYear.TrimEnd(), model.Seed.OrchardId, model.Seed.Clone.TrimEnd());
        return SeedRefId;
    }
    else
    {
        SeedRefId = String.Format("{0}{1}{2}{3}{4}{5}{6}",
        model.Customer.CustomerCode.TrimEnd(), model.Seed.CollectionCodeId.TrimEnd(), model.Seed.SpeciesId.TrimEnd(),
        model.Seed.Zone.TrimEnd(), model.Seed.Elevation.TrimEnd(), model.Seed.ColYear.TrimEnd(), model.Seed.OrchardId);
        return SeedRefId;
    }
}


texts:
in an MCMC procedure I am repeatedly (100,000+ times) running the following function to find the kth order statistic. I ran a profiler and noticed this function was most expensive. I am looking for a way to optimize this code for speed. The reason I think it can be done faster is because I do not want find the kth largest value, but the index of the kth largest value. However, now I'm effectively looping twice through the vector x, which seems inefficient to me.
The code below is an example, in practice I use R and Rcpp to run the code. Any ideas?

#include <iostream>
#include "C:\c++\armadillo-7.950.1\include\armadillo"

using namespace std;
using namespace arma;

int qSelectIdxC(arma::vec& x, const int k) {

    // ARGUMENTS
    // x: vector to find k-th largest element in
    // k: k-th statistic to look up

    // safety copy since nth_element modifies in place
    arma::vec y(x.memptr(), x.n_elem);

    // partially sorts y.
    std::nth_element(y.begin(), y.begin() + k, y.end());

    // the k-th largest value
    const double kthValue = y(k);

    // find and return the index of the k-th largest value;
    int idxK = std::find(x.begin(), x.end(), kthValue) - x.begin();
    return idxK;

}

int main() {

    vec test0 = regspace<vec>(0, 10); // 0, 1, ..., 10
    int ans0 = qSelectIdxC(test0, 5); // returns 5

    vec test1(100, fill::randu);
    int ans1 = qSelectIdxC(test1, 50);

    cout << "ans0" << ans0;
    cout << "ans1" << ans1;

    return 0;
}


texts:
I'm currently working on a text adventure game for my first project. I am a beginner so I am seeking help with my code. Please comment any tips and general help regarding with making my code better, faster or more organised! I only started Python two weeks ago so any help would be greatly appreciated. I decided to only submit the code for the first room as I don't want to submit too much code at once.

health = 100
coins = 0
tutorial = True
gameStart = False
death  = False
spawn = True
livingRoom = False
Bathroom = False
Bedroom = False
Kitchen = False
wardrobeSpawn = False
spawnStart = True
telev = False

def countCoins():
    print
    print("You have: " + str(coins) + " coins")

while gameStart == True:
    if spawn == True:
        if spawnStart == True:
            print
            print(bcolors.FAIL + "You wake up in a room you don't
recognise, with no idea how you got there")
            print
            print(bcolors.ENDC + "You look around and see a wardrobe
and a door")
            spawnStart = False
        elif spawnStart == False:
            print
            spawnIn = raw_input("")
            spawnIn = spawnIn.lower()
            if spawnIn == "coins":
                countCoins()
                spawnStart = False
            elif spawnIn == "wardrobe":
                if wardrobeSpawn == False:
                    print
                    print "The wardrobe seems quite empty, but you do
find a coin in the far left corner, you put it in your pocket"
                    print
                    coins += 1
                    wardrobeSpawn = True
                    spawnStart = False
                elif wardrobeSpawn == True:
                    print "This wardrobe looks oddly familiar, you have
already explored it"
                    print
                    spawnStart = False
            elif spawnIn == "door":
                print
                print ("You walk out the door")
                print
                spawn = False
                livingRoom = True
            elif spawnIn == "look":
                print("You look around and see a wardrobe and a door")
                print
                spawnStart = False
            else:
                print("That is an unvalid command. Try again")
                print
                spawnStart = False


texts: Preventing duplicate numbers from being entered

texts:
I recently wrote a program involving a MySQL database using C#. The program is simple: it allows users to enter numbers and ensures that no same number is entered twice. Now I know that it is not efficient and I need help in order to improve the code.

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Final
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        int i=0;
        int k = 0;
        int count = 0;
        int handler = 0;
        int loop = 0;
        private bool read_data(MySqlConnection def)
        {
            bool yes = false;
            int k = 0;
            int loop = 0;
          while(true)
          {
              string query = "SELECT CNIC FROM `voters`.`voters` WHERE ID=" + k.ToString() + ";";
              MySqlCommand cmd = new MySqlCommand(query, def);
              cmd.ExecuteNonQuery();
              MySqlDataReader Reader = cmd.ExecuteReader();
              if (Reader.Read())
              {
                  loop++;
                  k++;
                  if (textBox1.Text.Equals(Reader.GetString(0)))
                  {
                      yes = true;
                  }
                  Reader.Close();
              }
              else
              {
                  Reader.Close();
                  break;
              }
          }
          return yes;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            bool check;
            string query;
            string CNIC = textBox1.Text;
            string connectionString = "server=localhost;user=root;database=voters;port=3306;password=admin;";
            MySqlConnection conn = new MySqlConnection(connectionString);
            conn.Open();
            if(k==0)
            {
               query = "DELETE FROM `voters`.`voters`;" + "INSERT INTO `voters`.`voters`(`ID`,`Name`,`CNIC`) VALUES(" + i.ToString() + ",'Random'," + CNIC + ");";
             MySqlCommand comd = new MySqlCommand("DELETE FROM `voters`.`voters`;", conn);
                comd.ExecuteNonQuery();
                i++;
            }else{
              query = "INSERT INTO `voters`.`voters`(`ID`,`Name`,`CNIC`) VALUES(" + i.ToString() + ",'Random'," + CNIC + ");";
              i++;
            }
            k=1;
            check = read_data(conn);
            if(!check)
            {
                MySqlCommand cmd = new MySqlCommand(query, conn);
                cmd.ExecuteNonQuery();
            }
            else
            {
                MessageBox.Show("ERROR!.CNIC Already VOTED");
            }
            conn.Close();
        }
    }

}


texts:
Below is a chunk of some switch code used to create an array of objects which should be visible.  Previously I combined case -1 and case 0 to reduce redundancy, but I am wondering if this code can be reduced in size and/or improved in readability.

var visibles = [];
switch (hrdid) {
    case -1:
    case 0:
        if (row("tcd")) {
            visibles = ['lc', 'ts2', 'rtc', 'ctb'];
            if (row("cbr")) visibles.push('ccb2');
        } else {
            visibles = ['lc1', 'tc', 'rc', 'ico', 'ccb'];
        }
        if (hrdid == 0) visibles.push('bcf');
        if (hrdid == -1) {
            visibles.push('bcfa');
            visibles.push('cpma');
        }
        break;
    //case 1, etc...
}


texts: MVC routing with duplicate method entry points

texts:
The 3 methods below all need to have the same name: "Roles"

They need to be the same as I have a permissions system that will only allow the execution of a "Roles" method.

I don't feel too happy about the third method because in order to keep the compiler happy, I have to declare a pointless and never used string variable.

Can anyone think of a better way of doing this?

public partial class PartialsController
{
    [Route("roles")]
    public async Task<ActionResult> Roles()
    {
        ViewBag.InitialData = await Uow.Roles.Query(InitialQuery("name", "asc"));
        return PartialView("Roles/ListRoles");
    }

    [Route("roles/{id:guid}")]
    public async Task<ActionResult> Roles(Guid id)
    {
        ViewBag.Role = await Uow.Roles.GetById(id);
        ViewBag.Permissions = await Uow.Permissions.GetAll().Select(p => new { p.Id, p.Description }).ToListAsync();
        return PartialView("Roles/EditRole");
    }

    [Route("roles/new")]
    public async Task<ActionResult> Roles(string nothing)
    {
        ViewBag.Permissions = await Uow.Permissions.GetAll().Select(p => new { p.Id, p.Description }).ToListAsync();
        return PartialView("Roles/EditRole");
    }
}


texts: Utilising pymongo to scrape over 4 million urls using multiprocessing to examine the impact of coronavirus

texts:
So I want to do some research on the impact COVID-19 is having on businesses. I've managed to generate a database with the company name and the website URLs associated with it. Now I want to scrape them all as fast as possible so I can do some analysis on it. I am new to using parallel programming and am skeptical I am connecting to each database as safely as possible.
from __future__ import division

from multiprocessing import Pool

import pymongo as pym
import requests
from bs4 import BeautifulSoup

# Set up local client
client = pym.MongoClient('mongodb://localhost:27017/')
# Connect to local DB
db = client.local_db
# Connect to Collections
My_Collection = db.MyCollection
ScrapedPagesAprilCollection = db.ScrapedPagesApril

# I don't want to scrape these
LIST_OF_DOMAINS_TO_IGNORE = ['google.com/', 'linkedin.com/', 'facebook.com/']

def parse(url):
    if any(domain in url for domain in LIST_OF_DOMAINS_TO_IGNORE):
        pass
    elif '.pdf' in url:
        pass
    else:
        # print(url)
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0',
        }
        page = requests.get(url, headers=headers)
        print(f'{url}: {page.status_code}')
        if page.status_code == 200:
            soup = BeautifulSoup(page.text, 'lxml')
            text = soup.get_text(separator=" ")
            info_to_store = {
                '_id': url,
                'content': text
            }

            if 'coronavirus' in text:
                info_to_store['Impacted'] = True

            # Insert into Collection
            ScrapedPagesAprilCollection.replace_one(
                {'_id': url}, info_to_store, upsert=True)

        elif page.status_code != 200:
            print(f'{url}: {str(page.status_code)}')
            pass

def covid19_scrape_pages(collection, query: dict):
    """
    Wanting to update the pages already matched

    Parameters
    ----------
    collection : pymongo.collection.Collection
    query : dict

    Yields
    -------
    A url

    """
    # Get the cursor
    mongo_cursor = collection.find(query, no_cursor_timeout=True)
    # For company in the cursor, yield the urls
    for company in mongo_cursor:
        for url in company['URLs']:
            doc = ScrapedPagesAprilCollection.find_one({'_id': url})
            # If I haven't already scraped it, then yield the url
            if doc is None:
                yield (url)

def main():
    print('Make sure LIST_OF_DOMAINS_TO_IGNORE is updated by running',
          'blacklisted_domains.py first')
    urls_gen = covid19_scrape_pages(
        My_Collection, {})
    pool = Pool(8)
    pool.map(parse, urls_gen)
    pool.close()
    pool.join()

if __name__ == "__main__":  # Required logic expression
    main()


texts: Adding to a dictionary and skipping duplicate keys

texts:
What is the cleanest way to use dictionaries and protect against an unhandled ArgumentException if the key already exists in the dictionary?

I'd like to say that I can always guarantee uniqueness upstream, but I'm dealing with legacy code and mildly corrupt data from an old bug in the system.

I find myself using this pattern frequently but wonder if there is a better way.

public void AddToDictionaryContainsKey(Dictionary<int,string> myDictionary, int myKey, string myValue )
{
    if (!myDictionary.ContainsKey(myKey))
    {
        myDictionary.Add(myKey, myValue);
    }
}

Maybe a try/catch block -  but this seems less readable.  The advantage is that if I ever do decide to log the problem I have a place to do it.

public void AddToDictionaryTryCatch(Dictionary<int, string> myDictionary, int myKey, string myValue)
{
    try
    {
        myDictionary.Add(myKey, myValue);
    }
    catch (ArgumentException e)
    {
        // keep on truckin'
    }
}

The dictionaries are relatively small (typically < 1000 entries) so I prefer readability over performance.


texts:
Write a function that will take an integer argument say n.
n ranges from 2 <= n <= 100

The function would not take any argument from the user.
the function should print the pattern according to the value of n.

Let's say if

n = 3 so output should be.

1*2*3
7*8*9
4*5*6

n = 4

1*2*3*4
9*10*11*12
13*14*15*16
5*6*7*8

n = 5

1*2*3*4*5
11*12*13*14*15
21*22*23*24*25
16*17*18*19*20
6*7*8*9*10

and so on. . .

  Without using STL Stack

void showPattern(int n)
{
    int *arr = (int*)malloc(n * sizeof(int));
    int toggle = 1;
    int k;
    int top = -1;
    for (int i = 0; i < n; i++) {
        k = i*n + 1;
        if (toggle) {
            for (int j = 0; j < n; j++) {
                if (k < n || k%n)
                    cout << k << "*";
                else
                    cout << k;
                k++;
            }
            cout << endl;
            toggle = 0;
        }
        else {
            top++;
            arr[top] = i;
            toggle = 1;
        }
    }

    while (top != -1) {
        k = arr[top] * n + 1;
        for (int i = 0; i < n; i++) {
            if (k < n || k%n)
                cout << k << "*";
            else
                cout << k;
            k++;
        }
        cout << endl;
        top--;
    }

}

  Using STL Stack

void showPattern(int n)
{
    stack <int> stk;
    int itr, toggle = 1;

    for (int i = 0; i < n; i++) {

        if (toggle) {
            itr = i*n + 1;
            for (int j = 0; j < n; j++) {
                if (itr < n || itr%n) {
                    cout << itr << "*";
                }
                else {
                    cout << itr;
                }
            }
            cout << endl;
            toggle = 0;
        }
        else {
            stk.push(i);
            toggle = 1;
        }
    }

    int i;
    while (!stk.empty()) {
        itr = stk.top()*n + 1;
        stk.pop();
        for (int j = 0; j < n; j++) {
            if (itr < n || itr%n) {
                cout << itr << "*";
            }
            else {
                cout << itr;
            }
        }
        cout << endl;
    }

}


texts:
I wanted to have some advice about the code I have.

I managed to get what I wanted done, but I do not think it is the "proper" way of doing it in the programmers' world.

Could you help me improve the code by any means and also if there are any better ways of doing this please share them as well.

I have files named in the format:

501.236.pcd

501.372.pcd

...

612.248.pcd etc.

I wanted to put the filenames in ascending order according to the filenames using C++.

This is the code I use:

#include <string>
#include <iostream>
#include <boost/filesystem.hpp>
#include <sstream>

using namespace std;
using namespace boost::filesystem;

int main()
{
    vector <string> str,parsed_str;
    path p("./fake_pcd");
    string delimiter = ".";
    string token,parsed_filename;
    size_t pos = 0;
    int int_filename;
    vector <int> int_dir;

    //insert filenames in the directory to a string vector
    for (auto i = directory_iterator(p); i != directory_iterator(); i++)
    {
        if (!is_directory(i->path())) //we eliminate directories in a list
        {
        str.insert(str.end(),i->path().filename().string());
        }
        else
            continue;
    }

    //parse each string element in the vector, split from each delimiter
    //add each token together and convert to integer
    //put inside a integer vector
    parsed_str = str;
    for (std::vector<string>::iterator i=parsed_str.begin(); i != parsed_str.end(); ++i)
    {
        cout << *i << endl;
        while ((pos = i->find(delimiter)) != string::npos) {
        token = i->substr(0,pos);
        parsed_filename += token;
        i->erase(0, pos + delimiter.length());
    }

    int_filename = stoi(parsed_filename);
    int_dir.push_back(int_filename);

    parsed_filename = "";
    }

    cout << endl;

    parsed_str.clear();

    sort(int_dir.begin(), int_dir.end());

    //print the sorted integers
    for(vector<int>::const_iterator i=int_dir.begin(); i != int_dir.end(); i++) {
        cout << *i << endl;
    }

    //convert sorted integers to string and put them back into string vector
    for (auto &x : int_dir) {
        stringstream ss;
        ss << x;
        string y;
        ss >> y;
        parsed_str.push_back(y);
    }

    cout << endl;

    //change the strings so that they are like the original filenames
    for(vector<string>::iterator i=parsed_str.begin(); i != parsed_str.end(); i++) {
        *i = i->substr(0,3) + "." + i->substr(3,3) + ".pcd";
        cout << *i << endl;
    }

}

This is the output, first part is in the order the directory_iterator gets it, the second part is the filenames sorted in integers, and the last part is where I change the integers back into strings in the original filename format.

612.948.pcd
612.247.pcd
501.567.pcd
501.346.pcd
501.236.pcd
512.567.pcd
613.008.pcd
502.567.pcd
612.237.pcd
612.248.pcd

501236
501346
501567
502567
512567
612237
612247
612248
612948
613008

501.236.pcd
501.346.pcd
501.567.pcd
502.567.pcd
512.567.pcd
612.237.pcd
612.247.pcd
612.248.pcd
612.948.pcd
613.008.pcd


texts: Making pixels of RGB barcode suitable for scanning

texts:
Similar to Microsoft's HCCB before its discontinuation near 2015, Im trying to make a 2D barcode that uses RGB pixels to encode more than two possible states (Black/White).
Theoretically, at 100% data capacity, you could hold 16,777,216 different integers in a single pixel.
However, this level of storage is not feasible.

Consider the two RGB colors 47,213,71 and 47,213,72:

This unperceivable difference would have to be detected reliably even in suboptimal environments and lighting.
This is why Microsoft's HCCB only used 8 pre-determined colors, but I hypothesize modern cameras would still allow for greater detection and accuracy.

I wanted a barcode where you could change the gaps between colors, such that no two neighboring colors were less distant than the amount specified.
This way, a large gap like 128 could make each pixel represent a possible total of 8 colors - like Microsoft's original HCCB; While a small gap like 1 would give you the aforementioned 16,777,216 colors.
Now that I've finished explaining why anyone would want to do this, I can show you my C code. I'm not sure I did a good job at this, and I feel as though either my method or execution should be changed completely, so here's my approach to doing this
#include <stdio.h>
#include <stdint.h>

uint8_t* bind(uint32_t val, uint8_t bound){
  static uint8_t rgb[3];
  uint32_t buffer[3];
  uint32_t max = bound*(256/bound);

  buffer[0] = val * bound;
  buffer[1] = (buffer[0]/max)*bound;
  buffer[2] = (buffer[1]/max)*bound;

  rgb[0] = buffer[0] % max;
  rgb[1] = buffer[1] % max;
  rgb[2] = buffer[2] % max;

  return rgb;
}

uint32_t unbind(uint8_t* rgb, uint8_t bound){
  uint32_t max = 256/bound;
  return (rgb[0]/bound)+(rgb[1]/bound)*max+(rgb[2]/bound)*max*max;
}

int main(void) {
  uint32_t data = 1;
  uint8_t color_range = 128;

  uint8_t* colors = bind(data, color_range);
  uint32_t calculated = unbind(colors, color_range);

  printf("expected value: %u\nreturned value: %u\n\n", data, calculated);
  printf("rgb value: %u,%u,%u\n", colors[0], colors[1], colors[2]);
  return 0;
}


texts:
The following method retrieves a list of users and the subscriptions for each user, from my database. That said, it works, but it runs pretty dang slow. I'd like to improve the speed on it. Currently, it fetches a mere 90 records, and takes nearly 20 seconds to do so, partly because, for every record of final output, it's grouping the subs per user, and doing a fetch on that user to obtain userId, email, and username (all three as User below).

public IEnumerable<ActiveSubscriptionsSummary> ActiveSubscriptionsByUser(SubscriptionType type)
{
    var subs = new List<ActiveSubscriptionsSummary>();

    var subscriptions = _bss.ActiveSubscriptions(type);
    var subsByUser = subscriptions
        .GroupBy(s => s.UserId,
            s => s,
            (key, g) => new ActiveBuilderSubscriptionsSummary
            {
                User = _cs.ById(key),
                Subscriptions = g.ToList()
            })
        .ToList();

    return subsByUser;
}

_cs.ById above refers to a service call that retrieves the user:

public ICustomer ById(Guid id)
{
    return GetBackend().ById(id);
}

All I use from that method is UserId, UserName, and Email (in the ActiveSubscriptionsByUser method, that is).

_bss above refers to a service call, with this method:

public IEnumerable<Subscription> ActiveSubscriptions(string subscriptionType)
{
    var subs = _sms.CurrentSession.Query<Subscription>()
                    .Where(s => (s.SubscriptionType == subscriptionType) &&
                                (s.EndDate >= DateTime.Today.Date))
                    .ToList();
    return subs;
}

My goal here is to speed this thing up, as I know over time that "90" will be a pretty small number, and we'll potentially be showing 100's, if not 1000's, of subs on the screen. And 20 seconds for 90 equates to a long dang time for 1000+.

Is my GroupBy potentially something that can be better coded to make this run faster? Could I potentially join two queries "users" and "subs" in some better way?

Update
This is C#, running against an nHibernate-hooked SQL DB, outputting to Angular.


texts: Solving the travelling salesman problem using a genetic algorithm

texts:
I've got a simple program written in Golang that takes a map as input and tries to solve the travelling salesman problem by using a genetic algorithm. My Crossover method is a real performance killer due to intense use of make() (allocate memory / will provoke the GC).

What I'd like to do - and yet failed to do is outsource the creation of newGenes. pCrossover and therefore the size of newGenes will be the same over all calls of the function, so I'd like to avoid creating that slice again and again.

I am also interested in any suggestions for improvements of my coding style in Golang and other performance improvements I can take a look at.

My source is at Github.

Here is an excerpt of the function I am trying to improve:

func (ts *TravellingSalesman) Crossover() {
    // Crossover
    var nCrossover = int(ts.pCrossover * float64(ts.nGenes))
    var newGenes = make([]ga.Gene, nCrossover)
    for i:=0; i < nCrossover; i++ {
        newGenes[i].Data = make([]int, ts.geneLength)
        n := rand.Intn(ts.nGenes)
        m := rand.Intn(ts.nGenes)

        currentCity := ts.genes[n].Data[0];
        newGenes[i].Data[0] = currentCity
        for k:=1; k < ts.geneLength; k++ {
            nextN := findNextCity(&(ts.genes[n].Data), currentCity)
            nextM := findNextCity(&(ts.genes[m].Data), currentCity)

            existN := isInArray(&(newGenes[i].Data), nextN)
            existM := isInArray(&(newGenes[i].Data), nextM)

            // n exists, m doesnt -> take m
            if existN && !existM {
                newGenes[i].Data[k] = nextM
                currentCity = nextM
            } else if !existN && existM {
                newGenes[i].Data[k] = nextN
                currentCity = nextN
            } else if existN && existM {
                nextRandom := findNextRandomCity(newGenes[i].Data[0:k], &(ts.genes[n].Data))
                newGenes[i].Data[k] = nextRandom
                currentCity = nextRandom
            } else {
                // If both didn't exist, take the shorter one
                distN := ts.distMatrix.GetDistance(currentCity-1, nextN-1)
                distM := ts.distMatrix.GetDistance(currentCity-1, nextM-1)

                // Take the shorter route
                if distN < distM {
                    newGenes[i].Data[k] = nextN
                    currentCity = nextN
                } else {
                    newGenes[i].Data[k] = nextM
                    currentCity = nextM
                }
            }
        }
    }

    copy(ts.genes, newGenes)
}


texts:
I need to build a queue where the elements will be added and removed in chronological order by default. But if the client sets the priority flag for the queue I need to be able to pull the elements based on the priority order of the elements.

I currently have this implemented using two priority queues, however I do not like the approach as it seems like an overkill.

Please let me know if there is a better way of doing this or if there is an existing implementation that exists.

import javax.naming.OperationNotSupportedException;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class DynamicPriorityQueue<ComparableQueueElement> implements IQueue<ComparableQueueElement> {

    private static final int CONSTANT_HUNDRED = 100;
    private boolean fetchByCustomPriority = false;
    private final ReentrantLock lock;
    private final PriorityQueue<ComparableQueueElement> queue;
    private final PriorityQueue<ComparableQueueElement> customPriorityQueue;

    public DynamicPriorityQueue() {
        this(null);
    }

    public DynamicPriorityQueue(Comparator<ComparableQueueElement> comparator) {
        this.lock = new ReentrantLock();
        this.queue = new PriorityQueue<>(CONSTANT_HUNDRED);
        if (comparator != null)
            this.customPriorityQueue = new PriorityQueue<ComparableQueueElement>(CONSTANT_HUNDRED, comparator);
        else
            this.customPriorityQueue = null;
    }

    public void setFetchByCustomPriority(boolean fetchByCustomPriority) throws OperationNotSupportedException {
        if (this.customPriorityQueue == null)
            throw new OperationNotSupportedException("Object was created without a custom comparator.");

        this.fetchByCustomPriority = fetchByCustomPriority;
    }

    public void push(ComparableQueueElement t) throws InterruptedException {
        if (this.lock.tryLock(CONSTANT_HUNDRED, TimeUnit.MILLISECONDS)) {
            try {
                this.queue.offer(t);
                if (this.customPriorityQueue != null)
                    this.customPriorityQueue.offer(t);
            } finally {
                this.lock.unlock();
            }
        }
    }

    public ComparableQueueElement peek() {
        return this.fetchByCustomPriority ? this.queue.peek()
                : (this.customPriorityQueue != null ? this.customPriorityQueue.peek() : null);
    }

    public ComparableQueueElement pop() throws InterruptedException {
        ComparableQueueElement returnElement = null;
        if (this.lock.tryLock(CONSTANT_HUNDRED, TimeUnit.MILLISECONDS)) {
            try {
                if (this.fetchByCustomPriority && this.customPriorityQueue != null) {
                    returnElement = this.customPriorityQueue.poll();
                    this.queue.remove(returnElement);
                }
                else {
                    returnElement = this.queue.poll();
                    if (this.customPriorityQueue != null) {
                        this.customPriorityQueue.remove(returnElement);
                    }
                }
            } finally {
                this.lock.unlock();
            }
        }
        return returnElement;
    }
}


texts:
I have the following expression in my C++ code:

theta1 = theta0 - (acos((pow(constlength_link1 + length, 2) + (pow(length_base_end, 2) - pow(length_link2, 2)))
     / (2 * length_base_end * (constlength_link1 + length)))) * 180 / M_PI;

I understand that such a code will be very difficult for anyone else to debug. Should I break it down using additional variables?

Are there any other better approaches?

Edit: Sorry about the lack of details:

I am trying to calculate sum of two angles theta1 and theta2. These angles are being calculated by subtracting the inverse of cosine of an expression from a constant angle (theta0 or 180). The expression mentioned in the last line involves a division. The dividend is something like:

  (square of sum of two numbers) +/- (square of a number  - square of
  another number)

The divisor is something like:

  (2 * a number * (sum of two numbers))

The function is as shown below:

float length_angle(float length = 0.0)
{
    float theta1, theta2;

    theta1 = theta0 - (acos((pow(constlength_link1 + length, 2) + (pow(length_base_end, 2) - pow(length_link2, 2)))
     / (2 * length_base_end * (constlength_link1 + length)))) * 180 / M_PI;

    theta2 = 180 - (acos((pow(constlength_link1 + length, 2) - (pow(length_base_end, 2) - pow(length_link2, 2)))
     / (2 * length_link2 * (constlength_link1 + length)))) * 180 / M_PI;

    return theta1 + theta2;
}

I would like to write this expression better so that someone else can read or debug the code if required.


texts: Largest Sum Contiguous Subarray - Kadene's algorithm

texts:
I am looking forward to an answer to improve this code?
Thanks.
Test class
package test;

import main.algorithms.LargestSumContiguousSubarray;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class LargestSumContiguousSubarrayTest {

    LargestSumContiguousSubarray largestSumContiguousSubarray;

    @Before
    public void setUp(){
        largestSumContiguousSubarray = new LargestSumContiguousSubarray();
    }

    @Test
    public void testSumContiguousSubArray(){
        int[] a = {-2, -3, 4 - 1, -2, 1, 5, -3};
        int sum = 7;
        Assert.assertEquals(sum, largestSumContiguousSubarray.kadenesAlgo(a));
    }

}

LargestSumContiguousSubarray.java class
package main.algorithms;

public class LargestSumContiguousSubarray {

    // O(n)
    // Kadene's algorithm
    public int kadenesAlgo(int[] a) {

        // This is also works for negative numbers
        int max_so_far = a[0];
        int curr_max = a[0];

        for(int i=0;i<a.length; i++){
            curr_max = Math.max(a[i], curr_max+a[i]);
            max_so_far = Math.max(max_so_far, curr_max);
        }
        return max_so_far;
    }
}


texts: Display a number as a product of its prime factors

texts:
Task:

Link to original problem :https://www.spoj.com/problems/FACTCG2/

  The task in this problem is to write a number in a multiplication of
  prime
      numbers separated by “x”. You need to put the number 1 in this multiplication.

  Input:

  The input consists of several lines.

  Each line consists of one integer N (1 <= N <= 10^7) .

  Example Input:

           1
           2
           4
           8

  Example Ouput:

           1
           1 x 2
           1 x 2 x 2
           1 x 2 x 2 x 2

My approach:

I pre-compute an array Primes which contains the smallest prime factor of every number from 1 to 1e7 using the sieve.  Then to find the answer , I divide the number given in each query by its least prime factor until it becomes '1' or a prime number. Then I display it.

The code works for small inputs but SPOJ gives me time limit exceeded. I think maybe the vector in factorise function has
            something to do with it. I tried printing the answer without storing it in vector but 'x' makes it difficult .

My code:

#include <bits/stdc++.h>
using namespace std;
vector<long long>Primes(1e7);
bool prime(long long x)
{

    for(int i=2;i<=sqrt(x);i++)
    {
        if(x%i==0)
        return false;
    }
    return true;
}
void least_prime_factor()   //To store least prime factor of a
                             //  given number
 {

    Primes[1]=1;
                    for(int i=2;i<=1e7;i++)
                    {
                            if(Primes[i]==0)
                            {
                               Primes[i]=i;
                               for(int j=2;i*j<=1e7;j++)
                                {
                                    if(Primes[i*j]==0)
                                    Primes[i*j]=i;
                                }

                             }
                    }

 }
vector<long long>factorise(int x)  //This is to store the factors
                                   //of a number

{
    vector<long long>ret;
    while(x!=1||prime(x)!=true)
    {
        ret.push_back(Primes[x]);
        x=x/Primes[x];
    }
return ret;
}

int main() {

least_prime_factor();
int n;
while(scanf("%d", &n) == 1)
if(n==1)
{
    cout<<"1"<<endl;
}
else{

    vector<long long>ans=factorise(n);
    cout << "1 x" ;
    for(int i=0;i<ans.size();i++)
    {
        if(i==ans.size()-1)
            printf(" %d ", ans[i]);
        else
            printf(" %d x", ans[i]);
    }
    cout<<endl;
}
    return 0;
}


texts: Decimal to Binary Conversion and vice-versa in Python

texts:
Given a decimal number I need to convert it into binary
Given a binary number I need to convert it into decimal

After the conversion I need to perform some operation on it (for example, addition). I also need to print the result with a specified width.

Binary-Decimal:

n1 = int(input("Enter a binary number: "))
n2 = int(input("Enter a binary number: "))

# type cast to 'int' is done to provide width
decimalN1 = int("{0:d}".format(n1), 2)
decimalN2 = int("{0:d}".format(n2), 2)
decimalSum = int("{0:d}".format(n1 + n2), 2)

width = len(str(decimalSum))
print("max width = {}".format(width))

print ("{0:0{3}} + {1:0{3}} = {2:0{3}}".format(decimalN1, decimalN2, decimalSum, width))
print ("{0} + {1} = {2}".format(type(decimalN1), type(decimalN2), type(decimalSum)))

Decimal-Binary:

n1 = int(input("Enter a decimal number: "))
n2 = int(input("Enter a decimal number: "))

# type cast to 'int' is done to provide width
binaryN1 = int("{0:b}".format(n1))
binaryN2 = int("{0:b}".format(n2))
binarySum = int("{0:b}".format(n1 + n2))

width = (n1 + n2).bit_length()
print("max width = {}".format(width))

print ("{0:0{3}} + {1:0{3}} = {2:0{3}}".format(binaryN1, binaryN2, binarySum, width))
print ("{0} + {1} = {2}".format(type(binaryN1), type(binaryN2), type(binarySum)))

I want to know if there is any other (better) way of doing this. I know the bin() function could be used, but then it returns a string, so I cannot perform (integer) operation on it after the conversion.


texts: Optimize Recursive Fetching of information?

texts:
I wrote a small class that demonstrates my problem:

class Root
{
    private Leaf RootLeaf;
    private Dictionary<object, Leaf> AllItems = new Dictionary<object, Leaf>();  //dictionary contains a reference to each item, and the leaf it is assigned to (its parent)
    public Root()
    {
        RootLeaf = new Leaf();
    }

    public List<object> GetAllChildren
    {
        get { return RootLeaf.getAllChildren; }
    }

    public void Add(object o)
    {
        Leaf AddedTo = RootLeaf.Add(o);
        AllItems.Add(o, AddedTo); //Add object reference to AllItems dictionary
    }

    private IEnumerable<object> GetNeighbors(object obj)
    {
        foreach (object o in this.AllItems[obj].getAllChildren)
        {
            if (obj != o)
                yield return o;
        }
    }

    public void Update()
    {
        foreach (KeyValuePair<object, Leaf> i in AllItems)
        {
            foreach (object b in this.GetNeighbors(i.Key))
            {
                //Would do collision checks here
            }
        }
    }
}

class Leaf
{
    private const int MaxChildCount = 1;

    private List<object> Children = new List<object>();

    private Leaf[] ChildLeaves = null;
    private bool _LeavesGenerated = false; //Have the leaves been created? (Low Level, do not touch)
    private bool HasLeaves = false; //Should we use the leaves?

    protected void CreateLeaves()
    {
        if (!_LeavesGenerated)
        {
            //create each of the four leaves
            for (int i = 0; i < 4; i++)
                ChildLeaves[i] = new Leaf();
            _LeavesGenerated = true;
        }
        HasLeaves = true;
    }
    protected void RemoveLeaves()
    {
        HasLeaves = false;
    }

    /// <summary>
    /// Returns children of this leaf, and all of its subleaves
    /// </summary>
    public List<object> getAllChildren
    {
        get
        {
            List<object> outp = Children.ToList();
            if (HasLeaves)
            {
                foreach (Leaf l in ChildLeaves)
                    outp.AddRange(l.getAllChildren);
            }
            return outp;
        }
    }
    /// <summary>
    /// Get count of all children in this leaf, and its subleaves
    /// </summary>
    public int getChildCount
    {
        get
        {
            int outp = Children.Count;
            if (HasLeaves)
            {
                foreach (Leaf l in ChildLeaves)
                    outp += l.getChildCount;
            }
            return outp;
        }
    }

    static Random rand = new Random();
    /// <summary>
    ///
    /// </summary>
    /// <param name="o">The object to be added</param>
    /// <returns>The leaf the object was added to</returns>
    public Leaf Add(object o)
    {
        if (Children.Count >= MaxChildCount)
        {
            //Pick random subleaf, I know this isn't correct for a quadtree, but it will simplify this explanation code
            if (!HasLeaves)
                CreateLeaves();
            return ChildLeaves[rand.Next(0, 3)].Add(o);
        }
        else
        {
            Children.Add(o);
            return this;
        }
    }
}

I ran this through the ANTS profiler, and it not surprisingly pulled the Leaf.getAllChildren and Leaf.getChildCount as the two most expensive operations.  I'm ok with how everything thing else is laid out.  My question is: how could I optimize the two aforementioned properties?

The properties are called when the Root.Update() function is run.


texts:
Write a recursive version of the function reverse(s), which reverses the string s in place.

I'm studying K&R and wrote a code for the question.
void reverse(char s[], int n)   // The seconde argument should be always 1.
{               // The function should be always called as reverse(s, 1);
    int temp;
    int len;

    len = strlen(s);
    if ((len + 1) / 2 > n)
        reverse(s, n + 1);

    temp = s[n-1];
    s[n-1] = s[(len - 1) - (n-1)];
    s[(len - 1) - (n-1)] = temp;
}

The second argument n says reverse() is currently called at n-th times. The function works as if it sets an axis of symmetry at s[(strlen(s) + 1) / 2](since integer division is truncated, it's not always symmetric by the axis but the function behaves as if truncation doesn't happen and it is exactly an symmetric axis) and accordingly change s[n - 1] with s[(strlen(s) - 1) - (n - 1)] and vice versa. The function stops its recursive call when the index of the axis is larger than n.
I saw other solutions(this and this). I think they used nice idea for the question. But I wonder how you think about mine. Thanks for reading!


texts:
I have implemented a queue by using a stack data structure. How could I improve it?

package _amazonAskedQuestions.dataStructures;

import java.util.Iterator;
import java.util.Stack;

public class Queue_Stack<T> implements  Iterable<T>{

    Stack<T> stack = new Stack<>();

    public void enqueue(T item){
        Stack<Integer> temp = new Stack<Integer>();
        while(!stack.empty()){
            temp.push((Integer) stack.pop());
        }
        stack.push(item);
        while(!temp.empty()){
            stack.push((T) temp.pop());
        }
    }

    public T dequeue(){
        return stack.pop();

    }

    @Override
    public Iterator<T> iterator() {
        return (Iterator<T>) stack.lastElement();
    }

    public static void main(String args[]){

        Queue_Stack<Integer>  qs = new Queue_Stack<>();

        qs.enqueue(9);
        qs.enqueue(8);
        qs.enqueue(1);
        qs.enqueue(3);
        qs.enqueue(4);
        qs.enqueue(5);

       System.out.println( qs.dequeue());

    }
}


texts:
I've to create a class MyCalculator which consists of a single method long power(int, int). This method takes two integers,  and, as parameters and finds Math.pow(n,p).
- If either n or p is negative, then the method must throw an exception which says "n or p should not be negative.".
- If both n and p are zero, then the method must throw an exception which says "n and p should not be zero."

class MyCalculator {
    /*
    * Create the method long power(int, int) here.
    */
    long power(int n, int p) throws Exception {
        if(n==0 && p==0) {
            throw new Exception("n and p should not be zero.");
        } else if(n<0 || p<0) {
            throw new Exception("n or p should not be negative.");
        } else {
            return (long)Math.pow(n, p);
        }
    }
}

Is there any way to use Exception handling in a better way in such questions? We have to perform this check in most of the questions. So I need to understand it clearly.


texts: Detect the last resolve in an ES6 promise chain

texts:
I searched but failed to find a canonical pattern for ES6 promise-based queue.  In fact all I am making is a step-wise FIFO buffer to ensure that messages don't collide so a very simple queue structure: like a message, sausage machine...

All it does is create a chain of promises, that resolve, at a fixed interval, to the messages in the order that they were received.

It's important for my application to know when the queue has been cleared and the only way I could think to do this was to add a Promise.all after the last message has gone into the queue (I use a setTimeout to simulate this).

To feed the Promise.all, I'm accumulating an array of references to the chained promises and just for the hell of it, shifting them out of the queue after they resolve.

I puzzled over how to do this without adding the array, like to somehow kick a .then(_ => console.log('done') ahead of each new promise. In other words a queue 'head' that I unplug from the previous last element and plug into the current added promise.  But I couldn't figure out how to achieve that.

Is there a better way than this?

'use strict';
var t = 500;

function write (x, enc, cb) {
  process.stdout.write('write: ' + x);
  cb(x-1)
}
function f(x, write) {
  return new Promise(res => {
    setTimeout(_ => write(x, null, res), t)
  })

}

console.log('start');

var q = Promise.resolve(0);
var qs = [q];

[1,2,3,4,5,6,7,8,9,10]
  .map(n =>  {
    return {
      cb: function (_) {
        console.log('\tcb ' + n);
        qs.shift();
        return _
      },
      x: n
    }
  })  // [{ cb, x }...]
  .forEach(
    (o) => {

      q = q.then(() =>
        f(o.x, write)   // return a promise to write
          .then(_ => o.cb(_ + 1)) // followed by a synchronous write
      );
      qs.push(q);

    });

// monitor queue
setTimeout(_ => {
  console.log('register all ' + qs.length);
  Promise.all(qs).then(a => {   // detect queue completed
    console.log('all done');
    a.forEach((_, i) => console.log(_ + '\t' + i))
  });
} , t*5);


texts: Implementation of a doubly linked list in Java

texts:
I'd like to improve this code.

DoublyLinkList.java

public class DoublyLinkList<T> {

    private static class Node<T> {
        private T data;
        private Node next;
        private Node prev;

        public Node(T data) {
            this.data = data;
        }

        public void displayNode() {
            System.out.print(data + " ");
        }

        @Override
        public String toString() {
            return data.toString();
        }
    }

    public Node first = null;
    public Node last = null;

    public void addFirst(T data) {
        Node newNode = new Node(data);

        if (isEmpty()) {
            newNode.next = null;
            newNode.prev = null;
            first = newNode;
            last = newNode;

        } else {
            first.prev = newNode;
            newNode.next = first;
            newNode.prev = null;
            first = newNode;
        }
    }

    public boolean isEmpty() {
        return (first == null);
    }

    public void displayList() {
        Node current = first;
        while (current != null) {
            current.displayNode();
            current = current.next;
        }
        System.out.println();
    }

    public void removeFirst() {
        if (!isEmpty()) {
            Node temp = first;

            if (first.next == null) {
                first = null;
                last = null;
            } else {
                first = first.next;
                first.prev = null;
            }
            System.out.println(temp.toString() + " is popped from the list");
        }
    }

    public void removeLast() {
        Node temp = last;

        if (!isEmpty()) {

            if (first.next == null) {
                first = null;
                last = null;
            } else {
                last = last.prev;
                last.next = null;
            }
        }
        System.out.println(temp.toString() + " is popped from the list");
    }
}

DoublyLinkListDemo.java

public class DoublyLinkListDemo {

    public static void main(String[] args) {
        DoublyLinkList newList = new DoublyLinkList();
        newList.addFirst("arun");
        newList.addFirst("prakash");
        newList.addFirst(70);
        newList.addFirst(80);
        newList.addFirst(30);
        newList.displayList();
        newList.removeFirst();
        newList.removeFirst();
        newList.removeFirst();
        newList.removeLast();

        newList.displayList();
    }
}


texts:
This problem is from Automate The Boring Stuff using Python - Chapter 7.

  Write a function that takes a string and does the same thing as the strip()
  string method. If no other arguments are passed other than the string to
  strip, then whitespace characters will be removed from the beginning and
  end of the string. Otherwise, the characters specified in the second argument to the function will be removed from the string.

It takes a string and a character as input and return new stripped string.

#regexStrip.py - Regex Version of strip()

import re

def regex_strip(s, char=None):
    """
    Write a function that takes a string and does the same thing as the strip()
    string method. If no other arguments are passed other than the string to
    strip, then whitespace characters will be removed from the beginning and
    end of the string. Otherwise, the characters specified in the second argu-
    ment to the function will be removed from the string.
    """

    if not char:
        strip_left = re.compile(r'^\s*') #string starting with whitespace
        strip_right = re.compile(r'\s*$') #string ending with whitespace

        s = re.sub(strip_left, "", s) #replacing strip_left with "" in string s
        s = re.sub(strip_right, "", s) #replacing strip_right with "" in string s

    else:
        strip_char = re.compile(char)
        s = re.sub(strip_char, "", s)
    return s

if __name__ == '__main__':
    string_to_be_stripped = input("Enter string to be stripped: ")
    char_to_be_removed = input("Enter character to be removed, if none press enter: ")
    print(regex_strip(string_to_be_stripped, char_to_be_removed))

Output:

Enter string to be stripped: foo, bar, cat
Enter character to be removed, if none press enter: ,
foo bar cat


texts: Preparing a YouTube downloader based on Windows form

texts:
The program this function was written for is a Windows forms program.

This function downloads videos from the internet one after the other. It runs in a separate thread (so the user can drag the form around or whatever), but otherwise the form is disabled, so no more instances can be created without doing so explicitly in the code.

It does not, in fact, download the video. Instead, it sets up the function that will download the video, including all restrictions and such that relate to the user's options before clicking "download".

However, I feel like the function is bloated and clunky, among other concerns. Can someone help me increase its efficiency?

public void SetupDownloadingProcess(int retryCount, Collection<Tuple<string, int, VideoType>> urlList)
    {

        int previouslySelectedIndex = MainForm.SelectedQueueIndex;

        ObservableCollection<Tuple<string, int, VideoType>> finishedUrlList = new ObservableCollection<Tuple<string, int, VideoType>>();

        if (MainForm.UrlListNumberItems > 0)
        {

            MainForm.StartDownloadingSession(true);

            int position = 0;

            for (int count = 0, GlobalVariablesurlListCount = urlList.Count; count < GlobalVariablesurlListCount; count++)
            {

                if(MainForm.CurrentlyDownloading)
                {

                    try
                    {

                        Tuple<string, int, VideoType> url = urlList[count];

                        MainForm.SelectedQueueIndex = position;

                        position++;

                        Tuple<string, int, VideoType> tempTuple = DownloadVideos(url, position);

                        if (tempTuple != null)
                        {

                            finishedUrlList.Add(tempTuple);

                        }

                        Storage.WriteUrlsToFile(finishedUrlList, true);

                    }
                    catch(Exception ex)
                    {

                        var exceptionMessage = ex.Message;

                        if(retryCount <= 3)
                        {

                            MainForm.StatusBar = string.Format(CultureInfo.InstalledUICulture, "URL {0}: {1}. Retrying.... ({2})", count + 1, Trunicate(exceptionMessage, 50), retryCount < 3 ? (retryCount + 1).ToString(CultureInfo.CurrentCulture) : "Final Try");

                            System.Threading.Thread.Sleep(850);

                            SetupDownloadingProcess((retryCount + 1), urlList);

                        }
                        else
                        {

                            finishedUrlList.Clear();

                            MainForm.StatusBar = Trunicate(exceptionMessage, 100);

                        }

                    }

                }

            }

        }

        MainForm.CurrentlyDownloading = false;

        MainForm.StartDownloadingSession(false);

        MainForm.StartDownButtonEnabled = true;

        GlobalVariables.urlList = GetUnfinishedDownloads(finishedUrlList);

        Storage.WriteUrlsToFile(GlobalVariables.urlList, false);

        MainForm.RefreshQueue(previouslySelectedIndex, true);

    }

I prefer not to post all separate references as that would take forever and eat up a lot of room and be boring, but for the truly curious, my entire project can be found here.

I'm still relatively new to C# and coding in general, so please be patient with me and as thorough as possible.


texts:
The following is my code for my "drawer" to be display or hidden on the basis whether it has been clicked or not. I want to make this better as personally its messy. Any tips?

//Checks if the page loaded is of specific type
if(window.location.href.indexOf("home.php") > -1) {
      //Handles the displaying of the side bar on the home page.
      var button = document.getElementById('navIcon');
      button.onclick = function() {
          var div = document.getElementById('drawer');
          if (div.style.display !== 'block') {
              div.style.display = 'block';
              //If the document is over 900px. Readjusts the grid, Otherwise overlay
              if(document.body.clientWidth > 900) {
                  document.getElementById('resGrid').style.width = 'calc(100% - 240px)';
              }
          }
          else {
              div.style.display = 'none';
              document.getElementById('resGrid').style.width = '100%';
          }
      };
    }


texts: Function to determine what color shirt somebody should wear to a football game depending on what seat they have

texts:
I was tasked with writing a function to find what color shirt someone should wear to our college football game depending on what seat they sit in. Here is the function I came up with:

function getColor(section, row) {
  const colorA = "orange";
  const colorB = "white";
  section = section.toUpperCase();

  /* Case 1: Section is a special section */
  if (section.includes("TER") || section.includes("WC") || section.includes("EC")) {
    /* Numbers in special sections are guaranteed to be single digit,
       So just grab the last character in the section. */
    const number = section.slice(-1);
    // Even numbers are colorB, odd are colorA
    return (number % 2 === 0) ? colorB : colorA;
  }
  /* Case 2: Section is a single letter (No numbers) */
  else if  (section.length === 1) {
    /* A through Q have different row numbers than R through W */
    const section_divider = getSectionDivider(section);

    /* Odd-lettered (A, C, etc.) sections are colorA when above
       the section divider. Even-lettered section are colorB when
       above the section divider. */
    if (section.charCodeAt(0) % 2 === 0) {
      return (row >= section_divider) ? colorB : colorA;
    } else {
      return (row >= section_divider) ? colorA : colorB;
    }
  }
  /* Case 3: Section is two letters (No numbers) */
  else if (section.length == 2 && section.charAt(0) >= 'A' && section.charAt(0) <= 'Z'  &&
           section.charAt(1) >= 'A' && section.charAt(1) <= 'Z') {
    /* Double lettered sections are always the same color as the
       single letter's bottom row */
    return getColor(section.charAt(0), 0);
  }
  /* Case 4: Section is a single letter followed by a number */
  else if (!isNaN(section.slice(1))) {
    /* Row is WC */
    if (isNaN(row)) {
      /* WC rows should just match the section below them */
      return getColor(section, 0);
    }

    /* X3 and Z15 are special cases where the whole section isn't one
       color. They are both colorB above the section divider and colorA below. */
    if (section === "X3" || section === "Z15") {
      const section_divider = 16; // Just in case it changes in the future.
      return (row <= section_divider) ? colorA : colorB;
    } else {
      /* This is the number. (i.e. X4 => 4, Z13 => 13) */
      const number_in_section = parseInt(section.slice(1));
      return (number_in_section % 2 === 0) ? colorA : colorB;
    }
  }
  /* Case 5: Section is a double letter followed by a number */
  else {
    /* Double-letter-number sections are always the opposite of the
       single-letter version of its self's top row.
       (i.e. XX13 is whatever X13's top row isn't) */
    return getColor(section.slice(1), 1000) === colorA ? colorB : colorA;
  }
}

Is there a better way of solving this problem? Is the code clear?


texts: Modify or not modify your objects when creating computing functions?

texts:
See the examples below:

function map_cloning(obj,fn){
    result = {};
    for (var key in obj)
        result[key] = fn(obj[key]);
    return result;
};
function map_modifying(obj,fn){
    for (var key in obj)
        obj[key] = fn(obj[key]);
    return obj;
};

function sum_cloning(vector1,vector2){
    return [vector1[0] + vector1[1], vector2[0] + vector2[1]];
};
function sum_modifying(vector1,vector2){
    vector1.x += vector2.x;
    vector1.y += vector2.x;
    return vector1;
};

function tail_cloning(obj){
    return obj.slice(1);
};
function tail_modifying(obj){
    obj.splice(0,1);
    return obj;
};

Often you have to chose between cloning or not an object before making a computation. Which is best?


texts: Metalsmith plugin for stripping UTF8 BOM from files

texts:
I've been developing a metalsmith static site and I came across an issue where Visual Studio was automatically adding a BOM to the pages.

I wrote the following plugin for metalsmith (it needs to be run as the first plugin). This feels a little messy. It was written mostly as a copy-paste and a lot of debugging.

var stripBom = require('strip-bom');
var front = require('front-matter');
var extend = require('extend');

// **snip**

.use(function __utf8BOM_workaround(files, metalsmith, done)
{
    setImmediate(done);
    Object.keys(files).forEach(function (file)
    {
        var data = files[file];
        var parsed = front(stripBom(data.contents.toString()));
        data = extend({}, data, parsed.attributes);
        data.contents = new Buffer(parsed.body);

        files[file] = data;
    });
})


texts: Importing an Excel document into a project

texts:
I use the following code to verify that columns have data and display the appropriate error message.

My code is working but it just doesn't look tidy. Is there any way to refactor all the if statements into a loop to display the error message, possibly another method which checks all? checkIfColumnIsEmpty is a bool method which returns true if the column is empty.

        //if either column 0 and 1 are empty && column 2,3,4 and 5 are not
    if (!checkIfColumnisEmpty(r.ItemArray[0]) || !checkIfColumnisEmpty(r.ItemArray[1])
    && checkIfColumnisEmpty(r.ItemArray[2]) && checkIfColumnisEmpty(r.ItemArray[3])
    && checkIfColumnisEmpty(r.ItemArray[4]) && checkIfColumnisEmpty(r.ItemArray[5]))
    {
        if (checkIfColumnisEmpty(r.ItemArray[0]) && !checkIfColumnisEmpty(r.ItemArray[1]))
        {
            throw new ImportBOQException("Error importing document: First column is empty");
        }
        else if (!checkIfColumnisEmpty(r.ItemArray[0]) && checkIfColumnisEmpty(r.ItemArray[1]))
        {
            throw new ImportBOQException("Error importing document: Second column is empty");
        }
        else if (!checkIfColumnisEmpty(r.ItemArray[0]) && !checkIfColumnisEmpty(r.ItemArray[1]))
        {
            //all columns are valid so...
            Column0inSpreadsheet = r.ItemArray[0] as string;
            Column1inSpreadsheet = r.ItemArray[1] as string;

            //Other code which performs other operations, once the level as reached this far
        }
    }

    //if column 0 and 1 are NOT empty && Either column 2,3,4 or 5 is empty
    else if (checkIfColumnisEmpty(r.ItemArray[0]) && checkIfColumnisEmpty(r.ItemArray[1])
    || !checkIfColumnisEmpty(r.ItemArray[2]) || !checkIfColumnisEmpty(r.ItemArray[3])
    || !checkIfColumnisEmpty(r.ItemArray[4]) || !checkIfColumnisEmpty(r.ItemArray[5]))
    {
        if (checkIfColumnisEmpty(r.ItemArray[2]))
        {
            throw new ImportBOQException("Error importing document: Third column is empty");
        }
        else if (checkIfColumnisEmpty(r.ItemArray[3]))
        {
            throw new ImportBOQException("Error importing document: Fourth column is empty");
        }
        else if (checkIfColumnisEmpty(r.ItemArray[4]))
        {
            throw new ImportBOQException("Error importing document: Fifth column is empty");
        }
        else if (checkIfColumnisEmpty(r.ItemArray[5]))
        {
            throw new ImportBOQException("Error importing document: Sixth column is empty");
        }
        else
    //all columns are valid so...
        {
            Column2inSpreadsheet = (r.ItemArray[2]) as string;
            Column3inSpreadsheet = (r.ItemArray[3]) as string;
            Column4inSpreadsheet = (r.ItemArray[4]) as string;
            Column5inSpreadsheet = (r.ItemArray[5]) as string;

    //Other code which performs other operations, once the level as reached this far
        }
    }
    else
    //other errors ot related to empty colums
    {
        throw new Exception("Error Uploading");
    }
}


texts:
This craps game simulator is based on someone else's posted Python code that I've redone for practice. I'm interested in improving readability and making it more pythonic. I used unittest instead of nose because I'm using an online IDE.

from random import randrange
import unittest

class CrapsGame:
    def __init__(self):
        self.outcomes = {'2':False,'3':False,'12':False,'7':True,'11':True,
                '4&4':True,'5&5':True,'6&6':True,
                '8&8':True,'9&9':True,'10&10':True,
                '4&7':False,'5&7':False,'6&7':False,
                '8&7':False,'9&7':False,'10&7':False}

    def play(self, roll_dice):
        comeOut = str(roll_dice())
        print 'began game with ' + comeOut
        if comeOut in self.outcomes:
            return self.outcomes[comeOut]
        while True:
            point = str(roll_dice())
            print 'next roll is ' + point
            state = comeOut+'&'+point
            if state in self.outcomes:
                return self.outcomes[state]

class CrapsTest(unittest.TestCase):
    def testWinComeOut(self):
        game = CrapsGame()
        self.assertEquals(game.play(lambda: 7), True)

    def testLoseComeOut(self):
        game = CrapsGame()
        self.assertEquals(game.play(lambda: 2), False)

    def testWinPoint(self):
        game = CrapsGame()
        rollData = [5,6,5]
        self.assertEquals(game.play(lambda: rollData.pop()), True)

    def testLosePoint(self):
        game = CrapsGame()
        rollData = [7,5]
        self.assertEquals(game.play(lambda: rollData.pop()), False)

if __name__ == '__main__':
    unittest.main()


texts:
I am not much experienced in Python, just write some small script. All my codes are procedural. They work fine, and I always check them with pep8.

One of them is:

#!/usr/bin/python3
import os
import sys
import numpy as np
import scipy as sp
import scipy.optimize
import matplotlib.pyplot as plt

def f(x, a, b, c, d):
    return a + b*x + c*x**2 + d*x**3

data = []
fout = "tmpft"  # sys.argv[1] + "_trial.dat"
with open(fout, "w") as of:
    for subdir, dirs, files in os.walk(sys.argv[1]):
        for inp in files:
            if inp.endswith("SCF.out"):
                fsys = subdir + "/" + inp
                # print(fsys)
                with open(fsys) as finp:
                    for line in finp:
                        if "lattice constant  ALAT" in line:
                            lata = float(line.strip()[-7:])/1.88973
                        if " ERR " in line:
                            mom = line.strip()[61:70]
                        if "SCF - cycle converged" in line:
                            etot = float(line.lstrip()[10:25])
                            of.write("{:<10f} {:<15f} {:<15f}\n"
                                     .format(lata,  etot, float(mom)))

ffout = sys.argv[1]+".dat"
with open(ffout, "w") as ff:
    ff.write("#lat(A)          ETOT          MOM\n")
    with open(fout, "r") as uns:
        for line in sorted(uns):
            ff.write(line)
values = np.genfromtxt(fout, dtype=None, delimiter='   ', usecols=[0, 1, 2])
os.remove(fout)
etot = values[:, 1]
latp = values[:, 0]

popt, pcov = sp.optimize.curve_fit(f, latp, etot)
res = sp.optimize.minimize(lambda x: f(x, *popt), 2.8)
print('Function is minimized for {0}.'.format(float(res['x'])))
with open(ffout, 'a') as ff:
    ff.write('#Function is minimized for {0}\n'.format(float(res['x'])))

# Plot data
pout = sys.argv[1]+".png"
x = sp.linspace(2.80, 3.05, 100)
y = f(x, *popt)
plt.plot(x, y, lw=3)
plt.xlabel("Lattice Parameter")
plt.ylabel("Energy")
plt.title(sys.argv[1])
plt.scatter(latp, etot, s=60)
plt.scatter(res['x'], f(res['x'], *popt), color='red', s=80)
plt.savefig(pout)
plt.show()

This works fine, i.e. gives me proper/correct result. But I wonder if this is a good way of writing Python. If I take this as my standard example (most of my Python interaction is like this: read a file, fetch some data, post-process it and plot), how I can make it better? By "better", I mean, optimized, reusable and readable.

Like, as I already said, most of my python involves reading a line that matched a string. So, I would like to have it as a function (in C/fortran sense) etc.


texts: Rails form helper to display email fields and their validation errors

texts:
I have a repeated pattern throughout my app that looks like this:

<div class="form-group floating-label <%= f.object.errors[:to].any?? "has-error has-feedback" : "" %>">
  <% if f.object.errors[:to].any? %>
    <%= f.label f.object.errors[:to].join(", ") %>
  <% end %>
  <%= f.email_field :to, class: "form-control" %>
  <%= f.label :to %>
</div>

The only thing that changes is the attribute. Instead of the :to attribute, it might be something else. But everything else will remain the same.

I extracted it out into a helper method:

_form.html.erb

  <%= field_view "To", f.email_field(:to, class: "form-control") %>

form_helper.rb

  def field_view(label, *args, &block)
    # label = label.t internalization

    options = args.extract_options!
    field = args.first
    formatter = args.second

    data = capture(&block) if block_given?

    options[:class] = "form-group floating-label #{options[:class]}".strip

    element = formatter ? send(formatter, field) : field

    make_content label, element, options
  end

  def make_content(label, element, options)
    content_tag :div, options do
      element + content_tag(:label, label)
    end
  end

I do not want my form_helper to know anything about the field. Because sometimes it will be f.text_field :to, text_field_tag :to, f.select, etc. Too much change happening to make the form_helper aware of it.

What approach would you suggest in order to incorporate that error checking functionality which is shown in the first example?


texts: Efficiently consolidating an array of objects

texts:
In my program, I'm getting Facebook objects and using temp to display on a separate screen how many unread messages they have. However, we have since decided to consolidate similar messages, such as getting XP from a Facebook friend more than once. We want those messages to be one message with the sum of the XP gifted from the friend. That part is fine and done. But, this makes temp an inaccurate representation, because the program will show how many Facebook objects there are instead of how many consolidated messages

I have written this code to loop through the objects and get a count of how many there are (if there is an ill-formatted object, we don't want to count it so array.length is out of the question). Then I am looping through the array again TWICE to check items in the array against other items. If they are consolidated, I want the array to behave as if the objects weren't there, because removing items from an array while you're looping through it can cause problems and this seemed the easiest way.

Is there a way to do this more efficiently, perhaps in fewer loops?

var consolidated:Array = [];

for (var i:int = 0; i < requests.length; i++)
            {
                var dataJ:Object = JSON.parse(requests[i].data);

                if (dataJ.title == "ask")
                {
                    //check for duplicates
                    if (dupeCache[requests[i].from.id] == undefined)
                    {
                        dupeCache[requests[i].from.id] = true;
                        temp++;
                        consolidated.push(requests[i]);
                    }
                }
                else if (dataJ.title == "gift")
                {
                    temp++;
                    consolidated.push(requests[i]);
                }

            }
            var popped:int = 0;
            for (var j:int = 0; j < consolidated.length; j++)
            {
                var dataObjectJ:Object = JSON.parse(consolidated[j].data);
                popped= 0;
                for (var k:int = 0; k < consolidated.length; k++)
                {
                    var dataObjectK:Object = JSON.parse(consolidated[j].data);

                    if (consolidated[j] == consolidated[k]) continue;

                    if (consolidated[j].from.id == consolidated[k].from.id)
                        if (dataObjectJ.title == dataObjectK.title)
                            if(dataObjectJ.type == dataObjectK.type)
                            {
                                //we dont want to consolidate hearts
                                if (dataObjectJ.type == "heart") continue;
                                temp--;
                                popped++;
                            }
                }
                j += popped;

            }

            globals.blob.unreadMessageCount = temp;


texts: How to correctly get a IDisposeable when you need to lock the factory?

texts:
If I need to create a IDisposeable object from a factory, but if the factory object is not thread safe and requires me to lock on it is this the correct pattern to use?

public void DisposeExample(FactoryClass factoryClass)
{
    DispObject dispObject = null;

    lock(factoryClass)
    {
        dispObject = factoryClass.GetDispObject();
    }

    using(dispObject)
    {
        dispObject.DoWork();
    }
}


texts:
This gets every form element and calculates its width, then changes the input fields depending on the parent-form width:

$ ->
 # Alter 'input' Width
  inputResize = ->
   $('form').each ->
    tF = $(this)
    formWidth = tF.width()
    tF.find('input').each ->
     tE = $(this)
     inputBorder = (tE.outerWidth() - tE.innerWidth())
     inputPadding = parseInt(tE.css('padding-left')) + parseInt(tE.css('padding-right'))
     tE.css 'width', ->
      (formWidth - inputBorder - inputPadding)
 # on Resize
 $(window).resize ->
  inputResize()
 # on Init
  inputResize()

It works as intended, but to learn a bit more I just want to know if there is a smarter way to write this little code in CoffeeScript.


texts:
Purpose

This question comes from a HackerRank problem called Fibonacci Modified. I think I have coded a valid solution, but would like feedback about my approach, implementation, and of course, any errors / edge cases that I may have missed.

Task

Implementation

public class FibonacciModifiedImpl implements FibonacciModified {

    @Override
    public BigInteger calculateNextTerm(final BigInteger currentTerm, final BigInteger lastTerm) {
        if (-1 == lastTerm.compareTo(BigInteger.ZERO) ) {
            throw new IllegalArgumentException("last term must be non-negative");
        }

        if (-1 == currentTerm.compareTo(lastTerm)) {
            throw new IllegalArgumentException("current term must be greater than or equal to last term");
        }

        final BigInteger squaredTerm = new BigDecimal(Math.pow(currentTerm.doubleValue(), 2)).toBigInteger();
        return squaredTerm.add(lastTerm);
    }

    @Override
    public BigInteger calculateNthTerm(final BigInteger firstTerm, final BigInteger secondTerm, final int n) {
        if (-1 == firstTerm.compareTo(BigInteger.ZERO) ) {
            throw new IllegalArgumentException("first term must be non-negative");
        }

        if (-1 == secondTerm.compareTo(firstTerm)) {
            throw new IllegalArgumentException("second term must be greater than or equal to last term");
        }

        if (n < 1) {
            throw new IllegalArgumentException("number of terms must be greater than 0");
        }

        switch (n) {
            case 1: {
                return firstTerm;
            }

            case 2: {
                return secondTerm;
            }

            default: {
                int counter = 2;
                BigInteger currentTerm = secondTerm;
                BigInteger lastTerm = firstTerm;
                while (counter < n) {
                    BigInteger nextTerm = calculateNextTerm(currentTerm, lastTerm);
                    lastTerm = currentTerm;
                    currentTerm = nextTerm;
                    counter++;
                }

                return currentTerm;
            }
        }
    }
}


texts: OnKeyPress event do same stuff on multiple inputs

texts:
I have 3 inputs, when I press enter on them same operations happend.

This is my code

How would you do this better?

    var __this = this;
    var a = document.getElementById("content").getElementsByTagName("more-content")[0].getElementsByTagName("input")[0];
    var b = document.getElementById("content").getElementsByTagName("more-content")[1].getElementsByTagName("input")[0];
    var b = document.getElementById("content").getElementsByTagName("more-content")[2].getElementsByTagName("input")[0];

    a.onkeypress = function (e) {
        if (e.which == 13) {
            // do same stuff here
        }
    };
    b.onkeypress = function (e) {
        if (e.which == 13) {
            // do same stuff here
        }
    };
    b.onkeypress = function (e) {
        if (e.which == 13) {
            // do same stuff here
        }
    };


texts: Combining the text from selected TextFields into 1 TextView - Conditionally

texts:
ViewController2 (source) Has several TextFields, each with their own switches.

ViewController1 (destination) Has one TextView waiting for data to be sent to it from ViewController2 (source) But i need only the text from the TextFields that have their "switches" turned on.

I can get it working individually with TextField1 when Switch1 is turned on, but I don't know how to combine the text from several ones once turned on.

Example: If Switches for both TextField1 and TextField2 are turned on, then it should put the text form both of them into the single TextView on ViewController1

Question How do I combine the text from several ones once turned on ? At time there could be only 1 switch turned on, or at times many switches turned on.

My code that i am using so far

ViewController2 (Source)

 let defaults = UserDefaults.standard
    var switchON : Bool = false
    @IBAction func checkState(_ sender: AnyObject) {

        if Switch1.isOn{
            switchON = true
            defaults.set(switchON, forKey: "switch1ON")
        }
        if Switch1.isOn == false{
            switchON = false
            defaults.set(switchON, forKey: "switch1ON")
        }
        if Switch2.isOn{
            switchON = true
            defaults.set(switchON, forKey: "switch2ON")
        }
        if Switch2.isOn == false{
            switchON = false
            defaults.set(switchON, forKey: "switch2ON")

ViewController1(Destination)

override func viewDidLoad(){
        super.viewDidLoad()
        // Do any additional setup after loading the view.

  // Select Comments -----------------------------------
        if defaults.value(forKey: "switch1ON") != nil{
            let switch1ON: Bool = defaults.value(forKey: "switch1ON")  as! Bool
            if switch1ON == true{
                let userDefaults = UserDefaults.standard
                Reference.text = userDefaults.value(forKey: "PredefinedText1") as? String
            }

        if defaults.value(forKey: "switch2ON") != nil{
            let switch2ON: Bool = defaults.value(forKey: "switch2ON")  as! Bool
            if switch2ON == true{
                let userDefaults = UserDefaults.standard
                Reference.text = userDefaults.value(forKey: "PredefinedText2") as? String
            }
           // else if switch1ON == false{
            //    let userDefaults = UserDefaults.standard
            //    Reference.text = userDefaults.value(forKey: "") as? String
            //}
        }
        }


texts:
This is the complete rewrite of a function to decode an UTF-8 codepoints and return the encoding length (or 0 if the codepoint is \0). In response to the review of my previous version I decided that I needed a different approach and I should recognize ALL the invalid encodings (as per reviewer suggestion). If an invalid encoding is found, the first byte is returned with length 1.

I found a very good article about decoding UTF-8 by Bjoern Hoehrmann and followed the same approach which is based on the following Finite Automaton:

I directly coded it in C:

#define fsm
#define fsmGOTO(x)    goto fsm_state_##x
#define fsmSTATE(x)   fsm_state_##x :
#define fsmSTART

int utf8_cp(char * restrict txt, int32_t * restrict ch)
{
  int len;
  uint8_t *s = (uint8_t *)txt;
  uint8_t first = *s;

  fsm {
    fsmSTART {
      if (*s == 0x00) { *ch = *s;        len = 0; fsmGOTO(end); }
      if (*s <= 0xC1) { *ch = *s;        len = 1; fsmGOTO(end); }
      if (*s <= 0xDF) { *ch = *s & 0x1F; len = 2; fsmGOTO(2);   }
      if (*s == 0xE0) { *ch = *s & 0x0F; len = 3; fsmGOTO(4);   }
      if (*s <= 0xEC) { *ch = *s & 0x0F; len = 3; fsmGOTO(3);   }
      if (*s == 0xED) { *ch = *s & 0x0F; len = 3; fsmGOTO(5);   }
      if (*s <= 0xEF) { *ch = *s & 0x0F; len = 3; fsmGOTO(3);   }
      if (*s == 0xF0) { *ch = *s & 0x07; len = 4; fsmGOTO(6);   }
      if (*s <= 0xF3) { *ch = *s & 0x07; len = 4; fsmGOTO(7);   }
      if (*s == 0xF4) { *ch = *s & 0x07; len = 4; fsmGOTO(8);   }
      fsmGOTO(invalid);
    }

    fsmSTATE(8) {
      s++; if ( *s < 0x80 || 0x8f < *s) fsmGOTO(invalid);
      *ch = (*ch << 6) | (*s & 0x3F);
      fsmGOTO(3);
    }

    fsmSTATE(7) {
      s++; if ( *s < 0x80 || 0xbf < *s) fsmGOTO(invalid);
      *ch = (*ch << 6) | (*s & 0x3F);
      fsmGOTO(3);
    }

    fsmSTATE(6) {
      s++; if ( *s < 0x90 || 0xbf < *s) fsmGOTO(invalid);
      *ch = (*ch << 6) | (*s & 0x3F);
      fsmGOTO(3);
    }

    fsmSTATE(5) {
      s++; if ( *s < 0x80 || 0x9f < *s) fsmGOTO(invalid);
      *ch = (*ch << 6) | (*s & 0x3F);
      fsmGOTO(2);
    }

    fsmSTATE(4) {
      s++; if ( *s < 0xA0 || 0xbf < *s) fsmGOTO(invalid);
      *ch = (*ch << 6) | (*s & 0x3F);
      fsmGOTO(2);
    }

    fsmSTATE(3) {
      s++; if ( *s < 0x80 || 0xbf < *s) fsmGOTO(invalid);
      *ch = (*ch << 6) | (*s & 0x3F);
      fsmGOTO(2);
    }

    fsmSTATE(2) {
      s++; if ( *s < 0x80 || 0xbf < *s) fsmGOTO(invalid);
      *ch = (*ch << 6) | (*s & 0x3F);
      fsmGOTO(end);
    }

    fsmSTATE(invalid) {*ch = first; len = 1;}

    fsmSTATE(end)   { }
  }
  return len;
}

The code above, not only handles the invalid encondings, it's also much faster (33%) than my previous version!

I also compared my code with one directly based on the original version by Bjoern Hoehrmann (using a table to represent the FSM) and I found them being equally fast but mine being much clearer in terms of understanding how it works.

Any comment, feedback or suggestion is greatly appreciated.


texts: Return Full Month Name From 3 Letter Month

texts:
I have piece metaled this code together from multiple google searches and thanks to the function from the site mentioned in the code.  I am sure there are ways to optimize this for speed.  What do you guys suggest?

using System;
using System.Globalization;

public class Program
{
    public static void Main()
    {
        string shortmonth = "Mar";
        string num = GetMonthNumberFromAbbreviation(shortmonth);
        string monthname = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(Convert.ToInt32(num));
        Console.WriteLine(monthname);
    }
    //https://blogs.msmvps.com/deborahk/converting-month-abbreviations-to-month-numbers/
    private static string GetMonthNumberFromAbbreviation(string mmm)
    {
       string[] monthAbbrev =
          CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedMonthNames;
       int index  = Array.IndexOf(monthAbbrev, mmm) + 1;
       return index.ToString("0#");
    }
}


texts:
I'm working on a primality test and have written a recursive function that returns the value of the function

  \$b^{q-1} \bmod q\$

  where \$3<= q <= 32000\$

Is there any way to speed up my function? It works, but takes a while to return the answer as \$q\$ approaches 32000.

Variables:

  pow = \$q-1\$

  mod = \$q\$

  b is a variable ranging from \$1 < b < q \$

If q is prime, then b will be = to q if not, b will be a "strong" feature of non-primality. See Miller–Rabin primality test.

public int fF(int q)
    {
        int b = 2, v = 0;
        while(b < q)
        {
            v = operate(b, q-1, q);
            if (v != 1)
                break;
            b++;
        }
        return b;
    }

 int operate(int b, int pow, int mod)
    {
        if (pow == 2)
           return (b * b) % mod;
        return (pow % 2 != 0) ? (b * operate(b, pow - 1, mod)) % mod : (operate(b, pow / 2, mod) * operate(b, pow / 2, mod)) % mod;
    }


texts:
I decided to solve a problem from Code Golf called the four fours.
Problem description:

The Four fours puzzle is a popular recreational mathematical puzzle
that involves using exactly four 4s (and no other number) and a
defined set of operations to reach every number from 0 to a given
maximum.
In this version, the only following operators are allowed:

Any grouping symbols may be used
Addition (+), Subtraction (-), Multiplication (*), Division (/)
Factorial (!), Gamma function (Γ)
Exponentiation (^), Square root (√)
*Concatenation (eg. 44 is two 4s)
Decimal point (eg. 4.4 is two 4s), Overbar (eg. .4~ = 4/9)

Some assumption/changes I made:

I assumed that squaring a number is ok (using 4**2 or 16)
I assumed that decimal values, in the cases where they occur can be truncated (4.9 = 4)

Description of the algorithm
First I create a list of all the possible start values, that is:

The number itself
The number squared
The sqrt of the number
The factorial of the number
The gamma function of the number (factorial(number -1))

Then I iterate throu them with the random_reduce function that 'reduces' the list by applying each time a random function.
The function takes about 2 secons for all numbers upto a 100, finding a way to create all the numbers along the way.
I am looking for code-style advice and maybe a better algorithm suggestion.
from __future__ import division

import random
import operator as op
import math

def get_starts(lst,n):
    sqrt,power,fact,gamma = int(n**0.5),n**2,math.factorial(n),math.factorial(n-1)
    return ( [a,b,c,d] for a in (sqrt,n,power,fact,gamma) \
             for b in (sqrt,n,power,fact,gamma) for c in (sqrt,n,power,fact,gamma) \
             for d in (sqrt,n,power,fact,gamma))

def random_reduce(lst,functions):
    functions_used = []
    result = lst[0]
    for i in lst[1:]:
        fun = random.choice(functions)
        functions_used.append(fun)
        result = fun(result,i)
    return result,[i.__name__ for i in functions_used]

def how_to_obtain(n,lst,functions):
    for i in range(500):
        for l in get_starts(lst,4):
            result = random_reduce(l,functions)
            if n == result[0]:
                return n,[l,result[1]]

def concat(a,b):
    return int(str(a) + str(b))

def div(a,b):
    return a // b

def solve_44(max_):
    numbers_solutions = {}
    for i in range(max_):
        numbers_solutions[i] = how_to_obtain(i,[4,4,4,4],[concat, op.add, op.mul, op.sub,
                                         div, op.pow, op.mod])

    return numbers_solutions

def ratio_of_Nones_in_dictionary(dict_):
    return (len({i:dict_[i] for i in dict_ if dict_[i] == None}) / len(dict_))

def main(max_):
    solution = solve_44(max_)
    for i in solution:
        print(solution[i])
    print("The random search failed to find a solution {}% of the times.".format(
        ratio_of_Nones_in_dictionary(solution)*100))

if __name__ == "__main__":
    main(100)


texts: Find minimum singular value in a sorted array

texts:
A sorted array is passed to my method and i have to find the minimum singular value. If no such value is found the method returns 0.
I have created two versions of this method. In the first version, I iterate trough the array twice which works fine but there has to be a way to find the value with one iteration.
In the second version, I iterate through it once but i need it fixed so, that it works if the last index of the array is my minimum singular value e.g {1, 1, 2, 2, 3}.

//First version with two iterations
public int findMinimumSingularValue(int[] array) {

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

I've tried to implement it with only one iteration, but couldn't get it to work. Only the first version is up for review, but I'll leave my attempt at improvement here to illustrate what I have in mind:

//Second version with one iteration which needs to be fixed
public int findMinimumSingularValue(int[] array) {
    if(array.length == 0) {
        return 0;
    }
    int isNotUnique = array[array.length - 1];
    for (int i = 0; i < array.length; i++) {
        if (array[i] != array[i + 1] && array[i] != isNotUnique) {
            return array[i];
        }
        isNotUnique = array[i];
    }
    return 0;
}


texts:
I have over 2500 files in a directory tree- some of them are numbered, some of them aren't. eg.

1. That night it rained.epub
The sparrow returns at dawn.epub
001.  Tomorrow is a new day.epub
000.1. We are the children.epub

I created my C# code to iterate through all the directories and rename the numbered files to look neater, but at the same time should leave the unnumbered file unaltered like so:

001.    That night it rained.epub
The sparrow returns at dawn.epub
001.    Tomorrow is a new day.epub
000.1.  We are the children.epub

My coding looks like this:

class Program
{

static string path = @"C:\Users\Anja\Desktop\reekse";

static string name;
static string rpath;
static int numberperiod;
static string number;
static string newname;
static string movepath;

static void Main(string[] args)
    {

    foreach (var file in Directory.GetFiles(path, "*.epub", SearchOption.AllDirectories)) //searches for all the epub files even if there are 20 subdirectories between the file and the main directory
        {

        name = System.IO.Path.GetFileName(file);//gets the filename sans the path
        rpath = System.IO.Path.GetDirectoryName(file);//gets the path sans the  file

        numberperiod = name.IndexOf(".");//find the location of the 1st . (remember-zerobasing is used)

        if (numberperiod == 1)//first period - meaning no 0's is used in numbering
            {
            number = name.Substring(0, numberperiod + 1);//pick up the number as well as the . that follows the numbering

            name = name.TrimStart(number.ToCharArray());//convert the number to char and trim it
            name = name.TrimStart('.', ' ', ' ');// remove any potential blankspaces and . that may be at the start of the filename

            newname = "00" + number + "    " + name; // create a name that has the 0's, the number, adequite spacing, and the name
            }

        if (numberperiod == 2)//same as above but the numbering contains  two digits
            {
            number = name.Substring(0, numberperiod + 1);

            name = name.TrimStart(number.ToCharArray());
            name = name.TrimStart('.', ' ', ' ');

            newname = "0" + number + "    " + name;

            }

        if (numberperiod == 3)//files containing 3 digits
           {
            number = name.Substring(0, numberperiod + 1);

            if (number == "000.")// in case the file has odd numbering as  in the example
                {
                number = name.Substring(0, numberperiod + 3);

                name = name.TrimStart(number.ToCharArray());
                name = name.TrimStart('.', ' ', ' ');

                newname = number + "  " + name;
                }
            else
                {
                name = name.TrimStart(number.ToCharArray());
                name = name.TrimStart('.', ' ', ' ');

                newname = number + "    " + name;
                }

            }

        Console.WriteLine(newname.ToString());

        movepath = Path.Combine(rpath, newname);
        File.Move(file, movepath);
        }
   }
}

The coding works perfectly fine, but it just seems so tedious; I'm positive that there must be a simpler way of doing this like regex or Linq.

Can someone please help? I'm not any good when it comes to either Linq or regex. Can someone please help me rewrite this code to make it simpler?