texts: Closest element in std map when discarding values

texts:
I have the following situation: I have two std::map<int,float> and I want to go through the first map one by one and find the element in the second map with the key closest to the key in the first map. Now, this plain situation is obviously addressed in other question like e.g. this one, but here is where my situation deviates:
There might be elements in the second map that I do not want to consider because the value is below some criterion and thus even if the element is the closest, it will be discarded and now I have to check two other elements against the key. Below is a bit of dummy code that illustrates the input data and also a bit of code that seems to achieve what I want, but I am not sure if there is maybe a better/cleaner way of doing this.

#include <iostream>
#include <map>
#include <cmath>

void setClosest( std::map<int,float>::iterator & it, std::map<int,float>::iterator &upper, std::map<int,float>::iterator &lower, int key ) {
  it = fabs( upper->first - key ) < fabs( lower->first - key ) ? upper : lower;
}

int main(int, char**)
{
  std::map<int, float> map1;
  std::map<int, float> map2;

  map1[5000]  = 5.5;
  map1[10000] = 5.2;
  map1[12000] = 5.7;
  map1[15000] = 5.3;
  map1[20000] = 5.5;
  map1[25000] = 5.9;

  map2[10400] = 523.0;
  map2[12500] = 99.0;
  map2[15200] = 67.0;
  map2[15400] = 76.0;
  map2[20200] = 511.0;
  map2[25800] = 567.0;

  std::map<int,float>::iterator it = map1.begin();
  std::map<int,float>::iterator lower;
  std::map<int,float>::iterator upper;
  std::map<int,float>::iterator closest;

  for( ; it != map1.end(); ++it ) {
    int key     = it->first;
    float value = it->second;

    lower = map2.lower_bound(key);
    upper = ( lower == map2.begin() ? lower : lower-- );

    setClosest( closest, upper, lower, key);

    std::cout << key << ' ' << upper->first << ' ' << lower->first << " -> " << closest->first << std::endl;

    while( closest->second < 100 ) {
      std::cout << "skipping too low value " << closest->first << ' ' << closest->second << std::endl;
      closest == upper ? upper++ : lower--;
      setClosest( closest, upper, lower, key);
    }

    std::cout << key << ' ' << upper->first << ' ' << lower->first << " -> " << closest->first << std::endl;

  }

  return 0;
}

Output

5000 10400 10400 -> 10400
5000 10400 10400 -> 10400
10000 10400 10400 -> 10400
10000 10400 10400 -> 10400
12000 12500 10400 -> 12500
skipping too low value 12500 99
12000 15200 10400 -> 10400
15000 15200 12500 -> 15200
skipping too low value 15200 67
skipping too low value 15400 76
skipping too low value 12500 99
15000 20200 10400 -> 10400
20000 20200 15400 -> 20200
20000 20200 15400 -> 20200
25000 25800 20200 -> 25800
25000 25800 20200 -> 25800


texts: K-nearest neighbours in C# for large number of dimensions

texts:
I'm implementing the K-nearest neighbours classification algorithm in C# for a training and testing set of about 20,000 samples and 25 dimensions.

There are only two classes, represented by '0' and '1' in my implementation. For now, I have the following simple implementation:

// testSamples and trainSamples consists of about 20k vectors each with 25 dimensions
// trainClasses contains 0 or 1 signifying the corresponding class for each sample in trainSamples
static int[] TestKnnCase(IList<double[]> trainSamples, IList<double[]> testSamples, IList<int[]> trainClasses, int K)
{
    Console.WriteLine("Performing KNN with K = "+K);

    var testResults = new int[testSamples.Count()];

    var testNumber = testSamples.Count();
    var trainNumber = trainSamples.Count();
    // Declaring these here so that I don't have to 'new' them over and over again in the main loop,
    // just to save some overhead
    var distances = new double[trainNumber][];
    for (var i = 0; i < trainNumber; i++)
    {
       distances[i] = new double[2]; // Will store both distance and index in here
    }

    // Performing KNN ...
    for (var tst = 0; tst < testNumber; tst++)
    {
        // For every test sample, calculate distance from every training sample
        Parallel.For(0, trainNumber, trn =>
        {
            var dist = GetDistance(testSamples[tst], trainSamples[trn]);
            // Storing distance as well as index
            distances[trn][0] = dist;
            distances[trn][1] = trn;
        });

        // Sort distances and take top K (?What happens in case of multiple points at the same distance?)
        var votingDistances = distances.AsParallel().OrderBy(t => t[0]).Take(K);

        // Do a 'majority vote' to classify test sample
        var yea = 0.0;
        var nay = 0.0;

        foreach (var voter in votingDistances)
        {
            if (trainClasses[(int)voter[1]] == 1)
               yea++;
            else
               nay++;
        }
        if (yea > nay)
            testResults[tst] = 1;
        else
            testResults[tst] = 0;

    }

    return testResults;
}

// Calculates and returns square of Euclidean distance between two vectors
static double GetDistance(IList<double> sample1, IList<double> sample2)
{
    var distance = 0.0;
    // assume sample1 and sample2 are valid i.e. same length

    for (var i = 0; i < sample1.Count; i++)
    {
        var temp = sample1[i] - sample2[i];
        distance += temp * temp;
    }
    return distance;
}

This takes quite a bit of time to execute. On my system it takes about 80 seconds to complete. How can I optimize this, while ensuring that it would also scale to larger number of data samples? As you can see, I've tried using PLINQ and parallel for loops, which did help (without these, it was taking about 120 seconds). What else can I do?

I've read about KD-trees being efficient for KNN in general, but every source I read stated that they're not efficient for higher dimensions.

I also found this Stack Overflow discussion about this, but it seems like this is 3 years old, and I was hoping that someone would know about better solutions to this problem by now.

I've looked at machine learning libraries in C#, but for various reasons I don't want to call R or C code from my C# program, and some other libraries I saw were no more efficient than the code I've written. Now I'm just trying to figure out how I could write the most optimized code for this myself.

I cannot reduce the number of dimensions using PCA or something. For this particular model, 25 dimensions are required.

Also, I did track the execution time using a profiler, and it seems that more than 60% of the runtime is spent in the GetDistance() function, which is why I was wondering whether there exists a different algorithm using a different data structure that does this more optimally.


texts: Creating a Python namedtuple class that forces some of its fields to be floats

texts:
I've got a use case for namedtuple that requires some of the fields to be floats. I could require the code that's constructing the namedtuple to supply floats, but I'd like for the namedtuple class to be smart enough to convert strings it gets into floats for me (but only for a specified subset of fields). I have code to do this, but it's ugly:

from collections import namedtuple, OrderedDict

# This list is built at runtime in my application
_FIELDS_AND_TYPES = [("num1", True), ("num2", True), ("label", False)]
FIELDS_FORCE_FLOAT = OrderedDict(_FIELDS_AND_TYPES)

_MyNamedTuple = namedtuple("_MyNamedTuple", FIELDS_FORCE_FLOAT.keys())
class TypedNamedTuple(_MyNamedTuple):
    fields_force_float = FIELDS_FORCE_FLOAT
    def __new__(cls, *values_in):
        super_obj = super(_MyNamedTuple, cls)
        superclass = super_obj.__thisclass__
        values = [float(value) if cls.fields_force_float[fieldname] else value
                    for fieldname, value in zip(superclass._fields, values_in)]
        self = super_obj.__new__(cls, values)
        return self

print TypedNamedTuple("1.0", "2.0", "3.0")
# _MyNamedTuple(num1=1.0, num2=2.0, label='3.0')

Things I don't like about this code:

The output of print TypedNamedTuple("1.0", "2.0", "3.0") starts with _MyNamedTuple rather than TypedNamedTuple. I think this is a general problem with subclassing namedtuples, so fair enough. I could give both classes the same name to solve this.
My code has to pull in FIELDS_FORCE_FLOAT from a global variable.
TypedNamedTuple is inefficient (it runs zip and does a bunch of dictionary lookups). This is not so bad in my context but I'd like to know how to handle this "right."
If I wanted to create another namedtuple subclass that forces some of its args to be float, I'd basically be starting from scratch. My TypedNamedTuple is not reusable.

Is there a cleaner way to do this?

As for why I'm attempting to use namedtuples here at all (H/T @jonrsharpe), it's not set in stone but here are some things that pushed me in this direction:

The list of fields I'm interested in isn't known until runtime.
Immutability: I do not, in fact, have a reason to change any of these objects once they're constructed.


texts:
I stopped using Lodash to become better at JavaScript. These are recursive utility functions to deal with nested arrays:

const _ = {}

// find object in nested arrays
_.findDeep = (arr, obj) => {
  return arr.map(item => {
    const key = _.keys(obj)[0]
    if (item[key] === obj[key]) return arr
    if (item.children) return _.findDeep(item.children, obj)
    return undefined
  }).reduce((prev, curr) => {
    return prev || curr
  })
}

// insert new object above an object in nested array
_.insertUpDeep = (arr, obj, newObj) => {
  let found = _.findDeep(arr, obj)
  if (found) found.splice(found.indexOf(obj), 0, newObj)
  return arr
}

// TODO rename this into something less suggestive
_.insertDownDeep = (arr, obj, newObj) => {
  let found = _.findDeep(arr, obj)
  if (found) found.splice(found.indexOf(obj) + 1, 0, newObj)
  return arr
}

// same as the two above, but create a container for the
// two objects so they can have their own flow. e.g.
// flex-direction: row/column
_.insertLeftDeep = (arr, bj, newObj, contObj) => {
  let found = _.findDeep(arr, obj)
  if (found) {
    contObj.children.push(obj)
    contObj.children.push(newObj)
    found.splice(found.indexOf(obj), 0, contObj)
    found.splice(found.indexOf(obj), 1) // to avoid duplicating obj
  }
  return arr
}

export default _

Example input:

const colors = {
   name: 'orange'
   children: [{
     name: 'white'
   }, {
     name: 'green',
     children: [{
       name: 'yellow',
       children: [{
         name: 'red'
       }, {
         name: 'white'
       }]
     }, {
       name: 'green',
       children: [{
         name: 'purple',
         color: 'purple',
         path: 'writer'
       }]
     }]
   }, {
     name: 'gray'
   }]
 }

 const color = {
   name: 'brown'
 }

 const newColor = {
   name: 'white'
 }

 const container = {
   name: 'container'
   children: [
     color
   ]
 }

 insertUpDeep(colors, color, newColor)
 insertLeftDeep(colors, color, newColor, container)

I would like to know how to 1) make it simpler/easier to read 2) make it flexible as modularized as Lodash functions.

(I'm specially concerned about the number of parameters that insertLeftDeep has. It's easy to forget which arguments it's supposed to have.)


texts: Leap year check in Java (functional style)

texts:
I have done the leap year check on https://exercism.io already in a lot of languages. Today I came back to the exercise in Java and was playing around with some maybe more funny ways to do the check. The following more functional one kept me thinking of:

import java.util.stream.IntStream;

class Leap {

    boolean isLeapYear(final int year) {
        return IntStream.of(4, 100, 400)
            .filter(divisor -> year % divisor == 0)
            .count() % 2 == 1;
    }

}

What do you think? Is this readable? At least it seems to be extensible in case more rules will ever get added ;)

