texts:
package calc;

import com.sun.tools.corba.se.idl.constExpr.Equal;    //imports .equals(variable)
import java.util.Scanner;    //imports scanners

public class Calc {

    public static void main(String[] args) {
        boolean go = true;    //sets up loop

        while(go)    //creates loop to top
        {
            System.out.println("Hello this is my calculator!");
            System.out.println("To add, type a, to subtract, type s.");
            System.out.println("To multiply, type m, to divide, type d.");

            Scanner scan = new Scanner(System.in);    //sets up scanners
            Scanner scan1 = new Scanner(System.in);

            String action = scan.nextLine();    //tells comp. to take user input

            if("a".equals(action))    //addition
            {
                System.out.println("Now type in the first number you would like to add.");
                int add1 = scan.nextInt();
                System.out.println("Now type the second number.");
                int add2 = scan.nextInt();
                int add3 = add1 + add2;
                System.out.println(add1 + " added to " + add2 + " equals " + add3 + "!");
            }
            if("s".equals(action))    //subtraction
            {
                System.out.println("Now type in the first number you would like to subtract.");
                int sub1 = scan.nextInt();
                System.out.println("Now type the second number.");
                int sub2 = scan.nextInt();
                int sub3 = sub1 - sub2;
                System.out.println(sub1 + " subtracted bye " + sub2 + " equals " + sub3 + "!");
            }
            if("m".equals(action))    //multiplacation
            {
                System.out.println("Now type in the first number you would like to multiply.");
                int mul1 = scan.nextInt();
                System.out.println("Now type the second number.");
                int mul2 = scan.nextInt();
                int mul3 = mul1 * mul2;
                System.out.println(mul1 + " multiplied bye " + mul2 + " equals " + mul3 + "!");
            }
            if("d".equals(action))    //division
            {
                System.out.println("Now type in the first number you would like to divide.");
                int div1 = scan.nextInt();
                System.out.println("Now type the second number.");
                int div2 = scan.nextInt();
                int div3 = div1 / div2;
                System.out.println(div1 + " divided bye " + div2 + " equals " + div3 + "!");
            }

            System.out.println("Would you like to start over? (yes,no)");
            String startOver = scan1.nextLine();

            if("no".equals(startOver))
            {
                go = false;
                System.out.println("Bye");
            }
        }
    }
}

Would it be possible to make this more compact?
Does this code contain dead code?


texts:
I'm not sure if I should ask here. The program worked it's just that I'm not satisfied how I implemented it because I used two while loop to read a specific data and I have no idea what am I doing. How can I make it more efficient and instead of using two while loop?

spritesheet.txt

int main() {

fstream file("spritesheet.txt");

int x, y, width, height;
string num1, num2;
string line;
string data;

if (file.is_open())
{
    while (getline(file, line))
    {
        if (line == "enemy")
        {
            while (file >> data >> num1 >> num2)
            {
                if (data == "xy:")
                {
                    x = std::stoi(num1);
                    y = std::stoi(num2);
                    cout << "x: " << x << endl << "y: " << y << endl;
                }
                if (data == "size:")
                {
                    width = std::stoi(num1);
                    height = std::stoi(num2);
                    cout << "width: " << width << endl << "height: " << height << endl;
                }
            }
            file.close();
            break;
        }
    }
}
system("pause");

}


texts:
I'm trying to create a lost password function on my site. When a user enter their email it updates 2 columns in the users table with that email called: new_password_key and new_password_requested (int, using PHP time()), I then send them a link with that password key to a page where they may change their password.

It seems to work, and if they don't visit the link within 24 hours it's considered invalid and they have to request a new one.

Is it OK? Safe? Is there something else I should think of?

This is the https://mysite.com/password/key_goes_here page:

$value = isset($_GET['key']) ? $_GET['key'] : null;
$query = $db->prepare("SELECT new_password_key, new_password_requested FROM users WHERE new_password_key = ?");
$query->execute(array($value));
$row = $query->fetch();

if (!$row) {
    // not found
    header("Location: /password");
    die;
}

// if this key is older than 24 hours its invalid (expired)
if ($row['new_password_requested'] <= time() - (60 * 60 * 24)) {
    $query = $db->prepare("UPDATE users SET new_password_key = NULL, new_password_requested = 0 WHERE new_password_key = ?");
    $query->execute(array($value));
    header("Refresh: 3;url='/password'");
    return false;
}

if (count($_POST) > 0) {

    $new_password1 = trim($_POST['new_password1']);
    $new_password2 = trim($_POST['new_password2']);

    if (strlen($new_password1) < 4)
        $error = "passwords must be at least 4 characters long. please choose another (longer) password";
    else if ($new_password1 != $new_password2)
        $error = "passwords do not match";

    if (empty($error)) {
        $hash = password_hash($new_password1, PASSWORD_DEFAULT);
        $query = $db->prepare("UPDATE users SET password = ?, new_password_key = NULL WHERE new_password_key = ?");
        $query->execute(array($hash, $row['new_password_key']));

    }

}

This is the form where you enter your email to get a key:

if (count($_POST) > 0) {

$email = trim($_POST['email']);

$query = $db->prepare("SELECT email, new_password_key, new_password_requested FROM users WHERE email = ?");
$query->execute(array($email));
$row = $query->fetch();

if (empty($email))
    $error = "this field can not be empty";
else if (!filter_var($email, FILTER_VALIDATE_EMAIL))
    $error = "not a valid email address";
else if (!empty($row['new_password_key']))
    $error = 'a link has already been sent';
elseif ($query->rowCount() < 1)
    $confirmed = true;

if (empty($error)) {

    if ($row) {
        // email exists, send them mail
        $query = $db->prepare("UPDATE users SET new_password_key = ?, new_password_requested = ? WHERE email = ?");
        $query->execute(array(generateRandomString(25), time(), $row['email']));
        sendMail($email, 'lostpassword');
        $confirmed = true;
    } else {
       // email dont exist, tell them an email has been dispatched but dont actually send a mail we dont want them to know what emails are registered on this site
       $confirmed = true;
    }
}
}


texts:
I've written a simple module that creates a fully connected neural network of any size. The arguments of the train function are list of tuples with a training example array first and an array containing its class second, list that contains a number of neurons in every layer including the input and the output layers, a learning rate and a number of epochs.
To run a trained network I've written the run function, its arguments are an input and weights from the trained network. Since I'm a beginner to programming and machine learning I'll be very happy getting advice regarding computational efficiency and optimization.

import numpy as np
def weights_init(inSize,outSize): #initialize the weights
    return 2*np.random.random((inSize,outSize))-1

def Sigmoid(input, weights): #create a sigmoid layer and return a layer along with its derivative
    out = 1/(1+np.exp(-np.dot(input,weights)))
    derivative = out*(1-out)
    return out,derivative

def backProp(layers, weights, deriv, size, rate = 1):
    derivative = deriv.pop()#get the cost function derivative
    #reverse all the lists because we need to go backwards
    deriv = deriv[::-1]
    layers = layers[::-1]
    weights = weights[::-1]
    new_weights=[]
    #backpopagate
    new_weights.append(weights[0]+(layers[1].T.dot(derivative*rate))) #this one does not fit well the algorithm inside for loop, so it's outside of it
    for i in range(len(size)-2):
        derivative = derivative.dot(weights[i].T)*deriv[i]
        new_weights.append(weights[i+1]+(layers[i+2].T.dot(derivative*rate)))
    return new_weights[::-1]

def train(input,size,rate=1,epochs=1): #train the network
    layers=[]
    weights=[]
    derivs=[]
    for i in xrange(len(size)-1): #weights initialization
        weights.append(weights_init(size[i],size[i+1]))
    for i in xrange(epochs): #the training process
        for example, target in input:  #online learning
            layers.append(example)
            for i in xrange(len(size)-1):
                layer, derivative = Sigmoid(layers[i],weights[i])#calculate the layer and itd derivative
                layers.append(layer)
                derivs.append(derivative)

            loss_deriv = target-layer[-1] #loss function

            derivs[-1] = loss_deriv*derivs[-1] #multiply the loss function by the final layer's derivative
            weights = backProp(layers,weights,derivs,size) #update the weights
            layers=[]
            derivs = []
    return weights

def run(input,weights): #run a trained neural network
    layers=[input]
    for i in xrange(len(weights)):
        layer,derivative = Sigmoid(layers[i],weights[i])
        layers.append(layer)
    return layers

An example:

X = [(np.array([[0,0,1]]),np.array([[0]])),(    np.array([[0,1,1]]),np.array([[1]])), (np.array([[1,0,1]]),np.array([[1]])), (np.array([[1,1,1]]),np.array([[0]]))]

weights = train(X,[3,4,1],epochs=60000)
run(X[0][0],weights)


texts:
I have an associative array:

$input = [
    ['key'=>'x', 'value'=>'a'],
    ['key'=>'x', 'value'=>'b'],
    ['key'=>'x', 'value'=>'c'],
    ['key'=>'y', 'value'=>'d'],
    ['key'=>'y', 'value'=>'e'],
    ['key'=>'z', 'value'=>'f'],
    ['key'=>'m', 'value'=>'n'],
];

And I want to reform it simple in:

$output = [
    'x'=>['a','b','c'],
    'y'=>['d','e'],
    'x'=>'f',
    'm'=>'n'
]

So basically, conditions are:

If same key found then put values in an array.
If no same key found then value remains string.

You can replace associative array with object if you are more comfortable with objects.

Here is my working solution for this problem:

foreach($input as $in){
    if(!empty($output[$in['key']])){
        if(is_array($output[$in['key']])){
            $output[$in['key']][] = $in['value'];
            continue;
        }
        $output[$in['key']] = [$output[$in['key']],$in['value']];
        continue;
    }
    $output[$in['key']] = $in['value'];
}
print_r($output);

However I believe that it can be done in much compact and efficient way.
Please comment your answers if someone has better solution.
Your help is much appreciated!


texts: Using the $q service in AngularJS to handle promises

texts:
I have a service which needs to store some settings data in a DB and at the same time maintain a reference to that in the user'slocalStorage (we want two users logged in to the same account to be able to view them differently). This method looks for an existing previewSession in the localStorage and if not found, creates one and generates a unique URL.

As you can see at the beginning, I'm using the $q service to return a promise and then resolving that promise as and when all operations have finished. There is one use of the $http service and the save call is on a $resource object.

Is this a proper way to handle such a use-case, or could I have done it better?

To summarize the requirements:

Method gets called with a settings parameter
Method must always return a URL (unless an error occurs on the db level or some such thing)

var PREVIEW_SESSION_KEY_BASE = '<a constant string>';
function getPreviewSessionUrl(settings) {
        var deferred = $q.defer();

        $http.get('/' + appCode + '/reservedDomain',
            function(appResponse) {
                $localForage
                    .getItem(PREVIEW_SESSION_KEY_BASE + themeId)
                    .then(function(data) {
                        if (data) {
                            deferred.resolve(appResponse + '?<a query key>=' + data);
                        } else {
                            previewSessionResource.save(
                                {},
                                {
                                    settings: settings
                                },
                                function(previewResponse) {
                                    $localForage
                                        .setItem(PREVIEW_SESSION_KEY_BASE + themeId, previewResponse)
                                        .then(function(data) {
                                            deferred.resolve(appResponse + '?<a query key>=' + data);
                                        });
                                },
                                function(error) {
                                    deferred.reject(error);
                                }
                            );
                        }
                    });
            },
            function(error) {
                deferred.reject(error);
            }
        );

        return deferred.promise;
    }


