texts: Data model for tracking currency in a safe

texts:
I am attempting to design an application that tracks currency and recent transactions in a safe.  I am using entity-framework code-first in a wpf desktop application.

The first goal is to be able to track whats currently in the safe. For example - 87 Ones, 55 Twos, 76 fives, etc..

The second goal is to be able to track recent deposits/withdrawals into/out of the safe. For example - user X deposited 5 ones, 10 fives on 1/1/14.

Is the following a reasonable entity framework data model to accomplish this?

class Safe
{
    public int SafeId { get; set; }

    public CurrencySet Totals { get; set; }

    public ICollection<SafeTransaction> SafeTransactions { get; set; }
}

class CurrencySet
{
    public int CurrencySetId { get; set; }

    public int Ones { get; set; }
    public int Twos { get; set; }
    public int Fives { get; set; }
    public int Tens { get; set; }
    public int Twenties { get; set; }
    public int Fifties { get; set; }
    public int Hundreds { get; set; }
}

class SafeTransaction
{
    public int SafeTransActionId { get; set; }

    public TransactionType TransactionType { get; set; }

    public User User { get; set; }

    public CurrencySet Currency { get; set; }

    public DateTime TimeStamp { get; set; }

}

enum TransactionType
{
    Withdrawal,
    Deposit
}

One concern I have is tracking non-US currency. Not a requirement currently, but maybe in the future.


texts: Speed up position check for embedded length on stream

texts:
I received help with adding the length of a stream in the first 4 bytes, meaning it's there as an int.

I am adding it at the start and sending it, while the receiving part checks for its position.

However, the position checking is a bit slow, so I wonder if it's possible to improve it.  Maybe using unsafe pointers or something, but I'm not sure.

currentPosition = 0;
while (currentPosition < sizeof(int) && tt1.Connected)
{
    currentPosition += tt1.GetStream().Read(lenArray, currentPosition, sizeof(int) - currentPosition);
}

There is the example on what it does at the end of the receiving part.  It goes through it, and it's a bit slow.

I can't see much of what can be done here, but hopefully someone else has a better idea.

Here is the whole code, which may help show how it functions:

tempBytes = new byte[length];
ms = new MemoryStream(tempBytes);

int currentPosition = 0;

while (currentPosition < length && tt1.Connected)
{
    currentPosition += tt1.GetStream().Read(tempBytes, currentPosition, length - currentPosition);
}

newImage = Image.FromStream(ms);

gmp.DrawImage(newImage, 0, 0);

currentPosition = 0;
while (currentPosition < sizeof(int) && tt1.Connected)
{
    currentPosition += tt1.GetStream().Read(lenArray, currentPosition, sizeof(int) - currentPosition);
}
length = BitConverter.ToInt32(lenArray, 0);


texts:
Does my code look secure right now? I know that I still have the password hashing and so forth, but what about SQL injections? Do I have any? Are there any other security issues?

<?php
$con=mysqli_connect("localhost","root","xxx","s");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$name = $con->real_escape_string($_POST['name']);
$username = $con->real_escape_string($_POST['username']);
$email = $con->real_escape_string($_POST['email']);
$password1 = $con->real_escape_string($_POST['pass1']);
$password2 = $con->real_escape_string($_POST['pass2']);

if (empty($name) || empty($username) || empty($email) || empty($password1) || empty($password2))
{
    echo "Complete all fields";
    // you can stop it here instead of putting the curly brace ALL the way at the bottom :)
    return;
    }

if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
    echo $emailvalid = "Enter a  valid email";
    }

if (strlen($password1) <= 6)
{
echo $passlength = "Password must be at least 6 characters long";
}

// Password numbers
if (!preg_match("#[0-9]+#", $password1))
{
echo $passnum = "Password must include at least one number!";
}
if (!preg_match("#[a-zA-Z]+#", $password1))
{
echo $passletter = "Password must include at least one letter!";
}
if ($password1 <> $password2)
{
echo $passmatch = "Passwords don't match";
}

if(!(isset($emailvalid) || isset($passlength) || isset($passnum) || isset($passletter) || isset($passmatch))) {
mysqli_query($con,"INSERT INTO pass (Name,Username,Email,Password) VALUES     ('$name','$username','$email','$password1')");
 }

mysqli_close($con);
?>


texts: Designing a service/business logic layer that returns useful/consistent messages

texts:
This is a question regarding design of a service or business logic layer that returns or exposes messages meaningful to the user.

RegisterUser method that takes a user.  What should it return? Should it always return

a Service Information object?
a newly created user?
a boolean, and based on the result, you can interrogate this service's error messages?

public bool RegisterUser(User user)
{
    if (String.IsNullOrEmpty(user.EmailAddress) || !user.EmailAddress.IsValidEmailAddress())
    {
        AddMessage(new Message
        {
            Description = "Invalid Email Address",
            Success = false
        });
    }
    if (String.IsNullOrEmpty(user.Password))
    {
        AddMessage(new Message
        {
            Description = "Password is Required",
            Success = false
        });
    }
    return Messages.Count == 0;
}


texts:
I need some guidance on making the following code more idiomatic:

(ns cheaterpress.algorithm
  (:use [clojure.string :only [split lower-case]])
  (:use [clojure.test]))