Another funny fact: due to prime factorization we actually could also use the IntStream.of(2, 25, 16) (but for sure that doesn't help in readability).


texts: Play With Numbers Programming Challenge (mean value of subarrays)

texts:
I'm trying to solve this  Play With Numbers. I have passed the test cases but, I kept getting time limit exceeded.
Can someone help me improve its performance in order to pass the time limit, please?
Problem

You are given an array of n numbers and q queries. For each query you have to print the floor of the expected value(mean) of the subarray from L to R.

Input

First line contains two integers N and Q denoting number of array elements and number of queries.
Next line contains N space seperated integers denoting array elements.
Next Q lines contain two integers L and R(indices of the array).

Output

print a single integer denoting the answer.

Time Limit:
1.5 sec(s) for each input file.
Result Time:
Input 1: 1.999309
Input 2: 1.998019
#include <iostream>
#include <vector>
#include <math.h>

using namespace std;

int main() {

ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);

int n = 0, q = 0;
cin >> n >> q;

vector<int> nums(n);

for (size_t i = 0; i < n; i++)
{
    cin >> nums[i];
}

for (size_t i = 0; i < q; i++)
{
    float ans = 0.0f;
    int leftIndex = 0, rightIndex = 0;

    cin >> leftIndex >> rightIndex;

    leftIndex = leftIndex - 1;
    rightIndex = rightIndex - 1;

    for (size_t i = leftIndex; i <= rightIndex; i++)
    {
        ans = ans + nums[i];
    }

    ans = ans / (rightIndex - leftIndex) + 1;
    cout << floor(ans) << "\n";
    }
    system("pause");
 }


texts: Refactor Ruby code from Hacker News API. Trouble parsing the JSON data

texts:
I made a command line Hacker News reader in Ruby that pulls the latest 10 stories from HN and allows the user to cycle through them or open them with Launchy. This was to play around with Ruby and APIs.

The data that I pulled from HN was messy, like an array of hashes with arrays and hashes inside. I feel like my code is messy, and I am unsure of how it can be made cleaner.

Any advice? I'm still a begninner.

news.rb --

class News
  def initialize title, url, author
    @title = title
    @url = url
    @author = author
  end

  # Format display of each story.
  def to_s
    "\n\tTitle:  #{@title}\n
    \tAuthor: #{@author}\n
    \tUrl: #{@url}\n\n"
  end

  # Insert current object's url into a variable accessible by Launchy
  def get_url
    @url
  end

end

# Show the news story, and ask if user wants open link or move on.
def show_story
    puts @stories[@counter]
    @link = @stories[@counter].get_url
    puts "To view this story in your browser, type OPEN\n
    To see the next story, type NEXT"
    @start = gets.chomp.downcase
    shuffle
  end

# Determine if user wants to open link or move on.
def shuffle
  if @start == "open"
    Launchy.open(@link)
    next_story
  elsif @start == "next"
    @counter += 1
    show_story
  else
    puts "Sorry, you didn't type a correct command.\n
    To view this story in your browser, type OPEN\n
    To see the next story, type NEXT"
    @start = gets.chomp.downcase
    shuffle
  end
end

# After opening link, ask if user still wants to see next story
def next_story
  puts "Would you still like to see the next story? Type NEXT"
  @start = gets.chomp.downcase
  shuffle
end

runner.rb --

require 'json'
require 'rest-client'
require 'launchy'
require_relative 'news.rb'

# Pull the latest/top 10 stories from Hacker News
data = RestClient.get('http://api.thriftdb.com/api.hnsearch.com/items/_search?limit=10&sortby=product(points,pow(2,div(div(ms(create_ts,NOW),3600000),72)))%20desc&pretty_print=true')

# Parse using JSON
parsed = JSON.parse data

# Take out the everything not under "Results" key
results = parsed.reject { |key, value| key != "results"}

# Create array and slap the value of "Results" into it
pull_items = []
pull_items = results["results"].each do |items|
  pull_items << items
end

# Create an array and make each "Item" into its own item
pull_info = []
pull_items.each do |x|
  pull_info << x["item"]
end

# Create a new object for each news story
@stories = pull_info.map do |s|
  News.new s["title"], s["url"], s["username"]
end

# Logo and Welcome Message
puts <<STRING
  _   _            _               _   _
 | | | |          | |             | \\ | |
 | |_| | __ _  ___| | _____ _ __  |  \\| | _____      _____
 |  _  |/ _` |/ __| |/ / _ | '__| | . ` |/ _ \\ \\ /\\ / / __|
 | | | | (_| | (__|   |  __| |    | |\\  |  __/\\ V  V /\\__ \
 \\_| |_/\\__,_|\\___|_|\\_\\___|_|    \\_| \\_/\\___| \\_/\\_/ |___/
        Welcome to Hacker News... from the Command Line!
STRING

# View the first story
puts "\nTo see the latest post, press any key"
start = gets
@counter = 0
show_story


texts:
I'm working my way through an intermediate Python course on Pluralsight that focuses on unit testing and just finished my first assignment.

Basically the course itself focuses on teaching you how to write correct test-cases and gives you a baseline of the class to start solving the tests by yourself.

To clarify:

I'm more concerned on the implemented solutions to the test-cases than on the test-cases themselves. Sorry for any confusion!

I was hoping that I could get some feedback on my implemented solutions to the test-cases (they all are passing):

import unittest

from phonebook import Phonebook

class PhoneBookTest(unittest.TestCase):

    def setUp(self):
        self.phonebook = Phonebook()

    def test_phonebook_with_normal_entries_is_consitent(self):
        self.phonebook.add("Bob", "12345")
        self.phonebook.add("Mary", "012345")
        self.assertTrue(self.phonebook.is_consistent())

    def test_phonebook_with_duplicate_entries_is_inconsitent(self):
        self.phonebook.add("Bob", "12345")
        self.phonebook.add("Sue", "12345")  # identical to Bob
        self.assertFalse(self.phonebook.is_consistent())

    def test_phonebook_with_same_prefix_is_inconsistent(self):
        self.phonebook.add("Bob", "12345")
        self.phonebook.add("Sue", "123")  # prefix of Bob
        self.assertFalse(self.phonebook.is_consistent())

Here is my actual Phonebook class:

class Phonebook:

    def __init__(self):
        self._entries = {}

    def add(self, name, number):
        self._entries[name] = number

    def lookup(self, name):
        return self._entries[name]

    def is_consistent(self):
        if not self._entries:
            return True
        else:
            if self.check_duplicate():
                if self.check_prefix():
                    return True
        return False

    def check_duplicate(self):
        seen = set()
        for x in self.get_values():
            if x not in seen:
                seen.add(x)
            else:
                return False
        return True

    def check_prefix(self):
        prefixes = []
        for contact_number in self.get_values():
            if contact_number not in map(lambda number: number[0:len(contact_number)], prefixes):
                prefixes.append(contact_number)
            else:
                return False
        return True

    def get_values(self):
        return self._entries.values()

I'm mostly concerned of refactoring and the check_function and check_prefix functions performance and overall implementation. However I still consider myself to be a beginner, so all help would be appreciated! :)

Any feedback would be great!


texts:
I have this code which works for uploading multiple files (images). However, it seems inefficient due to having to a function for every single file upload (for 2 uploads, but there will be about 12 in total).

function readURL1(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            jQuery('#div1').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

function readURL2(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            jQuery('#div2').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

Then...

jQuery("#img1").change(function(){
    readURL1(this);
});

jQuery("#img2").change(function(){
    readURL2(this);
});


texts: Help to Refactor PHP Flip Image Code to smallest size as possible

texts:
I have written this PHP function which will flip an image (horizontally, like looking in a mirror). It reads the file, flips it, and writes it to a new filed called filename"_flipped".ext. I would like to refactor this to the smallest possible size, but maintaining human readability.

Here is the function:

function flip_image($filepath)
{
    if(file_exists($filepath)):

        //Array ( [dirname] => images
        //        [basename] => pig.png
        //        [extension] => png
        //        [filename] => pig
        //        [filesize] => 72 )
        $file = $this->get_file_info($filepath); // Returns above array

        // Is it allowed in our extensions array
        if(in_array($file['extension'], $this->allowed_exts)):

            // Reference our Image for the correct extension
            switch ($file['extension']) {
                case 'png':
                    $img = imagecreatefrompng($filepath);
                    break;
                case 'gif':
                    $img = imagecreatefromgif($filepath);
                    break;
                default: // Has to be JPG, or JPEG
                    $img = imagecreatefromjpeg($filepath);
                    break;
            }

            // Now we have our image...
            // Image Width & Height
            $size_x = imagesx($img);
            $size_y = imagesy($img);

            // Create Temp Image
            $temp = imagecreatetruecolor($size_x, $size_y);

            // Define a colour as transparant, allocate the colour, resample it
            imagecolortransparent($temp, imagecolorallocate($temp, 0, 0, 0));
            imagealphablending($temp, false);
            imagesavealpha($temp, true);

            $x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y);
            if ($x) {
                $img = $temp;
            }
            else {
                die('Unable to flip image');
            }

            $writepath = $file['dirname'] . "/" . $file['filename'] . "_flipped" . ".";
            // Write our file
            switch ($file['extension']) {
                case 'png':
                    imagepng($img, $writepath.$file['extension']);
                    break;
                case 'gif':
                    imagegif($img, $writepath.$file['extension']);
                    break;
                default: // Has to be PNG
                    imagejpeg($img, $writepath.$file['extension']);
                    break;
            }
            $flipped_path = $writepath.$file['extension'];
            imagedestroy($img);
            return $flipped_path;
        else:
            echo 'Incorrect File Type, Not an Image, .png .gif, jpeg. jpeg Only.';
            return false;
        endif;
    else:
        echo 'No Such file found, Check the file path';
        return false;
    endif;

}


texts: Efficient implementation of comparison operators for cards in a poker simulation

texts:
Just as a learning exercise, I am implementing a poker game simulator. I am purposefully not searching for ready made tutorials showing how to do this, relying mostly on the python docs - that way I hope to learn in a more memorable, albeit slower, way. I'm looking for advice on how to code the comparison between cards, so that e.g. Five beats Four.
My current implementation works, but I feel it is a little hacky and very inefficient in one particular detail and there must be a better way. In the Card class init, I am setting an attribute order which is just a list of the members of the CardValue enum, in the order they are declared.
While I could just use enum.auto(), or manually set the values as integers and hence simply use those for comparisons (still with eq etc), that would lose me the ability to make use of the enum values to form the human readable card value names.
Is there a better way to go about this than the below code? I feel like the comparison operators should be in the enum itself, but so far have not worked out how to get that to work with my meaningful values for the members of the enum.
from enum import Enum
from functools import total_ordering

class CardValue(Enum):
    TWO = "2"
    THREE = "3"
    ...
    ...
    KING = "King"
    ACE = "Ace"

@total_ordering
class Card:
    def __init__(self, value, suit):
        self.value = value
        self.suit = suit
        self.order = [en for en in CardValue] ### This seems wrong and very inefficient!

    def __eq__(self, other):
        if self.__class__ is other.__class__:
            return self.order.index(self.value) == self.order.index(other.value)

    def __lt__(self, other):
        if self.__class__ is other.__class__:
            return self.order.index(self.value) < self.order.index(other.value)


texts: My self-study inheritance and sub-class exercise

texts:
I'm self-studying Java and have a question about one of the end-of-chapter exercises.  The chapter focus is on inheritance and the book hasn't officially introduced polymorphism so I'm trying to stay within those bounds.

The exercise is:

  Write an inheritance hierarchy for classes Quadrilateral, Trapezoid, Parallelogram, Rectangle and Square.  Use Quadrilateral as the superclass of the hierarchy.  Create and use a Point class to represent the points in each shape.  Make the hierarchy as deep(i.e., as many levels) as possible.  Specify the instance variables and methods for each class.  The private instance variables of Quadrilateral should be the x-y coordinate pairs for the four endpoints of the Quadrilateral.  Write a program that instantiates objects of your classes and outputs each object's area(except Quadrilateral).

My classes are below and they compile and work OK.

Questions:

The exercise statement

  The private instance variables of Quadrilateral should be the x-y coordinate pairs for the four endpoints of the Quadrilateral.

I put the x-y coordinate instance variables in my Point class because it seemed to fit better and if I didn't, what purpose would Point serve other than to hold the four points.  With the way that I did it, it also calculates the distance between the points which seems to fit better to me. Comments?
I thought it would make more sense to use Point class inside Square directly instead of going through Quadrilateral like I did.  I used Quadrilateral because each sub-class will need points.  Taking Point out of Quadrilateral would make it have even less functionality than it does.  Of course it doesn't make sense to add a class just for the sake of adding a class but I'm kind of in that position by trying to meet the exercise objectives.  Comments?
Any other general feedback would be welcome.  Does it look professional?  Even though it's kind of small, would it be accepted in the corporate world?

package exercise9_8;
public class Point {
private int distanceX, distanceY;
private int x0, x1, y0, y1;

public Point( int x0, int x1, int y0, int y1 ){
    this.x0 = x0;
    this.x1 = x1;
    this.y0 = y0;
    this.y1 = y1;
    setDistanceX();
    setDistanceY();
}

private void setDistanceX(){
    distanceX = x1 - x0;
}

public int getDistanceX(){
    return distanceX;
}

private void setDistanceY(){
    distanceY = y1 - y0;
}

public int getDistanceY(){
    return distanceY;
}
}

package exercise9_8;
public class Quadrilateral {
Point point;

public Quadrilateral( int x0, int x1, int y0, int y1 ){
    point = new Point( x0, x1, y0, y1 );
}

protected int getDistanceX(){
    return point.getDistanceX();
}

protected int getDistanceY(){
    return point.getDistanceX();
}
}

package exercise9_8;
public class Square extends Quadrilateral{
private int area;

public Square( int x0, int x1, int y0, int y1 ){
    super( x0, x1, y0, y1 );
    setArea();
}

private void setArea(){
    area = super.getDistanceX() * super.getDistanceY();
}

public int getArea(){
    return area;
}
}

package exercise9_8;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class SquareTestNG {

@Test(enabled = true)
public void testGetNumberOfPoints(){
    Square sq = new Square( 5, 3, 5, 3 );
    assertEquals(sq.getArea(), 4);
}
}


texts:
Like many ASP.NET developers, I use the Newtonsoft library to convert C# objects into JSON. Is this use of Newtonsoft.Json.JsonConvert.SerializeObject secure?

Here is how I use it in a Razor view:

<script type="text/javascript">
    var json = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))
</script>

In Web Forms I might have this in my ASPX:

<script type="text/javascript">
    var json = <%= Newtonsoft.Json.JsonConvert.SerializeObject(Model)) %>