texts:
I've developed some PHP that grabs all of a business listing's categories and then displays just the children categories. This is built on Wordpress. I'm still in the learning process and would appreciate some assistance here. Any optimizations you can suggest I make to my code would be really helpful. Please note, if it's really technical, there's a good chance it'll go over my head at this point, so examples are appreciated.

<?php

$permalink = get_permalink( $id );

$seo = get_the_title()." : ";

$Category_links = ' Found in the ';

$term_list_category = wp_get_post_terms(get_the_ID(), 'listings_categories', array("fields" => "ids"));

//THIS CODE REMOVES PARENTS FROM BEING DISPLAYED IN THE LISTING CATEGORIES
foreach ($term_list_category as $k=>$term) {
    $children = get_term_children( $term, 'listings_categories');
if ($children)
    unset($term_list_category[$k]);
 }

$i = 0;

$count = count($term_list_category);

if ( $count > 0 ){

    foreach ( $term_list_category as $term_category ) {

        $thisCat = get_term_by( 'id', $term_category, 'listings_categories');

        $url = '{'slug'}.'" class="listing-links-cat" href="#" title="'.$thisCat->{'name'}.'" >'.$thisCat->{'name'}.'';

        $i ++;

        $seo .= " " . $thisCat->{'name'} . "";

        $Category_links .= " " . $url . "";

        if($count-1 == $i){
            $Category_links .= " and ";  $seo .= ", ";
        }elseif($count > 1 && $count !== $i){
            $Category_links .= ", ";  $seo .= ", ";
        }

    }
    $Category_links .= " Categories";
?>

<? echo $Category_links;  ?>


texts: Simple class, solely for setting "globals"

texts:
I'm aiming for the best and simplest way to access "global" variables set in the config file for my website. So I can use them anywhere, even inside functions

It's for file versioning, and I use htaccess to rewrite urls (trim out version part)

Right now, I'm at this:

// config.php:

class VERS {

  static $css = '_214';
  static $js = '_167';
  static $image = '_56';
  static $other = '_19';

}

// subpage.php:

require 'settings/config.php';
echo '<link type="text/css" rel="stylesheet" href="style'.VERS::$css.'.css" />';

Is this an ok solution? Are there downsides and/or better ways?

I want to avoid setting multiple DEFINE's, and I aim for a short version var call (like VERS::$css)

EDIT: This is not about alternatives to the filename method itself (like filename?queries etc.)


texts: Convert a JS DataTable to an array of objects

texts:
An API provides data as some sort of data table, column and rows.

I have written a function to get JS Objects from this DataTable.

function processAggregateData(data) {
    dataRows = data.data[0].rows
    var returnArray = [];
    for (var i = 0; i < dataRows.length; ++i){
        returnArray.push({
            index: dataRows[i].fld[0].v,
            average: dataRows[i].fld[1].v,
            min: dataRows[i].fld[2].v,
            max: dataRows[i].fld[3].v,
            sum: dataRows[i].fld[4].v,
            target: dataRows[i].fld[5].v,
            LLL: dataRows[i].fld[6].v,
            LL: dataRows[i].fld[7].v,
            L: dataRows[i].fld[8].v,
            H: dataRows[i].fld[9].v,
            HH: dataRows[i].fld[10].v,
            HHH: dataRows[i].fld[11].v,
            status: dataRows[i].fld[12].v
        })
    }
    return returnArray;
}

I would like to improve it, in particular:

There is a lot of 'magic constants', mapping a column number to an object property. I have tried to extract them, but have not found a way to do it without doubling the size of the function. Is that suitable here?
Of course, any improvement of the code is most welcome.

A note, to end, there is users on IE, so ECMA6 is not possible.

Thank you for your review :)


texts: What's the proper way to avoid long parameter lists?

texts:
If I architect to utilize use-cases then I soon arrive at long param lists. As an example:
class MainViewModel @Inject constructor(
    private val getUsers: GetUsers,
    private val deleteUser: DeleteUser,
    private val reorderUsers: ReorderUsers,
    private val getVenues: GetVenues,
    private val deleteVenue: DeleteVenue,
    private val reorderVenues: ReorderVenues,
    private val analytics: Analytics,
    private val dispatcher: CoroutineDispatcher
): ViewModel()

The multiple cases dealing with the same data type, three each for Users and Venues, seem like places for potential improvement.
I'm curious whether there's a pattern/structure to properly group such items. How might I refactor loosely related interactors to mitigate long lists of constructor parameters?


texts:
I've written a function which takes as an input:

a string to be modified
a vector of regular expressions on which to match
a vector of replacements
option to ignore case in the match statements

The function will then, from the users perspective, simultaneously perform all replacements in a 'safe' fashion. By 'safe' I mean sub-string matches are ignored in favor of longer matches (if 'the' and 'they' are patterns to match, ignore the sub-string 'the' in 'they') and also allow users to have cross-replacement (swap 'hey' for 'ho' and 'ho' for 'hey').

Examples:

rcpp_mgsub("hey ho",{"hey","ho"},{"ho","hey"},true)
// Expect "ho hey"
rcpp_mgsub("Hey, how are you?",{"hey","how","are","you"},{"how","are","you","hey"},true)
// Expect "how, are you hey?"

I've written a function in the R programming language that accomplishes this, but R isn't a fast language. R libraries can include pre-compiled C++11 code which can result in vastly faster functions.  To this end, I've written a C++11 function but the performance is actually significantly slower than R (3-7x slower in various comparisons I've done) so I realize there must be some significant inefficiencies in my function.

So, I'm curious what inefficiencies are present in the rcpp_mgsub function that I should focus on improving.

#include <iostream>
#include <string>
#include <regex>

std::string rcpp_mgsub(std::string string, std::vector<std::string> const& match, std::vector<std::string> const& replace, bool const& ic) {
  std::string newString = "";
  std::smatch matches;
  std::string prefix = string;
  std::string detected;
  std::string suffix;

  std::regex::flag_type flags;
  flags |= std::regex_constants::optimize;
  if(ic) flags |= std::regex_constants::icase;

  std::vector<std::regex> r(match.size());
  std::transform(match.begin(), match.end(), r.begin(),
                 [&flags](std::string m) {return std::regex (m, flags);});

  int j=0;
  while(string.size() > 0){
    prefix = string;
    detected = "";
    suffix = "";
    j = 0;
    for(int i=0;i < match.size();i++){
      if (std::regex_search(string,matches, r[i])) {
        std::string pr = matches.prefix();
        std::string m = matches[0];
        if(pr.size() < prefix.size() || (pr.size() == prefix.size() && m.size() > detected.size())){
          prefix = pr;
          detected = m;
          suffix = matches.suffix();
          j=i;
        }
      }
    }
    if(prefix == string){
      newString = newString+string;
      string = "";
    } else {
      newString = newString+prefix+std::regex_replace(detected,r[j],replace[j],std::regex_constants::format_sed);
      string = suffix;
    }
  }
  return newString;
}

int main()
{
   std::cout << rcpp_mgsub("hey ho hey",{"hey","ho"},{"ho","hey"},true) << "\n";
   std::cout << rcpp_mgsub("Hey, how are you?",{"hey","how","are","you"},{"how","are","you","hey"},true) << "\n";
   std::cout << rcpp_mgsub("Dopazamine is not the same as Dopachloride and is still fake.",{"[Dd]opa(.*?mine)","fake"},{"Meta\\1","real"},false);
   return(0);
}


texts: Dining philosophers problem with mutexes

texts:
I know this dining philosophers problem has been researched a lot and there are resources everywhere. But I wrote simple code to solve this problem with C and then turned to the Internet to see if it's correct. I wrote this with mutexes only and almost all implementations on the Internet use a semaphore. Now I'm not sure about my code.

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

#define NO_OF_PHILOSOPHERS 5

pthread_t philosophers[NO_OF_PHILOSOPHERS];
pthread_mutex_t mutex_forks = PTHREAD_MUTEX_INITIALIZER;;
int forks[NO_OF_PHILOSOPHERS];

void init()
{
    int i;
    for(i=0; i<NO_OF_PHILOSOPHERS; i++)
        forks[i] = 0;
}

void philosopher(int i)
{
    int right = i;
    int left = (i - 1 == -1) ? NO_OF_PHILOSOPHERS - 1 : (i - 1);
        int locked;
    while(1)
    {
            locked = 0;
            while(!locked)
            {
                pthread_mutex_lock(&mutex_forks);
                if(forks[right] || forks[left])
                {
                    pthread_mutex_unlock(&mutex_forks);     // give up the forks unless you can take both at once.
                    printf("Philosopher %d cannot take forks. Giving up and thinking.\n",i);
                    usleep(random() % 1000); // think.
                    continue;
                }
                forks[right] = 1; // take forks.
                forks[left] = 1;

                pthread_mutex_unlock(&mutex_forks);
                locked = 1;
            }

        printf("Philosopher %d took both forks. Now eating :)\n",i);
        usleep(random() % 500);
        printf("Philosopher %d done with eating. Giving up forks.\n",i);
        pthread_mutex_lock(&mutex_forks); // give up forks.
        forks[right] = 0;
        forks[left] = 0;
        pthread_mutex_unlock(&mutex_forks);
        usleep(random() % 1000);
    }

}

int main()
{
    init();
    int i;
    for(i=0; i<NO_OF_PHILOSOPHERS; i++)
        pthread_create( &philosophers[i], NULL, philosopher, (void*)i);
    for(i=0; i<NO_OF_PHILOSOPHERS; i++)
        pthread_join(philosophers[i],NULL);
    return 0;
}

Now for me, the code looks like it's working fine, but people on the Internet seem to make a lot of fuss than this to write the solution for Dining Philosophers.

As such, I thought of asking these questions:

Can there be a deadlock in the code?
Can there be a starvation of a philosopher?
Have I missed the whole point of the Dining Philosophers Problem?


texts: Generic BinaryReader/Writer Read/Write methods

texts:
I have an extension that implements all the BinaryReader/BinaryWriter in the Stream class. I want to create generic methods for them. Is there a nicer way of doing this?

public static void Write<T>(this Stream stream, T num)
{
    if (num is byte)
    {
        stream.Write((byte)(object)num);
    }
    else if (num is Int16)
    {
        stream.Write((Int16)(object)num);
    }
    else if (num is Int32)
    {
        stream.Write((Int32)(object)num);
    }
}

public static T Read<T>(this Stream stream)
{
    object ret = null;

    if (typeof(T) == typeof(byte))
        ret = stream.ReadInt8();
    else if (typeof(T) == typeof(Int16))
        ret = stream.ReadInt16();
    else if (typeof(T) == typeof(Int32))
        ret = stream.ReadInt32();

    if (ret == null)
        throw new ArgumentException("Unable to read type - " + typeof(T));
    return (T)ret;
}

Now using this for the Read method.