(def words (split (slurp "words") #"\s"))

(defn string-to-letter-hash [string]
  (loop [letters (seq string) letter-hash {}]
    (if (empty? letters)
      letter-hash
      (let [letter (first letters) letter-freq (get letter-hash letter 0)]
        (recur (rest letters) (assoc letter-hash letter (inc letter-freq)))))))

(defn can-play [word letters index]
  (loop [letters letters index index]
    (if (and (= (inc index) (count word)) (not (= 1 (count word))))
      true
      (let [letter (get word index) frequency (get letters letter 0)]
        (when (not (= 0 frequency))
          (recur (assoc letters letter (dec frequency)) (inc index)))))))

(println
  (time
    (count (doall (filter #(can-play % (string-to-letter-hash "abcdefghijklmnopqrstuvxyz") 0) (map lower-case words))))))

string-to-letter-hash takes a string and returns a map with the letter frequencies, e.g.:

(string-to-letter-hash "hello")
;=> {\h 1 \e 1 \l 2 \o 1}

can-play takes a letter frequency hash and a word, and then it finds out if it can make the word from the letters in the hash map. If it can, it returns true, otherwise, nil.

(can-play "hello" {\h 1 \e 1 \l 2 \o 1} 0)
;=> true
(can-play "lol" {\h 1 \e 1 \l 2 \o 1} 0)
;=> true
(can-play "hello world" {\h 1 \e 1 \l 2 \o 1} 0)
;=> nil

The last bit of code in my script basically gets all the words in a file and finds which of them can be played according to the can-play function.


texts:
Just a little thing I made to load 20 random images from imgur. I looked at the way that imgur references images on its site, and I felt like I could probably generate a random string of letters and numbers that would, on occasion, produce a valid image URL. So I threw this together in PHP, because I am trying to learn PHP. It takes a while to get the 20 that it does, way longer for more. I would like to speed it up, and my current project in PHP is to learn more about classes etc, but I really have no idea where to start.

I would love some feedback! I know this looks real amateur hour, but I am a real amateur, so go easy on me!

BEWARE: not everything on imgur is worksafe, so if you decide to try this code out on your own server, the images returned are truly random with no filter, so no telling what you might see.

    <title>Random imgur Loader</title>

<?php
$gcode1=generateCode(5);
$url3="http://i.imgur.com/".$gcode1.".jpg";
?>

    <img src="<?=$url3?>" alt="">

<?php
$pagepath=$_SERVER["PHP_SELF"];
if ($_GET['numimg']=='') {
    $numimg=20;
} else {
    $numimg=$_GET['numimg'];
}
?>

<?=$numimg?> random imgur images

<?php

function generateCode($length=6) {
    $source='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    $code='';

    for ($i=0; $i<$length; $i++) {
        $code .= $source[(rand() % strlen($source))];
    }

return $code;
}

$ii=1;
while ($ii<=$numimg):
    $gcode=generateCode(5);
    $url="http://i.imgur.com/".$gcode.".jpg";
    $url2="http://www.imgur.com/".$gcode;
    $headerfile=get_headers($url2, 1);
    $http_code=$headerfile[1];
    $imgheader=get_headers($url, 1);
    $imgcode=$imgheader["Content-Type"];
    #echo $imgcode;

    if ($imgcode == 'image/gif') {
        $bcode='red';
    } else {
        $bcode='gray';
    }

    if($http_code!="HTTP/1.1 404 Not Found") {
        print("");
        echo(str_repeat(' ',4096));
        if ($ii % 5 == 0) {
            print("

");
        }
        flush();
        $ii++;
    }
endwhile;
?>

<?php print("
Get $numimg more!
");?>


texts:
I've been running through The Little Schemer, and have hit the example of Peano multiplication.  The solution is given in TLS (reproduced below) -- however what interests me is the order of the algorithm.

(define mX
  (lambda (n m)
    (cond
      ((zero? m) 0)
      (else
        (+ n (mX n (1- m))))
      )))

My understanding is that this sort of operation is to be avoided, as the order of the operation is unnecessarily large.

To that end I've been trying to think of how to convert this to a linear operation (I was able to do so in the case of addition). Nesting two functions occurred to me, but once i do this i am unsure how to measure the order of the function.

(define (mX n m)
  (define (mX-aux n m product)
    (if (zero? m)
      product
      (mX-aux n (1- m) (+ product n))))
  (mX-aux n m 0))

Is this approach linear or recursive? Is there a another way to do this? In particular, is it possible to do this without setting variables?


texts: Unit testing needs only optional methods of protocol in Swift

texts:
I have a protocol which has quite more methods, it looks like:

  protocol MessageService {

    //configuration
    var fetchOfflineMessagesOnLogin: Bool {get set}//default true
    var maxCharsInMessage: UInt {get set}//default 400

    //connection
    var connectionState: ConnectionState { get }
    func login(hostName: String, port: UInt, username: String, password: String)
    func logoutFromService()

    //contacts
    func sendContactRequest(to peerUId: String)
    func acceptContactRequest(from peerUId: String)
    func removeContact(peerUId: String)
  }

I am unit testing the controller class which takes this protocol and operates on it according to various states.
There are some functions in this controller class that only interacts with only one method out of many protocol methods, and I while testing those methods, I wrote following unit test:

func testSendContactRequest() {
    class MessageServiceMock: MessageService {
        func sendContactRequest(to peerUId: String) {
            //tests
        }
    }
    //unit test setup
    let controller = Controller(service: MessageServiceMock())
    //...
}

func testAcceptContactRequest() {
    class MessageServiceMock: MessageService {
        func acceptContactRequest(from peerUId: String) {
            //tests
        }
    }
    //unit test setup
    let controller = Controller(service: MessageServiceMock())
    //...
}

But, apparently, compiler throws error

  MessageServiceMock does not conform to protocol

So I tried to make all the protocol methods optional by adding extension to it as (in test class file only):

fileprivate extension MessageService {

    var fetchOfflineMessagesOnLogin: Bool {
      get { return true }
      set {}
    }
    var maxCharsInMessage: UInt {
      get { return 400 }
      set {}
    }

    var connectionState: ConnectionState {
      return .connecting
    }
    func login(hostName: String, port: UInt, username: String, password: String) {}
    func logoutFromService() {}

    func sendContactRequest(to peerUId: String) {}
    func acceptContactRequest(from peerUId: String) {}
    func removeContact(peerUId: String) {}
}

Now error is gone and everything works fine.

I know other way to make protocol methods optional is using @objc optional keywords, but I can't use those as MessageService contains some Swift value types those are not convertible to ObjC objects.

So, is this solution is acceptable?
Are there any things that I can improve?


texts:
Could someone please point out the error(s) in the given code?  It was downvoted on Stack Overflow without any explanation, but it seems to be working fine for me:

int value(char roman)
{
   switch(roman)
   {
        case 'I':return 1;
        case 'V':return 5;
        case 'X':return 10;
        case 'L':return 50;
        case 'C':return 100;
        case 'D':return 500;
        case 'M':return 1000;
   }
}

int getdec(const string& input)
{
  int sum=0; char prev='%';
  for(int i=(input.length()-1); i>=0; i--)
  {
    if(value(input[i])<sum && (input[i]!=prev))
    {       sum -= value(input[i]);
            prev = input[i];
    }
    else
    {
            sum += value(input[i]);
            prev = input[i];
    }
  }
  return sum;
}

This was the output received from the code:

  I = 1 II = 2 III = 3 IV = 4 V = 5 VI = 6 VII = 7 VIII = 8 IX = 9 X = 10 XI = 11 XII = 12 XIII = 13 XIV = 14 XV = 15 XVI = 16 XVII = 17 XVIII = 18 XIX = 19 XX = 20 XXI = 21 XXII = 22 XXIII = 23 XXIV = 24 XXV = 25 XXVI = 26 XXVII = 27 XXVIII = 28 XXIX = 29 XXX = 30 XXXI = 31 XXXII = 32 XXXIII = 33 XXXIV = 34 XXXV = 35 XXXVI = 36 XXXVII = 37 XXXVIII = 38 XXXIX = 39 XL = 40 MMMMCMXCIX = 4999 CM = 900 XC = 90


texts: PHP 7.3.9: Check if uploaded file is an image (I don't care about the format)

texts:
I just care if it's any of the common formats so that later when I list all files, for those that are images, I can generate previews based on mime type.

So PHP.NET suggest to use exif_imagetype function to check if file is an image. In case of success an integer will be returned indicating one of 18 constants.

The check I do is against an UploadedFile so my method is quite simple. As this is code review. Would you optimize my code to be even better? Thanks for any hints.

/**
 * @link https://www.php.net/manual/en/function.exif-imagetype.php
 *
 * @param UploadedFile $file
 * @return bool
 */
private function isFileImage(UploadedFile $file): bool
{
    $result = exif_imagetype($file->getRealPath());

    return is_int($result) && $result >= 1 && $result <= 18;
}


texts: Ruby function to find numbers whose sum of squares of divisors is a perfect square

texts:
I am doing a problem my buddy gave to me and I have my solution which works but needs to be optimised. I have tried to optimise it as much as I can with my knowledge but it seems there is still room for improvement. I am trying to improve my ruby. Here is the challenge:

Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42. These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764. The sum of the squared divisors is 2500 which is 50 * 50, a square!

Given two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square. 42 is such a number.

The result will be an array of arrays, each subarray having two elements, first the number whose squared divisors is a square and then the sum of the squared divisors.

 def list_squared(m, n)
   array = []
  (m..n).to_a.each do |i|
     q =  (1..i/2).to_a.push(i).map {|x| x**2 if i % x == 0 }.compact.reduce(:+)
     array << [i, q] if Math.sqrt(q) % 1 == 0
   end
 array
end

This works but apparently is inefficient. Could someone point me in the right direction. I am assuming its the "map" but I initially had:

def list_squared(m, n)
 array = []
 (m..n).to_a.each do |i|
   q =  (1..i/2).to_a.select {|x| i % x == 0 }.push(i).map { |x| x**2 }.reduce(:+)
    array << [i, q] if Math.sqrt(q) % 1 == 0
  end
 array
end


texts: Finding the number of boxes that fit into a truck using JavaScript (Followup Q)

texts:
I have made a lot of changes to the code over the course of the evening, but after making most of the suggested changes, the variable that the answer is returning is showing up as "undefined". Could someone please help me find my errors in this code? I have tried and have not been able to find the errors due to my limited knowledge of JS.

<!DOCTYPE html>
<html>
<script>

  ////////////////////////////
 // Code by Zachary Holmes //
////////////////////////////

// This program determines the number of boxes that can fit into the back of a truck

// Declaring box size in centimetres, and converting it into metres
var boxHeight = prompt("What is the height of your box in centimetres?") / 100;
var boxWidth = prompt("What is the width of your box in centimetres?") / 100;
var boxLength = prompt("What is the length of your box in centimetres?") / 100;

// Declaring truck size in metres
var truckHeight = prompt("What is the height of your truck in metres?");
var truckWidth = prompt("What is the width of your truck in metres?");
var truckLength = prompt("What is the length of your truck in metres?");

// Declaring variables used in equation
var heightA = boxHeight > 0 ? ((truckHeight / boxHeight) | 0) : 0;
var widthA = boxWidth > 0 ? ((truckWidth / boxWidth) | 0) : 0;
var lengthA = boxLength > 0 ? ((truckLength / boxLength) | 0) : 0;

var heightB = boxHeight > 0 ? ((truckHeight / boxHeight) | 0) : 0;
var widthB = boxWidth > 0 ? ((truckLength / boxWidth) | 0) : 0;
var lengthB = boxLength > 0 ? ((truckWidth / boxLength) | 0) : 0;

var heightC = boxHeight > 0 ? ((truckWidth / boxHeight) | 0) : 0;
var widthC = boxWidth > 0 ? ((truckHeight / boxWidth) | 0) : 0;
var lengthC = boxLength > 0 ? ((truckLength / boxLength) | 0) : 0;

var heightD = boxHeight > 0 ? ((truckWidth / boxHeight) | 0) : 0;
var widthD = boxWidth > 0 ? ((truckLength / boxWidth) | 0) : 0;
var lengthD = boxLength > 0 ? ((truckHeight / boxLength) | 0) : 0;

var heightE = boxHeight > 0 ? ((truckLength / boxHeight) | 0) : 0;
var widthE = boxWidth > 0 ? ((truckWidth / boxWidth) | 0) : 0;
var lengthE = boxLength > 0 ? ((truckHeight / boxLength) | 0) : 0;

var heightF = boxHeight > 0 ? ((truckLength / boxHeight) | 0) : 0;
var widthF = boxWidth > 0 ? ((truckHeight / boxWidth) | 0) : 0;
var lengthF = boxLength > 0 ? ((truckWidth / boxLength) | 0) : 0;

var multiplesA = heightA * widthA * lengthA;
var multiplesB = heightB * widthB * lengthB;
var multiplesC = heightC * widthC * lengthC;
var multiplesD = heightD * widthD * lengthD;
var multiplesE = heightE * widthE * lengthE;
var multiplesF = heightF * widthF * lengthF;

var arrayA = [multiplesB, multiplesC, multiplesD, multiplesE, multiplesF];
var arrayB = [multiplesA, multiplesC, multiplesD, multiplesE, multiplesF];
var arrayC = [multiplesB, multiplesA, multiplesD, multiplesE, multiplesF];
var arrayD = [multiplesB, multiplesC, multiplesA, multiplesE, multiplesF];
var arrayE = [multiplesB, multiplesC, multiplesD, multiplesA, multiplesF];
var arrayF = [multiplesB, multiplesC, multiplesD, multiplesE, multiplesA];

// Calculations
var boxCount;

if (multiplesA > arrayA)
{
boxCount = multiplesA;
}

else if (multiplesB > arrayB)
{
boxCount = multiplesB;
}

else if (multiplesC > arrayC)
{
boxCount = multiplesC;
}

else if (multiplesD > arrayD)
{
boxCount = multiplesD;
}

else if (multiplesE > arrayE)
{
boxCount = multiplesE;
}

else if (multiplesF > arrayF)
{
boxCount = multiplesF;
}

// Output answer
alert("You can fit up to " + boxCount + (1 == boxCount ? " box" : " boxes") + " into the truck");

</script>
</html>


texts:
I am trying create an algorithm for finding the zero crossing (check that the signs of all the entries around the entry of interest are not the same) in a two dimensional matrix, as part of implementing the Laplacian of Gaussian edge detection filter for a class, but I feel like I'm fighting against Numpy instead of working with it.

import numpy as np

range_inc = lambda start, end: range(start, end+1)

# Find the zero crossing in the l_o_g image
# Done in the most naive way possible
def z_c_test(l_o_g_image):
    print(l_o_g_image)
    z_c_image = np.zeros(l_o_g_image.shape)
    for i in range(1, l_o_g_image.shape[0] - 1):
        for j in range(1, l_o_g_image.shape[1] - 1):
            neg_count = 0
            pos_count = 0
            for a in range_inc(-1, 1):
                for b in range_inc(-1, 1):
                    if a != 0 and b != 0:
                        print("a ", a, " b ", b)
                        if l_o_g_image[i + a, j + b] < 0:
                            neg_count += 1
                            print("neg")
                        elif l_o_g_image[i + a, j + b] > 0:
                            pos_count += 1
                            print("pos")
                        else:
                            print("zero")

            # If all the signs around the pixel are the same
            # and they're not all zero
            # then it's not a zero crossing and an edge.
            # Otherwise, copy it to the edge map.
            z_c = ((neg_count > 0) and (pos_count > 0))

            if z_c:
                print("True for", i, ",", j)
                print("pos ", pos_count, " neg ", neg_count)
                z_c_image[i, j] = 1

    return z_c_image

Here is the test cases it should pass:

test1 = np.array([[0,0,1], [0,0,0], [0,0,0]])
test2 = np.array([[0,0,1], [0,0,0], [0,0,-1]])
test3 = np.array([[0,0,0], [0,0,-1], [0,0,0]])
test4 = np.array([[0,0,0], [0,0,0], [0,0,0]])
true_result = np.array([[0,0,0], [0,1,0], [0,0,0]])
false_result = np.array([[0,0,0], [0,0,0], [0,0,0]])

real_result1 = z_c_test(test1)
real_result2 = z_c_test(test2)
real_result3 = z_c_test(test3)
real_result4 = z_c_test(test4)

assert(np.array_equal(real_result1, false_result))
assert(np.array_equal(real_result2, true_result))
assert(np.array_equal(real_result3, false_result))
assert(np.array_equal(real_result4, false_result))

How do I vectorize checking a property in a matrix range? Is there a quick way of accessing all of the entries adjacent to an entry in a matrix?


texts:
What are my options on how the loginToNetflix method is called? Is there a more clean and elegant way of accomplishing this?

loginToNetflix(credentials.username, credentials.password);

function loginToNetflix (username, password) {
casper.start('https://www.netflix.com/Login?locale=en-US', function() {
    this.echo('Attempting login to Netflix - filling and submitting login form');

    this.fill('form#login-form', {
            'email':    username,
         'password':    password,
       'RememberMe':    true
    }, true);
});

casper.then(function() {
    this.echo('Login Complete - Please check the cookie as defined in command line');
    //save the cookie for use by netflix scraper api
    var cookies = JSON.stringify(phantom.cookies);
    fs.write("netflix-cookies.txt", cookies, 644);
});

casper.run(function () {
    this.echo('Done - Exiting!');
    casper.exit();
});
}


texts:
I wrote a program for analyzing pictures. The problem I'm having is very slow processing time for medium images like 800x800. I think the root of the problem for this is the for loop where I complete my NumPy array with values. The main task for the program is to count how many times x intensity shows in each color channel and then plot them in a histogram. For example, in the end we will be able to see how many times do we get intensity 200 in red channel and so on.

My code is probably very hard to read but I tried to add comments to make things easier.

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

#Load an image
fname = 'picture1.jpg'
image_grey = Image.open(fname).convert("L")
image_rgb = Image.open(fname).convert("RGB")

arrey_grey = np.asarray(image_grey)
arrey_rgb = np.asarray(image_rgb)

#Get image size
with Image.open('picture1.jpg') as img:
    width, height = img.size

size = width * height

#Plot the uploaded image both grey and rgb
plt.imshow(arrey_grey, cmap='gray')
plt.show()

plt.imshow(arrey_rgb)
plt.show()

#Define numpy arrey for each color channel
matrix_red = np.zeros((256, 4),dtype = object)
matrix_red[:,1] = int(0)
matrix_red[:,2:] = float(0)

matrix_green = np.zeros((256, 4),dtype = object)
matrix_green[:,1] = int(0)
matrix_green[:,2:] = float(0)

matrix_blue = np.zeros((256, 4),dtype = object)
matrix_blue[:,1] = int(0)
matrix_blue[:,2:] = float(0)

# Completing first column with 0-255
for i in range(256):
    matrix_red[i][0] = i
    matrix_green[i][0] = i
    matrix_blue[i][0] = i

# Counting intensity for each color channel
for i in range(width):
    Matrix_Width = arrey_rgb[i]
    for i in range(height):
        Matrix_Height = Matrix_Width[i]
        Red_Value = Matrix_Height[0]
        Green_Value = Matrix_Height[1]
        Blue_Value = Matrix_Height[2]
        for i in range(256):
            if (matrix_red[i][0] == Red_Value):
                matrix_red[i][1] = matrix_red[i][1] + 1
            if (matrix_green[i][0] == Green_Value):
                matrix_green[i][1] = matrix_green[i][1] + 1
            if (matrix_blue[i][0] == Blue_Value):
                matrix_blue[i][1] = matrix_blue[i][1] + 1

# Data for task ahead
Hx = 0
for i in range(256):
    matrix_red[i][2] = matrix_red[i][1] / size
    Hx = (matrix_red[i][2] + matrix_red[i][3]) + Hx
    matrix_red[i][3] = Hx

#Plotting results
Frequencie_Red = np.zeros((256, 1),dtype = object)
Frequencie_Red[:,0] = int(0)

Frequencie_Green = np.zeros((256, 1),dtype = object)
Frequencie_Green[:,0] = int(0)

Frequencie_Blue = np.zeros((256, 1),dtype = object)
Frequencie_Blue[:,0] = int(0)

Intensity = np.zeros((256, 1),dtype = object)
Intensity[:,0] = int(0)

for i in range(256):
    Frequencie_Red[i] = matrix_red[i][1]
    Frequencie_Green[i] = matrix_green[i][1]
    Frequencie_Blue[i] = matrix_blue[i][1]

for i in range(256):
    Intensity[i] = i

pos = Intensity
width = 1.0

ax = plt.axes()
ax.set_xticks(pos + (width / 2))
ax.set_xticklabels(Intensity)

plt.bar(pos, Frequencie_Red, width, color='r')
plt.show()

plt.bar(pos, Frequencie_Green, width, color='g')
plt.show()

plt.bar(pos, Frequencie_Blue, width, color='b')
plt.show()

As i got pointed out in comment section I added test image and capture with my results.

This is the image I'm using to do my calculations.

The result looks like this. Where Red histogram is red channel and so on:

*Small note, I have no idea why under the first histogram there are black line.


texts: Caching that resets itself under certain circumstances: Reduce boiler plate code

texts:
In my machine learning programs I have the typical situation where I need to perform certain operations on data, which results in the following graph:

data --op A--> intermediate_state --op B--> final result type 1
data --op A--> intermediate_state --op C--> final result type 2
data --op A--> intermediate_state --op D--> final result type 3

So in order to not have to repeat operation A all the time I provide a "fit" method, which implements operation A.
Then, I implement transformation methods that implement the other operations.
However, since I usually only need some of the final results in the graph leaves, I want to calculate those on the one hand lazily, but then cache the result.
Since the operations require a parameter, I provide this one in the constructor.
I also need to pass a parametrized object with the same parametrization to different parts of the the program, where the data of operation A changes, without the parametrization changing.
That is the reason why fit is it's own method and not part of the constructor.
Also, because of that I cannot simply cache the results of the operations that are not A, without resetting them after invoking a new fit.
Here is my result in Python:
class MyClass:

    def __init__(self, parameter):
        self.parameter = parameter

    # expensive machine learning fitting
    def fit(self, data) -> MyClass:
        self.intermediate_data_ = data + self.parameter + 2
        self._complex_transform1 = None
        self._complex_transform2 = None
        return self

    # expensive machine learning operation version 1
    @property
    def complex_transform1(self):
        if self._complex_transform1 is None:
            self._complex_transform1 = self.intermediate_data_ / self.parameter / 2
        return self._complex_transform1

    # expensive machine learning operation version 2
    @property
    def complex_transform2(self):
        if self._complex_transform2 is None:
            self._complex_transform2 = self.intermediate_data_ / self.parameter / 5
        return self._complex_transform2

The problem I have with this approach is that I am repeating quite a bit of boiler plate code.
(Note, that I have many more operations that are not A.)
Namely:

The variables self._complex_transform1 and self._complex_transform2

The constructs if self._complex_transform1 is None: could be reduced from
     if self._complex_transform1 is None:
         self._complex_transform1 = self.intermediate_data_ / self.parameter / 2
     return self._complex_transform1

to
        return self.intermediate_data_ / self.parameter / 2

and I would save a nesting.
I was thinking of defining a container class that contains the results and is reset by fit. But I do not see how to implement this without basically introducing the same about of boilerplate code into the transform methods.
Some decorator-approach might be great, but I am not sure how to approach this.


texts:
I recently wrote this up and am wondering if there is a better way to achieve the results I want.

Essentially, we're taking a given year and adding 'th, nd, rd, st' depending on the digit.

Any suggestions on how to shorten this code and make it better?

Keep in mind that this is taking centuries that change every 01st year. For example, year 2000 is the 20th century, but 2001 is the 21st century.

def which_century(string)
  year = string.to_i
  modifier = 1

  return "1st century" if year < 101

  if year > 100 && string.end_with?("00")
    modifier -= 1
  end

  century = year / 100 + modifier
  p century
  if century > 10 && century < 20
    return century.to_s << "th century."
  end

  second_digit = century % 10

  case second_digit
  when 1 then century.to_s << "st century"
  when 2 then century.to_s << "nd century"
  when 3 then century.to_s << "rd century"
  else
    century.to_s << "th century"
  end
end

puts "Type in a year:"
answer = gets.chomp
p which_century(answer)


texts: Substitution of different occurrences of a string with changing patterns

texts:
I need to parse an invalid JSON string in which I find many repetitions of the same key, like the following snippet:

[...]
"term" : {"Entry" : "value1", [.. other data ..]},
"term" : {"Entry" : "value2", [.. other data ..]},
[...]

I thought of appending a suffix to each key, and I do it using the following code:

word = "term"
offending_string = '"term" : {"Entry"'
replacing_string_template = '"%s_d" : {"Entry"'

counter = 0
index = 0
while index != -1:
    # result is the string containing the JSON data
    index = result.find(offending_string, index)
    result = result.replace(offending_string,
                replacing_string_template % (word, counter), 1)
    counter += 1

It works, but I'd like to know if it is a good approach and if you would do this in a different way.


texts: Simple jQuery validation script works but it uses a ton of if/else statements

texts:
I've a jQuery validation script to check all form fields for a valid value and prevent form submission and display an error message if any fields fail. It was requested that the validation script not check fields one by one, but that it check and highlight ALL fields that failed validation. It works perfectly. But I am more a front-end person, than a real developer and even though it works I feel like it's twice as long as it needs to be.

I've tried to combine logic where I could but it still feels like I have a ton of if/else statements and it just doesn't seem very...well...elegant.

A little more background: The script is used by three different forms which each have a different number of fields (form 1 has only email, form 2 has email and country, form 3 has email, country, and gender). The script checks for a form ID before bothering to validate any fields that aren't there.

$("#footer_newsletter").submit(function(){
var hasValue = true;
var validEmail = true;
// validate email
if($.trim($("#newsletter_email").val()) == ""){
  $("#newsletter_email").addClass("error");
  hasValue = false;
}else{
  $("#newsletter_email").removeClass("error");
}if(!$("#newsletter_email").val().match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.([A-Z]{2,4})$/i)){
  $("#newsletter_email").addClass("error");
  validEmail = false;
}else{
  $("#newsletter_email").removeClass("error");
}
if(parseInt($("#newsletter_form_id").val()) > 0){
// validate country
  if($("#newsletter_country").prop("selectedIndex") == 0){
      $("#newsletter_country").addClass("error");
      hasValue = false;
  }else{
    $("#newsletter_country").removeClass("error");
  }
}
if(parseInt($("#newsletter_form_id").val()) > 1){
  // validate gender
  if($(".email_signup_form_wrapper :radio:checked").val() == undefined){
      $("#newsletter_gender").addClass("error");
      hasValue = false;
  }else{
    $("#newsletter_gender").removeClass("error");
  }
}
if(!validEmail && !hasValue){
  $("#error_required_field").show();
  return false;
}else if(!validEmail && hasValue){
  $("#error_valid_email").show();
  $("#error_required_field").hide();
  return false;
}else if(validEmail && !hasValue){
  $("#error_required_field").show();
  $("#error_valid_email").hide();
  return false;
}else if(validEmail && hasValue){
  $("#error_valid_email").hide();
  $("#error_required_field").hide();
  $("#newsletter_submit").hide();
  $("#newsletter_sending").show();
  $.ajax({ type: "get", url: $("#footer_newsletter").attr("action"), data: $("#footer_newsletter").serialize(), dataType: "script" });
  return false;
}

My basic thinking behind the script is this:

In all fields I have to check for a value, and in the email field I have to check for a VALID value so I create two variables at the top of the script to record whether a field has a value, and whether or not that value is valid if it's the email field.
Look at each field and test it's value. If it fails add a class of "error", otherwise remove the class "error".
Then, if any of the following are true: The form has empty fields and does not have a valid email address, or the form has all fields filled out but does not have a valid email address, or the form has a valid email address but not all fields are filled out then display the appropriate error message.
Otherwise, everything looks good so submit the form.

Here is a fiddle where you can see it in action. For simplicity I've removed the submission bit and the command to show the loading graphic.

http://jsfiddle.net/judah/Ppewz/21/


texts:
public function getData ($term) {
        $db = Database::getInstance();

        $term = htmlentities($term);

        //Kill the script if the term is blank
        if ($term == "") {
            die();
        }

        $query = "SELECT * FROM coils WHERE name like '%$term%' or
                                            resistance like '%$term%' or
                                            wraps like '%$term%' or
                                            wire_one like '%$term%' or
                                            wire_two like '%$term%' or
                                            wire_three like '%$term%' or
                                            wire_four like '%$term%' or
                                            wire_five like '%$term%' or
                                            wire_six like '%$term%'
                                            LIMIT 25";
        $prepareQuery = $db->getConnection()->prepare($query);
        $result = $prepareQuery->execute();
        $this->rowCount = $prepareQuery->rowCount();

        //Return the Query
        return $prepareQuery;
    }


texts: Scraping data unveiling a button from craigslist

texts:
I've written some code to parse the names and phone numbers from craigslist. It starts from the link in "m_url" then goes one layer deep to parse the name and then again another layer deep to parse the phone number. Note that it goes 2 layer deep only when it sees "show contact button" on that page so that it can unveil the phone number from that link to scrape. It only prints the result when it sees the button on that page. That's because there are around 120 names on that page but it prints only those containing that specific button. Sometimes when I come across such "show contact button" link within a page from where I am supposed to harvest data, I get frightened. That's why I tried to work on it. It works smoothly now. Any improvement on this script will be very helpful.

import re
import requests
from lxml import html

m_url = "http://bangalore.craigslist.co.in/search/reb?s=120"
base = "http://bangalore.craigslist.co.in"

def get_link(url):
    page1 = requests.get(url).text
    tree = html.fromstring(page1)
    for row in tree.xpath('//li[@class="result-row"]'):
        links = base + row.xpath(".//a[contains(concat(' ', @class, ' '), ' hdrlnk ')]/@href")[0]
        process_doc(links)

def process_doc(medium_link):

    page2 = requests.get(medium_link).text
    tree = html.fromstring(page2)
    try:
        name = tree.xpath('//span[@id="titletextonly"]/text()')[0]
    except IndexError:
        name = ""
    try:
        link = base + tree.xpath('//section[@id="postingbody"]//a[@class="showcontact"]/@href')[0]
    except IndexError:
        link = ""

    parse_doc(name, link)

def parse_doc(title, target_link):

    if target_link:
        page = requests.get(target_link).text
        tel = re.findall(r'\d{10}', page)[0] if re.findall(r'\d{10}', page) else ""
        print(title, tel)

get_link(m_url)

Pics of that button:


texts: Base adder, given base and two numbers of that base, it adds them

texts:
Nothing more to add than the title. Looking for code review, optimizations and best practices.

public final class BaseAdder {

    private BaseAdder() { }

    /**
     * Given two numbers and their bases, adds the number
     * and returns the result in the same base.
     *
     * This code supports max-base 26.
     *
     *
     * @param num1  the first number to be added
     * @param num2  the second number to be added
     * @param base  the base of the numbers
     */
    public static String add (String num1, String num2, int base) {

        if (base <  2) throw new IllegalArgumentException("The base should at least be 2. Input base is: " + base);
        if (base > 26) throw new IllegalArgumentException("The base should be less than 26. Input base is: " + base);

        /*
         * http://stackoverflow.com/questions/355089/stringbuilder-and-stringbuffer-in-java
         * and StringBuilder is intended as a drop in replacement for StringBuffer where synchronisation is not required –  Joel Dec 23 '09 at 8:52
         *
         */
        final StringBuilder stringBuilder = new StringBuilder();
        int carry = 0;
        for (int i = num1.length() - 1; i >= 0; i--) {
            int x =  getIntValue(num1.charAt(i), base) +   getIntValue(num2.charAt(i), base) + carry;

            if (x >= base) {
                carry = 1;
                x = x - base;
            } else {
                carry = 0;
            }
            stringBuilder.append(getCharValue(x, base));
        }

        if (carry == 1) stringBuilder.append(1);

        return stringBuilder.reverse().toString();
    }

    public static int getIntValue(char ch, int base) {
        if (ch > getCharValue(base - 1, base)) {
            throw new IllegalArgumentException(" invalid character " + ch + " for input base " + base);
        }

        if (ch >= '0' &&  ch <= '9') {
            return ch - '0';
        }
        Character.toUpperCase(ch);
        return ch - 'A' + 10;
    }

    public static char getCharValue(int x, int base) {
        if (x >= base) {
            throw new IllegalArgumentException(" invalid number " + x + " for input base " + base);
        }

        if (x >= 0 &&  x <= 9) {
            return (char) (x + '0');
        }

        return (char)(x + 'A' - 10);
    }

public static void main(String[] args) {
    assertEquals("100", BaseAdder.add("10", "10", 2));
    assertEquals("11", BaseAdder.add("10", "01", 2));

    assertEquals("25", BaseAdder.add("10", "15", 10));

    assertEquals("4A", BaseAdder.add("1C", "2D", 15));
    assertEquals("1B9", BaseAdder.add("CC", "ED", 16));

    assertEquals("1B", BaseAdder.add("C", "D", 14));
    assertEquals("1A", BaseAdder.add("C", "D", 15));
    assertEquals("19", BaseAdder.add("C", "D", 16));
}
}


texts:
I have tried to incorporate comments from my previous code review into this. So, I am hoping for less mistakes. If you spot any, please let me know mercilessly!

#include <iostream>
#include <queue>

void printsub(int* p, int len, std::queue<int> q) {

    if (!len) {
        while(!q.empty()) {
            std::cout << q.front() << " ";
            q.pop();
        }
        std::cout << "\n";
        return;
    }

    std::queue<int> t1(q);
    t1.push(p[0]);
    printsub(&(p[1]), len - 1, t1);

    std::queue<int> t2(q);
    printsub(&(p[1]), len - 1, t2);
}

int main() {
    int arr[] = {1, 2, 3, 4, 5, 6};

    std::queue<int> q;
    printsub(arr, ((sizeof(arr))/(sizeof(arr[0]))), q);
}


texts: x86 assembly function that determines whether an array is continuous

texts:
I wrote an x86 assembly function using MASM that tests for whether or not an array is continuous.  That is to say, if an array with length n that starts with the value k, all the subsequent entries in the array are k+1, k+2, ... k+n.

I am interested in becoming better at x86 and x86-64 assembly and I'm wondering if I could get some feedback on the quality of:

The algorithm itself
Comments - am I too thorough? Not thorough enough?
Label names - are they typically what you would expect handwritten x86 labels to look like?
The part at the end where I set eax in three different cases then jump to a final pop esi/ret instruction - this felt rather ugly to me, but I couldn't think of a better way to do it

Assembly code:

.386
.MODEL FLAT, C
.CODE
; Checks if an array if integers is continuously increasing.
; I.e. if an array of length n starts with element k, all
; the elements in the array are k, k+1, k+2, k+3... k+n
; Uses:
;   ESI - Loop counter (when loop >= length, done looping)
;   ECX - Data counter (compare for equality with k, k+1, etc...)
;   EDX - Pointer to start of array
; Params:
;   ESP+4 - Array pointer
;   ESP+8 - Array length
; Because of the PUSH ESI instruction at the start of the function,
; the value relative to ESP increases by 4 when they are accessed
; Returns:
; In EAX:
;   1 - If the array is continuous
;   0 - If the array is not continuous
;  -1 - If the function was passed an invalid (<1) length
iscontinuous PROC
    ; Preserve ESI
    push    esi
    ; Check for valid (>=1) length
    mov esi, dword ptr [esp+12]
    cmp esi, 1
    jl  invalid_length
    ; Load data array pointer into EDX and deref into ECX (for first number in data)
    mov edx, dword ptr [esp+8]
    mov ecx, dword ptr [edx]
    ; Set EAX as loop counter (start at 0 and keep going till EAX=ESI)
    xor eax, eax
continuity_loop:
    ; Compare array element with current position of counter (pointer to array + offset * sizeof(int))
    cmp dword ptr [edx+eax*4], ecx
    jne not_continuous
    inc     ecx
    inc eax

    cmp eax, esi
    jl  continuity_loop

; If we reached here without branching into not_continuous, we are good to go; return 1 indicating success
    mov eax, 1
    jmp end_iscontinuous
not_continuous:
    xor eax, eax
    jmp end_iscontinuous
invalid_length:
    mov eax, -1
end_iscontinuous:
    pop esi
    ret
iscontinuous ENDP
END

C code for test driver:

#include <stdio.h>

int __cdecl iscontinuous(int *data, int len);

int __cdecl wmain(int argc, wchar_t *argv[])
{
    int test[20] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20 };
    wprintf_s(L"Test 1 (expected pass): test[0..11] = %d\nTest 2 (expected fail): test[0..20] = %d\nTest 3 (expected pass): test[13..20] = %d\n",
        iscontinuous(test, 11),
        iscontinuous(test, 20),
        iscontinuous(test+12, 7)
    );
    return 0;
}

Program output:

Test 1 (expected pass): test[0..11] = 1
Test 2 (expected fail): test[0..20] = 0
Test 3 (expected pass): test[13..20] = 1


texts: What is wrong with this CancellationTokenSource example

texts:
Anybody mind providing an opinion on whether or not this is a good or bad example of Task Cancellation and why. I have my own opinion and I've been told that its baseless, just trying to find out who is off base. I don't think its me, but I am okay with it being me. I just need to know its me so I can evolve if required.
class Program
{
    static void Main()
    {
        ImportSource();
        Console.ReadKey();
    }
    public static void ImportSource()
    {
        var cancellationTokenSource = new CancellationTokenSource();
        var token = cancellationTokenSource.Token;
        var task1 = Task.Run(() => Import(token), token);
        Thread.Sleep(500);
        // if we attempt to cancel the token
        CancelToken(cancellationTokenSource);
    }
    public static void CancelToken(CancellationTokenSource cancellationTokenSource)
    {
        Console.WriteLine("Cancellation in process!");
        cancellationTokenSource.Cancel();
    }
    static void Import(CancellationToken token)
    {
        int i = 0;
        do
        {
            Thread.Sleep(100);
            // check if the token is cancelled
            if (token.IsCancellationRequested)
            {
                Console.WriteLine("Token was cancelled");
                break;
            }
            else
            {
                Console.WriteLine("Importing data is in process!");
                Import(token);
                i++;
            }

        } while (i < 1);
    }
}
```


texts:
I was challenged to implement a mechanmism to support indexed properties in a class structure.

I wanted to avoid the need to implement an abstract property indexer class every time you want to implement a new T just because the backing store has changed. Semantically, if C# did provide indexed properties, the get/set logic would be on the class declaring the indexed property (as there would be no type).

So I implemented the following logic:

public interface IIndexedProperty<TKey, TValue>
{
    TValue this[TKey index] { get; set; }
}
public class IndexedProperty<TKey, TValue> : IIndexedProperty<TKey, TValue>
{
    private Func<TKey, TValue> Getter { get; set; }
    private Action<TKey, TValue> Setter { get; set; }
    public IndexedProperty(Func<TKey, TValue> getter, Action<TKey, TValue> setter)
    {
        this.Getter = getter;
        this.Setter = setter;
    }
    public TValue this[TKey index]
    {
        get
        {
            return Getter(index);
        }
        set
        {
            Setter(index, value);
        }
    }
}

An example implementation:

public class MyClass
{
    public IIndexedProperty<string, string> Values { get; private set; }
    private Dictionary<string, string> ValueDictionary { get; set; }
    public MyClass()
    {
        Values = new IndexedProperty<string, string>(index => ValueDictionary[index], (index, value) => ValueDictionary[index] = value);
        ValueDictionary = new Dictionary<string, string>();
    }
}

What he doesn't like about this is twofold:

It isn't reusable (you have to implement the logic in your defining class each time you use it)
It holds references to two delegates.

Can you see ways in which this can be improved?


texts: Search products from database on base of search filters

texts:
I am writing a code to search Product database and return result to user.
user can select various options like product attributes that varies from product to product, also there may be case like for single attribute there can be multiple value. For Example user can select brand as filter and can select from given brand under brand option. There can be multiple tag for filter like this

Please guide me to improve this code, is there any design pattern i should use or can replace some statement with other to improve in any Sense.

public Models.Custom_Model.SubcategoryProductViewModel SubCategoryAds(long subcategoryId, Models.Custom_Model.SearchModel search)
    {
        var products = _db.products.Include(a => a.category).Include(c => c.subcategory).Include(c=>c.productattributes).Where(c => c.SubCategoryId == subcategoryId && c.subcategory.isActive && c.category.isActive);
        switch (search.criteria)
        {
            case Enum.SortingCriteria.New:
                products = products.OrderByDescending(c => c.ProductId);
                break;
            case Enum.SortingCriteria.Discount:
                products = products.OrderByDescending(c => c.Discount);
                break;
            case Enum.SortingCriteria.PricebyAsc:
                products = products.OrderBy(c => c.Price);
                break;
            case Enum.SortingCriteria.PricebyDsc:
                products = products.OrderByDescending(c => c.Price);
                break;
        }
        if(search.filter != null)
        {
            var fs = search.filter.SelectMany(c => c.Value.Select(a => new Models.Custom_Model.IdName {Id = c.Id,Name = a}));
            products.Where(z=>((z.productattributes.Select(c=>new Models.Custom_Model.IdName {Id = c.AttributeId,Name = c.Value})).Intersect(fs)).Any());
        }
        var productids = products.Skip((search.pageNo - 1) * search.pagesize).Take(search.pagesize).Select(c => c.ProductId).ToList();
        var subcategory = _db.subcategories.Include(c => c.category).SingleOrDefault(c => c.SubCategoryId == subcategoryId);
        string Name = string.Empty;
        Models.Custom_Model.IdName category = null;
        if (subcategory != null)
        {
            Name = subcategory.Name;
            category = new Models.Custom_Model.IdName() { Id = subcategory.CategoryId, Name = subcategory.category.Name };
        }
        var count = products.Count();
        var product = Business_Logic.ProductTile.ToproductTile(productids, _db);
        return new  Models.Custom_Model.SubcategoryProductViewModel {Category = category ,Name = Name,TotalItems = count, Products = product };
    }

search Model

public class SearchModel
{
    private int _pagesize = 50;

    public int pagesize
    {
        get { return _pagesize; }
        set { _pagesize =value; }
    }

    private int _pageNo = 1;

    public int pageNo
    {
        get { return _pageNo; }
        set { _pageNo = value; }
    }

    private Enum.SortingCriteria _criteria = Enum.SortingCriteria.New;

    public Enum.SortingCriteria criteria
    {
        get { return _criteria; }
        set { _criteria = value; }
    }

    private List<FiltersViewModel> _filter = null;

    public List<FiltersViewModel> filter
    {
        get { return _filter ; }
        set { _filter  = value; }
    }

}

FilterViewModel

public class FiltersViewModel
{
    public long Id { get; set; }

    public IEnumerable<string> Value { get; set; }
}


texts: Formatting a string in Python with three possible replacement fields

texts:
I'm looking for a much simpler way of formatting a string in Python which will have a different number of replacement fields in different cases. Here's what I'm doing now, which is working fine:

if '{yes}' in reply and '{value}' in reply:
    reply = reply.format(yes=get_yes(), value=value)
elif '{no}' in reply and '{value}' in reply:
    reply = reply.format(no=get_no(), value=value)
elif '{yes}' in reply:
    reply = reply.format(yes=get_yes())
elif '{no}' in reply:
    reply = reply.format(no=get_no())
elif '{value}' in reply:
    reply = reply.format(value=value)

The only problem is that this code has a Cognitive Complexity of 11 on Code Climate, which is higher than the allowed value of 5, and so I'm trying to find out a way of reducing it.

Additional information about variables and methods

reply is a string with will have one of the following combinations of replacement fields:

{yes} and {value}
{no} and {value}
{yes} only
{no} only
{value} only
no replacement field

get_yes() randomly returns a string that has the same meaning as "yes" ("yeah", "yep" etc.)
get_no() randomly returns a string that has the same meaning as "no" ("nah", "nope" etc.)
value is a numeric value (integer or float)


texts:
I have two arrays, each with shape (1, 51, 150, 207)

I need to add them such that:

newarray[0][0][0][0] = array1[0][0][0][0] + array2[0][0][0][0]
newarray[0][0][0][1] = array1[0][0][0][1] + array2[0][0][0][1]

for every element in the array.

Currently I'm creating a new array using nested while loops but this approach is extremely time consuming. Can anyone offer a better solution?

H = 0
NS = 0
EW = 0
height = []
while H < 51:
    northsouth = []
    while NS < 150:
        eastwest = []
        while EW < 207:
            eastwest.append(PH[0][H][NS][EW] + PHB[0][H][NS][EW])
            EW += 1
            print eastwest
        northsouth.append(eastwest)
        NS += 1
        print northsouth
    height.append(northsouth)
    H =+ 1


texts: Plugin architecture to extend/customize behavior of white label swift based application

texts:
I have a white label swift based application in which I need to change behavior depending on the customers. I would like to add that behavior in a dedicated framework in classes/struct that would be kind of plugins.
The needs are basically always the same :

extending C.D. data model
synchronizing new entities with backend
adding a new view controller between two existing...

So this is what I have been drafting so far, and I would like some advices / external views.
enum PluginType {
    case navigationPlugin, synchronizationPlugin, databasePlugin
}

protocol BasePluginProtocol {
    static var type: PluginType { get }
}

protocol NavigationPluginProtocol : BasePluginProtocol {
    func handle(navigationEvent : String, from presenter: UIViewController?)
}

protocol SynchronizationPluginProtocol : BasePluginProtocol {
    // returns names of entities to be synchronized with backend in the appropriate order
    func orderedSynchronizableEntities([String]) -> [String]
}

protocol DatabasePluginProtocol : BasePluginProtocol {
    // returns bundle containing CoreData customer model
    func databaseBundle(bundle : Bundle)
}

extension NavigationPluginProtocol {
    static var type: PluginType { return .navigationPlugin }
}

extension SynchronizationPluginProtocol {
    static var type: PluginType { return .synchronizationPlugin }
}

extension DatabasePluginProtocol {
    static var type: PluginType { return .databasePlugin }
}

class PluginManager {

    static var plugins = [BasePluginProtocol.Type]()

    static func plugin(_ pluginType : PluginType) -> BasePluginProtocol.Type? {
        return plugins.first(where: { $0.type == pluginType })
    }

    static public func registerPlugin(pluginType : BasePluginProtocol.Type) {
        plugins.append(pluginType)
    }
}

// Usage sample :

let plugin = PluginManager.plugin(.synchronizationPlugin) as! SynchronizationPlugin
let defaultEntitiesToSynchronize = [ ... ]
SynchronizationManager.synchronize(plugin.orderedSynchronizableEntities(defaultEntitiesToSynchronize))


texts:
I am trying to achieve a getter/setter behaviour that will reduce code in C++. The interface I would like to achieve is for example:

MyClass a;
a.velocity = 15; // Will dispatch a member function of MyClass responsible for setting "velocity".
someFloatFunc( a.velocity ); // Will implicitly convert to the argument type of someFloatFunc if necessary

I have come up with the following. Suggestions, comments, gotchas, are welcomed.

#include <iostream>
#include <functional>

#include <cassert>

using namespace std;

template <class T>
class encapsulate
{
public:
    typedef T                               value_type;
    typedef std::function<void( const T& )> setter_type;

    // Disable things like auto b = a.v;. Access value like: int b = a.v;
    encapsulate( const encapsulate& )=delete;

    encapsulate( T&in, setter_type fin ):
        v( in ),
        f(fin)
    {

    }

    encapsulate &operator= ( const T&o )
    {
        f( o );
        return *this;
    }

    operator T() const { return v; }

private:
    T           &v;
    setter_type f;
};

#define GETSET( TYPE, VARPUBLIC, VARPRIVATE, CLASS, SETTER ) \
    encapsulate<TYPE> VARPUBLIC {VARPRIVATE, std::bind(&CLASS::SETTER,this,std::placeholders::_1 ) };\
    private:  \
    TYPE VARPRIVATE; \
    public:

#define GETSETDEFAULT( TYPE, VARPUBLIC, VARPRIVATE, CLASS, SETTER, DEF ) \
    encapsulate<TYPE> VARPUBLIC {VARPRIVATE, std::bind(&CLASS::SETTER,this,std::placeholders::_1 ) };\
    private:  \
    TYPE VARPRIVATE = DEF; \
    public:

template <class T>
class A
{
public:

    GETSET( T, v, v_, A, setValue )
    void setValue( const T &other )
    {
        cout << "Setting value..." << endl;
        v_ = other;
    }

    GETSETDEFAULT( double, g, g_, A, setGrayLevel, 0 )
    void setGrayLevel( const double &gl )
    {
        if ( gl < 0 )
        {
            g_ = 0;
            return;
        }

        if ( gl > 1 )
        {
            g_ = 1;
            return;
        }

        g_ = gl;
    }
};

const double testval = 215.33;

//Implicit conversion test
void printInt( const int &c )
{
    std::cout << "PrintInt: " << c << std::endl;
    assert( c == int(testval));
}

int main()
{
    A<double> a;

    a.v = testval;
    std::cout << "a.v: " << a.v << std::endl;

    //auto b = a.v; // Disallowed
    double b = a.v;

    assert( a.v == b);

    b= testval-22;
    assert( a.v != b);

    printInt( a.v );

    return 0;
}


texts:
I have the following controller:

 angular.module("UserRoles")
.controller("UserRolesController", function($http, $scope){
    $scope.usersearch = "";
    $scope.users = [];
    $scope.roles = {
    }

    $scope.getusers = function(){
        $http.get("/api/finduser/"+$scope.usersearch)
            .success(function(data){
                $scope.users = data;
            });
    }
    // returns ([ [username, userid], ... ])

    $scope.getroles = function($event){
        var uid = $($event.currentTarget).find("a").data("userid");
        $http({
            "method": "GET",
            "url":"/api/rolesbyuser/",
            "params": {"user_dn": uid}
        }).success(function(data){
            console.log(data);
            $scope.roles = data;
        });
        // returns {ldapuser: ldapusername, direct_roles: [r1, r2], inheritedroles: [ir1ir2]}
    };
});

for the following HTML:

    <form ng-submit="getusers()">

            User Suchen: {{ usersearch }}
            <input ng-model="usersearch" type="text" class="form-control"
                    placeholder="username">

    </form>

                {{ user[0] }}

{{ roles.ldapuser }}

Direkte Rollen

                    {{ role }}

Vererbte Rollen

                    {{ role }}

Everything works fine:

In the form, I search for the user, then I am getting a user list in the format [[user, id] ...] . The site presents the user name and the id is saved in the data attribute of the user. If one clicks on one of the users on the left side, angular fetches the roles for the according user and displays them.

The questions are now:

My click event looks ugly (I use jQuery). What would be the angular way to perform this?

$($event.currentTarget).find("a").data("userid")

Is there an even better way to set the user to be searched for on click?
Should I really use only one controller or should I use one for user and one for roles?

$($event.currentTarget).find("a").data("userid")


texts: Sample scraping Project Gutenberg using Beautiful Soup and requests

texts:
I am trying to learn web scraping in Python using Beautiful Soup and requests. My program goes to the book page on Project Gutenberg with the given book number (Example). It then finds the link for the given format (text in this case) and then writes the contents of the book to a file on the hard disk.

How and what can I improve in this code?

import requests
from bs4 import BeautifulSoup
def go_gutenberg(file_format,book_no):
       url = "https://www.gutenberg.org/ebooks/"
       r =requests.get(url+str(book_no))
       r_html  = r.text
       soup = BeautifulSoup(r_html,"html.parser")
       for file in soup.find_all('a',class_="link"):
         if file_format in file.text:
           get_book=file.get('href')
           g = requests.get("https:"+get_book)

           with open("C:\\Users\\syed\\Documents\\Gutenberg\\Book"+str(book_no)+".txt",'wb') as open_file:
               for chunk in g.iter_content(10000):
                    open_file.write(chunk)

def main():
go_gutenberg("Text",1000)

if __name__=="__main__":main()

And this is sample HTML of the book links:

Plain Text UTF-8


texts:
I made a fizzbuzz program in Java 7 I'd like reviewed.

Given an input file with three numbers in each line, fizz, buzz, and count:

3 5 10
2 7 15

The output, for each line, should be the numbers from 1 to count, except that multiples of fizz are replaced with "F", multiples of buzz are replaced by "B", and multiples of both with "FB":

1 2 F 4 B F 7 8 F B
1 F 3 F 5 F B F 9 F 11 F 13 FB 15

The code, in Java 7:

package com.codeeval.fizzbuzz;

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

public class Main {
    public static void main(String[] args) throws IOException {
        String path = args[0];
        List<String> lines = getFileLines(path);

        StringBuilder sb = new StringBuilder();
        for (String line : lines){
            int[] arguments = getFizzBuzzArguments(line);
            int x = arguments[0];
            int y = arguments[1];
            int n = arguments[2];

            String result = fizzBuzz(x, y, n);
            sb.append(result).append('\n');
        }

        System.out.println(sb);
    }

    public static String fizzBuzz(int x, int y, int n) {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= n; i++) {
            boolean isX = (i % x == 0);
            boolean isY = (i % y == 0);
            String append;

            if (isX || isY) {
                if (isX && isY) { append = "FB"; }
                else if (isX) { append = "F"; }
                else { append = "B"; }
            } else { append = Integer.toString(i); }

            sb.append(append);
            if (i != n){ sb.append(' '); }
        }
        return sb.toString();
    }

    private static List<String> getFileLines(String path) throws IOException {
        File file = new File(path);
        BufferedReader buffer = new BufferedReader(new FileReader(file));
        List<String> lines = new ArrayList<>();
        String line;
        while ((line = buffer.readLine()) != null) {
            line = line.trim();
            lines.add(line);
        }

        return lines;
    }

    private static int[] getFizzBuzzArguments(String line){
        String[] arguments = line.split(" ");
        return getArrayOfInts(arguments);
    }

    private static int[] getArrayOfInts(String[] strings){
        int[] ints = new int[strings.length];

        for (int i = 0; i < strings.length; i++){
            ints[i] = Integer.parseInt(strings[i]);
        }

        return ints;
    }
}


texts:
I am looking for a way to turn a list of words that may have duplicates into a dictionary/map that counts the number of occurrences of words.  After spending some time with the problem, this seems to be one of the better ways, but maybe there are some downsides I am not seeing to this.

const magazine = "asdf ASDF wer wer";

This should produce a magazineMap of

const magazineMap = {
  asdf: 1,
  ASDF: 1,
  wer: 2
}

My solution to this was

function mapMagazine (magazine) {
    return magazine
        .split(' ')
        .reduce((initMap, word) => {
            return {
                ...initMap,
                [word]: (initMap[word] || 0) + 1
            }
        }, {});
}


texts: Script to pick random answers for a vocabulary quiz

texts:
I am making a small script, which, when run in the console on Vocabulary.com, picks one answer (the third or fourth) and clicks. Then the code checks if the answer was wrong or right and goes to the next question. Because the animations between the time the question is answered and the appearance of a "next question" button is very long, I had to use a weird mix of functions and setTimeout(). Although the code works, I feel like it is messy and maybe won't always work. How could I make this code perform better and make sure it is easy to edit?

To run the script, go on https://www.vocabulary.com and run this code in the console.

function clickNextButton() {
    for (v = 0; v < 4; v++) {
        document.getElementById("questionContainer").getElementsByTagName("a")[v].click();
    }

    function finalClick() {
        var foo = document.getElementById("blurbPane").getElementsByTagName("button")[0];
        foo.click();
    }

    setTimeout(finalClick, 1000);

}

var myElem = document.getElementsByClassName('source')[0];
if (myElem == null){
    console.log("no source")
} else{
    myElem.parentNode.removeChild(myElem);
}

var mathRandom = Math.floor(Math.random() * 2 + 2);
var selectChoices = document.getElementById("questionContainer").getElementsByClassName("choices")[0].getElementsByTagName("a")[mathRandom];
selectChoices.click();
setTimeout(partA, 1000);

function partA() {
    var ifMessage = document.getElementsByClassName("messagePane")[0].getElementsByTagName("h3")[0];
    var myColor = window.getComputedStyle(ifMessage).getPropertyValue("color");
    if (myColor == "rgb(204, 0, 0)") {
        clickNextButton();
    } else if (myColor == "rgb(83, 144, 7)") {
        document.getElementsByClassName("nextQuestion")[0].click();
    }
}


texts: Make file paths relative to the configuration file path

texts:
I have a configuration file which holds several file paths.

If these paths are relative, I want them to be relative to the path of the configuration file (and not to the path of the user working directory ("user.dir")).

Since it's not possible to change the working directory with Java, I've written this method:

public static File newFile(String parent, String child) {
  File file = new File(child);

  if(file.isAbsolute()) {
    return file;
  }

  return new File(parent, child);
}

The folder of my config file would be parent here.

Is there a better solution than this?


texts: List nearby bluetooth devices as well as devices in the database

texts:
I made a list of all nearby printer devices (that match the same name in the database) as well as all printer devices from the database. They are separated in the list by "--". I am able to get the code running and working. However, it is slow. Nearby devices amount to roughly 10-15 expected but devices in the database are around 400.

I was wondering how can I refactor my code to make it cleaner, concise and more efficient (most important). Currently, it's a bit slow, so I add a process bar while I call this method in the background. It can take up to a few seconds to generate the entire list.

Here's my code:

public async Task<List<Models.Printer>> ListAllPrinters()
{
    //Gets all printers inside the Database
    var printerDevices = await _deviceService.GetAllPrinters();

    //Gets all unpaired Bluetooth devices
    var unpairedDevices = BluetoothDevice.GetDeviceSelectorFromPairingState(false);

    //Gets all paired Bluetooth devices
    var pairedDevices = BluetoothDevice.GetDeviceSelectorFromPairingState(true);

    var unpairedNearDevices = (await DeviceInformation.FindAllAsync(unpairedDevices)).
        Select(x => x.Name).ToList();

    var pairedNearDevices = (await DeviceInformation.FindAllAsync(pairedDevices)).
        Select(x => x.Name).ToList();

    var nearbyDevices = unpairedNearDevices.Union(pairedNearDevices).ToList();

    List <Models.Printer> nearbyDevicesInDB = new List<Models.Printer>();
    List<Models.Printer> printers = new List<Models.Printer>();
    List<Models.Printer> printersList = new List<Models.Printer>();

        foreach (var printer in printerDevices)
        {
            printers.Add(new Models.Printer
            {
                SerialNumber = printer.SerialNumber,
                MacAddress = printer.MacAddress,
                IsInRange = false
            });

            //if nearby printer devices have the same name as device in database, then add it to nearbydevicesindb list
            if (nearbyDevices.Contains(printer.SerialNumber))
            {
                nearbyDevicesInDB.Add(new Models.Printer
                {
                    SerialNumber = printer.SerialNumber,
                    MacAddress = printer.MacAddress,
                    IsInRange = true
                });
            }
        }

    printersList = nearbyDevicesInDB;

    printersList.Add(new Models.Printer
    {
        SerialNumber = "--",
        MacAddress = "--"
    });

    printersList.AddRange(printers);

    return printersList;
}


texts: Building a profile image with a fly-out menu in the header

texts:
Background

I am more formally trained in backend/server-side coding. Over my career I have often found myself thrown into front-end coding. I have spent the last year and a half learning JavaScript/CSS3 on an "on Demand" basis. I feel like I am getting the hang of it, doing fancier things to meet UX requirements like animations and being able to layout a page without relying too much on a framework like Bootstrap.

Code

In this sample, I have put together an animated flyout menu for a profile image in a header. The idea is, you click on your profile image, and a menu animates to opacity 1, click it again, and the menu animates to opacity 0. For the sake of simplicity, the profile image is simply a cyan circle shaped div . If you would be so kind as to point out any flaws, or better practices I can adopt to make this code more readable/reliable/maintainable, it would be appreciated.

To see a working demo, I have built it in codepen: http://codepen.io/anon/pen/dNxeRN

HTML

    My Logo And Brand

Account settings

My Profile

Logout

CSS

*{
  margin: 0;
  padding: 0;
  font-family: helvetica, arial, sans-serif;
}

.header {
  padding-top: 5px;
  width: 1000px;
  height: 60px;
  border-bottom: 1px solid darkgrey;
  position: relative;
}

a.logo {
  display: inline-block;
  font-size: 25px;
  margin-top: 14px;
  margin-left: 10px;
  text-decoration:none;
  color: black;
}

.profile-image {
  width: 50px;
  height: 50px;
  background-color: cyan;
  border: 2px solid grey;
  border-radius: 50px;
  cursor: pointer;
  float:right;
  margin-right: 50px;
}

.fly-over{
  position: absolute;
  display: none;
  width: 300px;
  border-radius: 5px;
  box-shadow: 1px 1px 10px 1px rgba(0,0,0,.3);
  text-align: left;
  right: 36px;
  top: 80px;
}

.fly-over ul,
.fly-over ul li {
  margin: 0px;
  padding: 0px;
}

.fly-over ul li {
  list-style-type: none;
  padding-left: 20px;
  padding-top: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid lightgrey;
  cursor: pointer;
  transition: color, background-color 333ms;
}

.fly-over ul li:hover{
  background-color: #888888;
  color: white;
}

.fly-over:after{
  content: " ";
  display:block;
  position: absolute;
  width: 0px;
  height: 0px;
    border-left: 10px solid transparent;
    border-right: 10px solid transparent;
    border-bottom: 10px solid grey;
  bottom: 100%;
  left: 250px;
}

.fly-over.show{
  display: block;
}

.animation-fade-in,
.animation-fade-out{
  display: block;
  animation-name: fadeIn;
  animation-duration: 333ms;
  animation-timing-functon: ease-out;
  animation-fill-mode: forwards;
  animation-direction: normal;
}

.animation-fade-out{
  animation-direction: reverse;
}

@keyframes fadeIn{
  0%{
    opacity: 0;
  }
  100%{
    opacity: 1;
  }
}

JS

var el = document.getElementsByClassName("profile-image")[0];
var menuState = {
  visible: false
};
el.addEventListener('click', function(){
  var flyOverEl = document.getElementsByClassName("fly-over")[0];
  function onFadeInAnimationEnd(){
    this.classList.add('show');
    this.classList.remove('animation-fade-in');
    menuState.visible = true;
    this.removeEventListener('animationend', onFadeInAnimationEnd);
  }
  function onFadeOutAnimationEnd(){
    this.classList.remove('animation-fade-out');
    menuState.visible = false;
    this.removeEventListener('animationend', onFadeOutAnimationEnd);
  }
  if(menuState.visible){
    flyOverEl.classList.remove("show");
    flyOverEl.addEventListener("animationend", onFadeOutAnimationEnd)
    flyOverEl.classList.add("animation-fade-out");
  }
  else{
    flyOverEl.addEventListener("animationend", onFadeInAnimationEnd)
    flyOverEl.classList.add("animation-fade-in");
  }
})


texts:
I've just written my first angularjs directive, and I was hoping to get some feedback. I already have two doubts myself.

Why is it that I must use tElement.append() to append the canvas element? tElement.html() doesn't work, at all. That just returns [[object HTMLCanvasElement]] in plain text inside of the element.
Should I be accessing canvasElement[0]? It feels wrong, but it might not be.

Here's the code:

angular.module('yupDraw', [])
    .directive('yupCanvas', function factory() {

        // Create elements (templates) in vars here
        var canvasTemplate = '<canvas></canvas>';

        return {

            restrict: 'E',
            compile: function compile(tElement, tAttrs, transclude) {

                var canvasElement = angular.element(canvasTemplate);

                tElement.append(canvasElement);

                return function link(scope, element, attrs) {
                    var canvas = new fabric.Canvas(canvasElement[0], {
                        isDrawingMode: true
                    });
                }
            }
        };
    });

And I'm simply calling the directive like so: <yup-canvas></yup-canvas>

Fire away! :)


texts: Spelling a word with chemical elements in Rust

texts:
I tried solving this /r/dailyprogrammer challenge in Rust.

I'm a complete Rust beginner, and I'm sure I've made a lot of mistakes. I would be very thankful for any tips or help you might be able to provide.

Here are a couple of points that I found awkward/confusing:

In show_result, what I basically wanted to do was something like

symbols = spelling.map {|e| e.symbol}.join("")
elements = spelling.map {|e| e.name}.join(", ")

but that didn't seem to work.
I'm not exactly sure why I have to clone the elements to put them into the result vector. Can I/should I avoid this?
Coming from a dynamically typed garbage collected language, I had a hard time deciding when and where to use references.

Thank you very much!

extern crate csv;

use std::env;
use std::path::Path;
use std::collections::HashMap;
use std::option::Option;
use std::vec::Vec;

#[derive(Clone)]
struct Element {
    number: u16,
    symbol: String,
    name: String
}

impl Element {
    fn new (number: u16, symbol: &str, name: &str) -> Element {
        Element {
            number: number,
            symbol: symbol.to_string(),
            name: name.to_string()
        }
    }
}

// Read all elements from CSV file into a hash map
fn read_elements() -> HashMap<String, Element> {
    let mut elem_map = HashMap::new();

    let path = Path::new("./elements.csv");
    let mut csv_reader = csv::Reader::from_file(path).unwrap();
    for record in csv_reader.decode() {
        let (number, symbol, name): (u16, String, String) = record.unwrap();
        let symbol = symbol.trim();
        let name = name.trim();
        elem_map.insert(symbol.to_lowercase().to_string(), Element::new(number, symbol, name));
    };

    return elem_map;
}

// Try to spell target_word using elements from elem_map
fn spell_word(target_word: &str, elem_map: HashMap<String, Element>) -> Option<Vec<Element>> {
    let mut result: Vec<Element> = Vec::new();
    let target_word = target_word.to_lowercase().to_string();

    // How far we've matched so far
    let mut current: usize = 0;

    while current < target_word.len() {
        // Try matching the next two letters first
        if current + 2 <= target_word.len() {
            let next_two = &target_word[current..current + 2];
            if let Some(ref elem) = elem_map.get(next_two) {
                result.push((*elem).clone());
                current += 2;
                continue;
            }
        }

        // Try matching one letter if two letters failed
        let next_one = &target_word[current..current + 1];

        if let Some(ref elem) = elem_map.get(next_one) {
            result.push((*elem).clone());
        } else {
            // If no one letter element could be found,
            // this word cannot be spelled using elements
            return None;
        }
        current += 1;
    }

    return Some(result);
}

// Print the found spelling
// e.g. PoISON (polonium, iodine, sulfur, oxygen, nitrogen)
fn show_result(spelling: Vec<Element>) {
    let mut symbols: String = String::new();
    let mut elements: Vec<String> = Vec::new();

    for elem in spelling {
        symbols.push_str(&elem.symbol);
        elements.push(elem.name.to_lowercase());
    }

    println!("{} ({})", symbols, elements.join(", "));
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let elements = read_elements();

    if args.len() <= 1 {
        println!("Please provide a word to spell.");
    }

    let target_word: &str = &args[1];

    match spell_word(target_word, elements) {
        Some(spelling) => show_result(spelling),
        None => println!("Could not find a match for word \"{}\".", target_word)
    }
}


texts: Maximum sum subarray efficiency -- divide and conquer w/ vectors

texts:
I have successfully implemented a divide and conquer approach for find the maximum sum subarray (see code below). The code works fine and is correct, however I have an efficiency problem in that in order to recursively calculate sub-vectors, I need to do a copying operation which ordinarily wouldn't be there.

I'm using vectors because the larger program, to which this algorithm belongs, needs to read from a file and parse to the vectors. The lines vary in length, and as a result I've used vectors so that I can easily read a line, parse it to a vector, and then run it through a series of similar algorithms.

My question is: I'm trying to find a way that I can retain the use of the vectors but eliminate the copy operations so that my algorithm best reflects the \$O(nlogn)\$ runtime that the divide and conquer MSS algorithm should have.

I've tried modifying the function's header to include range values as parameters, but I can't figure out how to make that work with vectors.

int algorithm_3(vector<int> vect){

    int n = vect.size(); // size of array

    // BASE CASE
    if(n == 1){
        return vect.at(0);
    }

    // RECURSIVE CALLS
    int m = n / 2;

    // ** INEFFICIENT COPY OPERATIONS ** //
    vector<int> left_sub(vect.begin(), vect.begin() + m);
    vector<int> right_sub(vect.begin() + m, vect.end());

    int left_MSS = algorithm_3(left_sub);
    int right_MSS = algorithm_3(right_sub);

    // DETERMINE THE LEFTSUM AND RIGHTSUM FOR CASE 3: THE SUFFIX + PREFIX

    int leftsum = INT_MIN, rightsum = INT_MIN, sum = 0;
    for(int i = m; i < n; i++){
        sum += vect.at(i);
        rightsum = max(rightsum, sum);
    }

    sum = 0;
    for(int i = (m - 1); i >= 0; i--){
        sum += vect.at(i);
        leftsum = max(leftsum, sum);
    }

    int ans = max(left_MSS, right_MSS);

   return max(ans, leftsum + rightsum);
}


texts: React app that receives data via an AJAX requests, display the data and makes it searchable

texts:
I have recently started using React and wish to know if my code adheres to the React coding style, whether I am following the same approach towards solving any problem and is there any way I can make the code better.

var React = require('react');
var Bootstrap = require('react-bootstrap');
var xhr = require('superagent');
var Input = Bootstrap.Input;
var Panel = Bootstrap.Panel;

var Polls;
var View = React.createClass({
    getInitialState: function() {
        return {
            selectedPoll: '',
            query: ''
        };
    },
    componentDidMount: function() {
        var self = this;
        xhr.get('/polls').end(function(err, res) {
            if(err) {
                console.log(err);
            } else {
                Polls = res.body;
                if(self.isMounted()){
                    self.setState({
                        selectedPoll: res.body,
                        query: ''
                    });
                }
            }
        });
    },
    _onchange: function(value) {
        var result = [];
        (Polls).map(function(val) {
            if(val.uuid.toLowerCase().indexOf(value) !== -1 || val.question_text.toLowerCase().indexOf(value) !== -1) {
                result.push(val);
            }
        });
        this.setState({
            query: value,
            selectedPoll: result
        });
    },
    render:function() {
        return (

                    <SearchBar change={this._onchange} val={this.state.query} />
                        <PollList data={this.state.selectedPoll} />

                    <PollView />

        );
    }
});

var SearchBar = React.createClass({
    doSearch: function(e) {
        this.props.change(e.target.value.toLowerCase());
    },
    render: function() {
        return (
            <Input type="text" value={this.props.val} onChange={this.doSearch} />
        )
    }
});

var PollList = React.createClass({
    render: function() {
        var arr = [];
        if(this.props.data !== ''){
            this.props.data.map(function(value) {
                var head = value.uuid;
                var body = value.question_text;
                arr.push(
<Panel header={head} key={head}>{body}</Panel>
);
            });
        }
        return (

{arr}

        );
    }
});

var PollView = React.createClass({
    render: function() {
        return (

Dummy space

        );
    }
});

module.exports = View;


texts:
I wanted to write a human readable datetime.timedelta that can be used in log files.

Eg, "Report issued 1 hour, 44 minutes, 20 seconds ago"

I noticed that casting a timedelta to str() generates something almost like what I want, but not quite.

To this end I wrote this:

def verbose_timedelta(delta):
    hours, remainder = divmod(delta.seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    dstr = "%s day%s" % (delta.days, "s"[delta.days==1:])
    hstr = "%s hour%s" % (hours, "s"[hours==1:])
    mstr = "%s minute%s" % (minutes, "s"[minutes==1:])
    sstr = "%s second%s" % (seconds, "s"[seconds==1:])
    dhms = [dstr, hstr, mstr, sstr]
    for x in range(len(dhms)):
        if not dhms[x].startswith('0'):
            dhms = dhms[x:]
            break
    dhms.reverse()
    for x in range(len(dhms)):
        if not dhms[x].startswith('0'):
            dhms = dhms[x:]
            break
    dhms.reverse()
    return ', '.join(dhms)

Essentially, it's shaving off both ends of a list to make the results more meaningful.

The code above feels clunky though. Is there a more "Pythonic" way to do it? I'm using Python 2.7.3.


texts:
I am a beginner programmer and would like some feedback on this Tic Tac Toe game I made on Python. Any feedback would be appreciated, as I really want to get better at programming and pick up good habits. Here is my code. Something I would add is try statements for invalid user input, but this is not important as I would like feedback on how to optimise this code. I would also love feedback on the check_if_win() function as I believe there might be a better way of doing this. Thank you!

"""Tic Tac Toe"""

__author__ = "Enrique Gonzalez Aretos"

EMPTY = " "
PLAYER_1 = "X"
PLAYER_2 = "O"

# Create Board
def create_board():
    """
    Function which creates an empty game board
    :return: <list<list<str>>> Returns the game board
    """
    return [
        [EMPTY, EMPTY, EMPTY],
        [EMPTY, EMPTY, EMPTY],
        [EMPTY, EMPTY, EMPTY]
    ]
# Show board
def show_board(board):
    """
    Function which prints the board for the user
    :param board: <list<list<str>>> The Tic Tac Toe board
    :return: <str> A clean-looking version of the board
    """
    for x in board:
        # Find better way to print this
        print("|".join(x))

# Place X on spot
def place_player(board, active_player, row, column):
    """
    Function which places the player into the board
    :param board:
    :param active_player:
    :param row:
    :param column:
    :return:
    """
    if board[row-1][column-1] == EMPTY:
        board[row-1][column-1] = active_player

# Check if someone has won
def check_if_win(board, active_player):
    """
    Function which checks if the active player has won
    :param board: <list<list<str>>> Tic Tac Toe Board
    :param active_player: <str> The current active player
    :return: <bool> Return True or False
    """
    # Making lists which will store the diagonals and columns of baord
    diagonal1 = []
    diagonal2 = []
    column1 = []
    column2 = []
    column3 = []
    # Diagonal counter is used to index the different values in each row
    diagonal_counter = 1
    for row in board:
        # When each row is checked, the different indexes are organised
        # into the column and diagonal lists
        column1.append(row[0])
        column2.append(row[1])
        column3.append(row[2])
        diagonal1.append(row[diagonal_counter-1])
        diagonal2.append(row[-diagonal_counter])
        diagonal_counter += 1
        if "".join(row) == active_player * 3:
            return True

    # If statement which checks if any list is full of the active
    # player's symbol
    if "".join(column1) == active_player * 3 or "".join(column2) ==
    active_player * 3 or "".join(column3) == active_player * 3:
        return True
    elif "".join(diagonal1) == active_player * 3 or "".join(diagonal2)
    == active_player * 3:
        return True
    else:
        return False

def swap_player(active_player):
    if active_player == PLAYER_1:
        return PLAYER_2
    else:
        return PLAYER_1

def main():
    # Creates board and assigns starting player
    board = create_board()
    active_player = PLAYER_1
    while True:
        show_board(board)
        # Ask for player input
        row = int(input("\nIt is {}'s turn play. Choose a row (1-3):
              ".format(active_player)))
        column = int(input("Choose a column: "))
        place_player(board, active_player, row, column)
        # Checks if player has won
        if check_if_win(board, active_player) is True:
            show_board(board)
            print("\n{} won!".format(active_player))
            break
        active_player = swap_player(active_player)

if __name__ == "__main__":
    main()


texts:
I'm working on FFI wrapper for SDL2 library in Racket. The library includes several variadic functions (e.g. SDL_SetError, SDL_LogMessage etc); Racket FFI does not have straight way for importing those, but there's a workaround showcased here. Despite having little experience with Racket macros, I've decided to create one from the linked code to avoid excess code duplication. Here's my code:

#lang racket

(require (for-syntax racket/syntax)
         (for-syntax racket/format)
         ffi/unsafe)

(define sdl-lib (ffi-lib "libSDL2-2.0" '("0" #f)))

(define-syntax (define-vararg-func stx)
    (syntax-case stx ()
        [(_ name (arg-types ...) ret-type)
         (with-syntax*
             ([name-str (~a (syntax->datum #'name))]
              [arglist
               (map
                (lambda (arg)
                    (gensym (syntax->datum arg)))
                (syntax->list #'(arg-types ...)))]
              [full-arglist (append (syntax->list #'arglist) 'args)]
              [final-call (append '(apply fun) (syntax->list #'arglist) '(args))])
             #'(define name
                   (let ([interfaces (make-hash)])
                       (lambda full-arglist
                           (define itypes
                               (append (list arg-types ...)
                                       (map (lambda (x)
                                                (cond
                                                    [(and (integer? x) (exact? x)) _int]
                                                    [(and (number? x) (real? x))   _double*]
                                                    [(string? x)  _string]
                                                    [(bytes? x)   _bytes]
                                                    [(symbol? x)  _symbol]
                                                    [else
                                                     (error
                                                      "don't know how to deal with ~e" x)]))
                                            args)))
                           (let ([fun (hash-ref
                                       interfaces itypes
                                       (lambda ()
                                           (let ([i (get-ffi-obj
                                                     name-str sdl-lib
                                                     (_cprocedure itypes ret-type))])
                                               (hash-set! interfaces itypes i)
                                               i)))])
                               final-call)))))]))

;; macro usage
(define-vararg-func SDL_SetError (_string) _int)
(SDL_SetError "test %s %d" "test" 42)

(define SDL_GetError (get-ffi-obj "SDL_GetError" sdl-lib (_cprocedure '() _string)))
(displayln (SDL_GetError))

I'd love any feedback on the macro and suggestions on how to improve its readability.


texts: Returning items that meet a minimum value

texts:
I'm trying to find an alternative way to write this code such as using different ways to achieve checking if it's a subset and insertion.

def candidates(table, candidates, minsupp):
    count, supported = {}, {}
    for item in table:
        for c in candidates:
            if c.issubset(item):
                count[c] =  count.get(c, 0)
                count[c] = count[c] + 1

    total = float(len(table))
    l_sub_one = []
    for c in count:
        support = count[c] / total
        if support >= minsupp:
            l_sub_one.insert(0, c)
        supported[c] = support
    return l_sub_one, supported


texts: VBA Array Functions: insert element, remove element

texts:
An extension to array functions I am building for my snake game. This one allows you to remove / insert particular elements.

https://github.com/Evanml2030/Excel-ArrayFunctions

API CALLS

Private Declare PtrSafe Function VarPtrArray Lib "VBE7" Alias "VarPtr" _
        (ByRef Var() As Any) As LongPtr

Private Declare PtrSafe Sub CopyMemoryI Lib "kernel32.dll" Alias "RtlMoveMemory" _
        (ByVal dst As LongPtr, ByVal src As LongPtr, ByVal Length As Long)

Private Declare PtrSafe Sub CopyMemoryII Lib "kernel32.dll" Alias "RtlMoveMemory" _
        (ByRef dst As SAFEARRAY, ByVal src As LongPtr, ByVal Length As Long)

DATA STRUCTS

Private Type SAFEARRAY_BOUND
    cElements    As Long
    lLbound      As Long
End Type

Private Type SAFEARRAY
    cDims        As Integer
    fFeatures    As Integer
    cbElements   As Long
    cLocks       As Long
    pvData       As LongPtr
    rgsabound(0) As SAFEARRAY_BOUND
End Type

Public Type TestStruct
    Column       As Long
    Row          As Long
End Type

Private Const TESTSTRUCT_BYTELENGTH = 8

FUNCTIONS

Public Function ArrayInsertElement(ByRef ArrayOriginal() As TestStruct, ByRef ElementToAdd As TestStruct, ByRef Position As Long) As TestStruct()
Dim NewLength                  As Long
Dim CopiedBytesFirstSection    As Long
Dim CopiedBytesSecondSection   As Long

    NewLength = UBound(ArrayOriginal) + 1
    ReDim ArrayInsertElement(NewLength)

    CopiedBytesFirstSection = Position * TESTSTRUCT_BYTELENGTH
    CopiedBytesSecondSection = (NewLength - Position) * TESTSTRUCT_BYTELENGTH

    CopyMemoryI ArrayElementGetPointer(ArrayInsertElement, 0, TESTSTRUCT_BYTELENGTH), ArrayElementGetPointer(ArrayOriginal, 0, TESTSTRUCT_BYTELENGTH), CopiedBytesFirstSection
    CopyMemoryI ArrayElementGetPointer(ArrayInsertElement, Position, TESTSTRUCT_BYTELENGTH), VarPtr(ElementToAdd), TESTSTRUCT_BYTELENGTH
    CopyMemoryI ArrayElementGetPointer(ArrayInsertElement, Position + 1, TESTSTRUCT_BYTELENGTH), ArrayElementGetPointer(ArrayOriginal, Position, TESTSTRUCT_BYTELENGTH), CopiedBytesSecondSection
End Function

Public Function ArrayRemoveElement(ByRef ArrayOriginal() As TestStruct, ByRef Position As Long) As TestStruct()
Dim NewLength                  As Long
Dim CopiedBytesFirstSection    As Long
Dim CopiedBytesSecondSection   As Long

    NewLength = UBound(ArrayOriginal) - 1
    ReDim ArrayRemoveElement(NewLength)

    CopiedBytesFirstSection = Position * TESTSTRUCT_BYTELENGTH
    CopiedBytesSecondSection = (UBound(ArrayOriginal) - Position) * TESTSTRUCT_BYTELENGTH

    CopyMemoryI ArrayElementGetPointer(ArrayRemoveElement, 0, TESTSTRUCT_BYTELENGTH), ArrayElementGetPointer(ArrayOriginal, 0, TESTSTRUCT_BYTELENGTH), CopiedBytesFirstSection
    CopyMemoryI ArrayElementGetPointer(ArrayRemoveElement, Position, TESTSTRUCT_BYTELENGTH), ArrayElementGetPointer(ArrayOriginal, Position + 1, TESTSTRUCT_BYTELENGTH), CopiedBytesSecondSection
End Function

Public Function ArrayElementGetPointer(ByRef Arr() As TestStruct, ByVal ElementIndex As Long, ByVal ElementByteLength As Long) As LongPtr
Dim ptrToArrayVar  As LongPtr
Dim ptrToSafeArray As LongPtr
Dim ptrToArrayData As LongPtr
Dim ptrCursor      As LongPtr
Dim uSAFEARRAY     As SAFEARRAY

    ptrToArrayVar = VarPtrArray(Arr)
    CopyMemoryI VarPtr(ptrToSafeArray), ptrToArrayVar, 8
    CopyMemoryII uSAFEARRAY, ptrToSafeArray, LenB(uSAFEARRAY)
    ptrToArrayData = uSAFEARRAY.pvData
    ptrCursor = ptrToArrayData + (ElementIndex * ElementByteLength)
    ArrayElementGetPointer = ptrCursor
End Function


texts: Combining these Add and Remove methods into 1

texts:
I was wondering if it's possible to move these add remove methods into a single method:

public void AddToVipGroup(int companyID, string userID, string auditTrailUrl)
{
    string userName = "", groupName = "";
    GetUserAndGroupNames(companyID, userID, out userName, out groupName);
    GroupUtilities.AddUserToGroup(userName, groupName, auditTrailUrl);
}

public void RemoveFromVipGroup(int companyID, string userID, string auditTrailUrl)
{
    string userName = "", groupName = "";
    GetUserAndGroupNames(companyID, userID, out userName, out groupName);
    GroupUtilities.RemoveUserFromGroup(userName, groupName, auditTrailUrl);
}

private void GetUserAndGroupNames(int companyID, string userID, out string userName, out string groupName)
{
    var vipGroupSID = new MyDataAccess().GetVipGroupSID(companyID);
    if (string.IsNullOrEmpty(vipGroupSID))
        throw new Exception(string.Format("Company id: {0} has no vips group in db", companyID));

    //add user in Company Access vips group
    DBUser user = DBUser.LoadBySid(userID);
    DBGroup group = DBGroup.LoadBySid(vipGroupSID);

    userName = user.UserName;
    groupName = group.Name;
}

I am only looking to merge these methods, if it would be considered best practice.


texts:
Depending on how you count, this is my first Go program. I'm trying to read a CSV into a two-dimensional array of some numeric type, and then print it out.

(I want to use this to read "edge weights" to build a Graph; that is my next mission, unrelated to the code below.)

So the code below works. But particularly as I'm new to the language, I'd like to know:

Are there shorter ways to accomplish the same functionality?
Any ways to make this code more idiomatic?
float64 feels arbitrary, but Go is statically typed -- any way I can make this more dynamic, allowing other types?

Here 'tis; rip her apart if you want! Trying to learn.

package csfloat

import (
    "encoding/csv"
    "fmt"
    "os"
    "strconv"
    "strings"
)

// make2dFloatArray makes a new 2d array of float64s based on the
// rowCount and colCount provided as arguments
func make2dFloatArray(rowCount int, colCount int) [][]float64 {
    values := make([][]float64, rowCount)
    for rowIndex := range values {
        values[rowIndex] = make([]float64, colCount)
    }

    return values
}

// stringValuesToFloats converts a 2d array of strings into a 2d array
// of float64s.
func stringValuesToFloats(stringValues [][]string) ([][]float64, error) {
    values := make2dFloatArray(len(stringValues), len(stringValues[0]))

    for rowIndex, _ := range values {
        for colIndex, _ := range values[rowIndex] {
            var err error = nil

            trimString :=
                strings.TrimSpace(stringValues[rowIndex][colIndex])

            values[rowIndex][colIndex], err =
                strconv.ParseFloat(trimString, 64)

            if err != nil {
                fmt.Println(err)
                return values, err
            }
        }
    }

    return values, nil
}

// ReadFromCsv will read the csv file at filePath and return its
// contents as a 2d array of floats
func ReadFromCsv(filePath string) ([][]float64, error) {
    file, err := os.Open(filePath)
    if err != nil {
        return nil, err
    }

    reader := csv.NewReader(file)
    stringValues, err := reader.ReadAll()
    if err != nil {
        return nil, err
    }

    values, err := stringValuesToFloats(stringValues)
    if err != nil {
        return nil, err
    }

    return values, nil
}