</script>


texts: Pass Async function to new Promise constructor

texts:
I'm having a hard time wrapping my head around whether or not this works or how I can even test it but....

I want to use Async/Await inside a Promise, which means, when I create a new Promise, I have to pass it an async function... something like this:

const getData = function(){
  return new Promise(async function(resolve, reject){
    try {
      const results = await axios.get(some_data);
      resolve(results);
    }
    catch(er) { reject(er); }
  })
}

I've tried to test it myself, but I can't tell if it's working correctly or not. Anyone try this before?


texts: Finding 10-unique-digit number with i-first-digits divisible by i

texts:
I was posed this question by a friend:

  I am a natural number written with 10 different digits such that for all \$i ∈ {1, . . ., 10}\$ the number formed by my \$i\$ first digits (from left to right) is divisible by \$i\$. Who am I?

I came up with a brute-force solution over the next hour or so (a few attempts failed) and came eventually finished with this:

# !/usr/bin/python
# -*- coding: utf-8 -*-

# build all possible permutations
import itertools
base_number = ['1','2','3','4','5','6','7','8','9','0']
perms = itertools.permutations(base_number)

# join the permutation lists into single numbers by joining each into a string
all_nums = [''.join(item[0:10]) for item in perms]

'''
Check whether each item is divisible by i (from 10-->2) for subset of item,
item[0:i]. For example;

    i = 10, number = 1234567890
    number[0:10]   = 1234567890

        is this divisible by i(10)? Yes.

    i = 9, number = 1234567890
    number[0:9]   = 123456789

        is this divisible by i(9)? Yes.

    i = 8, number = 1234567890
    number[0:8]   = 12345678

        is this divisible by i(8)? No.

We do not check whether the number is divisible by 1 as all integers are
divisible by 1.

'''
for i in range(10,1,-1):
    legits = [x for x in all_nums if int(x[0:i])%i==0]
    all_nums = legits
    print "%-10d # of result can be divided by %d" % (len(legits),i)

print legits

I considered that a recursive algorithm could perform this task much more efficiently but have not considered how to actually code the pseudo-code'ish solution I was shown;

f(1) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
f(2) = for n in f(1):
       find solutions to i for $$n * 10 + i = 0 (mod 2)$$
       where i isn't a digit of n.

I welcome all feedback, but I'm specifically hoping to hear about my coding-style/practices and the algorithm I developed.


texts:
I need to find the odd occurring numbers as a list. For example the below list should give 1 and 2 as output.
Is there a way that I can do it in a better way?
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1,2,2,4,2,4));
List<Integer> OddOcuranceNumbers =
numbers.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.filter(map -> map.getValue() % 2 == 1).map(s -> s.getKey())
.collect(Collectors.toList());
System.out.println(OddOcuranceNumbers);
    }


texts: Creating a wrapper class to use for mocking that uses IDisposable

texts:
I have a third party component that I am trying to write unit tests around. The problem is that I can't mock the object and there is no interface.

I decided to create an interface and a wrapper class calling into the code for the sake of mocking. I looked into the class definition that is generated by Visual Studio using the meta data and noticed a few things:

The class has two constructors (one takes a parameter)
The class inherits from IDisposable

My questions are:

Does my implementation below look right?
Did I handle the IDisposable implementation correctly in the proxy class?
Do I need the second constructor in the proxy class since the interface does not support constructor definitions? I use dependency injection in my code and I assume unless I tell my DI framework to use the second constructor I don't really need it but I am not sure.

The meta data looks like (slimmed down version):

public class PopClient : IDisposable
{
    public const int DefaultPort = 110;
    public const int DefaultSSLPort = 995;

    public PopClient();
    public PopClient(AddressFamily addressFamily);
    public bool HasTimeStamp { get; }
    public List<string> Capability();
    public void Connect(string host);
    protected override void GetServerGreeting();
}

Based on the meta data, my interface looks like (after removing methods/properties/access modifiers that are invalid in an interface definition):

public interface IPopClient : IDisposable
{
    bool HasTimeStamp { get; }
    List<string> Capability();
    void Connect(string host);
    void ConnectSSL(string host);
}

Based on the interface, I then created the wrapper class:

public class PopClientProxy : IPopClient
{
    private readonly Pop3 pop3;

    public PopClientProxy()
        this.pop3 = new Pop3();

    public PopClientProxy(AddressFamily addressFamily)
        this.pop3 = new Pop3(addressFamily);

    public bool HasTimeStamp
        get { return pop3.HasTimeStamp; }

    public List<string> Capability()
        return pop3.Capability();

    public void Connect(string host)
        pop3.Connect(host);

    public void Dispose()
    {
        if (pop3 != null)
            pop3.Dispose();
    }
}


texts: 3 versions of SQL query to find students with simultaneous classes

texts:
This is a toy example where we have 3 tables:

Student(snum, sname)
Enrolled(snum, cname)
Class(cname, meets_at)

and we want to find the sname of the students that are enrolled in at least
two classes that meet at the same time.

Here are three attempts, which one is best and why ?

select sname, (count(distinct cname) - count(distinct meets_at))
from (select st.*, cl.*
      from Student st, Class cl, Enrolled en
      where st.snum = en.snum
      and cl.cname = en.cname)
group by sname
having count(distinct cname) - count(distinct meets_at) >= 1;

select S.sname
from Student S
where S.snum in (
                select E.snum
                from Enrolled E, Class C
                where E.cname = C.cname
                group by E.snum, C.meets_at
                having count(E.cname) >= 2
                );

select S.sname
from Student S
where S.snum in ( select E1.snum
                  from Enrolled E1, Enrolled E2, Class C1, Class C2
                  where E1.snum = E2.snum and E1.cname <> E2.cname and
                  E1.cname = C1.cname and E2.cname = C2.cname
                  and C1.meets_at = C2.meets_at);


texts: Finding the given word from jumbled letters

texts:
I have tried to write JavaScript code to check whether I can form a word from the given string (jumbled):

function findWord(word, jumbledLetters, isSameLength) {
if(isSameLength && word.length !== jumbledLetters.length)
return false;

var uniquePosition = {};
for(var i = 0; i< word.length; i++)
for(var j=0; j< jumbledLetters.length; j++){
  if(word[i] === jumbledLetters[j] && j !== uniquePosition[j]) {
    uniquePosition[j] = j;
    break;
  }
}
return Object.keys(uniquePosition).length === (word.length);
}

I could do this with string permutation with minor changes, but I tried something like the above one. Could you please suggest refactoring to be done for the above code?


texts:
A bit of background: some time ago I wrote a piece of code that can be used for memoization with functions taking one parameter. Now I want to extend this to deal with functions with arbitrary number of parameters. However, thats a different story and here I want to focus only on one part of it: When memoizing the parameters and return values I could use a map<tuple<parameter_types...>,return_type>, but instead I was in the mood to get in touch with variadic templates and tried this:

#include <map>
#include <iostream>