static Dictionary<Type, Func<Stream, object>> ReadFuncs = new Dictionary<Type, Func<Stream, object>>()
{
    {typeof(bool), s => s.ReadBoolean()},
    {typeof(byte), s => s.ReadInt8()},
    {typeof(Int16), s => s.ReadInt16()},
    {typeof(Int32), s => s.ReadInt32()},
    {typeof(Int64), s => s.ReadInt64()},
    {typeof(string), s => s.ReadString()},
};
public static T Read<T>(this Stream stream)
{
    if (ReadFuncs.ContainsKey(typeof(T)))
        return (T)ReadFuncs[typeof(T)](stream);

    throw new NotImplementedException();
}


texts:
I have a query below using CTE. I am wondering if there are some approach other than this. So I am collecting some advise to refactor it. Or does the query look good even though I am using this IN (SELECT InvariantLanguageCultureCode FROM y) statement many times in the query?

DECLARE  @ReportingInstanceID INT

 SET @ReportingInstanceID=34
 ;WITH x AS (
        SELECT  [dbo].[tenant_Reporting_Instance].UserID
        FROM    [dbo].[tenant_Reporting_Instance]
        WHERE   tenant_Reporting_Instance.ReportingInstanceID = @ReportingInstanceID
        )
        ,y AS ( SELECT  [TRCCore].[dbo].[pr_Language].InvariantLanguageCultureCode
        FROM    [TRCCore].[dbo].[pr_Language]
                JOIN [dbo].[tenant_User_Setting] ON tenant_User_Setting.LanguageID = pr_Language.LanguageID
        WHERE   tenant_User_Setting.UserID IN (SELECT UserID FROM x))
        ,Default_User_Settings_CTE ( RoundingTypeInvariantCode, AgingDateValue, CurrencyLabel, JobZoneLinkTypeLabel, MatchPeriodLabel, PayFrequencyLabel, PayTypeLabel )
                  AS ( SELECT   r.RoundingTypeInvariantCode ,
                                a.AgingDateValue ,
                                cur.CurrencyLabel ,
                                jz.JobZoneLinkTypeLabel ,
                                m.MatchPeriodLabel ,
                                pf.PayFrequencyLabel ,
                                pt.PayTypeLabel
                       FROM     dbo.tenant_User_Setting s
                                JOIN TRCCore.dbo.pr_Rounding_Type r ON r.RoundingTypeID = s.RoundingTypeID
                                JOIN dbo.tenant_Aging_Date a ON a.AgingDateID = s.AgingDateID
                                JOIN TRCCore.dbo.translation_pr_Currency cur ON cur.CurrencyID = s.CurrencyID
                                                              AND cur.LanguageCultureCode IN (SELECT InvariantLanguageCultureCode FROM y)
                                JOIN dbo.translation_tenant_Job_Zone_Link_Type jz ON jz.JobZoneLinkTypeID = s.JobZoneLinkTypeID
                                                              AND jz.LanguageCultureCode IN (SELECT InvariantLanguageCultureCode FROM y)
                                JOIN dbo.tenant_Match_Period m ON m.MatchPeriodID = s.MatchPeriodID
                                JOIN dbo.translation_tenant_Pay_Frequency pf ON pf.PayFrequencyID = s.PayFrequencyID
                                                              AND pf.LanguageCultureCode IN (SELECT InvariantLanguageCultureCode FROM y)
                                JOIN dbo.translation_app_Pay_Type pt ON pt.PayTypeID = s.PayTypeID
                                                              AND pt.LanguageCultureCode IN (SELECT InvariantLanguageCultureCode FROM y)
                       WHERE    s.UserID IN (SELECT UserID FROM x)
                     )
        SELECT * FROM Default_User_Settings_CTE


texts: Coordinates Struct for Flow Field Pathfinding... am I doing this right?

texts:
I am slowly creating a flow field pathfinding solution for Unity3D.  I'm trying to follow Elijah Emerson's description, which appears in the book 'Game AI Pro' (volume 1).
The map is divided into sectors, and each sector houses three fields: cost, integration, flow, which need each other to calculate the flow field.
At one point I got fed up trying to reference locations in space between sectors and fields, so created a Coordinates object to handle this task.  But I'm not sure if I've created an object which makes good sense for an optimal solution?  I initially created a Struct, because the object is a data type which holds just world X and Y, along with a reference to the world this belongs to.
Because of this, I didn't want to load the object with more data fields, but I did need to reference various things described above.  So I added get-only properties which call data from elsewhere.  But is this fast and optimal?  I don't know.  I know there's an inevitable trade between memory and processing, but I just don't know what makes sense here for a fast solution.
using UnityEngine;

public struct Coordinates
{
    public readonly FlowFieldWorld world;
    public readonly int worldX, worldY;
    public int SectorX { get { return worldX % world.SectorSize; } }
    public int SectorY { get { return worldY % world.SectorSize; } }
    public FlowFieldSector Sector { get { return world.Sectors[worldX / world.SectorSize, worldY / world.SectorSize]; } }
    public CostTile Cost { get { return Sector.CostField[SectorX, SectorY]; } }
    public IntegrationTile Integration { get { return Sector.IntegrationField[SectorX, SectorY]; } }
    public FlowTile Flow { get { return Sector.FlowField[SectorX, SectorY]; } }
    public bool IsWalkable { get { return Cost.Value != 255; } }
    public readonly static Coordinates zero = new Coordinates(0, 0, null);
    public Vector3 Vector3 { get { return new Vector3(worldX, 0, worldY); } }

    public Coordinates(int worldX, int worldY, FlowFieldWorld world)
    {
        this.worldX = worldX;
        this.worldY = worldY;
        this.world = world;
    }

    public Coordinates(Coordinates coordinates)
    {
        this.worldX = coordinates.worldX;
        this.worldY = coordinates.worldY;
        this.world = coordinates.world;
    }

    public static bool operator ==(Coordinates left, Coordinates right)
    {
        return left.worldX == right.worldX && left.worldY == right.worldY;
    }

    public static bool operator !=(Coordinates left, Coordinates right)
    {
        return left.worldX != right.worldX || left.worldY != right.worldY;
    }

    public override bool Equals(object obj)
    {
        return obj is Coordinates coordinates && Equals(coordinates);
    }

    public bool Equals(Coordinates other)
    {
        return worldX == other.worldX && worldY == other.worldY;
    }

    public override int GetHashCode()
    {
        int hashCode = 1845962855;
        hashCode = hashCode * -1521134295 + worldX.GetHashCode();
        hashCode = hashCode * -1521134295 + worldY.GetHashCode();
        return hashCode;
    }

}


texts:
Task : Implement Insertion Sort in Python.

def insert_sort(a):
""" Fuction to sort a given list a """
    if len(a)==0:
        print "Please give valid input"
    for i in range(1, len(a)):
        current = 0
        while current < i:
            if a[i] < a[current]:
                a[current], a[i]= a[i] , a[current]
            current = current + 1
    return a

print insert_sort([12,54,66,43,11,33,34,33,1,45])

How can this code be better?


texts: IDL code for minimum distance calculation

texts:
I made a program in IDL for performing a minimum distance classification on multispectral satellite data. This is what my main function looks like:

function minimum_distance, stack, exercising_data

  ;variables
  nbands = get_number_of_bands()
  nclasses = get_number_of_classes()
  x_size = (size(stack, /DIMENSIONS))[0]
  y_size = (size(stack, /DIMENSIONS))[1]
  result = MAKE_ARRAY(x_size,y_size,/INTEGER)

  ;calculate class mean for each class
  class_means = calculate_class_means(exercising_data)

  ;find closest class mean for each point and create result image
  i = 0
  foreach point, stack[0,*,0], i do begin
    foreach point, stack[*,i,0], j do begin
      print, string(i) + "-" + string(j)
      point = REFORM(stack[j,i,*],7,1)
      dist_array = [[point],[class_means]]
      class = (DISTANCE_MEASURE(dist_array))[0:nclasses-1]
      class = min(class,location)
      result[j,i] = location
    end
  end

  ;prepare result for display
  result = result * (255/(nclasses-1))
  result = REVERSE(ROTATE(result,2))

  return, result

end

The stack is an array of tif files of Landsat 7 data that I load with the read_tiff function. The exercising data looks like this:

;Forst
[ $
  [39,25,21,29,14,80,12], $
  [40,25,20,28,11,79,12], $
  [37,24,20,29,14,81,11], $
  [43,28,25,34,14,79,12], $
  [44,29,29,40,13,79,13], $
  [41,27,23,32,14,80,13], $
  [0,0,0,0,0,0,0], $
  [46,31,27,36,13,79,12] $
], $

... (more classes)

;Water
[ $
  [39,24,19,13,9,92,10], $
  [37,22,19,13,9,92,10], $
  [38,24,20,13,9,90,10], $
  [40,24,22,15,9,89,10], $
  [37,22,19,13,10,92,9], $
  [38,23,20,13,10,89,9], $
  [37,23,18,13,9,90,9], $
  [39,25,20,13,9,90,9] $
] $

The program actually works, but doesn't have a good performance. This is due to the nested foreach-loops within the minimum_distance function. With larger satellite images it takes a very long time to process. I can imagine that you can reach a much better performance using some IDL function that I don't know of. Do you know a way in how I can give this program a better performance and replace the foreach-loops?

If you want to take a look at the complete program, here it is.


texts: Should this Point class remain a class, or become a struct?

texts:
I am just beginning to dabble in C++. Would you implement this as a class like I did, or a struct? What are the pros and cons?

class Point
{
private:
    double _x;
    double _y;

public:
    Point();
    Point(double x, double y);
        ~Point();
        Point(Point& other);
        double GetX();
        void SetX(double x);
        double GetY();
        void SetY(double y);
};

Point::Point() : _x(0.0), _y(0.0)
{
}

Point::Point(double x, double y) : _x(x), _y(y)
{
}

Point::Point(Point& other) : _x(other._x), _y(other._y)
{
}

Point::~Point()
{
}

double Point::GetX()
{
    return _x;
}

void Point::SetX(double x)
{
    _x = x;
}

double Point::GetY()
{
    return _y;
}

void Point::SetY(double y)
{
    _y = y;
}


texts: childrenCount function in old and functional styles

texts:
I'm trying to transition myself from my old coding-style (if-else, for.. in) to functional programming. I've tried to update the following code:

Old

class test {
    childrenCount(group) {
        let childCount = 0;
        let excluded = ['html'];
        let iterable = group.children || group;

        for (let key in iterable) {
            let elem = iterable[key];

            if (elem.type === 'group') {
                this.childrenCount(elem);
            }else if (element.properties && excluded.indexOf(elem.properties.type) == -1){
                childCount += 1;
                if(!elem.visibility){
                    childCount -= 1;
                } else if (element.properties.seen && !element.properties.showerror || element.properties.required){
                    childCount -= 1;
                }
            }
        }
        group.childrenCount = childCount;
    }
}

New

class test {
    childrenCount(group){
        group.childrenCount = 0;
        let excluded = ['html'];
        let iterable = group.children || group;

        let countElement = (elem) => {
            if (isCountable(elem))
                return isVisible && isValidAnswer(elem) ? 0 : 1;
            return 0;
        };

        let isValidAnswer = elem => {
            return (elem.properties.seen && !elem.properties.showerror) ||
                   !elem.properties.required;
        };

        let isVisible = elem => {
            return !elem.visibility;
        };

        let isCountable = elem => {
            try{return excluded.indexOf(elem.properties.type) == -1;}
            catch (err) {}
        };

        let isGroup = elem => {
            return elem.type === 'group';
        };

        Object.keys(iterable).forEach(k => {
            let elem = iterable[k];
            if(isGroup(elem))
                this.childrenCount(elem)
            else
                group.childrenCount += countElement(elem);
        });
    }
}

Now I am thinking: the old code was smaller. It was not as readable, but the new code is significantly bigger.

Is my functional programming too excessive?
Is it better or worse then my old way of writing functions?
Are both methods just plain right or wrong, any advice for improvement?

I feel that the second one is more testable because I could test the individual functions, that's important I think. But on the other hand, if I have enough input-space-partitioning, the first one would be testable too (just less precise).


texts: C# Performance in a CircularBuffer architecture in size and time

texts:
I need to speed up a circular buffer that has space and time requirements.
Each cell in the circular buffer represents a list of N elements to be sent. The shipment takes place if the list reaches N elements, or if the elapsed time exceeds X ms.
At the moment I have found this solution, but I am quite sure it is not the best possible to achieve my goal. I would like to understand if there are improvements for architecture.
public class RingBuffer<T> : IDisposable
{
    protected class TimerArray
    {
        private Timer _timer;
        private Int32 _index;
        private RingBuffer<T> _ring;

        public TimerArray(RingBuffer<T> ring, Int32 index)
        {
            _index = index;
            _ring = ring;
            _timer = new Timer(t => { ring.Send(_index); }, null, ring.TimerPeriod, ring.TimerPeriod);
        }

        public Boolean TimerReset()
        {
            return _timer.Change(_ring.TimerPeriod, _ring.TimerPeriod);
        }
    }

    protected Object _locker = new Object();
    protected ConcurrentQueue<T>[] _buffers;
    protected TimerArray[] _timer;
    protected Int64 current = 0;

    public Int32 RingDimension { get; set; }
    public Int32 SendSize { get; set; }
    public Int32 TimerPeriod { get; set; }
    public ISender Sender { get; set; }

    public Int64 BufferSize { get; set; }

    public RingBuffer(ISender sender, Int32 size, Int32 msTimer)
    {
        RingDimension = 10;
        Init(sender, size, msTimer);
    }

    public RingBuffer(ISender sender, Int32 dimension, Int32 size, Int32 msTimer)
    {
        RingDimension = dimension;
        Init(sender, size, msTimer);
    }

    protected void Init(ISender sender, Int32 size, Int32 msTimer)
    {
        _buffers = new ConcurrentQueue<T>[RingDimension];

        Sender = sender;
        SendSize = size == 0 ? -1 : size;
        TimerPeriod = msTimer;

        for (int i = 0; i < RingDimension; i++)
            _buffers[i] = new ConcurrentQueue<T>();

        if (TimerPeriod > 0)
        {
            _timer = new TimerArray[RingDimension];
            for (int i = 0; i < RingDimension; i++)
                _timer[i] = new TimerArray(this, i);
        }
    }

    public void Enqueue(T item)
    {
        lock (_locker)
        {
            if (!Object.ReferenceEquals(item, null))
                _buffers[current].Enqueue(item);
        }

        if (_buffers[current].Count >= SendSize)
        {
            lock (_locker)
            {
                if (_buffers[current].Count >= SendSize)
                {
                    var previous = Interlocked.Exchange(ref current, (current + 1) % RingDimension);
                    if (TimerPeriod > 0)
                        _timer[previous].TimerReset();

                    BufferSize += Sender.Enqueue(_buffers[previous].ToList());
                    _buffers[previous] = new ConcurrentQueue<T>();
                }
            }
        }
    }

    protected void Send(Int64 index)
    {
        if (_buffers[index].Count > 0)
        {
            lock (_locker)
            {
                if (_buffers[index].Count > 0)
                {
                    BufferSize += Sender.Enqueue(_buffers[index].ToList());
                    _buffers[index] = new ConcurrentQueue<T>();
                }
            }
        }
    }

    public virtual void Dispose()
    {
    }
}

Enqueue method is called by program anytime that a message is ready, check the list dimension and send it when list is full.
Send method is called by a Timer array that set a boundry limit for message latency.


texts:
I have a widget like below:

class MainWidget(QWidget):
    #This is grabbed by another function for the name of the page
    name = "First Page"

    def __init__(self, parent, sidebarWidget, customModulesLen):
        QWidget.__init__(self, parent=parent)
        self.customModulesLen = customModulesLen #How many pages there are total
        self.parent = parent #The parent QStackedWidget
        self.sidebarWidget = sidebarWidget #The progress sidebar

        #This the only real content so far, a button to go to the next page
        lay = QVBoxLayout(self)
        pushButton = QPushButton("Next")
        lay.addWidget(pushButton)
        pushButton.clicked.connect(self.onNext)

    def onNext(self):
        """Iterate forward in the QStackedWidget, and update the progress bar"""

        if self.parent.Stack.currentIndex() < self.customModulesLen:
            activeMenu = self.sidebarWidget.menuContainer.findChildren(QLabel)[self.parent.Stack.currentIndex() + 1]
            activeMenu.setPalette(self.sidebarWidget.activeMenuPalette)
            previousMenu = self.sidebarWidget.menuContainer.findChildren(QLabel)[self.parent.Stack.currentIndex()]
            previousMenu.setPalette(self.sidebarWidget.inactiveMenuPalette)

        self.parent.Stack.setCurrentIndex((self.parent.Stack.currentIndex() + 1) % (self.customModulesLen + 1))

The above widget is a page that I'm importing and using for a QStackedWidget. It works just fine, and doesn't appear to be against any major conventions to me atleast.

The problem is that I've never really done this before in PyQT, and I'm having some difficulty determining if this is a good approach at accomplishing this, or if there's some shortcuts or general good idea's I'm missing.


texts:
The problem I want to solve is to replace a given string inside tags.

For example, if I'm given:

  Some text abc [tag]some text abc, more text abc[/tag] still some more text

I want to replace abc for def but only inside the tags, so the output would be:

  Some text abc [tag]some text def, more text def[/tag] still some more text

We may assume that the tag nesting is well formed. My solution is the following:

def replace_inside(text):
    i = text.find('[tag]')
    while i >= 0:
        j = text.find('[/tag]', i+1)
        snippet = text[i:j].replace('abc', 'def')
        text = text[:i] + snippet + text[j:]
        i = text.find('[tag]', j)
    return text

I was wondering if it can be solved in a more elegant way, for example, using regex.


texts: Using global variables in my node.js program configuration

texts:
I know using global variables in JavaScript is bad practice.  Here I am using config, host and port as global variables as I have added a watch function to watch for the changes in the config.json file.  Is the use of global variables in this example a bad practice or is it ok to use them?

config.json file

{
    "host":"127.0.0.1",
    "port":8000
}

server.js file

(function(){

    var fs = require("fs");
    config = JSON.parse(fs.readFileSync("config.json")); //global variable
    host = config.host;  //global variable
    port = config.port;  //global variable
})();

var http = require("http");
var server = http.createServer(function(request,response){
    response.writeHead(200,{"Content-Type":"text/plain"});
    response.end("Hello World");
});

server.listen(port,host,function(){
    console.log("Server listening at:"+host+" on port:"+port);
});

fs.watchFile("config.json",function(){
    config = JSON.parse(fs.readFileSync("config.json"));  //global variable(overwritten)
    host = config.host;  //global variable(overwritten)
    port = config.port;  //global variable(overwritten)

    server.close();
    server.listen(port,host,function(){
          console.log("Server listening at:"+host+" on port:"+port);
       };
    }
});


texts: Function to generate all subsets of size n

texts:
The function works this way:

Set is an instance variable, and is an array of type generic.
nElement is the size of all the subsets that you want. For example if you give it the value 3 the function will return all the subsets of Set of size 3
The idea is that we create an array named indices (indices = index in French) that will follow the index that we want for each subset.
We know that all of our subsets have a size of 3 elements so if indices[2] = 3 we have to increment indices[1] by 1 and set all of the following indices[i] to indices[i-1]+1.

Example

Set = {1,2,3,4} nElement = 3

for the first subset the indices = {0,1,2} -> {1,2,3}
for the second subset the indices = {0,1,3} -> {1,2,4} indices[2] = 3 so we indices[1]++ and indices[2] = indices[1]+1
for the third subset the indices = {0,2,3} -> {1,3,4} indices[2] = indices[2] = 3 so we indices[1]++ and indices[2] = indices[1]+1 but indices[1] now = 2 and the max value that indices[1] can have is 2 so indices[0]++ and indices[1] = indices[0]+1
for the fourth subset the indices = {1,2,3} -> {2,3,4}

Code

public List<T[]> GenerateCoupleOf(int nElement)
{
    if (nElement < 1)
        throw new Exception("nElement must be greater than 0");

    List<T[]> tr = new List<T[]>();
    T[] arr;

    int[] indices = new int[nElement];
    T[] temp_arr = new T[nElement];

    for (int i = 0; i < indices.Length; i++)
        indices[i] = i;

    while (indices[0] <= Set.Length - 1 - ((Set.Length - 1) - (Set.Length - 1 - indices.Length + 0)) + 1)
    {
        for (int i = 0; i < indices.Length; i++)
            temp_arr[i] = Set[indices[i]];

        arr = new T[nElement];

        for (int i = 0; i < indices.Length; i++)
            arr[i] = Set[indices[i]];

        tr.Add(arr);

        indices[indices.Length - 1]++;

        for (int i = indices.Length - 1; i > 0; i--)
        {
            if (indices[i] > Set.Length - 1 - ((Set.Length - 1) - (Set.Length - 1 - indices.Length + i)) + 1)
            {
                indices[i - 1]++;
                for (int j = i; j < indices.Length; j++)
                    indices[j] = indices[j - 1] + 1;
            }
        }
    }

    return tr;
}


texts: Squaring the two digits in the middle of a four-digit number

texts:
I got a four-digit positive number. I need to square the two digits in middle to generate a new number on which the same procedure is applied. The numbers get saved in a list. This loops as long as there isn't an equal number generated (the list contains the number already). If a number is generated containing less than four digits, the code takes the first and middle digit.

1 23 4
23² = 529
52 9
52² = 2704
2 70 4
70² = ...

I've done the core magic within int current = (int) Math.Pow (number % 1000 / 10, 2);. Is this the most elegant way to solve this?

ArrayList<int> numbers = new ArrayList<int> ();

public void generateNumbers (int number) {

    // just in case :)
    if (number > 9999) {

        throw new ArgumentOutOfRangeException ("Number must be smaller than 10,000");

    }

    // Remove the thousands and get the times 10 fits in (you've only the two numbers in the middle left)
    int current = (int) Math.Pow (number % 1000 / 10, 2);

    // Repeat until an equal number is in the ArrayList
    if (numbers.Contains (current)) {

        return;

    } else {

        numbers.Add (current);
        this.generateNumbers (current);

    }

}