template<typename VALUE,typename KEY,typename...MORE_KEYS>
struct VariadicMap {
    typedef VariadicMap<VALUE,MORE_KEYS...> inner_map_type;
    typedef std::map<KEY,inner_map_type>    map_type;
    VALUE& get_ref(const KEY& k, const MORE_KEYS&...more_keys){
        return map[k].get_ref(more_keys...);
    }
    VALUE* find(const KEY& k,const MORE_KEYS&...more_keys){
        auto it = map.find(k);
        if (it == map.end()) { return nullptr; }
        return it->second.find(more_keys...);
    }
private:
    map_type map;
};

template <typename VALUE,typename KEY>
struct VariadicMap<VALUE,KEY> {
    VALUE& get_ref(const KEY& k){
        return map[k];
    }
    VALUE* find(const KEY& k) {
        auto it = map.find(k);
        if (it == map.end()) { return nullptr; }
        return &(it->second);
    }
private:
    std::map<KEY,VALUE> map;
};

used like this:

int main() {
    VariadicMap<double,int,int,int> vm;
    vm.get_ref(1,2,3) = 1;
    std::cout << "x = " << vm.get_ref(1,2,3) << "\n";
    auto x = vm.find(1,2,3);
    if (x != nullptr) { std::cout << "x = " << *x << "\n";}
    return 0;
}

The rationale was that I would expect it to be much faster to search n maps of size m instead of searching a huge map of size n*m, where n is the number of parameters and m the number of values for each parameter. Especially to find that a key is not in the map it can be sufficient to consider only one parameter.

Indeed, when I compared the performance to a map<tuple<parameter_types...>,return_type> both inserting and finding values was faster (or at least not slower) with this VariadicMap for the examples I tried. However, what I dont like is...

I didnt know how to avoid the ugly inversion of <key,value> to <value,keys>, because of keys being a parameter pack.
the get_ref method mimics the operator[], but I cannot implement it as operator[] because it is only allowed to take a single parameter.

Please note that this was mainly an excercise, but harsh critisism is of course welcome ;). Code also here


texts: A recursive web-crawler created using vba

texts:
I had a desire to make a recursive web crawler in vba. As I don't have much knowledge on vba programming, so it took me a while to understand how the pattern might be. Finally, I've created one. The crawler I've created is doing just awesome. It starts from the first page of a torrent site then tracking the site's next page link it moves on while extracting names until all links are exhausted. Any input on this to make it more robust will be a great help. Thanks in advance.

Here is what I've written:

Sub yify(dynamic_link As String)

    Application.ScreenUpdating = False
    Const main_link As String = "https://yts.ag"
    Dim http As New XMLHTTP60, html As New HTMLDocument
    Dim movie As Object, link As Object

    With http
        .Open "GET", dynamic_link, False
        .send
        html.body.innerHTML = .responseText
    End With
    For Each movie In html.getElementsByClassName("browse-movie-title")
        ActiveCell.Value = movie.innerText   ''Scraping movie names
        ActiveCell.Offset(1, 0).Select
    Next movie

    For Each link In html.getElementsByClassName("tsc_pagination")(0).getElementsByTagName("a")
        If InStr(link.innerText, "Next") > 0 Then
            yify (main_link & Split(link.href, ":")(1))  ''Feeding next page link to the crawler
        End If
    Next link
    Application.ScreenUpdating = True

End Sub

Sub RecursiveCrawler()
    Range("A1").Select
    yify ("https://yts.ag/browse-movies/0/all/documentary/0/latest")  ''Crawling process starts here
End Sub


texts: Writing error handling and users routing for my JSON RESTful API

texts:
I'm currently making an app for my side project and I was looking to get some insight on the main js file, what can I improve, the error handling, what am I doing wrong, etc. I'm mostly confused about the error handling.

This is the main javascript file:

import express from 'express'
import cors from 'cors'
import dotenv from 'dotenv'

dotenv.config()
const morgan = require('morgan')
const app = express()

// Require routes
const usersRouter = require('./routes/users')

// Configs
require('./cfg/mongoose')

// Express middlewares / settings
app.set('port', process.env.PORT || 3000)
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

// Environment specific middlewares
if (app.get('env') === 'production') {
  app.use(morgan('combined'))
} else {
  app.use(morgan('dev'))
}

// Routing
app.use('/users', usersRouter)

app.get('/', (req, res) => {
  res.status(200).send({
    message: 'Welcome to the API! '
  })
})

// Handles 404
app.use((req, res, next) => {
  res.status(404).send({ error: 'Invalid endpoint' })
})

// Generic error handler
app.use((err, req, res, next) => {
  if (err.errors) {
    let errors = {}
    for (const errorName in err.errors) {
      errors = { ...errors, [errorName]: err.errors[errorName].message }
    }
    res.status(400).send({ errors })
  } else {
    res.status(err.output.statusCode).send({
      message: err.message || 'Internal server error'
    })
  }
})

// Server
app.listen(app.get('port'), () => {
  console.log(`Server listening on port ${app.get('port')}`)
})

And this is the users route:

import express from 'express'
import mongoose from 'mongoose'
import User from '../models/User'
import boom from '@hapi/boom'
const router = express.Router()

router.post('/', async (req, res, next) => {
    const { phone_number, email, password, name } = req.body
    try {
        const newUser = await User.create({
            name,
            email,
            phone_number,
            password,
        })
        res.status(201)
            .set('Location', `${req.hostname}${req.baseUrl}/${newUser.id}`)
            .send(newUser.id)
    } catch (err) {
        next(boom.boomify(err, { statusCode: 400 }))
    }
})

router.get('/', async (req, res, next) => {
    let users
    try {
        users = await User.find({}, 'name email').lean()
        Object.values(users).map(user => {
            user.profile_url = `${req.hostname}${req.baseUrl}/${user._id}`
        })
        if (!users.length) next(boom.notFound('Cannot find any users'))
        res.status(200).send(users)
    } catch (err) {
        next(boom.badImplementation())
    }
})

router.get('/:id', async (req, res, next) => {
    try {
        const user = await User.findById(
            req.params.id,
            'name email phone_number'
        )
        res.status(200).send(user)
    } catch (err) {
        next(boom.notFound('User not found'))
    }
})

router.delete('/:id', async (req, res, next) => {
    try {
        await User.deleteOne({ _id: mongoose.Types.ObjectId(req.params.id) })
        res.sendStatus(204)
    } catch (err) {
        next(boom.notFound('User not found'))
    }
})

router.put('/:id', async (req, res, next) => {
    let user
    try {
        const { email, phone_number, password, name } = req.body
        user = await User.findOneById(req.params.id, '-__v')
        user.email = email || user.email
        user.phone_number = phone_number || user.phone_number
        user.password = password || user.password
        user.name = name || user.name
        let updatedUser = await user.save()
        res.status(200).send(updatedUser)
    } catch (err) {
        next(boom.notFound('User not found'))
    }
})