texts:
Assuming I have 5 arrays, all just indexed arrays, and I would like to combine them, this is the best way I can figure, has anyone found a more efficient solution?

function mymap_arrays() {
    $args = func_get_args();
    $key  = array_shift($args);

    return array_combine($key, $args);
}

$keys   = array('u1', 'u2', 'u3');
$names  = array('Bob', 'Fred', 'Joe');
$emails = array('bob@mail.com', 'fred@mail.com', 'joe@mail.com');
$ids    = array(1, 2, 3);

$u_keys = array_fill( 0, count($names), array('name', 'email', 'id') );

$users  = array_combine($keys,
            array_map('mymap_arrays', $u_keys, $names, $emails, $ids)
          );

This returns:

Array
(
    [u1] => Array
        (
            [name] => Bob
            [email] => bob@mail.com
            [id] => 1
        )

    [u2] => Array
        (
            [name] => Fred
            [email] => fred@mail.com
            [id] => 2
        )

    [u3] => Array
        (
            [name] => Joe
            [email] => joe@mail.com
            [id] => 3
        )

)

EDIT: After a lot of benchmarking, this is the fastest solution I've come up with

function test_my_new() {
    $args    = func_get_args();
    $keys    = array_shift($args);
    $vkeys   = array_shift($args);
    $results = array();

    foreach($args as $key => $array) {
        $vkey = array_shift($vkeys);

        foreach($array as $akey => $val) {
            $result[ $keys[$akey] ][$vkey] = $val;
        }
    }

    return $result;
}

$keys   = array('u1', 'u2', 'u3');
$names  = array('Bob', 'Fred', 'Joe');
$emails = array('bob@mail.com', 'fred@mail.com', 'joe@mail.com');
$ids    = array(1,2,3);
$vkeys  = array('name', 'email', 'id');

test_my_new($keys, $vkeys, $names, $emails, $ids);


texts: Find All Permutations of String in Scala

texts:
I created the following function, permutations, to produce all permutations of a List[A].
Example:
scala> net.Permutations.permutations("ab".split("").toList)
res3: List[List[String]] = List(List(a, b), List(b, a))

Code:
object Permutations {

  def permutations[A](str: List[A]): List[List[A]] =
    str match {
      case Nil => List(Nil)
      case list @ _ :: _ =>
        val shifteds: List[List[A]] =
          shiftN(list, list.length)

        shifteds.flatMap {
          case head :: tail =>
            permutations(tail).map { lists: List[A] =>
              head :: lists
            }
          case Nil => Nil
        }
    }

  private def shiftN[A](list: List[A], n: Int): List[List[A]] = {
    if (n <= 0) Nil
    else {
      val shifted: List[A] = shift(list)
      shifted :: shiftN(shifted, n - 1)
    }
  }

  private def shift[A](arr: List[A]): List[A] = arr match {
    case head :: tail => tail ++ List(head)
    case Nil => Nil
  }
}

I think it's correct since the following property-based check succeeds:
import munit.ScalaCheckSuite
import org.scalacheck.Prop._
import org.scalacheck.Gen

class PermutationsSpec extends ScalaCheckSuite {

  private val listGen: Gen[List[Int]] =
    for {
      n <- Gen.choose(0, 7)
      list <- Gen.listOfN(n, Gen.posNum[Int])
    } yield list

  property("permutations works") {
    forAll(listGen) { list: List[Int] =>
      val mine: List[List[Int]] = Permutations.permutations(list)
      val stdLib: List[List[Int]] = list.permutations.toList
      assert(stdLib.diff(mine).isEmpty)
    }
  }

}

Please evaluate for correctness, concision and performance.


texts:
I implemented type (UserRuleManager) that will apply list of rules to entity User. I need your code review and your advices.

Here is usage of that type

private void ProcessUser(User user)
{
    if (!_userRuleManager.ApplyGeneralRules(user))
    {
        SetWarning();
    } else if (!_userRuleManager.ApplySpecificRules(user)) {
        SetWarning();
    } else {
        CreateUser(user);
    }
}
private void SetWarning()
{
    foreach (var warningMessage in _userRuleManager.GetWarnings())
    {
        Warnings.Add(warningMessage);
    }
}

I have 2 types of rule: general and specific.  First, I'm trying to apply general rules (ApplyGeneralRules) and if it is false then get list of warnings. The same for specific rules (ApplySpecificRules).

In implementation of UserRuleManager I have:

private list of warnings:

   private readonly List<string> _warnings;

private property

    private bool IsVerified
    {
        get { return _warnings.Count == 0; }
    }

method to return list with warnings

public ICollection<string> GetWarnings()
{
    return _warnings;
}

method for general rules

public bool ApplyGeneralRules(User user)
{
    _warnings.Clear();
    ICollection<Rule> rules = _userRepository.GetActiveGeneralRules(user.CustomerId);

    foreach (Rule rule in rules.OrderBy(x => x.Order))
    {
        if (RuleChecker.IsVerified(rule, user))
        {
            _warnings.Add(string.Format("General rule : {0}", rule.TypeId));
        }
    }

    return IsVerified;
}

and method for specific rules

public bool ApplySpecificRules(User user)
{
    _warnings.Clear();
    var questions = GetQuestions(user);

    if (!questions.Any())
    {
        _warnings.Add(string.Format("No questions with code {0}", user.QuestionCodeId));
        return false;
    }
    foreach (var question in questions.OrderBy(q => q.Order))
    {
        var rules = _userRepository.GetSpecificRules(user.CustomerId, question.Id);
        foreach (var rule in rules)
        {
            if (!RuleChecker.IsVerified(rule, user))
            {
                _warnings.Add(string.Format("Specific rule: {0} -> {1} -> {2}", question.TypeId, question.CodeId, rule.TypeId));
            }
        }
    }

    return IsVerified;
}

Could you please give me advice how can I improve or maybe implement more proper relation between this entities. What the pattern can I use here?
 Thank you in advance and let me know if I should give more information

UPDATE

public static bool IsVerified(Rule rule, User user) {

RuleParameterValue daysParameter = rule.RuleParameterValues.SingleOrDefault(v => v.RuleParameterTypeId == Rule.Parameter.Days);

if (daysParameter == null) {
    return false;
}

int days = daysParameter.IntValue;
DateTime? lastLoginDateUtc = _userRepository.GetLastLoginDate(user.Id);
if (lastLoginDateUtc == null || lastLoginDateUtc.Value.AddDays(days) <= DateTime.UtcNow) {
    return true;
} else {
    return false;
}
}


texts:
I wrote a simple quadratic function solver with unit tests. Can anyone check if this is okay?

Quadratic function class

public class QuadraticFunction {
    private Integer a,b,c;

    public QuadraticFunction(Integer a, Integer b, Integer c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public Result calculate() throws NullPointerException{
        if(calculateDelta()>0){
          return new DeltaBiggerThanZero(calculateX1(),calculateX2());
        }else if(calculateDelta() == 0){
            return new DeltaEqualsZero(calculateOneRoot());
        }else{
            return new NoSolution();
        }
    }

    private Double calculateDelta(){
        return Math.pow(b,2) - 4*a*c;
    }

    private Double rootOfDelta(){
        return Math.sqrt(calculateDelta());
    }

    private Double calculateX1(){
        return (-b-rootOfDelta())/2*a;
    }

    private Double calculateX2(){
        return (-b+rootOfDelta())/2*a;
    }

    private Double calculateOneRoot(){
        return Double.valueOf((-b)/2*a);
    }

Result class example

final public class DeltaBiggerThanZero implements Result{

    private Double x1, x2;

    public Double getX1() {
        return x1;
    }

    public Double getX2() {
        return x2;
    }

    public DeltaBiggerThanZero(Double x1, Double x2) {
        this.x1 = x1;
        this.x2 = x2;
    }
    public String printSimpleResult() {
        return "Rozwiązaniem równiania jest: x1="+x1+" x2="+x2;
    }
}

This is a test:

public class QuadraticFunctionTest {
    @Test
    public void testIfEquationHasTwoResults() throws Exception {
        QuadraticFunction quadraticFunction = new QuadraticFunction(1,-4,-5);
        Result result = new DeltaBiggerThanZero(-1.0,5.0);

        assertEquals(quadraticFunction.calculate().getX1(), result.getX1());
        assertEquals(quadraticFunction.calculate().getX2(), result.getX2());
    }

    @Test
    public void testIfEquationHasOneResult(){
        QuadraticFunction quadraticFunction = new QuadraticFunction(1,6,9);
        Result result = new DeltaEqualsZero(-3.0);

        assertEquals(result.getX1(), quadraticFunction.calculate().getX1());
    }

    @Test
    public void testIfTheresNoSolution() throws Exception {
        QuadraticFunction quadraticFunction = new QuadraticFunction(1,2,5);
        Result result = new NoSolution();
        assertEquals(quadraticFunction.calculate().getX1(), null);
        assertEquals(quadraticFunction.calculate().getX2(), null);
    }
}


texts:
I build an addition chain (more information about addition chains: Wikipedia) calculator that produces shorter chains than chains with the length equal to the number that's being tried to achieve.
It doesn't always produces the shortest chains (if were talking about a big number). However still gives a pretty short chain compared to the max sized chain the number would get.
It is faster than, brute-force calculating (but obv. less accurate in finding the shortest chain (like I said above)), since it relies on an algorithm (I'm not sure if an algorithm is the right word, but basically I just used logical steps to find a short chain). Basically it starts from the given number and goes backwards to 1.

It works as followed:

Check if the number is even or odd, if it's odd check if it's a prime number.
If it's an even number, just divide by 2. If it's odd find the biggest factor and divide the number by it, till the factor itself is reached. If it's a prime number, subtract it by 1 and follow the steps for an even number
Step 1 and 2 are always repeated, and before (before and after would duplicate the values, so only 'before') every action, the current state of the number is added to a list

(It is also checking if every number had (n+1)/2 length of chains, so there's a tiny step for that, but that's not very important. This was an extra thing I did, for my math class.)
So let's say we have 5, it's an odd number so we subtract by 1 to get an even number: 4. Now we divide it by 2 and get 2, since 2 is also an even number we divide again and we got to 1 and the program stops and prints the list which is: [5, 4, 2, 1] (which is the shortest possible addition chain (I know that this only works for tiny numbers btw, for big numbers it still shortens the chain (of max size) a lot which is cool for me))

I am learning programming by myself and haven't touched sort/search algorithms, what could I have done better in terms of the quality of my code or even the logical steps I use to calculate?

n = int(input())  # kan tot 8 cijfers snel(<1min), na 8 traag

BewijsN = (n + 1) / 2

List1 = []

def IsEven(n):
    if n % 2 == 0:
        return True

    else:
        return False

def IsPrime(n):
    for x in range(n - 2):
        x += 2

        if n % x == 0:
            return False

    return True

def BigFactorCheck(n):
    for x in range(n):
        x += 1

        if n % (n - x) == 0:
            return n - x

while n > 1:
    if IsEven(n) == False:

        if IsPrime(n):
            List1.append(n)
            n += -1  # Prim naar even

        else:  # Oneven
            List1.append(n)
            BigFactor = BigFactorCheck(n)

            for x in range((n // BigFactor) - 2):
                x += 1
                List1.append(n - BigFactor * x)

            n = n - BigFactor * (x + 1)  # lelijk, maar werkt

    while IsEven(n):
        List1.append(n)
        n = n // 2

        if n == 1:
            List1.append(n)

List1.sort()
print(len(List1), List1)
if len(List1) - 1 <= BewijsN:
    print(True, len(List1) - 1, "<=", BewijsN)


texts: Deeply nested search through Document tree

texts:
I have this code block, where I search for the value of Ordnungsbegriff. I have to search through a tree of my CurrentDocument.

How can I rewrite it to be more dynamic? I don't know at which level I will find my value.

string xy = "";
try
{

    if (string.IsNullOrEmpty(CurrentDocument.Ordnungsbegriff))
    {
        if (string.IsNullOrEmpty(CurrentDocument.ParentDocument.Ordnungsbegriff))
        {
            if (string.IsNullOrEmpty(CurrentDocument.ParentDocument.ParentDocument.Ordnungsbegriff))
            {
                if (string.IsNullOrEmpty(CurrentDocument.ParentDocument.ParentDocument.ParentDocument.Ordnungsbegriff))
                {
                    if (string.IsNullOrEmpty(CurrentDocument.ParentDocument.ParentDocument.ParentDocument.ParentDocument.Ordnungsbegriff))
                    {
                        if (string.IsNullOrEmpty(CurrentDocument.ParentDocument.ParentDocument.ParentDocument.ParentDocument.ParentDocument.Ordnungsbegriff))
                        {
                            if (string.IsNullOrEmpty(CurrentDocument.ParentDocument.ParentDocument.ParentDocument.ParentDocument.ParentDocument.ParentDocument.Ordnungsbegriff))
                            {
                                xy = "Nach 6. Ebene, Suche abgebrochen.";
                            }
                            else
                                xy = CurrentDocument.ParentDocument.ParentDocument.ParentDocument.ParentDocument.ParentDocument.ParentDocument.Ordnungsbegriff;
                        }
                        else
                            xy = CurrentDocument.ParentDocument.ParentDocument.ParentDocument.ParentDocument.ParentDocument.Ordnungsbegriff;
                    }
                    else
                        xy = CurrentDocument.ParentDocument.ParentDocument.ParentDocument.ParentDocument.Ordnungsbegriff;
                }
                else
                    xy = CurrentDocument.ParentDocument.ParentDocument.ParentDocument.Ordnungsbegriff;
            }
            else
                xy = CurrentDocument.ParentDocument.ParentDocument.Ordnungsbegriff;
        }
        else
            xy = CurrentDocument.ParentDocument.Ordnungsbegriff;
    }
    else
      xy = CurrentDocument.Ordnungsbegriff;

}
catch (Exception)
{
    xy = "Fehler in  Suche";
}


texts: PHP Going Multiple Directories Back Best Practice

texts:
I'm writing a php library for managing configurations of an application.

but the problem is anyone who uses my library will store their configuration files in ./config folder of their project root directory.

e.g. var/www/example.com/config/site.php

and my library is installed in a sub directory of the project

i.e  vendor/azi/config/src/Config.php

To Load files from project root i am doing it this way

    if (!defined('PATH_TO_CONFIG_DIR')) {
        define('PATH_TO_CONFIG_DIR', dirname(dirname(dirname(dirname(dirname(__FILE__))))) . "/config/");
    }

is it right
? Or It can be more efficient. Code suggestion will be helpful.

Github : https://github.com/azeemhassni/Config


texts:
I often use jQuery plugins for front-end functionality in web applications. This requires me to write code like this, where I am assigning a function to an object property:

var trainingDiary = $("#training_diary").fullCalendar({
  dayClick: function(date, allDay, jsEvent, view) {

    var title = prompt('Event Title:');
    var dayObj = $(this);
    //console.log($(this));
    if (title) {
     $.ajax({
      url: "/app_dev.php/addtrainingday",
      global: false,
      type: "POST",
      data: "dayNo=" + date.getDate(), //returns day of month. getDay() returns day of week
      async:true,
      success: function(msg) {

               trainingDiary.fullCalendar('renderEvent',
                {
                  title: title,
                  start: date,
                  allDay: allDay,
                  backgroundColor:'#cccccc'
                },
            true // make the event "stick" across calendar pages
          )

      dayObj.css({'background-color':'#339933','background-image':'url()'})
      console.log(msg.valueOf());
      } //end ajax success
     })
   } else {
      trainingDiary.fullCalendar('unselect');
   }

  },

  theme: true,
  header: {left:'title',
            center: '',
            right: 'today prev next'},
  firstDay:1

});

The code becomes hard to read and maintain as there is now a success function within an Ajax function within yet another function. How can I improve the code so that dayClick: function(...) can call a function defined outside of the fullCalendar call? In this case, fullCalendar is a jQuery plugin.


texts:
let formData = new FormData();
  formData.append('File', document.file);
  formData.append('DocumentType', document.documentType);

  product = {
    ...values,
    productType: productT,
  };

  for (var key in product) {
    if (key != 'createdDate' && key != 'expirationDate') {
      formData.append(key, product[key]);
    } else {
      formData.append(key, new Date(product[key]).toUTCString());
    }
  }

  await createproduct(formData);

I need to send file and other data about product in one request so I added all the stuffs in FormData, and I have issues only with Dates, I must convert it to date because somehow it get confused if I don't convert it.

Can I somehow refactor this code to do this part about dates more elegant, if condition in for loop somehow smells bad..

P.S EDIT:

for (var key in product) {
   const transform = DateTransformer[key];
   formData.append(key, transform ? transform[product[key]] : product[key]);
}


texts: List iteration, creation, or comprehension

texts:
I suspect that this can be done in a much neater way using list comprehension in python:

poses = []
for x,y in get_points(spline):
    pose = Pose2D()
    pose.theta = 0
    pose.x=x
    pose.y=y
    poses.append(pose)
return poses

Is there a way to create a nice one liner for the above? (I do not have a constructor that takes the three arguments for Pose2D)


texts:
I have a program that will format a phone number in this format: (###)###-####

def obtain_phone_number
  loop do
   print 'Enter phone number: '
    phone_num = gets.chomp
    if !(phone_num[/\d{10}/])
      puts 'Invalid phone number, must contain 10 digits only'
    else
      formatted_phone_num = phone_num.insert(0, '(').insert(4, ')').insert(8, '-')
      return formatted_phone_num
    end
  end
end

When run:

irb(main):013:0> obtain_phone_number
Enter phone number: 1234567894
=> "(123)456-7894"
irb(main):014:0> obtain_phone_number
Enter phone number: 7894561234
=> "(789)456-1234"
irb(main):015:0> obtain_phone_number
Enter phone number: 5555555555
=> "(555)555-5555"

This works and all, and is great, but are there better ways to format a phone number? Something that's not as ugly as phone_num.insert(0, '(').insert(4, ')').insert(8, '-'). This just seems like it could be done in a more simplistic and easier way, and not to mention it will allow more than 10 digits.


texts: How to optimize the code to save data at GAE datastore?

texts:
I have the following code (for Country and City classes key_name is numeric id with addition of 'i' at the beginning):

def add_country(country, country_name):
  if country and country_namef and country_name != '':
    return Country.get_or_insert('i'+str(country), country_name=country_name)
  else:
    return None

def add_city(city, city_name, country):
  if country and city and city_name and city_name != '':
    return City.get_or_insert('i'+str(city), city_name=city_name, parent=country)
  else:
    return None

Is it correct code or can it be optimized somehow?


texts:
following code below works fine but feels kind of a mess. any one has a better way to do this
I am creating a basic "Enter Pin" to unclick screen on a app. So if user enter 1st digit, than ellipse1 should be filled. and if user enter 2nd digit, than ellipse1 and ellipse2 should be filled. and if user enter 3rd digit, than ellipse1, ellipse2, and ellipse3 should get filled. and so on
in view class, I have 4 ellipse, representing 4 digit pin. if user enter a digit, ellipse color get filled.
in viewmodel, I am a method that check if digit was pressed. if it is than fill ellipse color
in helperclass, i am just checking if ellipse is transpaent (not pressed), or fill color (key was pressed)
view class
 <Ellipse Fill="{Binding EllipseFill1}" />
 <Ellipse Fill="{Binding EllipseFill2}" />
 <Ellipse Fill="{Binding EllipseFill3}" />
 <Ellipse Fill="{Binding EllipseFill4}" />

ViewModel class
  List<int> CreatePin = new List<int>; //4 digit pin is store here
  public void OnKeypadTapCommand(string value)
    {
        //Set color of Pin
        EllipseFill1 = helperCLass.SetColorPin(CreatePin, Brush.White, 1);
        EllipseFill2 = helperCLass.SetColorPin(CreatePin, Brush.White, 2);
        EllipseFill3 = helperCLass.SetColorPin(CreatePin, Brush.White, 3);
        EllipseFill4 = helperCLass.SetColorPin(CreatePin, Brush.White, 4);
    }

Heloperclass
    public Brush SetColorPin(List<int> valueList, Brush value, int PinNumber)
    {
        //Pin#1
        if (PinNumber == 1)
        {
            if (valueList.Count == 0)
                return Brush.Transparent;
            else
                return value;
        }
        //Pin#2
        else if (PinNumber == 2)
        {
            if (valueList.Count == 0 || valueList.Count == 1)
                return Brush.Transparent;
            else
                return value;
        }
        //Pin#3
        else if (PinNumber == 3)
        {
            if (valueList.Count == 3 || valueList.Count == 4)
                return value;
            else
                return Brush.Transparent;
        }
        //Pin#4
        else if (PinNumber == 4)
        {
            if (valueList.Count == 4)
                return value;
            else
                return Brush.Transparent;
        }
        else
        {
            return Brush.Transparent;
        }

    }


texts: Create 1% Sample Using Multiprocessing in Python

texts:
I'm trying to process a large dataset (300GB, myfile.txt in the script) line by line using multiprocessing. I want to define a 1% random sample based one variable (contained in unique_ids_final.txt). My first step is to define the sample and then I want to read the data file using multiprocessing. I would like to improve the efficiency of the code in two ways:

First, I'd like to pass the pct1 object from the parent to the child so that it only needs to be defined once. I've seen a description of this on thelaziestprogrammer.com: Pass Data to Workers w/o Globals, but I'm relatively new to python and don't understand how to implement it in my code.

Second, I'd like to define the chunks without reading in the data. In chunkify() I get the start of each chunk and the number of bytes that need to be read by looking for the end of the line after reading in 1MB of data. I was hoping to use seek to move forward by 1MB and then find the end of the line, but this creates problems because later I need to read in the chunks and read treats '\n' as one byte, while seek treats it as two.

Any other suggestions to increase efficiency would also be much appreciated!

#define sample
uid = list(line.strip() for line in open('Subsets/unique_ids_final.txt'))
pct1 = round(len(uid)/100)
random.seed(1)
id_pct1 = set(random.sample(uid, k=pct1))
id_pct1.add(vname)

#read original file and write 1% sample using multiprocessing
def worker(chunkStart, chunkSize, q):
    with open('myfile.txt') as f:
        tlines = []
        f.seek(chunkStart)
        lines = f.read(chunkSize).splitlines()
        for line in lines:
            data = line.split('*')
            if data[30] in id_pct1: tlines.append(line)
        q.put(tlines)
        return tlines

def chunkify(fname,size=1024*1024):
    fileEnd = os.path.getsize(fname)
    with open(fname, 'r') as f:
        chunkEnd2 = 0
        while True:
            chunkStart = chunkEnd2
            f.seek(chunkStart)
            f.read(size)
            chunkEnd1 = f.tell()
            f.readline()
            chunkEnd2 = f.tell()
            chunkSz = 1024*1024 + chunkEnd2 - chunkEnd1 - 1
            yield chunkStart, chunkSz
            if chunkEnd2 >= fileEnd:
                break

def listener(q):
    with open('myfile1pct.txt', 'w') as out_f1:
        while True:
            m = q.get()
            if m == 'kill': break
            else:
                for line in m:
                    out_f1.write(line+'\n')
                    out_f1.flush()

def main():

    manager = mp.Manager()
    q = manager.Queue()
    pool = mp.Pool()

    watcher = pool.apply_async(listener, (q,))

    jobs = []
    for chunkStart, chunkSize in chunkify('myfile.txt'):
        jobs.append(pool.apply_async(worker,(chunkStart,chunkSize,q)))

    for job in jobs:
        job.get()

    q.put('kill')
    pool.close()
    pool.join()

if __name__ == '__main__':
    main()


texts: Is this appropriate way to pass data from presentation to application layer?

texts:
What is the best practices to pass data from presentation to application layer?

Currently I have something like this:

in presentation layer:

the controller:

public class ProductController : Controller
{
    private readonly IProductService _productService;

    public ProductController(IProductService productService)
    {
        _productService = productService;
    }

    public ActionResult ProductCreateAction(ProductCreateViewModel vm)
    {
        _productService.CreateProduct(vm);
        return Json(new { Ok = true });
    }
}

and the view model:

public class ProductCreateViewModel : ICreateProductCommand
{
    public string Name { get; set; }
    public int Price { get; set; }
}

in application layer:

public class ProductService : IProductService
{
    public void Create(ICreateProductCommand command)
    {
        var product = new Product(command.Name, command.Price);
        //... add to repositoey and call SaveChanges ...
    }
}

public interface ICreateProductCommand
{
    string Name { get; set; }
    int Price { get; set; }
}

(using FluentValidation here)

public class CreateProductCommandValidator : AbstractValidator<ICreateProductCommand>
{
    public CreateProductCommandValidator()
    {
        RuleFor(x => x.Name)
            .NotEmpty();

        RuleFor(x => x.Price)
            .NotEmpty();
    }
}

Is it ok to continue using this approach or there are better practices?
Is it better to have one save action in controller or separate create/update actions?

i.e.:

public ActionResult Save(SomeViewModel vm)
{
    if(vm.Id.HasValue)
    {
        //update
    }
    else
    {
        //create
    }
}

vs.

public ActionResult Create(SomeViewModel vm)
{
    //create
}

public ActionResult Update(SomeViewModel vm)
{
    //update
}


texts:
I've automated downloading of data from a 3rd party website. The process involves logging into the site, downloading the data, then logging out - lather, rinse, repeat for each client.

The code is in VBA using Access as the host and Selenium Basic to handle the browser details. Hate all you want, but I've implemented it as a WebDownloader interface with multiple implementations (one for each of the sites I have to download from). Plus, when the only tool you have is a stone, everything looks like a nail....

Occasionally we can't get logged into the system for one or more of a variety of reasons (like our AP department is very slow about paying bills and a site will shut us off...).

The following code handles the login process. Prior to this, the browser is opened and the website's login page is retrieved. Once I've gotten to this point, it's safe to assume that everything is ready for the login process to begin.

This works, but it's ugly, and my concern is that the normal, expected course of action goes through the error handler.

Private Sub IWebDownloader_LoginToWebPage()

  Const USER_NAME_FIELD_ID As String = "login"
  Const PASSWORD_FIELD_ID As String = "password"
  Const LOGIN_BUTTON_CLASS_ID As String = "btn-form"

  LogManager.Log TraceLevel, "ApptPlusWebDownloader.IWebDownloader_LoginWebPage"

  On Error GoTo ErrorHandler
  With this.Driver
    .FindElementById(USER_NAME_FIELD_ID).SendKeys this.UserID
    .FindElementById(PASSWORD_FIELD_ID).SendKeys this.Password
    .FindElementByClass(LOGIN_BUTTON_CLASS_ID).Click
  End With
  Dim noteElement As WebElement
  Set noteElement = this.Driver.FindElementByClass("note")
  'assumes we find a note which, normally, we shouldn't
  this.IsLoggedIn = False
  If InStr(1, noteElement.text, "disabled") Then
    LogManager.Log WarnLevel, "Login disabled --- ApptPlus message: " & noteElement.text
  Else
    LogManager.Log WarnLevel, "Login warning --- ApptPlus message: " & noteElement.text
  End If

CleanExit:
  Exit Sub

ErrorHandler:
  With Err
    If .Number = 7 Then
      this.IsLoggedIn = True
    Else
      LogManager.Log ErrorLevel, "ApptPlus Failed to login. UserID: " & this.UserID
      this.IsLoggedIn = False
    End If
  End With
  Resume CleanExit

End Sub

The only way to determine if there's a login issue is to look for the note element appearing on the login page - failure to find that element is expected, preferred and is a good thing.

I could resolve this by wrapping with an OERN like this:

On Error Resume Next
Set noteElement = this.Driver.FindElementByClass("note")
'handle the expected error which is really a good thing here
On Error GoTo ErrorHandler

Is that the best way to go about this, or does someone see something better I could do?

I'm also open to any other tips or suggestions anyone sees that could improve the code.


texts: Indexing and searching an list of rectangles to see if they contain a point

texts:
I have a flat list of rectangles, in the following format (id, x co-ord, y co-ord, height and width):
[ { id: 4206, x: 360, y: 700, width: 60, height: 50 } ,
   { id: 6621, x: 1260, y: 1100, width: 60, height: 50 } ]

I want to index this by range of X values, and then use that indexed object to speed up a search for a point inside.
My full code is here:

// arbitrary setup, no need to review
const grid = [];
const height = 50;
const width = 60;
let index = 0;
for (let row = 0; row < 300; row++) {
  for (let col = 0; col < 300; col++) {
    grid[index] = {
      id: index,
      x: width * col,
      y: height * row,
      width,
      height
    };
    index++;
  }
}
// try and find these points
const points = [{
  x: 400,
  y: 700
}, {
  x: 1300,
  y: 1105
}]

// body - please review approach, style less important

const indexedGrid = grid.reduce((acc, curr) => {
  if (curr.x === undefined) return acc;
  if (acc[curr.x]) {
    acc[curr.x].shapes.push(curr);
    acc[curr.x].endEdge = Math.max(acc[curr.x].endEdge, curr.width + curr.x)
  } else acc[curr.x] = {
    shapes: [curr],
    startEdge: curr.x,
    endEdge: curr.width + curr.x
  };
  return acc;
}, {})
const indexedEdges = Object.values(indexedGrid).map(val => ({
  start: val.startEdge,
  end: val.endEdge
}));
const shapesContainingPoints = points.map(
  (point) => ({
    point,
    xRange: indexedEdges.filter(
      edge => (point.x >= edge.start && point.x < edge.end)
    )
  })
).map(
  pointWithRange => indexedGrid[pointWithRange.xRange[0].start].shapes.filter(
    shape => {
      return (pointWithRange.point.y >= shape.y && (pointWithRange.point.y < (shape.y + shape.height)))
    }
  )
);

//footer - purely to show results in the this question, no need to review
console.log(shapesContainingPoints)

I'm fully aware this code could be tidied up a lot, but the main thing I was hoping to ascertain, is if this 'index and search' pattern suits the following use case.
I'm drawing a load of rectangles in a html canvas element, and I want to be able to find which rectangle was clicked on using the x, y co-ords of the mouse. So I plan to create a flat list of the squares, and then index them by their X value. And from that X value, look along the row, filtering by Y value.
Currently the data only includes perfectly tiling rectangles, but in the future I may have to handle an alternating offset (every other row is shifted by a small value) or other less standard layouts.
Here are some example grids (all right angled) that I need to handle:
https://algorist.com/images/figures/bin-packing-R.png
https://i.stack.imgur.com/JG3iT.png
https://codeincomplete.com/articles/bin-packing/packed.png
I have no plans to have the number, size or position of the rectangles to change over time. I don't have a good grasp of quite how many total rectangles I will need to look over, but I'm expecting anything from 4 to 4000 say.
But it feels very clunky (overly complicated, and thus hard to comprehend/maintain), and that there should be a better approach to this problem? I'm also interested in performance, but that's secondary to maintainability at the moment.
If there is not a better alternative, is there anyway of improving my current approach?


texts: Python program to find the factorial of a number using recursion

texts:
A factorial of a number is the product of all the integers from 1 to that number.

For example, the factorial of 5 (denoted as 5!) is 1*2*3*4*5 = 120. The factorial of 0 is 1.

def recur_factorial(x):

    if x == 1:
        return 1
    else:
        return (x * recur_factorial(x - 1))

num = int(input("Enter number: "))

print("The factorial of", num, "is", recur_factorial(num))

So I would like to know whether I could make this program shorter and more efficient.

Also, I would like to know the advantages and disadvantages of recursion.


texts: Python binary to decimal converter (without using built-ins)

texts:
Any ideas how I could improve this? I already know that there is no checking for anything other than a 1, so you can enter a 2 or an a or a b and it will be interpreted as a 0, not interfering with the program's functionality. What I would like to know is if anyone has any suggestions for improving the logic.

def main():

  #Input
  binary = input("Enter a line of binary: ")

  #Reverses input
  toCalc = binary[::-1]

  #Finds length of input
  binLen = len(binary)

  #Variables
  total = 0
  exp = 0 #Exponent

  #loop while current character place is less than input length
  while exp < binLen:
    if toCalc[exp] == "1": #If current char is a '1', add 2^exp to the total
        total += 2 ** int(exp)
    exp += 1
  print (total)
  main()

main()

Here is a link to a working version of the script.


texts:
I haven't really worked much with asynchronous code so I'm wondering if I am doing something wrong/something could go wrong. Right now of all the test cases that I have done, my code has worked but I'm not sure if I will get side effects or not.

I won't post any of the business logic, just the iteration part with the asynchronous function in it:

function asyncInIteration(skinArray)  {
   request("/someaddresshere", function (err, response, data)  {

      var left = something.length;

      for (var i = 0;i<something.length;i++) (function (i) {
          request("/someotheraddress", function (err, response, data) {
             if (--left === 0)  {
                 console.log("End of for loop");
             }
          })
      })(i);
   });
}

Basically, what I am trying to do with this code is loop through an array (skinArray) and add values to it via sending HTTP requests.

The most important thing for me is that:

Every value of i should only be repeated once.
When I call --left === 0, that has to be called once, and only after all values of i have been gone through.

If someone wants to see the code with the business logic, you can find it here.


texts: Scala Direction enum with Enumeration and collection usage

texts:
I've just implement direction enum

object Direction extends Enumeration {
  type Direction = Value
  val Up, Right, Down, Left = Value

  val pairs = HashSet() ++ List((HashSet() ++ List(Up, Down)), (HashSet() ++ List(Right, Left)))

  def isOpposite(one: Direction, other: Direction): Boolean = {
    pairs.contains(HashSet() ++ List(one, other))
  }
}

Usages

direction match {
  case Right => ...
  case Left => ...
  case Up => ...
  case Down => ...
}

if(Direction.isOpposite(d1, d2))...

Can I improve it some how?


texts: Sort Stack using just an additional stack

texts:
The problem is from the cracking coding Interview programming book.

The problem is that:

  Sort Stack: Write a program to sort a stack such that the smallest
  items are on the top. You can use an additional temporary stack, but
  you may not copy the elements into any other data structure (such as
  an array).

Below is my code in scala to sort Stack s, however, I think
it is not the optimal solution in scala, may I know any other solutions can be written in functional programming language scala.

import scala.collection.mutable.Stack
    def sorted(s: Stack[Int]): Unit={
        def sortedwithtemp(original: Stack[Int], temp:Stack[Int], current: Int): Unit=(current, temp.top)match{
          case (a,b) if a>=b =>temp.push(a);
          if(original.size==0) original.pushAll(temp)
          else {
            val curr= original.pop()
          sortedwithtemp(original, temp, curr)
          }

          case (a,b) => original.push(temp.pop());
           if (temp.isEmpty) {temp.push(current); val curr= original.pop();sortedwithtemp(original, temp, curr)}
           else sortedwithtemp(original, temp, current)
        }

        val tempstack=new Stack[Int]
        if (s.size>=2){
          tempstack.push(s.pop())
          val current=s.pop()
          sortedwithtemp(s, tempstack, current)
        }
   }


texts: Smallest number in BST which is greater than or equal to N

texts:
Given a Binary Search Tree and a number N, the task is to find the
  smallest number in the binary search tree that is greater than or
  equal to N. Print the value of the element if it exists otherwise
  print -1.

Please review the code, the unit tests are just for the demo. please comment about performance thanks.

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TreeQuestions
{
    /// <summary>
    /// https://www.geeksforgeeks.org/smallest-number-in-bst-which-is-greater-than-or-equal-to-n/
    /// </summary>
    [TestClass]
    public class SamllestNumberBstGreatherThanOrEqualToN
    {
        [TestMethod]
        public void SmallestNumberBstGreatherThanOrEqualToNTest()
        {
            BstNode root = new BstNode(19 );
            BstNode left = new BstNode(7);
            BstNode right = new BstNode(21);
            root.Left = left;
            root.Right = right;
            BstNode leftLeft = new BstNode(3);
            BstNode leftRight = new BstNode(11);
            BstNode leftRightLeft = new BstNode(9);
            BstNode leftRightRight = new BstNode(14);
            root.Left.Left = leftLeft;
            root.Left.Right = leftRight;
            root.Left.Right.Left = leftRightLeft;
            root.Left.Right.Right = leftRightRight;
            int result = SmallestNumberGratherThanOrEqual(root, 20);
            Assert.AreEqual(21, result);
        }

        [TestMethod]
        public void SmallestNumberBstGreatherThanOrEqualToNTest2()
        {
            /*    19
        /    \
       7     21
     /   \
    3     11
         /   \
         9    14
          */

            BstNode root = new BstNode(19);
            root = root.Add(root, 7);
            root = root.Add(root, 3);
            root = root.Add(root, 11);
            root = root.Add(root, 9);
            root = root.Add(root, 13);
            root = root.Add(root, 21);
            int result = SmallestNumberGratherThanOrEqual(root, 18);
            Assert.AreEqual(19, result);
        }

        private int SmallestNumberGratherThanOrEqual(BstNode root, int num)
        {
            int smallest = -1;
            while (root != null)
            {
                if (root.Value >= num)
                {
                    smallest = root.Value;
                    root = root.Left;
                }
                else
                {
                    root = root.Right;
                }
            }
            return smallest;
        }
    }
}

here is also the BST class

public class BstNode
{
    public int Value;
    public BstNode Left;
    public BstNode Right;
    public BstNode Parent;

    public BstNode(int keyt)
    {
        Value = keyt;
    }

    public BstNode Add(BstNode node , int key)
    {
        if (node == null)
        {
            return new BstNode(key);
        }
        if (node.Value < key)
        {
            node.Right = Add(node.Right, key);
        }
        else
        {
            node.Left = Add(node.Left, key);
        }
        return node;
    }

}


texts: Count the number of biggest numbers on the board

texts:
I coded two answers to this challenge. The first one was a standard attempt, but after it timed out, I figured out the "trick" to solving the problem much more simply. However, I'd still appreciate comments and critiques on my first attempt, because there will be other problems that will need a long approach and I'd like to improve how I'd code the answer.

Challenge
Julia is playing a game on an infinite 2-dimensional grid with the bottom left cell referenced as (1, 1). All the cells contain a value of zero initially. The game consists of n steps. In each step, Julia is given two integers a and b. The value of each of the cells in the coordinate (u, v) satisfying 1 ≤ u ≤ a and 1 ≤ v ≤ b, is increased by 1. After n such steps, if x is the largest number in any cell on the board, how many instances of x are there on the board?

Complete the function countX that has one parameter, a string array, steps, denoting the values of a and b for each of steps of the game. The function should return the total number of occurrences of greatest integer x in the grid after n steps.

Sample Input and Output *
Input: [ '18 29', '32 17', '34 9', '38 15', '36 22', '7 14', '5 100' ]
Output: 2

First Attempt

function countX(stepArr){
    let board = []; //2 dimensional array
    let bigNum = 0;
    let bigNumCount = 0;

    const stepArrCount = stepArr.length;

     for(let k = 0; k < stepArrCount; k++){
        const sArr = stepArr[k].split(" ");
        let s1 = sArr[0]; //vertical steps
        let s2 = sArr[1]; //horiz steps

        for(let i = 0; i < s1; i++){
            let stopCompare = false;
            for(let j = 0; j < s2; j++){
                if(board[i] !== undefined){
                    if(board[i][j] !== undefined){
                        board[i][j]++;
                    }
                    else{
                        board[i][j] = 1;
                    }
                }
                else{
                    board[i] = [];
                    board[i][j] = 1;
                }
                if((k + 1 === stepArrCount) && !stopCompare){
                    if(board[i][j] > bigNum){
                        bigNum = board[i][j];
                        bigNumCount = 1;
                    }
                    else if(board[i][j] === bigNum){
                        bigNumCount++;
                    }
                    else{
                        stopCompare = true;
                    }
                }
            }
        }
     }

    return bigNumCount;
}

Second Attempt

function countX(stepArr){
    let sArr = stepArr[0].split(" ");
    let smallColA = parseInt(sArr[0]);
    let smallColB  = parseInt(sArr[1]);

    if(sArr.length > 1){
        for(let i = 1; i < stepArr.length; i++){
            sArr = stepArr[i].split(" ");
            let s1 = parseInt(sArr[0]);
            let s2 = parseInt(sArr[1]);
            if(s1 < smallColA){
                smallColA = s1;
            }
            if(s2 < smallColB){
                smallColB = s2;
            }
        }
    }

    return smallColA * smallColB;

}

* Explanation of Input and Output (provided by challenger)
Assume that the following board corresponds to cells (i, j) where 1 ≤ i ≤ 4 and 1 ≤ j ≤ 7.
At the beginning the board is in the following state:

0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0

After the first step we obtain:

0 0 0 0 0 0 0
0 0 0 0 0 0 0
1 1 1 0 0 0 0
1 1 1 0 0 0 0

After the second step we have:

0 0 0 0 0 0 0
1 1 1 1 1 1 1
2 2 2 1 1 1 1
2 2 2 1 1 1 1

Finally, after the last step the board will look like this:

1 0 0 0 0 0 0
2 1 1 1 1 1 1
3 2 2 1 1 1 1
3 2 2 1 1 1 1

So, the maximum number is 3 and there are exactly two cells which contain 3. Hence the answer is 2.


texts:
Here is my bootstrap pagination code. Maybe it can be simplified.

const pagination = {
  pre: 0,
  curr: 1,
  max: 6,
  list: null,
  cn: '',
  swap() {
    pagination.list.children[pagination.pre].classList.remove(pagination.cn);
    pagination.list.children[pagination.curr].classList.add(pagination.cn);
  },
  changeBy(n) {
    pagination.pre = pagination.curr;
    pagination.curr += n;
    if (pagination.curr < 1) {
      pagination.pre = 0;
      pagination.curr = 1;
    } else if (pagination.curr > pagination.max) {
      pagination.pre = pagination.max - 1;
      pagination.curr = pagination.max;
    }
    pagination.swap();
  },
  prev() {
    pagination.changeBy(-1);
  },
  next() {
    pagination.changeBy(1);
  },
  activate(i) {
    return () => {
      pagination.pre = pagination.curr;
      pagination.curr = i;
      pagination.swap();
    }
  },
  setHandler() {
    pagination.list.children[0].addEventListener("click", pagination.prev);
    pagination.list.children[pagination.max + 1].addEventListener("click", pagination.next);
    for (let i = 1; i < (pagination.max + 1); i += 1) {
      pagination.list.children[i].onclick = pagination.activate(i);
    }
  },
  init(list, cn) {
    pagination.list = list;
    pagination.cn = cn;
    pagination.setHandler();
  }
}

let list = document.querySelector(".pagination"),
  cn = "active",
  init = pagination.init(list, cn);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

        &laquo;

1

2

3

4

5

6

        &raquo;


texts:
I've created my first gem as Instagram API wrapper https://github.com/agilie/instagram_api_gem. I would be very pleased if you give me some feedback on code organization, methods elegancy and so on.

The thing I concerned about the most is next. I have a module Resource

  module Resource
    include Client

    private

    def show(id, options = {})
      raise 'Resource ID is required' unless id
      make_request resource_path(id), query: options
    end

    def index(id, resource_name, options = {})
      raise 'Resource ID is required' unless id
      make_request resource_path("#{id}/#{resource_name}"), query: options
    end

    def create(id, resource_name, options = {})
      raise 'Resource ID is required' unless id
      make_request(resource_path("#{id}/#{resource_name}"), { body: options }, :post)
    end

    def destroy(id, resource_name, resource_id = nil, options = {})
      raise 'Resource ID is required' unless id
      path = "#{id}/#{resource_name}"
      path = "#{path}/#{resource_id}" if resource_id
      make_request(resource_path(path), { query: options }, :delete)
    end
  end

And I use methods from it like this

  class Tag
    include Search
    include Resource

    def initialize(tag_id = nil)
      @tag_id = tag_id
    end

    def recent_media(options = {})
      index @tag_id, 'media/recent', options
    end
  end

Does this implementation look good or are there more elegant solutions?
I would be very pleased if you give me some feedback regarding the whole code organization and implementation, which could be found here https://github.com/agilie/instagram_api_gem

You are welcome to contribute if you prefer.