module.exports = router
```


texts: Slow delete query on table with composite index

texts:
after profiling my application, it turns out that a single method is taking 3 minutes to run, which is about a third of the total runtime.

The method deletes approx. 400.000 rows from each table (PROCESSED_CVA and PROCESSED_DVA).

The code executing the queries :

public final static String DELETE_CVA = "delete from PROCESSED_CVA where RUN_ID = ?";
public final static String DELETE_DVA = "delete from PROCESSED_DVA where RUN_ID = ?";
public void purge(Run run) throws HibernateException {
    Session session = null;
    if (session == null) {
        session = sessionFactory.openSession();
    }
    Transaction t = session.beginTransaction();
    try {
        SQLQuery query = session.createSQLQuery(DELETE_CVA);
        query.setLong(0, run.getRunId());
        query.executeUpdate();
        query = session.createSQLQuery(DELETE_DVA);
        query.setLong(0, run.getRunId());
        query.executeUpdate();
        t.commit();
    } catch (HibernateException he) {
        logger.error("Failed to purge processed cva and dva for run: " + run.getRunId(), he);
        t.rollback();
        throw he;
    }
}

Both tables have the same structure.

CREATE TABLE "PROCESSED_CVA" (
"DEAL_ID" VARCHAR2(23 BYTE),
"NTT_ID" VARCHAR2(10 BYTE),
"CVA" FLOAT(126),
"RUN_ID" NUMBER(10,0))  ;
ALTER TABLE "PROCESSED_CVA" ADD CONSTRAINT "PK_CVA" PRIMARY KEY ("DEAL_ID", "RUN_ID")

There is an index on the primary key.

The execution plan :

OPERATION                       OBJECT_NAME     OPTIONS         COST
DELETE STATEMENT                                                100582
    |_ DELETE                   PROCESSED_CVA
        |_ INDEX                PK_CVA          SKIP SCAN       100582
            |_ Access Predicates
                |_ RUN_ID=100
            |_ Filter Predicates
                |_ RUN_ID=100

Can I speed this up ?

UPDATE
DBMS : Oracle


texts: Selecting a specific row with a desired value

texts:
I am trying to get a row if it has the desired specific value, otherwise get the first or default:

dr =
   (from avTable in DAL.DataStore.DSet.Tables["Values1"].AsEnumerable()
    join pavTable in DAL.DataStore.DSet.Tables["Values2"].AsEnumerable()
        on avTable.Field<int>("PK") equals pavTable.Field<int>("FK_Value")
    where
          pavTable.Field<int>("FKI_ProductAttribute") == Value2 &&
          avTable.Field<string>("Name") == "Specific Value"
    select avTable).FirstOrDefault() ??
    (from avTable in DAL.DataStore.DSet.Tables["Values1"].AsEnumerable()
     join pavTable in DAL.DataStore.DSet.Tables["Values2"].AsEnumerable()
     on avTable.Field<int>("PK") equals pavTable.Field<int>("FK_Value")
     where pavTable.Field<int>("FKI_ProductAttribute") == Value2
     select avTable).FirstOrDefault();

This smells. Is there a better way to do this?

I want to do something like this:

var dt =
   (from avTable in DAL.DataStore.DSet.Tables["Values1"].AsEnumerable()
    join pavTable in DAL.DataStore.DSet.Tables["Values2"].AsEnumerable()
        on avTable.Field<int>("PK") equals pavTable.Field<int>("FK_Value")
    where
          pavTable.Field<int>("FKI_ProductAttribute") == Value2 &&
          avTable.Field<string>("Name") == "Specific Value"
    select avTable)

DataRow dr = dt.Select("PK = Specified value");
If(dr==null) dr = dt.FirstOrDefault();

and then do a select based on a specified value. If that is null, then grab the first or default. This seems to be more DRY, but is it more or less efficient?. Also, I have a hard time doing a select on the dt based on the specific value (lack of Linq expertise and Google prowess to find the answer I am looking for).


texts: Numerical precision of implementation for convex quadrilateral area

texts:
I have implemented a method to compute a convex quadrilateral area in R3. The method works fine, but I am having numerical precision problems in the 8th decimal place. Take a look on the method:

internal static double GetTriangleArea(double ax, double ay, double az,
            double bx, double by, double bz,
            double cx, double cy, double cz
            )
        {
            /**
             * AB = B-A = (ux, uy, uz)
             * AC = C-A = (wx, wy, wz)
             *
             * S = 0.5*sqrt{(uy*wz - uz*wy)² + (uz*wx - ux*wz)² + (ux*wy - uy*wx)²}
             * */

            var ux = bx - ax;
            var uy = by - ay;
            var uz = bz - az;

            var wx = cx - ax;
            var wy = cy - ay;
            var wz = cz - az;

            var t1 = uy*wz - uz*wy;
            var t2 = uz*wx - ux*wz;
            var t3 = ux*wy - uy*wx;
            var s = 0.5*Math.Sqrt(t1*t1 + t2*t2 + t3*t3);

            return s;
        }

        internal static double GetConvexQuadrilateralArea(double ax, double ay, double az,
            double bx, double by, double bz,
            double cx, double cy, double cz,
            double dx, double dy, double dz)
        {
            var triangle1 = GetTriangleArea(ax, ay, az, bx, by, bz, cx, cy, cz);
            var triangle2 = GetTriangleArea(ax, ay, az, cx, cy, cz, dx,dy,dz);

            return triangle1 + triangle2;
        }

And this is the test:

[TestMethod]
        public void ParallelogramOfBaseBAndHeightHMustHaveAreaEqualToBTimesH()
        {
            var random = new Random(1);
            const double scale = 10000;
            for (var counter = 0; counter < 1000; counter++)
            {
                double baseLength = random.NextDouble() * scale;
                double height = random.NextDouble() * scale;

                double dx = random.NextDouble()*scale;

                var a = new[] { 0, 0, 0 };
                var b = new[] { baseLength, 0, 0 };
                var c = new[] { baseLength+dx, height, 0 };
                var d = new[] { 0F+dx, height, 0 };

                double expected = baseLength * height;

                var result = MathUtils.GetConvexQuadrilateralArea(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2],
                    d[0], d[1], d[2]);

                Assert.AreEqual(expected, result, Epsilon*scale,
                    string.Format("sideA: {0}, height: {1}, dx: {2}", baseLength, height, dx));
            }
        }

This test fails with the following message: Expected a difference no greater than <1E-09> between expected value 74813926.2967871 and actual value 74813926.2967871. sideA: 8552.44307245707, height: 8747.66726454146, dx: 4721.64729829954.

My question is: is there a way to increase the numerical precision of my implementation while still using double precision numbers?


texts:
I am trying to change static to dhcp in the /etc/network/interfaces file and vice versa using Python.

def setMode(mode,port,interfaces):
    #If the port's mode is not configured in the interface file, add a line for it, and return
    if "iface "+port+" inet " not in interfaces:
        newLine="\niface "+port+" inet "+mode
        interfaces="".join([interfaces,newLine])
        return interfaces

    #split the string by port to get to the line containing the port's ip mode
    #then split the third element of the resulting list by newline to isolate the end of that line
    split1=interfaces.partition(port+" inet ")
    split2=split1[2].partition("\n")
    #split the isolated line by space to get each word in it. the last element in the resulting list will be the current ip mode
    line=split2[0].split(" ")
    #if the current mode matches the new mode, return
    if line[len(line)-1] == mode:
        line=" ".join(line)
        split2="".join([line,split2[1],split2[2]])
        interfaces="".join([split1[0],split1[1],split2])
        return interfaces
    #otherwise set the last element to the new mode
    line[len(line)-1]=mode
    #join the line and lines back to recreate the full string
    line=" ".join(line)
    split2="".join([line,split2[1],split2[2]])
    interfaces="".join([split1[0],split1[1],split2])

    return interfaces

This is the code I am taking over with.  I am using str.partition() to achieve this.  mode == static or dhcp, port = eth8 or eth0, etc, interfaces = copy of interfaces file.

/etc/network/interfaces looks like this:

auto lo
iface lo inet loopback

auto eth8
iface eth8 inet static
address 10.8.100.36
netmask 255.255.0.0
gateway 10.8.1.1


texts: Is there a more efficient way to simulate in R, by exposition factor, gender and disease profile?

texts:
I started working with R recently and need to do a simulation for 100 000 people that
divides them in exposition factor for a disease, gender and presence or absence of
disease.
My background info is that the probability of being exposed to this risk factor is 0.15 in this population. The probability of being a woman, among exposed people is 0.2 and among non exposed people is 0.5. I also know that there are 4 gamma distributions - divided by gender and exposition factor - that characterize the disease. If X> 35, from each gamma, then you have the disease. I used the following code to answer this question:

n<-100000
exposition<-rep(0,n)
#vector that represents non exposed ("non exposed" = 1, "exposed" = 0)
gender<-rep(0,n) #vector that reprsents gender ("women" = 1, "men" = 0)
disease<-rep(0,n)
#vector that represents disease ("with disease" = 0, "without disease" = 1)
u<-runif(n,0,1)
b<-runif(n,0,1)
c<-runif(n,0,1)

#in 100 000 cases atributes non expostion
for(i in 1:n){if(u[i]>0.15)exposicao[i]<-1}

#cycle that determines the gender of the subjects
for(j in 1:n){{if(exposicao[j]==1 & b[j]>0.5)genero[j]<-1}
{if(exposicao[j]==0 & b[j]<0.2)genero[j]<-1}}

#Cycle that determines the state of disease from the subjects. I define people with
disease as people with c[x] inferior to the probability of having the disease
(P(X>35)), according to their gamma distribution. I used the results from that
calculation.

     for(x in 1:n){{if(expositon[x]==1 & gender[x]==1 & c[x]<0.06840084)doentes[x]<-1}
 #if the person is non exposed and woman X2~G(12,2)
 {if(exposition[x]==0 & gender[x]==1 & c[x]<0.1698673)doentes[x]<-1}
 #if it's exposed and woman X3~G(14,2)
 {if(exposicao[x]==1 & genero[x]==0 & c[x]<0.02010428)doentes[x]<-1}
 #if it's non exposed and man X1~G(10,2)
 {if(exposicao[x]==0 & genero[x]==0 & c[x]<0.3275424)doentes[x]<-1}}
 #if it's exposed and man X4~G(16,2)


texts: Expandable text boxes for legends of fieldsets

texts:
What is the best way to refactor the following script?

The above script will be applied to the following HTML and ASP.NET code:

            <fieldset>
                <legend>
                    +
                    KengLink Function
                </legend>

                    <asp:CheckBoxList ID="UserRoles" runat="server" />

            </fieldset>
            <fieldset>
                <legend>
                    +
                MI Sheet
                </legend>

                    <asp:CheckBoxList ID="UserRolesMISheet" runat="server" />

            </fieldset>


texts: Bash to find all placeholder variables in a file and replace will real variables

texts:
I am looking to make a generic config file using variables such as:
$PLACEHOLDER_USER

Then after moving the file into the correct position I want to replace every instance of *$PLACEHOLDER_VARIABLE* into the value of $VARIABLE from my settings.sh file.

In the example below *"$PLACEHOLDER_USER"* in log.conf would be replace by "tom"

log.conf

deploy = $PLACEHOLDER_USER

settings.sh

USER="tom"

deploy.sh

FILE="/home/logging/log.conf"
ln -s /home/log.conf $FILE
while IFS== read variable value
do
  sed -i "s/\$PLACEHOLDER_$variable/$value/g" $FILE
done < settings.sh

Is there a better way of doing this?


texts:
I'm making a Battleship game using python 2.7.  However, how to make it is not currently my issue.  The main aspect that I'm asking about is the style and method of making the code.  Am I following best (or even good) practice? Are the comments too much, too little, unclear? If someone could give me some pointers based on my code on how to make it more readable and standard, it would be highly appreciated.

from random import randint

# Adds the board to use as a list later
board = []

# Numbering my rows and columns
row_num = ["0", "1", "2", "3", "4"]

# "0" string begins a space as the row numbering pushed in the output text.  Could the space be better implemented in print board?
columns = ["  0", "1", "2", "3", "4"]

for x in range(5):
    board.append(["-"] * 5)

# Function for making the board.  Added tabs to make it more in the middle and clearer.
def print_board(board):
    row_num = 0
    print "\t\t", "   ".join(columns)
    for row in board:
        print "\t\t", row_num, "   ".join(row)
        row_num += 1

print "Let's play Battleship!"
print_board(board)

# Functions for playing agasint the computer
def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

print "Would you like to play agasint the computer or against a friend?"

# Choosing the location of the battleship and data validation of raw_input
def game_type(game_input):
    global ship_row
    global ship_col
    if game_input == 1:
        ship_row = random_row(board)
        ship_col = random_col(board)
    elif game_input == 2:
        ship_row = int(raw_input("Choose a Row to place your battleship:"))
        ship_col = int(raw_input("Choose a Column to place your battleship:"))
    else:
        print "That is not a valid input.  Please try again"
        game_type(int(raw_input("To play against the computer press 1, to play against a friend press 2: \n")))

game_type(int(raw_input("To play against the computer press 1, to play against a friend press 2: \n")))

# Printing the sollution for easy testing
print ship_row
print ship_col

# Starts the actual game
for turn in range(4):
    turn
    print "Turn", turn + 1

    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Column:"))

    if guess_row == ship_row and guess_col == ship_col:

        print "Congratulations! You sunk my battleship!"
        board[guess_row][guess_col] = "X"
        print_board(board)
        break
    # Data Validation for the inputs.  Maybe this shouldn't make a player miss but rather allow to retry
    else:
        if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
            print "Oops, that's not even in the ocean."
        elif(board[guess_row][guess_col] == "O"):
            print "You guessed that one already."
        else:
            print "You missed my battleship!"
            board[guess_row][guess_col] = "O"
            if turn == 10:
                print "Game Over"
                break
        print_board(board)


texts:
As part of a project I made a GPA calculator. It takes in the class name and letter grade for that class and adds them to a list (eventually I'll add some features that require me to have the grades and classes paired to each other) then adds points according to the grade and then divides by 6 the number of classes I have and gives me a total GPA.

        #GPA Calc

#Lists
classes= []
grades = []

#Collects the data of Class names and Grades in Letter Form
def collect():
    i = 0
    while (i <= 5):
        className = input("Enter Class Name: ")
        classes.append(className)
        i = i +1

    print(classes)
    y = 0
    while (y <=5):
        grade = input("Enter Your Grade For Each Class Listed in Order (Letter Form): ")
        grade = grade.upper()
        grades.append(grade)
        y = y + 1
    calculate()

def calculate():
    total= 0
    for element in grades:
        if element == "A+":
            total = total + 4.0
        elif element == "A":
            total = total + 4.0
        elif element == "A-":
            total = total + 3.7
        elif element == "B+":
            total = total + 3.3
        elif element == "B":
            total = total + 3.0
        elif element == "B-":
            total = total + 2.7
        elif element == "C+":
            total = total + 2.3
        elif element == "C":
            total = total + 2.0
        elif element == "C-":
            total = total + 1.7
        elif element == "D":
            total = total + 1.0
    gpa = total / 6
    print(gpa)

collect()

It all works the way it should, but if someone more experienced could tell me a better way to work with the class names and the grade associated and if there is a more efficient way to calculate the grades with some kind of dictionary or some other way, that would be appreciated.


texts: Is there a better way to search directories for a file or files?

texts:
Edit:

The purpose of this method is to search a specific directory for a given file type, ex. (*.txt, *.pdb, *.exe") then move the file(s) to a given destination directory and delete the original file from the source directory.

Is there a better way to write the following code?:

/// <summary>
/// Moves a specific file type from a given
/// source directory to a destination directory.
/// </summary>
/// <param name="sourceDir">The source directory.</param>
/// <param name="destDir">The destination directory.</param>
/// <param name="fileExt">Type of file to be moved.</param>
private static void MoveFilesToDirectory(string sourceDir, string destDir, string fileExt)
{
    try
    {
        if ( !Directory.Exists(sourceDir) )
        {
            Console.WriteLine("{0} does not exist.", sourceDir);
            return;
        }

        if ( !Directory.Exists(destDir) )
        {
            Directory.CreateDirectory(destDir);
        }

        foreach ( String dir in Directory.GetDirectories(sourceDir) )
        {
            foreach ( String file in Directory.GetFiles(dir, fileExt) )
            {
                string fileName = Path.GetFileName(file);
                string moveFileTo = Path.Combine(destDir, fileName);

                if ( !File.Exists(moveFileTo) )
                {
                    Directory.Move(file, moveFileTo);
                }

                File.Delete(file);
            }

            MoveFilesToDirectory(dir, destDir, fileExt);
        }
    }
    catch ( IOException ex )
    {
        Console.WriteLine(ex.Message);
    }
}


texts:
I got the C++ implementation of depth-first search (DFS) from here and made slight modifications to it. The modified code is as follows:
#include "stdafx.h"
#include <iostream>
#include<map>
#include<list>

class Graph {
    void DFSUtil(int v);
public:
    std::map<int, bool> visited;
    std::map<int, std::list<int>> adj;
    void addEdge(int v, int w);
    void DFS();
};

void Graph::addEdge(int v, int w)
{
    adj[v].push_back(w);
}

void Graph::DFSUtil(int v)
{
    visited[v] = true;
    std::cout << v << " ";

    std::list<int>::iterator i;
    for (i = adj[v].begin(); i != adj[v].end(); ++i)
        if (!visited[*i])
            DFSUtil(*i);
}

void Graph::DFS()
{
    for (auto i : adj)
        if (visited[i.first] == false)
            DFSUtil(i.first);
}

int main()
{
    Graph g;
    g.addEdge(0, 1);
    g.addEdge(0, 9);
    g.addEdge(1, 2);
    g.addEdge(2, 0);
    g.addEdge(2, 3);
    g.addEdge(9, 3);

    std::cout << "Depth First Traversal result\n";
    g.DFS();

    std::cin.get();

    return 0;
}

What further improvements can I make to this code?


texts: Counting the number of words in a string

texts:
I have written this program to count the number of words in a string. I have checked my program for the worst-case scenario. If any of you can find any cases for which this program doesn't work, please let me know so that I can work and improve it.

And just to be clear, we don't want symbols like, "," , "!" , "?", "." , "\n" to be counted as words. But obviously, "I" should be counted as word, as we consider it in the language. I have made sure of all this by replacing them with spaces. Let me know if I have missed something.

Is this a good solution?  How can I improve the code?

#include <iostream>
#include <string>

void replace(std::string& str, char x, char y);
int countWords(std::string x);

int main(){
std::cout<<countWords(" \n \t Hello, world ! ");
}

void replace(std::string& const str, char x, char y){
for(unsigned int i=0;i<str.size();i++){
    if(str[i]==x) str[i]=y;
}
}

int countWords(std::string x){

replace(x,',',' ');
replace(x,'.',' ');
replace(x,'!',' ');
replace(x,'?',' ');
replace(x,'(',' ');
replace(x,')',' ');
replace(x,'\n',' ');
replace(x,'\t',' ');
replace(x,'"',' ');

if(x.empty()) return 0;
int Num=1;

for(unsigned int i=1;i<x.size();i++){
    if(x[i]==' ' && x[i-1]!=' ') Num++;
}
if(x.back() == ' ') Num--;
return Num;
}


texts: Should I use module pattern for this notification controller?

texts:
I have the following code, I use this pattern for the entire JavaScript code. I'm trying to re-factor my code again. Should I use the Module pattern? Revealing Module Pattern to be specific?

What's happening is, somewhere in my code I say Dnianas.Notification.init().

First I bind the events, and I will handle them one by one.

Is there a better way to do this?

Also I notice that I don't use the var keyword. because they depend on each other.

Dnianas.Notification = {
    init: function () {
        this.bindEvents();
        this.cache();
    },

    bindEvents: function () {
        $(document).on('click', '#opennotifii', this.markAsRead);
    },

    cache: function () {
        $notification = $('#opennotifii');
    },

    countNotifications: function () {
        var $notifications = $('.boxnotificationsusers').children().find('#boxsendnotifi');
        ids = [];

        // Add unread notifications to the ids array.
        $notifications.each(function () {
            if ($(this).data('read') === 0) {
                ids.push($(this).data('id'));
            }
        });

        return ids;
    },

    markAsRead: function () {
        self = Dnianas.Notification;
        ids = self.countNotifications();

        if (ids.length > 0) {
            var request = $.ajax({
                url: '/notifications/read',
                data: {
                    notifications: ids,
                    _token: token,
                }
            });

            request.done(function (data) {
                self.renderNotificationCount(data);
            });
        }
    },

    renderNotificationCount: function (data) {
        if (data.seen) {
            $notification.find('.not_nu1').fadeOut(200);
        }
    }
};


texts: Object-oriented design of list of primes

texts:
Is there a better way to implement this class, or does it not constitute implementation in the first place?  This is one of my first few tries at OOP.  Any suggestions will be much appreciated.

#include <iostream>
#include <vector>
#include <cmath>

class PrimeList
{
    public:
        std::vector<int> vPrime;
        void initVector(int n)
        {
            for (int i=2; i <= n; ++i)
                vPrime.push_back(i);
        }
};

int main()
{
    // Instantiate an object "primes" of type PrimeList.
    PrimeList primes;

    // Get the input variable to pass to the initVector method.
    std::cout << "Enter the upper limit of the list of primes you want     to generate:" << std::endl;
    int n;
    std::cin >> n;

    // Create a vector filled with every integer from 2 to n.
    primes.initVector(n);

    // Begin the sieve
    for (int a=0; a < sqrt(n); ++a) {
        for (int b=a+1; b < primes.vPrime.size(); ++b) {
            if (primes.vPrime[b] % primes.vPrime[a] == 0) {
                primes.vPrime.erase(primes.vPrime.begin() + b);
            }
        }
    }

    // Print the list of primes from 2 to n.
    for (int i=0; i < primes.vPrime.size(); ++i)
        std::cout << primes.vPrime[i] << std::endl;
    return 0;
}


texts:
Problem:

Pascal’s triangle is a useful recursive definition that tells us the coefficients in the expansion of the polynomial (x + a)^n. Each element in the triangle has a coordinate, given by the row it is on and its position in the row (which you could call its column). Every number in Pascal’s triangle is defined as the sum of the item above it and the item that is directly to the upper left of it. If there is a position that does not have an entry, we treat it as if we had a 0 there. Below are the first few rows of the triangle:
Item:   0  1  2  3  4  5
Row 0:  1
Row 1:  1  1
Row 2:  1  2  1
Row 3:  1  3  3  1
Row 4:  1  4  6  4  1
Row 5:  1  5 10 10  5  1
  `...`

Define the procedure pascal(row, column) which takes a row and a column, and finds the value at that position in the triangle. Don’t use the closed-form solution, if you know it.
def pascal(row, column)

Solution:
def pascal(row, column):
    """
    >>> pascal(0, 0)
    1
    >>> pascal(5, 4)
    5
    >>> pascal(0, 1)
    0
    """
    if column == 0:
        return 1
    elif row == 0:
        return 0
    else:
        return pascal(row-1, column) + pascal(row-1, column-1)

Can we improve this code using memoization? because, pascal(5,4) = pascal (4, 4) + pascal(4, 3)


texts:
What this should do is wait for dataBlockSize bytes to be ready and then continue, but wait for 10ms if they are not ready yet to not block the CPU, but not the first time as I do not want to wait once even if the bytes are ready.

Is there a better way of doing this?

while (!cancellationToken.IsCancellationRequested)
{
    var ftdiStatus = ftdiDevice.GetRxBytesWaiting(ref rxBytes);
    if (ftdiStatus != FTDI.FT_STATUS.FT_OK)
        return null;

    if (rxBytes >= dataBlockSize)
        break;

    Thread.Sleep(10);
}


texts: Use and understanding of async/await in .NET 4.5 +

texts:
I am just about to embark upon a massive job of multi-threading a cost-engine.  I could use TPL of which I am very familiar, but would like to leverage the async/await keywords of .NET 4.5 to make life that little bit simpler.

Is my understanding of what is going on correct?  How can I improve this design?

CancellationTokenSource cancelSource;

// Mark the event handler with async so you can use await in it.
private async void StartButton_Click(object sender, RoutedEventArgs e)
{
    cancelSource = new CancellationTokenSource();
    CancellationToken token = cancelSource.Token;
    TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
    IProgress<ProgressInfo> progressInfo = new Progress<ProgressInfo>(ReportProgress);
    await ProcessScript(progressInfo, token, uiScheduler);

    // await sets up the following as an Contnuation to
    // continue once returned from await.
    this.resultsTextBox.AppendText("\nReturn to caller...\n\n");
}

// Class to report progress...
private void ReportProgress(ProgressInfo progressInfo)
{
    this.progressBar.Value = progressInfo.PrecentComplete;
    this.progressLabel.Content = progressInfo.Message;
}

private async Task ProcessScript(IProgress<ProgressInfo> progressInfo,
                                 CancellationToken token,
                                 TaskScheduler uiScheduler)
{
    ProgressInfo pi = new ProgressInfo();
    pi.PrecentComplete = 0;
    pi.Message = "In script processor...";
    progressInfo.Report(pi);

    Thread.Sleep(5000); // This is UI Blocking...
    string str = this.resultsTextBox.Text;
    str = "We have added this => going into await...";
    this.resultsTextBox.AppendText(str);
    Task task = Task.Factory.StartNew(() => LongRunning(uiScheduler));

    pi.Message = "Task set";
    pi.PrecentComplete = 50;
    progressInfo.Report(pi);

    // awaits the long runniing task - non-UI blocking.
    await task;

    // The await above sets this up as a continuation on the UI thread.
    pi.Message = "Task awaited";
    pi.PrecentComplete = 95;
    progressInfo.Report(pi);

    this.resultsTextBox.AppendText("Where are we now??");
    return;
}

private bool LongRunning(TaskScheduler uiScheduler)
{
    // Allow access to the UI from this background thread from
    // the ThreadPool.
    Task.Factory.StartNew(() =>
        {
            this.resultsTextBox.AppendText("\n\nNow in 'LongRunning'!! Waiting 5s simulating HARD WORK!!");
        }, CancellationToken.None,
           TaskCreationOptions.None,
           uiScheduler);

    // Simulate hard work.
    Thread.Sleep(7000);
    Task.Factory.StartNew(() =>
    {
        this.resultsTextBox.AppendText("\n\n\nHARD WORK COMPLETE!!");
    }, CancellationToken.None,
       TaskCreationOptions.None,
       uiScheduler);
    return true;
}


texts: Triangle-numbers with lots of divisors (Project-Euler Problem 12)

texts:
The following is my python solution of project euler 12.

  The sequence of triangle numbers is generated by adding the natural
  numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7
  = 28.
  The first ten terms would be:

  1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

  Let us list the factors of the first seven triangle numbers:

 1: 1
 3: 1,3
 6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

  We can see that 28 is the first triangle number to have
  over five divisors.

  What is the value of the first triangle number to have over five
  hundred divisors?

It works fine and runs in half second. I fixed a random upper limit for the search of primes (using the sieve of eratosthenes).

def SE(n):                  #Sieve of Eratosthenes
    sieve = range(3, n, 2)
    top = len(sieve)
    for si in sieve:
        if si:
                bottom = (si*si - 3)/2
                if bottom >= top:
                    break
                sieve[bottom::si] = [0] * -((bottom-top)//si)
    return [2] + filter(None, sieve)

primes = SE(13000)        #Here's the problem

def nod(n):                 #function that returns the number of divisors
    nd = 1
    for i in primes:
        if i <= n:
            t = 1
            while n % i == 0:
                n /= i
                t += 1
            nd *= t
        else:
            return nd

c = 0
i = 1
d = 1
d1 = 0
while c < 500:                 #loop for checking each triangle number
    if i % 2 == 0:
        d = nod(i+1)
    else:
        d1 = nod((i+1)/2)
    c = d * d1
    i += 1
print i*(i-1)/2


texts: Recursive linear search - branch style and layout

texts:
Is my layout of the if/else statement reasonable?

It feels clumsy to me to spread the termination condition over the first three lines of the function. Can I squeeze it into one or two lines? Would it help if I used the ternary operator? How can I make the JavaScript more idiomatic (while still using recursion)?  Any other improvements?

var containsA = function(sentence) {
  if (sentence.length == 0) {
    return false;
  }
  else {
    return sentence[0] === 'A' || containsA(sentence.substr(1));
  };
};

var containsA = function(sentence) {
  if (sentence.length == 0) {
    return false;
  }
  else {
    return sentence[0] === 'A' || containsA(sentence.substr(1));
  };
};

// Unit tests
var assert = function(code) {
  if (eval(code)) {
    document.write(code + " test passed.
");
  }
  else {
    document.write(code + " test FAILED.
");
  };
};

assert("!containsA('')");
assert("containsA('A')");
assert("!containsA('a')");
assert("containsA('HAH!')");
assert("!containsA('carrots')");

I have simplified details that are not relevant to my question. This simpler version attempts to reimplement String.prototype.contains(). If I convert my string to an array I could use Array.prototype.find() but my hunch is that would be less readable.


texts:
This is a kind of follow up to my previous sort implementation question with specific questions to insertion sort, and Modern C++ idioms. Anybody seeing this post can see how I got to this modern equivalent of a typical C-style sort you can find everywhere on the web by visiting my prior sorting review.

I am writing, as review for an interview, Modern C++ compliant versions of sorting algorithms I previously have seen. This post is about insertion sort, and insertion sort only.

// Shift/bubble each element toward the front into a sorted sub-array
template<typename BdIterator, typename Comparator = std::less<typename std::iterator_traits<BdIterator>::value_type>>
void sort_insertion(BdIterator beg, BdIterator end, Comparator cmp = Comparator())
{
    BdIterator front, cur, prev;
    // Assume the first element is sorted.
    for (front = beg + 1u; front != end; ++front)
    {
        cur = front;
        prev = cur - 1u;
        // Bubble the "next" element towards the front by swapping it with its
        // "prev" neighbor until it is in its sorted position.
        while (cur != beg && cmp(*cur, *prev))
            std::iter_swap(cur--, prev--);
    }
}

As before, I am looking for any performance optimizations I may have missed in the algorithm itself, as well as Modern C++ constructs I may not be abiding by for this example.

One specific question I have deals with the unsigned integer I am adding and subtracting from the iterators to move to the next and previous values in the container. Since there is no way to get the type of container for the provided iterators, I do not see a way to get the size_type of the assumed container to add and subtract the correct types rather than just unsigned/signed integers.

The fact that I am subtracting prevents me from declaring the minimal Iterator template type as forward iterators (We are moving the iterator backwards). Is there a better way around this or should I just stick to making the minimum BiDirectionalIterators?


texts: Cleaning up an utterance using multiple regex substitutions

texts:
I need to use regex for some stuff (mentioned in code comments) and wrote the following code, which works perfectly fine for my need, but I wanted to know if there was a way to improve this code?

Am I using re.compile correctly in this case?

import re

def regex(utterance):

    utterance = utterance.lower()

    # Replacing non ASCII characters with space
    message_ascii = re.compile(r'[^\x00-\x7F]+')
    message_ascii = message_ascii.sub(r' ', utterance)

    # If comma after number, replace comma with space
    message_comma_no = re.compile(r'(?<=[0-9]),')
    message_comma_no = message_comma_no.sub(r' ',message_ascii)

    # If comma after words, add space before and after
    message_comma_word = re.compile(r'(?<=[a-z]),')
    message_comma_word = message_comma_word.sub(r' , ',message_comma_no)

    # If "Dot and space" after word or number put space before and after
    message_dot = re.compile(r'(?<=[a-z0-9])[.] ')
    message_dot = message_dot.sub(r' . ',message_comma_word)

    # If any other punctuation found after word or number put space before and after
    message_punct = re.compile(r"(?<=[a-zA-Z0-9])(?=[?;!()'\"])|(?<=[?;!()'\"])(?=[a-zA-Z0-9])")
    message_punct = message_punct.sub(r' ', message_dot)

    # Remove Excess whitespaces
    message = ' '.join(message_punct.split())

    return message


texts:
I've written a python script that solves a restricted variant of Subset Product by using integer factorization. The purpose of the script is for my empirical observations of the similarities between factorization and the NP-complete problem.

The code compares two sets (or lists) from the original input arr and the factor list res. Because of the comparison, it is able to find the divisors and multiply them to see if they arrive to the target product.

Before using the code be aware that input must be positive integers only.

print('Solves restricted Subset Product')
print('Where only non-repeating integers exist in list')
print('Subset Product Solver')
arr = list(map(int, input('Enter numbers WITH SPACES: ').split(' ')))
print('enter your target integer: ')
target = int(input())

# Here I am using the same algorithm
# for integer factorization for a
# restricted variant of subset product

res = [];
for i in range(1, target+1):
  if target % i == 0:
    res.append(i)

compare_sets = set(res) & set(arr)

# These lines of code multiply all elements
# in compare_sets.

def multiplyList(compare_sets) :

    # Multiply elements one by one
    result = 1
    for x in compare_sets:
         result = result * x
    return result

# Driver code

k = multiplyList(compare_sets)

# This loop is intended to comb through the
# compare_sets list. To make sure I don't go
# over and miss the target integer

for i in compare_sets:
    if k / i == target:
      if len(compare_sets) > 1:
        compare_sets.remove(i)
        print('yes, a subset product exists')
        print(compare_sets)
        quit()

if k == target:
 if len(compare_sets) > 1:
  print('yes, a subset product exists')
  print(set(res) & set(arr))
  quit()
else:
  print('no')
  quit()

print('no')

Question

Are my variable names funky and should be re-written?
 What part of the code is the worst in terms of time complexity (ignoring factoring)?
What more efficient "pythonic" methods can I use to improve the code?


texts: Stopping ncurses printing with key presses

texts:
I've been updating a little text-based game of mine to have the text roll out over a time period to give the appearance that it's being typed. I'm doing this by using non-blocking output with ncurses.

The text to be output is passed to a function called TimedPrint, along with arguments for the screen to print it on, the position on screen to print, and the time period between each printed letter. (printGridsLineTimed is basically the same thing as TimedPrint but for printing whole Grids, a class I have created representing blocks of text).

//somewhere in main.cpp

unsigned tries = 0;
unsigned maxTries = 4;
unsigned currentX = //a number;
unsigned currentY = //a number;

{

    unsigned Period = 15;
    if(TimedPrint(stdscr, "Welcome to ROBCO Industries (TM) Termlink.", 1, 1, Period)) Period = 0;
    if(TimedPrint(stdscr, "Password Required", 1, 2, Period)) Period = 0;
    if(TimedPrint(stdscr, "Attempts remaining: " + std::to_string(maxTries-tries), 1, 4, Period)) Period = 0;
    if(printGridsLineTimed<gridX, gridY>(stdscr, GridVec.cbegin(), GridVec.cend(), Period)) Period = 0;
    if(TimedPrint(stdscr, ">", currentX - 1, currentY, Period)) Period = 0;

}

//in functions.cpp

int TimedPrint(WINDOW* w, const std::string& s, unsigned newX, unsigned newY, unsigned Period){

    unsigned x = 0, y = 0;
    getyx(w, y, x); //obtain current cursor position
    wmove(w, newY, newX);
    wclrtoeol(w);
    wtimeout(w, 0); //no delay in input. If the user hasn't added a command, wgetch(w) returns ERR.
    for(auto it = s.begin(); it != s.end(); ++it){
        if(*it == ' '){
            waddch(w, *it);
            wrefresh(w);
            continue;
        }
        waddch(w, *it);
        wrefresh(w);
        int result = wgetch(w);
        switch(result){
            case KEY_UP:
            case KEY_DOWN:
            case KEY_LEFT:
            case KEY_RIGHT:
            case 0xA: //If user gives a valid input, print the remainder, move back and return the key pressed
                while(++it != s.end()){
                    waddch(w, *it);
                }
                wrefresh(w);
                wtimeout(w, -1); //back to normal waiting
                wmove(w, y, x);
                return result;
        }
        Sleep(Period); //determines how fast the letters appear. Too slow and the game feels laggy since input isn't processed until after this.

    }
    wtimeout(w, -1); //back to normal waiting
    wmove(w, y, x);
    return 0;

}

TimedPrint detects when there is a key press and, if that key press is valid, prints the remaining text instantly and returns what key was pressed. I use this returned value to set Period to 0 which means the rest of the text is printed automatically. So the user can press enter and everything gets printed at once. What I'm curious about though is the code within the block scope seems like it should be possible to simplify, but I don't know how.

It is laborious to check whether every print returns a value and then set period to zero. Do you personally feel there could be a better approach to this? I could always set TimedPrint to take a reference to unsigned instead and then change Period in the function manually but:

I want rvalues to be passed to TimedPrint.
It doesn't seem intuitive or natural that it would change the value of the time period. It should only print what is given to it and return the value of any key presses. If I were to extend this function to use in other programs, the functions applicability feels limited if it changes the time period passed to it.


texts: Find the shortest & best starting move in Mancala (Kalah)

texts:
The version of Mancala impelemented in this game is as follows:

The board looks like this:

   O   O   O   O   O   O
@                         @
   O   O   O   O   O   O

Each O represents a pit that contains four 'seeds'. The @ is called the 'store' where seeds are accumulated, as points.

Each player takes one side (top or bottom) of the board, and play begins by a player removing the seeds from one pit on their side of the board and 'sowing' them one seed per pit in the adjacent pits, in a counter-clockwise order. A player deposits a seed in their own 'store' when passing it. The opponents 'store' is ignored. If the last seed in a players hand is sown in the 'store' the player can move again, picking any pit on their side of the board.

The version of the game coded for allows for 'relay' play, i.e. a turn ends only when the last seed in the players hand is sown in an empty pit. Otherwise, the player can scoop up the seeds in the last pit sown and continue sowing into the next pit, etc.

If the last seed in sown in an empty pit on the player's own side of the board, they capture the seeds in the pit opposite it (on the opponent's side) and deposit them in their store.

This code searches for two things:

The shortest sequences of choices that will win on the first move (>24 points)
The sequence that gives the most points on the first move.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Mancala
{
    static public class Program2
    {
        static (int[] seq, int count) shortest, max;

        public static void Main(string[] args)
        {
            Branch(Enumerable.Empty<int>(), new int[] { 4, 4, 4, 4, 4, 4, 0, 4, 4, 4, 4, 4, 4 });
            Console.WriteLine($"Shortest:     ({shortest.count}) | {string.Join(",", shortest.seq)}");
            Console.WriteLine($"Max:          ({max.count}) | {string.Join(",", max.seq)}");
            Console.ReadKey();
        }

        static void Branch(IEnumerable<int> seq, int[] initialState)
        {
            for (int i = 0; i <= 5; i++)
            {
                var pit = i;
                var state = initialState.ToArray();

                do {
                    var hand = state[pit];
                    state[pit] = 0;
                    for (int j = pit + 1; j <= pit + hand; j++) state[j % 13]++;
                    pit = (pit + hand) % 13;
                } while (pit != 6 && state[pit] > 1) ;
                if (pit < 6 && state[pit] == 1) state[6] += state[12 - pit];  // capture rule
                if (state[6] > 24) Update(seq.Concat(new int[] { i }), state[6]);
                if (pit == 6) Branch(seq.Concat(new int[] { i }), state);
            }
        }

        static void Update(IEnumerable<int> seq, int count)
        {
            var vseq = seq.ToArray();
            if (shortest.count == 0 || vseq.Length < shortest.seq.Length || vseq.Length == shortest.seq.Length && count > shortest.count)
                shortest = (vseq, count);
            if (count > max.count || count == max.count && vseq.Length < max.seq.Length)
                max = (vseq, count);
        }
    }
}


texts: Conditionally inserting MySQL entries in a Flask app

texts:
I am a newbie in back-end developing. I know that the biggest part of back-end development is interaction with database.

I established a connection and the code is 100% working, but I am wondering if it is well optimized. There is one function where I make double insertion into the database but before I commit this insertion I make two requests to the database to determine whether I should insert or not.

from flask import Flask, jsonify, request, url_for
import MySQLdb

def connection():
    conn = MySQLdb.connect(host='somehost',
                           user='root',
                           passwd='some password',
                           db='users_addresses',
                           port=3306
                           )
    c = conn.cursor()
    return c, conn

def processing():
    # some actions
    try:
        c, conn = connection()
        c = conn.cursor()
        mc_address_existence, id = mc_address_exist(c, conn, mc_address=box_id)
        if mc_address_existence and not login_exist(c, conn, login):

            c.execute("INSERT INTO accounts_info (uid, first_name, second_name, email, phone_number) "
                      "VALUES ({},"
                            " '{}',"
                            " '{}', "
                            "'{}',"
                            " {} ) ".format(id, first_name, second_name, email, phone_number)
                      )

            c.execute("INSERT INTO logins_passwords (uid, login, password) "
                      "VALUES ({},"
                      "'{}',"
                      " '{}' ) ".format(id, login, password)
                      )
            conn.commit()
            c.close()
            conn.close()
            return jsonify({'result': True})
        return jsonify({'result': False})
    except Exception as e:
        return str(e)

And here are two functions for determining whether to make the insertion or not:

def mc_address_exist(c, conn, mc_address):
    # Should I wrap it for try/except?
    # c = conn.cursor()
    c.execute("SELECT uid, mc_address "
              "FROM boxes_id "
              "WHERE mc_address='{}' ".format(mc_address))
    res = c.fetchall()
    # c.close() Should I close?
    # conn.close()
    if res:
        return True, res[0][0]
    return False, 0

def login_exist(c, conn, login):
    # should I wrap it for try/except?
    c.execute("SELECT * "
              "FROM logins_passwords "
              "WHERE login='{}' ".format(login))
    res = c.fetchall()
    # c.close() should I close it or not?
    # conn.close()
    if res:
        return True
    return False

It is working code, but maybe not optimized. Here are three questions:

Should I close the cursor (conn, c) in the checking functions?
Should I wrap the database's selection checking functions into try/except?
Maybe I should use with as instead?


texts:
This is a problem from Interview Street in Dynamic Programming section.

  Billboards (20 points)

  ADZEN is a very popular advertising firm in your city. In every road
  you can see their advertising billboards. Recently they are facing a
  serious challenge , MG Road the most used and beautiful road in your
  city has been almost filled by the billboards and this is having a
  negative effect on the natural view.

  On people's demand ADZEN has decided to remove some of the billboards
  in such a way that there are no more than K billboards standing
  together in any part of the road.

  You may assume the MG Road to be a straight line with N
  billboards.Initially there is no gap between any two adjecent
  billboards.

  ADZEN's primary income comes from these billboards so the billboard
  removing process has to be done in such a way that the billboards
  remaining at end should give maximum possible profit among all
  possible final configurations.Total profit of a configuration is the
  sum of the profit values of all billboards present in that
  configuration.

  Given N,K and the profit value of each of the N billboards, output the
  maximum profit that can be obtained from the remaining billboards
  under the conditions given.

  Input description

  1st line contain two space separated integers N and K. Then follow N
  lines describing the profit value of each billboard i.e ith line
  contains the profit value of ith billboard.

  Sample Input

6 2
1
2
3
1
6
10

  Sample Output

21

  Explanation

  In given input there are 6 billboards and after the process no more
  than 2 should be together.

  So remove 1st and 4th billboards giving a configuration _ 2 3 _ 6 10
  having a profit of 21. No other configuration has a profit more than
  21. So the answer is 21.

  Constraints

1 <= N <= 100,000 (10^5)
1 <= K <= N
0 <= profit value of any billboard <= 2,000,000,000 (2 * 10^9)

My solution (psuedocode):

Let Profit[i] denote the Profit from ith billboard.
(i, j) denotes the range of billboards
MaxProfit(i, j) for all (i, j) such that i<=j and i-j+1 <= K is:
    MaxProfit(i, j) = Profit[i] + Profit[i+1] + ... + Profit[j];

For other (i,j) MaxProfit equals,

MaxProfit(i, j)
{
    max = 0;
    for all k such that i<=k<=j // k denotes that, that position has no   billboard
    {
        temp = MaxProfit(i, k-1) + MaxProfit(k+1, j);
        if(temp > max)
        max = temp;
    }
    return max;
}

Code:

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

long **DP;
long returnValue(long i, long j);
int main()
{
    long N, K;
    scanf("%ld", &N);
    scanf("%ld" ,&K);

    DP = (long**) malloc(sizeof(long *) * N);

    long ARR[N];
    long j, z, i=0;
    for(i=0;i<N;i++)
    {
        DP[i] = (long*)malloc(sizeof(long) * N);
        scanf("%ld", &ARR[i]);
    }

    for(i=0;i<N;i++)
    {
        long sum=0;
        for(j=1;j<=K && (i+j-1)<N;j++)
        {
            sum += ARR[i+j-1];
            DP[i][i+j-1] = sum;
        }
    }

    for(j=K+1;j<=N;j++)
    {
        for(i=0;i<=N-j;i++)
        {
            long max = 0;
            for(z=i;z<=i+j-1;z++)
            {
                long temp = returnValue(i, z-1) +     returnValue(z+1, i+j-1);
                if(temp > max)
                    max= temp;
            }
            DP[i][i+j-1] = max;
        }
    }
    printf("%ld\n", DP[0][N-1]);
    for(i=0;i<N;i++)
    {
            free(DP[i]);
    }
    free(DP);
}

long returnValue(long i, long j)
{
    if(i<=j)
    {
        //printf("%d\n", DP[i][j]);
        return DP[i][j];
    }
    else
        return 0;
}

My solution is of order O(N2). So I get TLE and Segmentation fault for larger N. I have already passed 6/10 test cases. I need to pass remaining 4.


texts:
The question was:

  Create an algorithm to check if two strings differ by one character.

This wasn't my interview, so I tried to understand the question.

Options:

just compare the chars one by one, I assume the lower case and uppercase isn't the same.
compare the chars in any given order meaning "tube" and "bute" are the same...

Please be as strict as you can and find my bugs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{

    public class Program
    {
        public static void Main()
        {
            Console.WriteLine("Please Enter some text");
            string stringToCheck1 = "Out";
            string stringToCheck2 = "tuo";

            bool result = CompareStrings(stringToCheck1, stringToCheck2);
            PrintMessage(result);
            result = CompareAllLetters(stringToCheck1, stringToCheck2);
            PrintMessage(result);
        }
        public void PrintMessage(bool result)
        {
            if (result)
            {
                Console.WriteLine("Strings are less than one letter apart");
                return;
            }
            Console.WriteLine("Strings are more than one letter apart");
        }

        //checks if the letters one by one
        public static bool CompareStrings(string stringToCheck1, string stringToCheck2)
        {
            //check if strings are not the same size
            if (Math.Abs(stringToCheck2.Length - stringToCheck1.Length) > 2)
            {
                return false;
            }

            int counter = 0;
            for (int i = 0; i < stringToCheck1.Length; i++)
            {
                if (stringToCheck1[i] != stringToCheck2[i])
                {
                    counter++;
                }
            }
            if (counter > 1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        //checks if the letters in any order
        public static bool CompareAllLetters(string stringToCheck1, string stringToCheck2)
        {
            //check if strings are not the same size
            if (Math.Abs(stringToCheck2.Length - stringToCheck1.Length) > 2)
            {
                return false;
            }

            List<char> string1LettersList = new List<char>();
            List<char> string2LettersList = new List<char>();
            foreach (var c in stringToCheck1)
            {
                string1LettersList.Add(c);
            }

            foreach (var c in stringToCheck2)
            {
                string2LettersList.Add(c);
            }

            for (int i = 0; i < string1LettersList.Count; i++)
            {
                if (string2LettersList.Contains(string1LettersList[i]))
                {
                    string2LettersList.Remove(string1LettersList[i]);
                }
            }
            if (string2LettersList.Count > 2)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
}