texts: Rotating a character upside down and vice versa

texts:
I have a pretty straightforward task, but I find it hard to figure out how to improve it. The code is pretty straightforward, but rather bad. There are some clarifications / extra details at the bottom. Let's assume the direction of the positive Z axis is (from the screen) towards you, the reader. Let's say I have this character:

Its angle / rotation along the Z axis is 0 initially. What I want it to do is rotate (say anticlockwise) around the Z axis with a particular speed (adjusted by RotationRate). When it reaches a (cumulated/total) rotation of 180, the rotation should stop. At this point the character will be upside down. If I now tap the screen again, the rotation should start again, but in the opposite direction, until it reaches an angle of 0. Now the character will look again like in the original photo above.

private bool Rotating = false;
private bool IsNormalPosition = true;
private float CharacterTargetAngle = 0;
private float RotationRate = 180 * 5;
private float Threshold = 30;

private IEnumerator Rotate()
{
    while (Rotating)
    {
        var angle = transform.eulerAngles;

        if (Mathf.Abs(CharacterTargetAngle - angle.z) < Threshold)
        {
            angle.z = CharacterTargetAngle;
            Rotating = false;

            transform.eulerAngles = angle;
        }
        else
        {
            transform.Rotate(0, 0, RotationRate * Time.deltaTime);
        }

        yield return new WaitForFixedUpdate();
    }
}

// called when user taps screen
public void OnTap()
{
    if (IsNormalPosition)
    {
        CharacterTargetAngle = 180;
    }
    else
    {
        CharacterTargetAngle = 0;
    }

    IsNormalPosition = !IsNormalPosition;
    RotationRate *= -1;

    if (!Rotating)
    {
        Rotating = true;

        StartCoroutine("Rotate");
    }
    else
    {
        StopCoroutine("Rotate");
        StartCoroutine("Rotate");
    }
}

Other details / clarifications:

Note that if the character is still rotating and I tap the screen again, I want its current rotation to stop and change direction immediately. For this I am setting a Rotating flag. If this is false, then it means the character is either upside down or sitting normally, so I only have to start the Rotate() coroutine. If, however, Rotating is true, I need to stop the previously started coroutine before starting the new rotation coroutine.

CharacterTargetAngle represents the angle I am aiming at: either 0 or 180.

IsNormalPosition represents whether the character has an angle of 0 (true) or 180 (false).

RotationRate represents the speed of rotation. Currently the character can rotate at a speed of 180 * 5 degrees per second. I reached this value after trying many others.


texts: Query of users for some age, gender, and state, using a subselect

texts:
I have this query:

SELECT * FROM
(SELECT u.id,u.email,u.verified,u.verified_on,u.created_on,ca.html AS age,cg.html AS gender,cs.html AS state
FROM users u
LEFT JOIN combo ca ON ca.combo_group='age' AND ca.value =u.age
LEFT JOIN combo cg ON cg.combo_group='gender' AND cg.value =u.gender
LEFT JOIN combo cs ON cs.combo_group='state' AND cs.value =u.state ORDER BY created_on DESC) users ORDER BY email ASC;

I am using sub query because I want sort created_on DESC and email ASC.

Would using sub query affect performance?


texts: Setting PHP variables for 2 years back and 2 years in the future

texts:
The following code gets years (dates), 1 and 2 years back (for example 2017 - 2016) and 1 and 2 years into the future (for example 2019 - 2020). Now PHP is not my expertise so I would like to get some help cleaning this up.

Is there a different approach I should use when doing this?

//Filter jaren
$year = date("Y");
$yearBack = $year;
$yearBack--;
$yearDoubleBack = $yearBack;
$yearDoubleBack--;
$yearAhead = $year;
$yearAhead++;
$YearDoubleAhead = $yearAhead;
$YearDoubleAhead++;


texts: Java console version Conway's Game of Life

texts:
I did a super simple version of Conway's Game of Life and would like a review.

public class Conway {
        String [][] grid;
        int [][] neighbors;
        int [][] directions = {{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};
        Conway (int gridSize) {
                this.neighbors = new int [gridSize][gridSize];
                this.grid = new String[gridSize][gridSize];
                for (int row = 0; row < this.grid.length; row++) {
                        for (int cell = 0; cell < this.grid[row].length; cell++) {
                                this.grid[row][cell] = (Math.random() > .9) ? "x|" : " |";
                                System.out.print(this.grid[row][cell]);
                        }
                        System.out.println();
                }
                this.getNeihbors();
        }
        void getNeihbors() {
                int i = 0;
                for (int row = 0; row < this.grid.length; row++ ) {
                        for (int col = 0; col < this.grid[row].length; col++) {
                                for (int drow = 0; drow < this.directions.length; drow++) {
                                        int x = (this.directions[drow][this.directions[drow].length-this.directions[drow].length]);
                                        int y = (this.directions[drow][this.directions[drow].length - 1]);
                                        x = row + x;
                                        y = col + y;
                                        if (x < 0) {
                                                x += this.grid.length;
                                        } else if (x + 1 > this.grid.length) {
                                                 x -= x;
                                        }
                                        if (y < 0) {
                                                y += this.grid[row].length;
                                        } else if (y + 1 > this.grid[row].length) {
                                                 y -= y;
                                        }
                                        if (this.grid[x][y] == "x|") i++;
                                }
                                this.neighbors[row][col] = i;
                                i=0;
                        }
                }
                this.showGrid();
        }
        void showGrid() {
                for (int row = 0; row < this.grid.length; row++) {
                        for (int cell = 0; cell < this.grid[row].length; cell++) {
                                if (this.grid[row][cell] == " |" && this.neighbors[row][cell] == 3) {
                                        this.grid[row][cell] = "x|";
                                } else if (this.grid[row][cell] == "x|" && this.neighbors[row][cell] > 3) {
                                        this.grid[row][cell] = " |";
                                } else if (this.grid[row][cell] == "x|" && this.neighbors[row][cell] < 2) {
                                        this.grid[row][cell] = " |";
                                }
                                System.out.print(this.grid[row][cell]);
                        }
                        System.out.println();
                }
                this.getNeihbors();
        }
        public static void main(String[] args) {
                Conway c = new Conway(80);
        }
}


texts: Getting output of a NodeJS script in PHP

texts:
I'm using a NodeJS script to do some geo calculations using the h3.js library by Uber. the concept of getting a nodejs script result back into php is new to me. I found the following example online, which I'm not following.
$output = [];
$arg = escapeshellcmd('some variable to pass on');
$command = 'node /var/www/hex/src/h3.js ' . $arg;
exec($command, $output);

var_dump($output);

This is returning the correct result, which I'm using console.log() for on the NodeJS side.

I'm wondering if my method has any implications I might not be aware of
Is this the way to go for a case like this?


texts: Idiomatic iterator for a linear function

texts:
A while back, I asked a question about implementing an idiomatic iterator in C++. I've recently revisited the code, and I'm bothered by the duplication in the begin and end iterators. The code goes over a collection/iterator over a domain, and lazily produces the range using the iterator. After trimming down some code from the accepted answer, here's what I have:

class LinearFunction
{
public:
    LinearFunction(double m, double b) : m_(m), b_(b) { }

    double operator()(double x) const { return m_ * x + b_; }
private:
    double m_, b_;

};

template <typename IterType>
class LinearFunctionIterator
{
public:
    LinearFunctionIterator(IterType iter, LinearFunction const &linearFunction)
        : xIter_(iter), linearFunction_(linearFunction) { }

    LinearFunctionIterator &operator++() {
        ++xIter_;
        return *this;
    }

    double operator*() const {
        return linearFunction_(*xIter_);
    }

    bool operator!=(LinearFunctionIterator const &other) const {
        return xIter_ != other.xIter_;
    }

private:
    IterType xIter_;
    LinearFunction linearFunction_; // <--- (1)
};

template <typename IterType>
class LinearFunctionIteratorProxy
{
public:
    LinearFunctionIteratorProxy(IterType xBegin, IterType xEnd,
                                LinearFunction const &linearFunction)
        : xBegin_(xBegin), xEnd_(xEnd), linearFunction_(linearFunction) { }

    LinearFunctionIterator<IterType> begin() const {
        return { xBegin_, linearFunction_ };
    }

    LinearFunctionIterator<IterType> end() const {
        return { xEnd_, linearFunction_ };
    }

private:
    IterType xBegin_, xEnd_;
    LinearFunction linearFunction_;
};

template<typename Container>
auto makeLinearFunction(Container const &domain,
                        LinearFunction const &linearFunction)
-> LinearFunctionIteratorProxy<decltype(std::begin(domain))>
{
    return { std::begin(domain), std::end(domain), linearFunction };
}

Usage:

#include "LinearFunction.h"
#include <iostream>
#include <vector>

int main()
{
    std::vector<double> domain { 1.0, 5.0, 2.0, 8.0 };
    LinearFunction linearFunction(10.0, 5.0);

    std::cout << "Range:\n";
    for(auto rangeValue : makeLinearFunction(domain, linearFunction))
    {
        std::cout << rangeValue << ", ";
    }
}

What I'm looking for from the review:

Notice in the example usage, that there are three copies of the LinearFunction instance: one in the proxy, one in the begin iterator, and one in the end. Is there a better way to achieve the same behavior without this duplication?
General advice to improve this code would be appreciated.


texts:
What do you think about quality of code in this method?

It should:

Generate new key based on keys in array
The key should start with "TG"
Code should find the max number in array keys with "TG-" and increment this number
It should have 7 digits
No need to check what if there is a key TG9999999, and what if array is empty or doesn't have keys "TG-"

private static string[] allKeys = new string[]
{
    "TG0000006",
    "TG0000026",
    "TG0000086",
    "TG0000796",
    "TG0023106",
    "LG0004406",
    "MS0000796",
    "TT0023106",
    "LK0004406",
};

static string GenerateKey()
{
    var keys = allKeys.Where(k => k.StartsWith("TG"));
    List<int> nums = new List<int>();
    foreach (var key in keys.Select(str => Regex.Match(str, @"\d+").Value))
    {
        int num;
        if (int.TryParse(key, out num))
            nums.Add(num);
    }
    string newNum = (nums.Max() + 1).ToString();
    return "TG" + new string('0', 7 - newNum.Length) + newNum;
}


texts: Faster function iteration on Pandas df with axis=1

texts:
I have the following function that allows me to calculate the marketing spend on my advertising campaigns.

The problem is that it's now taking too long (over 15 minutes) to apply the function to said dataframe, as it now has more than 8 months of historical data.

I have no idea if there's a way to speed up the process. Any help would be appreciated if you know a faster way to iter through rows.

def actual_spend_atlas(row):

    filterdatemediaplanid_day = (atlas_df.Date == row.Date) & (atlas_df.MediaPlanIndex == row.MediaPlanIndex)
    filterdatemediaplanid_total = (atlas_df.MediaPlanIndex == row.MediaPlanIndex)

    total_impressions_day = atlas_df.ix[filterdatemediaplanid_day, 'Impressions'].sum()
    total_impressions = atlas_df.ix[filterdatemediaplanid_total, 'Impressions'].sum()

    if row.Amnet == "Amnet":
        spend = atlas_df.AmnetCost * (row.Impressions / filterdatemediaplanid_day)

    if row.CostMethod == 'FLF' or row.CostMethod == 'CPH':

        if total_impressions < 500:
            spend = 0
        else:
            rate = row.BookedRate
            spend = rate * (row.Impressions/ total_impressions)

    elif row.CostMethod == 'CPC':
        spend = row.BookedRate * row.Clicks

    elif row.CostMethod == 'CPM':
        cpm_impressions = row.Impressions / 1000.0
        rate = row.BookedRate
        spend = rate * cpm_impressions

    else:
        spend = 0

    return spend

atlas_df['Spend'] = atlas_df.apply(actual_spend_atlas, axis=1)


texts:
This is an efficiency question to the following code, written in MS Visual in C#. If any explanation is missing, please let me know and I will add. What this part of the program does is:

Button is pushed
Motor starts moving (by sending 9-byte array with command)
Waiting for Sensor to register a change in value
Motor stops
Motorposition is saved (command to get position is send and 9-byte array response is send by the motor), to have access to it later on and return there

Calls like rotate() and stop() are commands that write data into a 9-byte-array and write bytearray to serial port.

Now, my main issue is Step 5. I read on Stack Overflow that "if you have to use wait() and there is no point of using the DataReceived implementation". So should I really get rid of this or is there a nice way to handle this? If I do it without the wait() it saves the answer that is send after the stop command (every command also sends an answer).

And would it be more efficient to use DataReceived in step 3? In the beginning I save a value as new 0, and compare the current sensor readout here to this 0 value.

private void button13_Click(object sender, EventArgs e)
{
    //rotate right speed
    string Test = textBox4.Text;
    byte[] A = new byte[9];
    rotate(A, Test);
    //read sensor
    serialPort2.WriteLine("SR,00,002\r\n");
    string b = serialPort2.ReadLine();
    decimal caliber = decimal.Parse(Regex.Split(b, "SR,00,002,")[1]);
    decimal b1 = 0;
    do
    {
        serialPort2.WriteLine("SR,00,002\r\n");
        string z = serialPort2.ReadLine();
        b1 = decimal.Parse(Regex.Split(z, "SR,00,002,")[1]);
    }
    while (b1 <= caliber);
    // stop motor
    byte[] B = new byte[9];
    stop(B);
    //save position
    System.Threading.Thread.Sleep(5000);
    byte[] C = new byte[9];
    getPosi(C);
    System.Threading.Thread.Sleep(5000);
    M = buf;
    //move to 0
    byte[] D = new byte[9];
    MoveTo0(D);
}

In case it is needed for understanding the code above:

//global variables
byte[] buf = new byte[9];
byte[] M = new byte[9];
private void button1_Click(object sender, EventArgs e)      //Ports öffnen
{
    serialPort3 = new SerialPort();
    serialPort3.PortName = "COM6";
    serialPort3.Handshake = Handshake.RequestToSend;
    serialPort3.ReceivedBytesThreshold = 8;
    serialPort3.DataReceived += new SerialDataReceivedEventHandler(DataRecievedHandler);
    serialPort3.Open();
}
private void DataRecievedHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    int bytes = serialPort3.BytesToRead;
    byte[] buffer = new byte[bytes];
    sp.Read(buffer, 0, bytes);
    string hex = BitConverter.ToString(buffer);
    hex.Replace("-", "");
    MessageBox.Show(hex);
    buf = buffer;
}

Other methods:

private void rotate(byte[] A, string Test) //Rotate Motor Right
    {
        A = MB.TMCL_RMR(Test);
        serialPort3.Write(A, 0, A.Length);
    }

    private void stop(byte[] B) // Stop Motor
    {
        B = MB.TMCL_MST();
        serialPort3.Write(B, 0, B.Length);
    }

    private void getPosi(byte[] C) //Get Position
    {
        C = MB.GET_POSI();
        serialPort3.Write(C, 0, C.Length);
    }

    private void MoveTo0(byte[] D) //Move to 0
    {
        D = MB.MoveTo0();
        serialPort3.Write(D, 0, D.Length);
    }

And as example a method from my seperate motorcontrolclass on how the bytearray is created. Each hex-byte references a certain information, last byte is a checksum. If this array is send to the serial port it will request the motorposition as an answer.

public byte[] GET_POSI()
    {
        byte[] E = new byte[9];
        E[0] = 0x1;
        E[1] = 0x6;
        E[2] = 0x1;
        E[3] = 0x0;
        E[4] = 0x0;
        E[5] = 0x0;
        E[6] = 0x0;
        E[7] = 0x0;
        E[8] = 0x08;
        return E;
    }

The code is working as I want it to for several input tests. I just thought there might be a better way than the Thread.Sleep().


texts: Hackerrank CTCI "Stacks: Balanced Brackets" Javascript Solution

texts:
Here is the original problem, and below is my solution. I wonder what can be improved? Or is there a fundamentally better algorithm out there? Thank you! My intuition is telling me that it can be more concise and efficient than this.

  Input Format

  The first line contains a single integer, , denoting the number of
  strings.  Each line  of the  subsequent lines consists of a single
  string, , denoting a sequence of brackets.

  Output Format

  For each string, print whether or not the string of brackets is
  balanced on a new line. If the brackets are balanced, print YES;
  otherwise, print NO.

function main() {
    var t = parseInt(readLine());
    var i, isBalanced, stack, exp, len

    for (var a0 = 0; a0 < t; a0++) {
        exp = readLine().split('');

        stack = [];
        isBalanced = true;
        i = -1;
        len = exp.length;

        while (++i < len) {
            switch (exp[i]) {
                case "{":
                case "[":
                case "(":
                    stack.push(exp[i])
                    break;

                case "}":
                    if (stack.pop() !== "{") {
                        isBalanced = false
                    }
                    break;
                case "]":
                    if (stack.pop() !== "[") {
                        isBalanced = false
                    }
                    break;
                case ")":
                    if (stack.pop() !== "(") {
                        isBalanced = false
                    }
                    break;
                default:
            }

            if (isBalanced === false) {
                console.log("NO")
                break;
            }
        }

        if (isBalanced === true) {
            if (stack.length > 0) {
                if (stack[0] === "{" || stack[0] === "[" || stack[0] === "(") {
                    console.log("NO")
                }
            } else {
                console.log("YES");
            }
        }

    }
}


texts:
I have been doing some personal projects for fun and most of them have visual representation of boards (ej: sudoku solvers, chess PGN viewer, etc) and I always end up doing something like this:

var wid=10;
var hei=6;
var len=(wid*hei);
var map="005000200000000008000600000006000700000040000000500030400000".split("");

var str="

";

for(var i=0;i<len;i++){
    if(i&&!(i%wid)){
        str+="

";
    }
    str+=""+((map[i]!=0)?map[i]:"&nbsp;")+"	";
}

str+="

";

document.body.innerHTML+=str;

with CSS styles like:

*{margin:0;padding:0;}
#board{margin:15px auto;text-align:center;}
#board,#board td{border:1px solid #000;}
#board td{width:45px;height:47px;font-size:20px;}

I want to know if there is a better, more readable way to achieve this?, maybe using arr.join()?


texts: Way to check if a byte array contains another byte Array

texts:
I'm checking if an byte array contains a another Byte Array with this Code:

private int IndexOf(int index, byte[] AllBytes, byte[] searchByteArray)
{
    for (int i = index; i <= AllBytes.Length - 1 - searchByteArray.Length - 1; i++)
    {

        for (int j = 0; j <= searchByteArray.Length - 1; j++)
        {
            if (AllBytes[i + j] == searchByteArray[j])
            {
                if (j + 1 == searchByteArray.Length)
                    return i;
            }
            else
                break;
        }
    }
    return -1;
}

That works perfect and I get the index of the first byte back.

But the problem is I want to check very large Data.

My "big" Array contains around 900000000 Bytes and my searchArray about 10-20 Bytes. In that way my function is very very slow. Is there a way to make a better performance?

I need the Index of every found match so I do it into a loop:

for (int i = (IndexOf(0, allData, suchBytes) - 1); i < allData.Length; i++)
{
    Debug.WriteLine(i);
    tmpIndex = IndexOf(i, allData, suchBytes);

    if (tmpIndex > -1)
    {

        Byte1_Index.Add(tmpIndex + suchBytes.Length);
        Debug.WriteLine("Counter: " + Byte_Index_Counter);
        i = tmpIndex;
        Byte_Index_Counter++;

    }
}

And it takes a way too much time...


texts:
I have written this code to invert a binary tree.

Thus if the original tree is:

Then the tree returned should be:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root==NULL)
            return NULL;

        /* Performing post-order traversal of the tree */

        //Visiting the left node first
        if(root->left != NULL)
            invertTree(root->left);

        //Visiting the right node next
        if(root->right != NULL)
            invertTree(root->right);

        //Visiting the current node; swapping the left and the right nodes of the current node
        TreeNode* tn = new TreeNode(0);
        tn=root->right;
        root->right=root->left;
        root->left=tn;

        return root;
    }
};

While the code runs correctly and returns the required output, I think I am invoking undefined behavior when the control hits the leaf nodes.  Since, at the leaf, a new node is created and it is assigned (incorrectly) the right of the current node and so on.

Could someone please clarify if what I am doing is indeed wrong?

Note: The question and the images are taken from LeetCode.com


texts:
I had a task to convert some JPG images into PNG format using Python. I successfully did it but I was wondering if somehow I could make my code better than my current one.

Code -

#Python Code

import os
from PIL import Image

path1 = sys.argv[1]
path2 = sys.argv[2]

if not os.path.exists(path2):
    os.makedirs(path2)

for filename in os.listdir(path1):
    if filename.endswith(".jpg"):
        # print(filename.split(".")[0])
        im = Image.open(f"{path1}{filename}")
        # print(Image.open(f"{path1}{filename}"))
        im.save(f"{path2}/{filename.split('.')[0]}.png", "png")
        print("Lets go")


texts:
I've now used the tips, you can find here and there, to improve my code:

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.Dimension;
public class CaesarCipher {

    enum WhatToDo {ENCRYPT, DECRYPT};

    public static void main(String[] args) {

        String UserInput = JOptionPane.showInputDialog("Please enter text:");
        String text = UserInput.replaceAll("[^a-zA-Z]+", "");
        text = text.toUpperCase();

        String message = "Please enter shift to the right:";
        int shift = findShift(message);

        String out = "";
        message = "Encrypt or decrypt?";

        out = MakeDecision(message, text, shift);

        JTextArea msg = new JTextArea(out);
        msg.setLineWrap(true);
        msg.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(msg);
        scrollPane.setPreferredSize(new Dimension(300,300));
        JOptionPane.showMessageDialog(null, scrollPane);
    }

    public static int findShift(String msg) {
        String UserInput = JOptionPane.showInputDialog(msg);
        int shift;
        try {
           shift = Integer.parseInt(UserInput);
        }
        catch (NumberFormatException e) {
            shift = findShift("Please enter shift as a number:");
        }

        return shift;
    }

    public static String MakeDecision(String message, String text, int shift) {

        String UserInput = JOptionPane.showInputDialog(message);
        UserInput = UserInput.toUpperCase();
        String out = "";

        if(WhatToDo.ENCRYPT.name().equals(UserInput) == true) {
        boolean test = true;
        out = EncryptOrDecrypt(text, shift, test);
        }

        else if(WhatToDo.DECRYPT.name().equals(UserInput) == true) {
            boolean test = false;
            out = EncryptOrDecrypt(text, shift, test);

        }
        else {
            message = "Illegal Choice! Encrypt or decrypt?";
            out = MakeDecision(message, text, shift);
        }

        return out;

    }

    //Encryption
    public static String EncryptOrDecrypt(String text, int n, boolean test) {
        int count = 0;
        int alphabetLength = 0;
        int decryptFactor = 1;

        if(!test) {
            decryptFactor = -1;
        }

        StringBuilder out = new StringBuilder(); //Empty string for result.
        while (count < text.length()) {
            final char currentChar = text.charAt(count);
            if (currentChar >= 'A' && currentChar <= 'Z') {
                if (currentChar + n > 'Z') {
                    alphabetLength = 26;
                }
                out.append((char)(currentChar + (n*decryptFactor) - (alphabetLength*decryptFactor)));
            }
            else {
                out.append(currentChar);
            }
            count++;
            alphabetLength = 0;
        }
        return out.toString();
    }

}

Do you think that this now is good code? Do you have any tips for further improvement?


texts: Optimizing for data import in Neo4j using py2neo

texts:
Here is my code for importing from a .csv to a neo4j graph using py2neo and cypher statements. I've noticed that it slows down significantly the bigger the graph gets. It takes several seconds just to parse ~10,000 lines. I'm curious to see if there are any glaring mistakes or improvements to be made.

Before doing any of the import, I created indexes for every node and property, based off of this blog.

The machine I'm working on is windows 7 with 65gb RAM, so it's certainly fast enough to handle a large graph. The upload of a 20 million line csv took weeks, so there has to be something that can be improved on.

I am currently stuck with using windows, I can't switch over to Linux. I also can't use Jexp's batch importer unfortunately.

import csv
import sys
import os
from py2neo import neo4j,node, rel, cypher
import time

def main():

    f = "C:file_path/file.csv"

    graph_db = neo4j.GraphDatabaseService("http://localhost:7474/db/data/")

    with open(f, 'r+') as in_file:
        reader = csv.reader(in_file, delimiter = ',')
        next(reader, None)  # skip headers
        batch = neo4j.WriteBatch(graph_db)

        try:
           i = 0
           j = 0
            for row in reader:
                if row:
                    if (i == 10000):
                        print j, "processed"
                        i = 0
                    i += 1
                    j += 1
                    character = strip(row[0])
                    first_name = strip(row[1])
                    last_name = strip(row[2])
                    actor = strip(row[3])
                    character_birth = strip(row[4])
                    character_death = strip(row[5])
                    allegiance = strip(row[6])
                    house = strip(row[7])
                    territory = strip(row[8])
                    region = strip(row[9])

                    query = neo4j.CypherQuery(graph_db,
                    """CYPHER 2.0
                       merge (character:Character {Character: {a}, First_Name:{b}, Last_Name:{c}, Actor:{d}, Birth:{e}, Death:{f}})
                       merge (house:House{House:{g}, Allegiance:{h}})
                       merge (territory:Territory {Territory: {i}})
                       merge (region:Region {Region: {j}})
                       merge (character)-[:Of_House{House:{k}}]-(house)-[:Is_From]->(territory)-[:Is_In]->(region)
                       """)
                    result = query.execute(a = character, b = first_name, c = last_name, d = actor, e = character_birth, f = character_death, g = house, h = allegiance, i = territory, j = region, k = house)

    except Exception as e:
        print e, row, reader.line_num #print the line number to fix any data errors in file

def strip(string): return''.join([c if 0 < ord(c) < 128 else ' ' for c in string]) #removes non utf-8 chars from string within cell

if __name__ == '__main__':
    start=time.time()
    main()
    end = time.time() - start
    print "Time to complete:", end


texts:
In my very specific scenario, I need to get an NSDate holding the next time the hour will be 7 (either AM or PM).

On the case that this is the first time to do this, I need to jump extra 12 hours (e.g., if I got Apr 1st 7AM - to jump it to 7PM).

After playing with playgrounds I was able to achieve what I believe solves this, but looking at my code it feels too hard-coded and full of magic numbers. I am wondering if there is a cleaner way to do this.

//constants
NSInteger secInHour = 60 * 60;
NSInteger secInMin = 60;
NSInteger NO_VALUE = NSIntegerMax;

//Break "now" to components
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
cal.locale = [NSLocale localeWithLocaleIdentifier:@"he_IL"]; //force a 24hr locale - easier to calculate
NSInteger nowHr = [cal component:NSCalendarUnitHour fromDate:date];
NSInteger nowMin = [cal component:NSCalendarUnitMinute fromDate:date];
NSInteger nowSec = [cal component:NSCalendarUnitSecond fromDate:date];
NSTimeInterval nowMS = date.timeIntervalSince1970 - (double)((int)date.timeIntervalSince1970);

//Get closest "7" hour
BOOL isFirstTime = YES;
NSInteger firstTimeDelta = isFirstTime ? 12 : 0;

//find hour distance
NSInteger addHr = NO_VALUE;
BOOL alarmToConcludeDay = true;
if (nowHr >= 7 && nowHr < 19) {
    //now is day
    alarmToConcludeDay = true;
    addHr = 19 - nowHr - 1;
} else {
    //now is night
    alarmToConcludeDay = false;
    if (nowHr < 7) {
        addHr = 7 - nowHr - 1;
    } else {
        addHr = 7 - nowHr - 1 + 24;
    }
}

//sum everything
if (addHr != NO_VALUE) {
    //how much to add to now?
    NSInteger addMin = 60 - nowMin - 1;
    NSInteger addSec = 60 - nowSec - 1;
    NSInteger addMS = 1 - nowMS;

    NSTimeInterval addTotal = (double)((addHr + firstTimeDelta) * secInHour + addMin * secInMin + addSec) + addMS;

    NSDate *alarmDate = [date dateByAddingTimeInterval:addTotal];
}


texts: Tell, Don't Ask when dealing with displaying model attributes or a null replacement

texts:
I have the following model:

# == Schema Information
#
# Table name: clients
#
#  id         :integer          not null, primary key
#  first_name :string(255)
#  last_name  :string(255)
#  email      :string(255)
#

class Client < ActiveRecord::Base
  def full_name
    if first_name.blank? && last_name.blank?
      'Name: unknown'
    else
      first_name + ' ' + last_name
    end
  end

  def email_address
    email.blank? ? 'Email: unknown' : email
  end
end

Which has the following spec:

RSpec.describe Client, type: :model do

  describe 'full_name' do
    it 'should return first_name + last_name if not blank' do
      @client = create(:client, first_name: 'John', last_name: 'Doe')
      @client.full_name.should == 'John Doe'
    end

    it "should return 'Name: unkonwn' if name is blank" do
      @client = create(:client, first_name: '', last_name: '')
      @client.full_name.should == 'Name: unknown'
    end
  end

  describe 'email_address' do
    it 'should return email if email is not blank' do
      @client = create(:client, email: 'example@example.com')
      @client.email_address.should == 'example@example.com'
    end

    it "should return 'Email: unkonwn' if email is blank" do
      @client = create(:client, email: '')
      @client.email_address.should == 'Email: unknown'
    end
  end
end

As you can see I am creating methods (email_address, full_name) to display attributes (or a combination of attributes) in views.  If the attribute is blank I want to return a string saying the value is unknown.

I have many more attributes that I would like to display this way, but it seems inefficient to come up with alternative method names for methods that simply return the attribute or the "blank alternative".

As an example, these are some of the other attributes: sex, age, source.  Rather than calling client.sex or client.age I would create a method and call client.name_of_sex or client.age_string -- it starts to get awkward (I went from email to email_address in the above example).

The alternative I know is to put logic in my views:

<% if client.email.blank? %>
  Email: unknown
<% else %>
  <%= client.email %>
<% end %>

This is inappropriate for a number of reasons, but my current alternative (the example above) doesn't seem to be optimal.

Is this a point where I should get into making a view-model? Is there some other way I could elegantly perform the actions I want?  Or is the way I'm doing it a reasonable thing to do (I'm going to have a lot of attributes I want to display this way)?


texts: Separate model from DB mapper (entity manager)

texts:
I've read that it is good to separate model from DB mapper (entity manager) (but at the end, it is perhaps personal - just a matter of opinion). Anyway, if I understood correctly, I should not have data models with DB connections, I should not have any methods with SQL (CRUD) in a class, right?

I will give you how my code looks and if you could tell me how to separate - where to put CRUD (for example separate file name), how it would look and how class User should look after that.

I have a database with a table named users with the following columns:

id
username
password
first_name
last_name

In the directory includes I have database.php:

$connection = new PDO($dsn, $user, $pass, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

Also, in the directory includes I have user.php with a class named User and it has DB connection and methods with CRUD (SQL):

<?php

class User
{
    protected $connection = null;

    protected $statments = [];

    protected static $table_name="users";

    protected $id = null;
    protected $username = null;
    protected $password = null;
    protected $first_name = null;
    protected $last_name = null;

    private $arrayOfUserInstances = array();

    public function __construct(PDO $connection)
    {
        $this->connection = $connection;
    }

    // SETTERS ...

    // GETTERS ...

    // METHODS:

    private function instantiate($record) {
        $user = new User($this->connection);
        foreach ($record as $attribute=>$value) {
            if (property_exists('User', $attribute)) {
                $user->$attribute = $value;
            }
        }
        return $user;
    }

    public function findAllUsers()
    {
        if (!isset($this->statments[__METHOD__])) {
            $this->statments[__METHOD__] = $this->connection->prepare("SELECT * FROM users");
        }
        $stmt = $this->statments[__METHOD__];
        if (!($stmt->execute())) {
            return null;
        }
        while ($record = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $user = $this->instantiate($record);
            $this->arrayOfUserInstances[] = $user;
        }
        $stmt->closeCursor();
        return $this->arrayOfUserInstances;
    }

    public function findById($id)
    {
        if (!is_numeric($id) || $id < 1) {
            throw new InvalidArgumentException('ID must be positive integer');
        }
        if (!isset($this->statements[__METHOD__])) {
            $this->statements[__METHOD__] = $this->connection->prepare('SELECT * FROM users WHERE id = :id');
        }
        $stmt = $this->statements[__METHOD__];
        $stmt->execute([':id' => $id]);
        $record = $stmt->fetch(PDO::FETCH_ASSOC);
        $stmt->closeCursor();
        if (!$record) {
            return null;
        }

        return $this->instantiate($record);
    }

    public function fullName() {
        if (isset($this->first_name) && isset($this->last_name)) {
            return $this->getFirstName()." ".$this->getLastName();
        } else {
            return null;
        }
    }
}


texts: Which is correct : Open one Connection for inserting List of objects or open connection for every single insertion?

texts:
I have written the following method twice but I don't know which is better from performance perspective, code design and best practice.

  First:

public int Insert()
        {
            int affectedRow = -1;
            using (IfxConnection con = new IfxConnection(ConfigurationManager.ConnectionStrings["sh"].ToString()))
            {

                StringBuilder cmdTxt = new StringBuilder();
                cmdTxt.Append(" INSERT INTO shedule(day,short,name,depcode,studycode,batchnum) VALUES (?,?,?,?,?,?) ");
                using (var myIfxCmd = new IfxCommand(cmdTxt.ToString(), con))
                {
                    myIfxCmd.CommandType = CommandType.Text;
                    myIfxCmd.Parameters.Add("day", IfxType.Char);
                    myIfxCmd.Parameters.Add("short", IfxType.NVarChar);
                    myIfxCmd.Parameters.Add("name", IfxType.NVarChar);
                    myIfxCmd.Parameters.Add("depcode", IfxType.Integer);
                    myIfxCmd.Parameters.Add("studycode", IfxType.Integer);
                    myIfxCmd.Parameters.Add("batchnum", IfxType.Integer);

                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }

                    myIfxCmd.Parameters[0].Value = ((object)this.DayId) ?? DBNull.Value;
                    myIfxCmd.Parameters[1].Value = ((object)this.ShortName) ?? DBNull.Value;
                    myIfxCmd.Parameters[2].Value = ((object)this.Name) ?? DBNull.Value;
                    myIfxCmd.Parameters[3].Value = this.DepCode;
                    myIfxCmd.Parameters[4].Value = this.StudyCode;
                    myIfxCmd.Parameters[5].Value = this.BatchNum;

                    affectedRow = myIfxCmd.ExecuteNonQuery();
                }
            }
            return affectedRow;
        }

THEN :

   foreach (Day a in days)
    {
        affectedRow = a.Insert();
    }

  Second:

public int Insert(List<Day> days)
        {
            int affectedRow = -1;
            using (IfxConnection con = new IfxConnection(ConfigurationManager.ConnectionStrings["sh"].ToString()))
            {

                StringBuilder cmdTxt = new StringBuilder();
                cmdTxt.Append(" INSERT INTO shedule(day,short,name,depcode,studycode,batchnum) VALUES (?,?,?,?,?,?) ");
                using (var myIfxCmd = new IfxCommand(cmdTxt.ToString(), con))
                {
                    myIfxCmd.CommandType = CommandType.Text;
                    myIfxCmd.Parameters.Add("day", IfxType.Char);
                    myIfxCmd.Parameters.Add("short", IfxType.NVarChar);
                    myIfxCmd.Parameters.Add("name", IfxType.NVarChar);
                    myIfxCmd.Parameters.Add("depcode", IfxType.Integer);
                    myIfxCmd.Parameters.Add("studycode", IfxType.Integer);
                    myIfxCmd.Parameters.Add("batchnum", IfxType.Integer);

                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }
                    foreach (Day a in days)
                    {
                        myIfxCmd.Parameters[0].Value = ((object)a.DayId) ?? DBNull.Value;
                        myIfxCmd.Parameters[1].Value = ((object)a.ShortName) ?? DBNull.Value;
                        myIfxCmd.Parameters[2].Value = ((object)a.Name) ?? DBNull.Value;
                        myIfxCmd.Parameters[3].Value = a.DepCode;
                        myIfxCmd.Parameters[4].Value = a.StudyCode;
                        myIfxCmd.Parameters[5].Value = a.BatchNum;

                        affectedRow = myIfxCmd.ExecuteNonQuery();
                    }
                }

            }

            return affectedRow;
        }


texts: Approach to download files through POST request

texts:
I have a requirement to download multiple files using POST request. So I am using form submit to get this done.

I have followed two approaches to accomplish this.

Create a Form. Fill input details with payload data. Then set the target of the Form to _self then manually submit the Form. But I see few problems with this approach. Like, When payload is incorrect or Server has download API problems the current page will be redirected to 404 page.

var method = "POST";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", "https://some-url");
appendFormData(form, options.data.items);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);

2) Second approach is similar to the first one, except that I am creating an iframe, appending it to DOM and providing iframe as the target for Form. This works but the problem is, I am not sure when to remove the iFrame from the DOM.

    var method = "POST";
    var iframe = document.createElement("iframe");
    iframe.setAttribute("name", "hidden-frame");
    iframe.style.display = "none";
    document.body.appendChild(iframe);
    var iDocument = iframe.contentWindow.document;
    var form = iDocument.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", "https://some-url");
    form.setAttribute("target", "hidden-frame");
    appendFormData(form, options.data.items);
    iDocument.body.appendChild(form);
    form.submit();

Can you please suggest ways to improve the above solution or suggest if there are any better approach to accomplish the same.


texts: Using OLEDB to connect to a MS Access 2007 file

texts:
I am working on a program which use OLEDB to connect to a MS Access 2007 file. My program has a possibility to add and delete records from file by using SQL statements which select deleted item by ID.

Now, I was warned that my code might cause SQL injection which would delete all entries from the file. How can I prevent this? Where lies the problem? One person mentioned that I could avoid it by having good field verification, but what should I verify for?

This is how I delete items:

// SQL query which will delete entry by using entry ID.
string SQL = "DELETE FROM PersonalData WHERE DataID = " + txtEntryID.Text;

private void DeleteData(string SQL)
{
    // Creating an object allowing me connecting to the database.
    // Using parameters in command will avoid attempts of SQL injection.
    OleDbConnection objOleDbConnection = new OleDbConnection();
    // Creating command object.
    objOleDbConnection.ConnectionString =
        "Provider=Microsoft.ACE.OLEDB.12.0;" +
        "Data Source=" + filePath + ";" +
        "Persist Security Info=False;" +
        "Jet OLEDB:Database Password=" + pass + ";";
    OleDbCommand objOleDbCommand = new OleDbCommand();

    objOleDbCommand.CommandText = SQL;

    // Assigning a connection string to the command.
    objOleDbCommand.Connection = objOleDbConnection;

    try
    {
        // Open database connection.
        objOleDbConnection.Open();
        objOleDbCommand.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        // Displaying any errors that
        // might have occured.
        MessageBox.Show("Error: " + ex.Message);
    }
    finally
    {
        // Close the database connection.
        objOleDbConnection.Close();
    }

    // Refreshing state of main window.
    mainWindow.DisplayFileContent(filePath);

    lblMessage.Text = "Data was successfully deleted.";

    // Clearing text box field.
    txtEntryID.Clear();
}


texts: Codility binary gap solution using indices

texts:
I am seeking a review of my codility solution.

Whilst the problem is fairly simple, my approach differs to many solutions already on this site. My submission passes 100% of the automated correctness tests.

I am looking for feedback regarding the design of my solution, and any comments in relation to how this submission might be graded by a human.

Problem description:

  A binary gap within a positive integer N is any maximal sequence of
  consecutive zeros that is surrounded by ones at both ends in the
  binary representation of N.

  For example, number 9 has binary representation 1001 and contains a
  binary gap of length 2. The number 529 has binary representation
  1000010001 and contains two binary gaps: one of length 4 and one of
  length 3. The number 20 has binary representation 10100 and contains
  one binary gap of length 1. The number 15 has binary representation
  1111 and has no binary gaps. The number 32 has binary representation
  100000 and has no binary gaps.

  Write a function:

  def solution(N)

  that, given a positive integer N, returns the length of its longest
  binary gap. The function should return 0 if N doesn't contain a binary
  gap.

  For example, given N = 1041 the function should return 5, because N
  has binary representation 10000010001 and so its longest binary gap is
  of length 5. Given N = 32 the function should return 0, because N has
  binary representation '100000' and thus no binary gaps.

  Write an efficient algorithm for the following assumptions:

  N is an integer within the range [1..2,147,483,647].

Solution:

def solution(N):

    bit_array = [int(bit) for bit in '{0:08b}'.format(N)]
    indices = [bit for bit, x in enumerate(bit_array) if x == 1]

    if len(indices) < 2:
        return 0

    lengths = [end - beg for beg, end in zip(indices, indices[1:])]

    return max(lengths) - 1


texts: Student information demo in Swing using MVC

texts:
I've followed several guides on how to implement MVC in Java, and so far I've come up with the classes shown below. From my understanding, MVC follows these guidelines.

The Model should be independent and unaware of the View and Controller.
The View should wait for interaction from the user and inform the Controller.
The Controller gets and sets information in the Model and updates the View if necessary.
It's possible for the View to reference the Model. (This is what I don't understand).

Model:

public class Student_Model {

    private String fname, lname;

    public String getFirstName(){
        return this.fname;
    }
    public String getLastName(){
        return this.lname;
    }
    public void setFirstName(String newFname){
        this.fname = newFname;
    }
    public void setLastName(String newLname){
         this.lname = newLname;
    }

}

View

public class Student_View {

    public JPanel panel;
    public JTextField student_fname, student_lname;
    public JLabel stu_fname_label, stu_lname_label;
    public JButton changeName;

    public Student_View(){

        panel = new JPanel();
        panel.setPreferredSize(new Dimension(200,200));
        panel.setBackground(Color.red);

        student_fname = new JTextField(20);
        student_lname = new JTextField(20);

        stu_fname_label = new JLabel("First Name: ");
        stu_lname_label = new JLabel("Last Name: ");

        changeName = new JButton("Change student data");

        panel.add(stu_fname_label);
        panel.add(student_fname);
        panel.add(stu_lname_label);
        panel.add(student_lname);
        panel.add(changeName);

        panel.setVisible(true);

    }
}

Controller

public class Student_Controller implements ActionListener {

    Student_Model student_model;
    Student_View student_view;

    public Student_Controller(Student_Model sm, Student_View sv){
        this.student_model = sm;
        this.student_view = sv;

        initActionListeners(this);
    }

    public void actionPerformed(ActionEvent e) {
        student_model.setFirstName("Bill");
        System.out.println(student_model.getFirstName());

    }
    public void initActionListeners(ActionListener al){
        student_view.changeName.addActionListener(al);

    }

}

And finally it's put together in the as such:

public class MVC_Design_Demo extends JFrame {

    public MVC_Design_Demo(){
        setPreferredSize(new Dimension(500,500));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setLocationRelativeTo(null);
        getContentPane().setBackground(Color.black);

        init();

    }
    public void init(){

        Student_Model newStudent = retrieveStudentInfo();
        Student_View student_view = new Student_View();
        add(student_view.panel);
        Student_Controller student_control = new Student_Controller(newStudent, student_view);

    }

    public static void main(String[] args){
        MVC_Design_Demo mvc = new MVC_Design_Demo();
        mvc.setVisible(true);
        mvc.pack();

    }
    public static Student_Model retrieveStudentInfo(){
        Student_Model sm = new Student_Model();
        sm.setFirstName("John");
        sm.setLastName("Smith");
        return sm;

    }
}

Does this follow the MVC design pattern and are my above assumptions about the guidelines MVC should follow correct?


texts:
So here I wanted to make a system that registered a person's account. It remembers the person's email, account, first and last names, by writing to a file. You can login to that account by typing the email and password according to that email and then you would get a hello message, saying your first and last name that you used to register your account with.

data_text = []
first_names = []
last_names = []
emails = []
passwords = []

def user_choice():
    print('Hello user, create an account or login to an existing one.')
    choice = input('Insert "1" if you wish to create an account or "2" if you wish to login: ')
    print('\r')
    if choice == '1':
        create_account()
        user_choice()
    else:
        login_account()
        user_choice()

def register_info():
    with open('Login_Data.txt', 'r') as login_data:
        global data_text, first_names, last_names, emails, passwords
        data_text = login_data.readlines()
        for i in data_text:
            data_text[data_text.index(i)] = i.strip()
        emails = (data_text[2::4])

def create_account():
    with open('Login_Data.txt', 'a') as login_data:
        first_name = input('First name: ')
        last_name = input('Last name: ')
        email = input('Insert your Email adress: ')
        while email in emails:
            print('That email is already registered')
            email = input('Insert another Email adress: ')
        password = input('Create a password: ')
        passwordc = input('Confirm your password: ')
        info = [first_name, last_name, email, password]
        while passwordc != password:
            print('The passwords do not match.')
            passwordc = input('Reinsert your password: ')
        for i in info:
            login_data.write(i)
            login_data.write('\n')
    print('Nice! Your account was registered.')
    print('\r')
    register_info()

def login_account():
    register_info()
    with open('Login_Data.txt', 'r'):
        login_email = input('Email: ')
        while login_email not in emails:
            print('Invalid Email')
            login_email = input('Reinsert your Email: ')
        login_password = input('Password: ')
        while login_password != data_text[data_text.index(login_email) + 1]:
            print('Invalid password')
            login_password = input('Reinsert your password: ')
        print('Hello {} {}, welcome back!'.format(data_text[data_text.index(login_email) - 2], data_text[data_text.index(login_email) - 1]))
        print('\r')
user_choice()


texts: Log Likelihood Calculations for Censored Data in R

texts:
I am calculating the log-likelihood of data that have some observations censored. For uncensored "a" clusters, the likelihood calculates P(Y=y). For censored "b" clusters, it calculates that Y is at least size Y, P(Y≥y). So the likelihood is L=mult[P(Y=y)P(Y≥y)].

The below code is my working, actual-in-use code that calculates this log likelihood based on censorship status. However, when in place with several other functions, it is extremely slow since it has to iterate through each row in the dataset (datasets are usually several thousand rows long, and maximization runs through several thousands of iterations of R and k values).

My hope is that someone will know of an alternative way to approach this that will increase performance. I am (obviously) not an expert coder.

new_likelihood <- function(Y,R,k) {
  p_function <- function(y,n){ #Create a dummy function to use in for loop
     exp(log(n)-log(y)+lgamma(k*y+y-n)-(lgamma(k*y)+lgamma(y-n+1))+(y-n)*log(R/k)-(k*y+y-n)*log(1+R/k))
    }
  liks_a <- numeric(nrow(Y)) # initialize vector of logliks for `a` clusters
  liks_b <- numeric(nrow(Y)) # initialize vector of logliks for `b` clusters

  #Loop through each row of the data
  for(i in 1:nrow(Y)){
    y <- Y[i,1]
    n <- Y[i,2]
    c <- Y[i,3]

      if (c==0){ #For uncensored, apply regular PDF
        liks_a[i] <- log(p_function(y,n))
      } #outputs a value of 0 in liks_a[i] if c=1, so doesnt affect sum(log(liks))

      if(c==1){ #for censored, sum to do 1-(sum(Y-1))
        liks_b[i] <- log(1-sum(p_function(1:(y-1),n)))
      } #outputs a value of 0 if in liks_b[i] if c=0, so doesnt affect sum(log(liks))
  }
  sumliks <- sum(liks_a,liks_b)
  return(sumliks)
}

# Example data
Y_censor0 <- cbind(c(3,2,2,10,1,1),c(1,1,1,1,1,1),c(0,0,0,0,0,0)) # 3-column data w/ no one censored
Y_censor1 <- cbind(c(3,2,2,10,1,1),c(1,1,1,1,1,1),c(0,0,1,1,0,0)) # 3-column data with some censored

# Test
new_likelihood(Y_censor0,0.9,0.25)
new_likelihood(Y_censor1,0.9,0.25)
```


texts: Multithreaded app for writing to a MySQL database

texts:
I have a multi-threaded app (WCF) that writes to a MySQL db. I want to use MySQL's built in connection pooling abilities.

As far as I can tell, to do that, I should set MySqlConnectionStringBuilder.MinimumPoolSize to some value approximately equal to the number of threads I connect. Then Open/Close the connection for each call to the db. Is this correct? If not, what is the proper way to use pooling?

Here is the function I use to send data to the db. It gets called by many threads throughout the day. Hundreds, maybe thousands of times per day.

private static void execute(MySqlCommand cmd)
{
    try
    {
        MySqlConnectionStringBuilder cnx = new MySqlConnectionStringBuilder();
        cnx.Server = MySqlServer;
        cnx.Database = Database;
        cnx.UserID = UserId;
        cnx.Password = Pass;
        cnx.MinimumPoolSize = 100;
        cmd.Connection = new MySqlConnection(cnx.ToString());
        cmd.Connection.Open();
        cmd.ExecuteNonQuery();
    }
    catch (MySqlException e)
    {
        System.Console.WriteLine(e.Message);
    }
    finally
    {
        if (null != cmd.Connection)
        {
            cmd.Connection.Close();
        }
    }
}


texts: "specific case" object that stands for "any object" : is it a good idea ?

texts:
I got tired of doing (more or less) this in my rails controllers :

class ThingsController < ApplicationController

  def index
    @category = Category.find( params[:category_id] ) if params[:category_id].present?
    scope = @category ? @category.things : Thing.scoped
    @things = scope.order( :title )
  end
end

...wich also leads to a lot of conditionals in the template if @category is absent.

I had this idea (a variation on the NullObject pattern) :

class Category < ActiveRecord::Base

  def self.one_or_any( id )
    where( id: id ).first || any_category
  end

  def self.any_category
    @any_category ||= begin
      new( title: "Any category" ) do |generic|
        generic.instance_eval{ def things ; Thing.scoped end }
        generic.readonly!
        generic.freeze
      end
    end
  end
end

Which would in turn allow me to do :

class ThingsController < ApplicationController
  def index
    @category = Category.one_or_any( params[:category_id] )
    @things   = @category.things.order( :title )
  end
end

... and to get rid of category-related conditionals in the template.

I Just wonder if this is a good idea, and if it has drawbacks i don't see yet. Thoughts ?

Note : Of course the actual implementation can be different (use a specific subclass of Category instead of extending an instance, for example - or even using a decorator).


texts: Basic structure for interactive single window application

texts:
This is the basic structure I usually end up with whenever I'm writing a simple application. More recently I've learned about singletons and have started to incorporate them into my design, but other that that I haven't changed much about it in recent times.

I've been wondering if there is anything in here that I could improve on or that is considered bad practice.

Main

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | UnsupportedLookAndFeelException | IllegalAccessException e) {
            e.printStackTrace();
        }

        Controller.getInstance();
    }
}

Controller

import javax.swing.*;

public class Controller {
    private static Controller instance;

    private static final int FPS = 30;
    public static final int WIDTH = 600;
    public static final int HEIGHT = 800;

    private final JFrame frame;

    private Timer timer;

    public static Controller getInstance() {
        return instance != null ? instance : (instance = new Controller());
    }

    private Controller() {
        //Do setup
        frame = new AppFrame();

        timer = new Timer(1000/FPS, e -> update());
        timer.start();
    }

    private void update() {
        //Update model
        frame.repaint();
    }
}

AppFrame

import javax.swing.*;

public class AppFrame extends JFrame {
    public AppFrame() {
        super("My Example App");
        setResizable(false);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        add(new AppPanel());

        //Do more setup if applicable

        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }
}

AppPanel

import javax.swing.*;
import java.awt.*;

public class AppPanel extends JPanel {
    private final Dimension DIMENSION = new Dimension(Controller.WIDTH, Controller.HEIGHT);

    @Override
    public Dimension getPreferredSize() {
        return DIMENSION;
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        //Draw things on g2
    }
}


texts: For-loop for mixing audio (left channel, stereo to mono)

texts:
This is a very simple for loop, but I find it very, complex-looking.  I hope you can give me some insight on how it may be improved.

int Tindex = 0;
int16_t Test[960];
int TestSize = SampleSize / 2; //Test is 16Bit, Half size of 32bit
int TestChannels = 2; //Stereo
float copy = 0; //Used to store Audio data used to Mixdown to Mono
bool left = true; //Only use Left Channel
bool MixMono = true; //MixMono has priority over left
if (MixMono || left) //Change the approprite variables if it's Mono instead of Stereo
{
    int16_t Test[960 / 2];
    TestSize = TestSize / 2; //If Mono is used, Half Channel/Size.
    TestChannels = 1; //Mono
}
int ChannelCheck = 0;

for (int i = 0; i < bufferSize; i += 1)         //For Loop for Downmixing and BitDepth Conversion
{
    int s = (micBuffer[i] * 32768.0f); //32bit Float to 16Bit Int

    ChannelCheck++;

    if (MixMono)//Mixdown Stereo to Mono
    {
        copy += s;
        if (ChannelCheck == 2)
        {
            Test[Tindex] = copy / 2;
            copy = 0;
            Tindex++;
            ChannelCheck = 0;
        }

    }
    else if (left)
    {
        if (ChannelCheck == 1)
        {
            Test[Tindex] = s;
            ChannelCheck -= 2;
            Tindex++;
        }
    }
    else
    {
        Test[Tindex] = s;
        Tindex++;
    }
}
//End of For Loop

I tried commenting most stuff, so it should be self-explained.

It's pretty much a mix stereo to mono.  It combines 2 indices from the float array (add them), then divide them (to keep the correct volume).

16-bit conversion just multiplies by Int16 Max; not much there.  I would like to have some kind of dithering, so if anyone knows some easy references, please offer them.

But as you can see, it's overly complicated with checks all over the place.  I think it can be improved, but I can't really figure out a good way to do it.


texts: Spaces-to-tabs converter, updated version

texts:
I recently posted Spaces To Tabs Converter but it had lots of bugs, so I rewrote the code. I wanted to ask, is it good code? I didn't find any bugs.

#include <stdio.h>
#define TABVALUE 4
#define ARRAYSIZE 3

void emptyArray(int *a);

int main(void) {
    int c, d, s;
    int savedChars[ARRAYSIZE];
    c = s = d = 0;
    while ((c = getchar()) != EOF) {
        if (c == ' ') {
            s = 0;
            s++;
            for (int j = 0; j < TABVALUE - 1; j++) {
                d = getchar();
                if (d != EOF) {
                    savedChars[j] = d;
                    savedChars[j + 1] = '\0';
                    if (d == ' ') {
                        s++;
                    } else {
                        break;
                    }
                }
            }
            if (s == TABVALUE) {
                emptyArray(savedChars);
                putchar('\t');
                s = 0;
            } else {
                putchar(c);
                for (int i = 0; i < 3; i++) {
                    if (savedChars[i] != '\0') {
                        putchar(savedChars[i]);
                    }
                }
            }
        } else {
            if (c != EOF) putchar(c);
        }
    }
    return 0;
}

void emptyArray(int *a) {
    for (int i = 0; i < ARRAYSIZE; i++) {
        a[i] = '\0';
    }
}


texts: Convert number from base-10 number system to any number system

texts:
I wrote a small method for convert number from base-10 number system to any number system (code is not perfect but that is not the point).
My question is if I get right single responsibility principle. Is 2nd approach better than 1st or 'charReplace' functionality is too small for creating own method ?

    public static string convertNumber(BigInteger num, int baseNum)
    {
        string symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        if (baseNum < 2 || symbols.Length + 10 < baseNum)
        {
            throw new Exception;
        }

        var result = "";
        do
        {
            var partResult = (int)(num % baseNum);
            if (partResult >= 10)
            {
                result = result.Insert(0, symbols[partResult - 10].ToString());
            }
            else
            {
                result = result.Insert(0, partResult.ToString());
            }
            num /= baseNum;
        } while (num != 0);

        return result;
    }

vs.

    static readonly string Symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    public static string convertNumber(BigInteger num, int baseNum)
    {
        if (baseNum < 2 || Symbols.Length + 10 < baseNum)
        {
            throw new Exception;
        }

        var result = "";
        do
        {
            var partResult = (int)(num % baseNum);
            result = result.Insert(0, charReplace(partResult));
            num /= baseNum;
        } while (num != 0);

        return result;
    }

    private static string charReplace(int number){
        if (number < 10){
            return number.ToString();
        }

        return Symbols[number - 10].ToString();
    }


texts: Importing and deleting product data in WordPress

texts:
I am interested in how to handle errors/exceptions/returned data correctly.

For example, I have a script which creates, updates and deletes products data.

Here is method that receives data from an API, processes and decides what to create/update/delete.

private function importProducts($brand)
{
    $products = $this->dsApi->getProductsByBrand($brand);

    //returns ['create' => [], 'update' => [], 'delete' => [] ]
    $preparedProducts = $this->prepareProducts($products, $brand);

    foreach ($preparedProducts['delete'] as $key => $product) {
        $this->deleteProduct($product);
        $this->log->info(
            'Brand ' . $brand->name . '(' . $brand->id_brand . ')'
            . ' id: ' . $product . ' was deleted'
        );
    }

    foreach ($preparedProducts['create'] as $key => $product) {

        $this->importProduct($product, $brand);
        $this->log->info(
            'Brand ' . $brand->name . '(' . $brand->id_brand . ') sku: ' . $product['sku'] . ' was imported'
        );
    }

    foreach ($preparedProducts['update'] as $key => $product) {
        $this->importProduct($product, $brand, $product['idProductWc']);
        $this->log->info(
            'Brand ' . $brand->name . '(' . $brand->id_brand . ') sku: ' . $product['sku']
            . ' id: ' . $product['idProductWc'] . ' was updated'
        );
    }
}

And for example deleteProduct() method:

private function deleteProduct($product)
{
    wp_delete_post($product, true);

    $args = [
        'order' => 'ASC',
        'post_mime_type' => 'image',
        'post_parent' => (int) $product['idProductWc'],
        'post_status' => 'inherit',
        'post_type' => 'attachment',
    ];
    $child = get_children($args);
    foreach ($child as $id => $item) {
        wp_delete_attachment($id, true);
    }
}

Is the deletion method written correctly? Is it necessary to handle an error in wp_delete_post() method? How to handle it? What to write in logs in this case? Should the method return a response?


texts: Object oriented architecture with an image processing code

texts:
This code is python 3X code (in django).
It takes an instance of user entry, and process images: it creates a resized version of original image, 2 thumbs, saves all, and update instance fields to point to correct files so it's correctly saved.
Then it returns the updated instance.

I'm not sure this code object oriented architecture is correct. It seems lots of line of redundant code. Could I have made it smarter?
I tried to break code on several methods that doe only one thing.
Then I process it with the method call 'execute' which is used elsewhere in the script when this code is used.

Also what do you think of encapsulation of this code?

class ImageProcessing:
    def __init__(self, instance, image):
        self.instance = instance
        self.image = image

        # Settings
        self.sizes                    = OrderedDict()
        self.sizes['image_main']      = (800, 800)
        self.sizes['thumbsize_big']   = (200, 200)
        self.sizes['thumbsize_small'] = (100, 100)
        self.png_compress = 6
        self.jpg_compress = 80
        self.has_iterated = 0
        # Variables
        self.slug = slugify(instance.myField, allow_unicode=True)
        self.saving_path = instance.savePath
        self.base_dir = settings.BASE_DIR + self.saving_path
        self.image_format = self.image.image.format.lower()
        has_iterated = 0

    def resize_image(self, image, size):
        myimage = Image.open(image)
        myimage = myimage.resize(size, Image.ANTIALIAS)
        return myimage

    def save_image(self, image, save_dir, png_compress, jpg_compress):
        if self.image_format == 'png':
            image.save(save_dir + '.png', compress_level=png_compress, format='PNG')
        if self.image_format == 'jpg' or 'jpeg':
            image.save(save_dir + '.jpg', quality=jpg_compress, format='JPEG')

    def execute(self):
        for key, value in self.sizes.items():
            save_dir = self.base_dir + self.slug + '_' + key

            if self.image_format == 'png':
                # Save images on disk
                self.save_image(self.resize_image(self.image, value),save_dir, self.png_compress, self.jpg_compress)
                # Save images in fields
                if self.has_iterated == 0: self.instance.image_main = self.saving_path + self.slug + '_' + key + '.png'
                if self.has_iterated == 1: self.instance.image_thumbsize_big = self.saving_path + self.slug + '_' + key + '.png'
                if self.has_iterated == 2: self.instance.image_thumbsize_small = self.saving_path + self.slug + '_' + key + '.png'
                self.has_iterated += 1
            if self.image_format == 'jpg' or 'jpeg':
                self.save_image(self.resize_image(self.image, value),save_dir, self.png_compress, self.jpg_compress)
                if self.has_iterated == 0: self.instance.image_main = self.saving_path + self.slug + '_' + key + '.jpg'
                if self.has_iterated == 1: self.instance.image_thumbsize_big = self.saving_path + self.slug + '_' + key + '.jpg'
                if self.has_iterated == 2: self.instance.image_thumbsize_small = self.saving_path + self.slug + '_' + key + '.jpg'
                self.has_iterated += 1

        return self.instance


texts: Custom Security for API access from server to mobile application

texts:
i am not the best at security but need a custom way to securely store personal identifiable information like name, address etc - Can i please have some feedback on this custom code, from my perspective it looks okay but with security not being my strong point i don't trust myself.

The data is passed from my application over HTTPS in the header along with a custom auth code which is made up from the users unique ID, fcm ID, package name and the epoch date they obtained the auth code.

This is sent to the server on every request and decrypted to make sure that we have the correct user - the server won't provide any details back to the unless the epoch date matches (this is stored in the database on the auth creation)

Here is the encrypt / decrypt function

function encrypt($string, $public_key = "public key", $action = "e") {
     $secret_key = "secret key";
     $encrypt_method = "AES-256-CBC";
     $key = hash( 'sha256', $public_key );
     $secret = substr( hash( 'sha256', $secret_key), 0, 16 );

     if( $action == 'e' ) {
          $output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $secret) );
     } else if ( $action == 'd') {
          $output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $secret);
     }
     if (empty($output)) {
          denyAccess();
     }
     return $output;
}

the data stored in the database uses the same function but with different keys so the data is encrypted twice.


texts:
I would like to know whether I could make my solution to this Leetcode challenge much faster.

  There is a brick wall in front of you. The wall is rectangular and has
  several rows of bricks. The bricks have the same heights but different
  widths. You want to draw a vertical line from the top to the
  bottom and cross the least bricks.

  The brick wall is represented by a list of rows. Each row is a list of
  integers representing the width of each brick in this row from left to
  right.

  If your line goes through the edge of a brick, then the brick is not
  considered as crossed. You need to find out how to draw the line to
  cross the least bricks and return the number of crossed bricks.

  You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.

  Note -

  The width sum of bricks in different rows are the same and won't exceed INT_MAX.
  The number of bricks in each row is in the range [1, 10,000]. The height of the wall is in the range [1, 10,000]. The total number of
  bricks in the wall won't exceed 20,000.

  Example -

Input: [[1,2,2,1],
        [3,1,2],
        [1,3,2],
        [2,4],
        [3,1,2],
        [1,3,1,1]]

Output: 2

  Explanation -

Here is my solution to this challenge -

import collections

def least_bricks(wall):
    return len(wall) - max(collections.Counter(sum(row[:i + 1]) for row in wall for i in range(len(row[:-1]))).values(), default = 0)

Here is the time taken for the example output -

%timeit least_bricks([[1,2,2,1], [3,1,2], [1,3,2], [2,4], [3,1,2], [1,3,1,1]])

>>> 13 µs ± 1.07 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Here is my Leetcode result (85 test cases) -

Taken from - https://docs.python.org/3/library/collections.html#collections.Counter -

  A Counter is a dict subclass for counting hashable objects. It is a
  collection where elements are stored as dictionary keys and their
  counts are stored as dictionary values. Counts are allowed to be any
  integer value including zero or negative counts. The Counter class is
  similar to bags or multisets in other languages.


texts: Method returning IEnumerable should ToList() or not

texts:
I can't decide whether my method that returns an IEnumerable<T> should itself be lazy or whether it should build a list and return that. I often opt for the latter so I can be sure the enumeration of each value isn't performed multiple times.
For example:

public IEnumerable<UserProfile> GetUsers()
{
    var allDepartments = GetAllDepartments(active: true); // Returns IEnumerable<Department>
    var allUsers = GetAllUserDepartments(active: true); // Returns IEnumerable<User>
    var users
        = allDepartments
            .Join(allUsers, x => x.Department, y => y.Department, (x, y) => y, StringComparer.OrdinalIgnoreCase)
            .Distinct()
            .Select(x => GetUserProfile(x))
            .ToList(); // Is this recommended or not

    return users;
}

The key part is each enumeration is doing something (GetUserProfile) non trivial, it might be expensive, it might not, but what's the recommendation for a method that returns an IEnumerable<T>? Should it care about whether the caller might enumerate it several times or not?

Assume only IEnumerable<T> functionality is required by the caller and my question can be reworded into:

How do I signify to the caller that each enumeration may be expensive?

How expensive may change their implementation decisions, if they enumerate the whole lot several times then a ToList() makes sense to them to perform, if they don't enumerate the whole lot, then a ToList() would be a waste for me (or the caller) to perform?


texts: Idomatic way to ignore `finally` block after cancelling network request

texts:
In React, it is quite common for me to have something similar to the following.

async componentDidMount() {
    try {
        this.setState({ isLoading: true })
        const { data } = await axios.get('...')
        this.setState({ data })
    } catch(error) {
         handleError(error)
    } finally {
        this.setState({ isLoading: false })
    }
}

This is great because the cleanup code (isLoading: false) is DRY. That is, until I try to cancel network requests on unmount. That code would look like this:

async componentDidMount() {
    try {
        this.axiosCancelTokenSource = axios.CancelToken.source()
        this.setState({ isLoading: true })
        const { data } = await axios.get('...', {
            cancelToken: this.axiosCancelTokenSource.token,
        })
        this.setState({ data })
    } catch(error) {
         if (axios.isCancel(error)) return
         handleError(error)
    } finally {
        this.setState({ isLoading: false })
    }
}
componentWillUnmount() {
    if (this.axiosCancelTokenSource) this.axiosCancelTokenSource.cancel()
}

The problem with this is that it will setState after the component unmounts, which React will warn againts.

As far as I see it, these are my options for dealing with this:

Ignore the warning.
React gives a warning when you setState after unmount because it indicates a memory leak (in this case, the lingering network request, if not cancelled). If the network request is cancelled, there is still a setState after unmount, but just to set a flag. There is no more lingering network request. It should be safe to ignore the warning in this case, but it doesn't feel right.
Check what error was thrown in the finally block and add the same if statement as the catch block. This seems incredibly hacky and would require extra code to save the error from the catch block.
Check if the component is mounted in the finally block. This is also hacky and requires boilerplate code to update a this.isMounted flag.
Put the cleanup code at the end of try and after the condition in catch. This is not DRY. Humans are also very forgetful; I cannot count how many times I have forgotten to set isLoading = false in catch.
Define a cleanup() function before the try and call it in try and catch. This is a decent option, but requires extra function calls, making it harder to follow.

So far, it looks like the first or fifth options are best, depending on how much you care about seeing warning messages. Am I missing any good options?


texts:
I have a form which needs to display value in its input field initially. There is no post API used, only get and put. I could show the data initially by updating the state from the componentWillReceiveProps lifecycle method. What is an efficient way to show the data in form field? Here is what I have done. The reason to put saga code is if I have done the wrong way or not. It's the flow of my code from fetching to putting the value in the form field.

container.js

const mapDispatchToProps = dispatch => ({
  fetchEmailService: () => dispatch(fetchEmailService())
});

const mapStateToProps = createStructuredSelector({
  email: selectEmailService()
});

class EmailService extends React.PureComponent {
  state = {
    emailService: {
      api_key: "",
      domain: ""
    },
  };

  componentDidMount() {
    this.props.fetchEmailService();
  }

  componentWillReceiveProps(nextProps, prevProps) {
    if (nextProps.email) {
      nextProps.email
        .entrySeq()
        .map(([key, value]) => {
          this.setState(state => ({
            emailService: { ...state.emailService, [key]: value }
          }));
        })
        .toArray();
    }
  }

  render() {
    const { emailService, errors } = this.state;
    const { email } = this.props;
    if (email.size === 0) {
      return
fetching...
;
    }
    return (
      <form onSubmit={this.handleSubmit}>
        <TextFieldGroup
          name="api_key"
          type="text"
          value={emailService.api_key}
          onChange={this.handleChange}
          error={errors.api_key}
        />
        <TextFieldGroup
          name="domain"
          type="text"
          value={emailService.domain}
          onChange={this.handleChange}
          onBlur={this.handleBlur}
        />
        <button className="btn btn-primary">Save Changes</button>
      </form>
    );
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(EmailService);

reducer.js

function emailServiceState(state = initialState, action) {
  switch (action.type) {
    case EMAIL_SERVICE_FETCH_REQUEST:
      return state.set("requesting", true).set("successful", false);
    case EMAIL_SERVICE_FETCH_SUCCESS:
      return state.set("successful", true).set("emailService", fromJS(action.emailService.data));
    case EMAIL_SERVICE_FETCH_FAILURE:
      return state.set("error", action.error);
    default:
      return state;
  }
}

selectors.js

export const selectEmailService = () => state =>
  state.getIn(["emailService", "emailService"]);

sagas.js

function* fetchemailService(action) {
  yield call(
    EmailApi.get(
      "api/configuration/email-service",
      emailServiceFetched,
      emailServiceFetchingError
    )
  );
}

function* emailServiceWatcher() {
  yield takeLatest(EMAIL_SERVICE_FETCH_REQUEST, fetchemailService);
}

export default [emailServiceWatcher];


texts: Is this login page safe and can it be optimized?

texts:
<?php
$page = 'Login';
session_start();
include 'header.php';
$user_error = '';
$pass_error = '';
$login_error = '';

if(isset($_SESSION['username'])){
header('location: control-painel.php');
}
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$cost = '11';
$salt = 'Cf1f11ePArKlBJomM0F6aJ';
$password_hash = crypt($password, '$2a$' . $cost . '$' . $salt . '$');
$id = 0;

if(empty($username)){
    $user_error = 'Please insert a username';
}
if(empty($password)){
    $pass_error = 'Please insert a password';
}
elseif(!empty($username) && !empty($password)){
    $stmt = $mysqli -> prepare('SELECT id FROM user WHERE username = ? AND password = ?');
    $stmt -> bind_param('ss', $username, $password_hash);
    $stmt -> execute();
    $stmt -> bind_result($id);
    $stmt -> fetch();

    if($id){
        $_SESSION['username'] = $username;
        $_SESSION['email'] = $email;
        header('location: control-painel.php');
        die();
    }
    else{
        $login_error = 'User or Password invalid';
    }
}
}
?>

    <?php echo $user_error; ?>

    <?php echo $pass_error; ?>

    <?php echo $login_error; ?>

        <form method="post">
            Username:
            <input type="text" name="username" class="text bradius">
            Password:
            <input type="password" name="password" class="text bradius">
            <input type="submit" class="submitbutton bradius" name="login" value="Login">
        </form>

<?php
include "footer.php";
?>


texts: How to implement HasMany() relationship with PHP?

texts:
Suppose User and Item are two models, and User has many Item. Both models are derived from the parent Model class. In order to retrieve the list of all items a particular user has:

    $user = new User(100);  // User with ID = 100
    $items = $user->getItems();

Now suppose that there are two tables in a database, users and items. In order to find all the items a particular user owns:

    SELECT * FROM users INNER JOIN items ON (users.item_id = items.id) WHERE users.id = 100

I'm trying to implement this functionality as a PHP magic method. Basically what this means is that if you call $users->getItems(), getItems() is not actually a defined method in User. Instead, it will invoke $users->__call('getItems', FUNCTION_ARGS); So basically:

    class Model {
        ...
        function __call($method_name, $args) { /* ? */ }

How would I go about implementing this?


texts: Measure website home page total network size in bytes

texts:
We have a requirement to check the size of some of our website home pages, in MB. This is to ensure that they are not growing too large, and that large images haven't been uploaded. I couldn't find much info on this, but have come up with following which is working as required.

The code is designed to either run locally on my machine, or by leveraging our Selenium grid. It simply loads home page, and from the browser Performance log, we strip out the Network.dataReceived (bytes) information and sum it.

Finally, we have set levels which the site should fall within.

#!/usr/bin/python
""" This script will simply check the download page size (bytes) of a Home page."""
import argparse
import re
import sys

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

parser = argparse.ArgumentParser(description="This script will measure size of a home page.")
parser.add_argument('--site', default='somewebsite.com', required=True)
parser.add_argument('--local', action='store_true', default=False)
parser.add_argument('--datacentre', choices=['dc1', 'dc2'])
args = parser.parse_args()

logging_prefs = {'performance' : 'INFO'}

if args.local:
    caps = DesiredCapabilities.CHROME.copy()
    caps['loggingPrefs'] = logging_prefs
    driver = webdriver.Chrome(desired_capabilities=caps)
else:
    profile = webdriver.FirefoxProfile()
    profile.set_preference('plugin.state.flash', 0)
    profile.set_preference("webdriver_enable_native_events", False)
    profile.update_preferences()
    caps = DesiredCapabilities.FIREFOX.copy()
    caps['loggingPrefs'], caps['acceptSslCerts'] = logging_prefs, False
    if args.datacentre == 'dc1':
        driver = webdriver.Remote(
            command_executor='http://selenium/hub',
            desired_capabilities=caps,
            browser_profile=profile)
    elif args.datacentre == 'dc2':
        driver = webdriver.Remote(
            command_executor='http://selenium/hub',
            desired_capabilities=caps,
            browser_profile=profile)

driver.implicitly_wait(30)
driver.set_page_load_timeout(30)
url = "http://" + args.site + "/"
driver.get(url)
total_bytes = []

try:
    for entry in driver.get_log('performance'):
        if "Network.dataReceived" in str(entry):
            r = re.search(r'encodedDataLength\":(.*?),', str(entry))
            total_bytes.append(int(r.group(1)))
except Exception:
    print 'error'
    driver.close()
    sys.exit(3)
if total_bytes is not None:
    mb = round((float(sum(total_bytes) / 1000) / 1000), 2)

if args.local:
    from datetime import datetime
    d = (datetime.today()).strftime("%d-%m-%y-%H-%M")
    filename = 'results_{}.txt'.format(str(d))
    with open(filename, 'a') as f:
        f.write("{}, {}\n".format(args.site, mb))

try:
    if mb < 2.0:
        print "OK. Total Network Data Received size for {}: {}MB".format(args.site, str(mb))
        sys.exit(0)
    elif mb >= 2.0 and mb < 4.0:
        print "Warning. Total Network Data Received size for {}: {}MB".format(args.site, str(mb))
        sys.exit(1)
    elif mb > 4.0:
        print "CRITICAL. Total Network Data Received size for {}: {}MB".format(args.site, str(mb))
        sys.exit(1)
except Exception:
    print "UNKNOWN. Something went wrong."
    sys.exit(3)
finally:
    driver.close()


texts: Turning on/off setInterval locating - using React.js

texts:
I work with the GoogleMaps API, using React.js.
Inside the GoogleMap component:

I have a component called UserLocationTimer, which activates
setInterval within useEffect and samples the user's location every 2
seconds, centering the map accordingly. In addition, returns the
UserLocation component that displays the marker of the user's
location on the map.

In case the user drags the map, I catch the event isDragged, and return only the UserLocation component that displays the
marker of the user's location on the map.

It works fine, however, how would you optimize this code?
Is there a more efficient way to catch the dragging event and stopping the timer interval from the parent, instead using conditional rendering?
  <GoogleMap
    . . .
    onDrag={(map) => {
      setIsDragged(true);
    }}
    onDragEnd={(map) => {
      setIsDragged(true);
    }}

  >
    . . .

    {!isDragged && (
      <UserLocationTimer
        userLocation={userLocation}
        setUserLocation={setUserLocation}
        panTo={panTo}
      ></UserLocationTimer>
    )}

    {isDragged && (
      <UserLocation userLocation={userLocation}></UserLocation>
    )}

  </GoogleMap>

export const UserLocationTimer = (props) => {
  const [timer, setTimer] = useState(null);

  useEffect(() => {
    const interval = setInterval(() => {
      setTimer(new Date());
      locateMe();
    }, 2000);
    return () => clearInterval(interval);
  }, []);

  function locateMe() {
    // locating using geolocation...
  }

  return (
    <>
      {timer && <UserLocation userLocation={props.userLocation}></UserLocation>}
    </>
  );
};

export const UserLocation = (props) => {

  if (props.userLocation)
    return (
      <>
        <Marker
          position={{
            lat: props.userLocation.lat,
            lng: props.userLocation.lng,
          }}
          icon={{
            url: userLocationIcon,
            scaledSize: new window.google.maps.Size(30, 30),
            origin: new window.google.maps.Point(0, 0),
            anchor: new window.google.maps.Point(15, 15),
          }}
        />
      </>
    );
  else return null;
};


texts: Use parameter to filter results in a database without directly allowing users to access database

texts:
So background context:

I wrote this script for a personal project that holds a large amount of items, I already display and am able to filter the results based on its country/location. I am a student PHP coder and would like constructive criticism on my thought process/code.

Thought Process:

I decided to code my country filter script as the countries are from a pre-defined list in my database (table: countries) and for extra safety precautions I wanted to ensure the end-user never gains direct access to the database queries - as from my understanding this is where security issues can become apparent. Essentially, the idea is that I grab a list of the countries from the database and store it in an array, then I compare that list to the users input. If there is a match then filter the results as such, if not change their input to NULL which produces a "No Result" message further on.

Table: countries

+----+-------------+-------------+
| id | name        | slug        |
+----+-------------+-------------+
| 1  | Australia   | australia   |
+----+-------------+-------------+
| 2  | New Zealand | new-zealand |
+----+-------------+-------------+

Table: items

+----+----------+-----------------------------------+-----------+---------+
| id | name     | description                       | countryid | suspend |
+----+----------+-----------------------------------+-----------+---------+
| 1  | Item One | description of Item One           | 1         | 0       |
+----+----------+-----------------------------------+-----------+---------+
| 2  | Item Two | description of suspended Item Two | 2         | 1       |
+----+----------+-----------------------------------+-----------+---------+

PHP Code:

if(isset($_GET['l'])) {
$location = strip_tags($_GET['l']);
$sql = "SELECT slug FROM countries";
$countries = $db->prepare($sql);
$countries->execute();
$getCountryList = $countries->fetchAll(PDO::FETCH_COLUMN); // Get all country slugs
if(in_array($location, $getCountryList)) { // Match country slugs to inputted country - this ensures the user input never touches the database >:)
  $sql = "SELECT countryid, name FROM countries WHERE slug = :slug LIMIT 1";
  $matchCountry = $db->prepare($sql);
  $matchCountry->execute(array(':slug' => $location));
  $countryDetails = $matchCountry->fetch(PDO::FETCH_ASSOC);
  $location = $countryDetails['countryid']; // The ID so I can search the items
  $locationName = $countryDetails['name']; // This now equals the nice to read name e.g "Australia"
} else {
  $location = '';
  $_GET['l'] = '';
}
}

The snippet that filters the items:

if(isset($_GET['l']) && $_GET['l'] != '') {
                // Location
                $sql = "SELECT * FROM items WHERE items.suspend = 0 AND items.countryid = :countryid GROUP BY items.id";
                $results = $db->prepare($sql);
                $results->execute(array(':countryid' => $location));
}

I hope I have given all the information needed! I'd like to know specifically if this extreme measure is over the top and if there is a better way to achieve such functionality.


texts:
I'm updating a stats bar on the page after a user action. The code works, but as you can see, it's very messy.

Is there a shorter way of writing this function? Seems like a complete mess. I thought about using $.each a couple times to cycle through, but since I need to compare values from the first two array keys in the multi-dimensional array, it makes things much more complicated.

Here's an example of the post object data:

{
    {team_avg: {overdue: 1, in_review: 2, in_progress: 1, assigned: 1}}
    {user: {assigned: 5, overdue: 3, in_review: 4, in_progress: 1}
}

Here's my current (mess) for the $.post callback:

$.post("{{ route('task.load') }}", { _token: $('meta[name=csrf-token]').attr('content') }, function(data) {

    $task_summary = $('.taskload-stats');

    // update # of assigned
    $assigned = $task_summary.find('.assigned');
    $assigned.html(data.user.assigned);

    if (data.user.assigned > data.team_avg.assigned) {
        $assigned.append(' ');
    } else if (data.user.assigned === data.team_avg.assigned) {
        $assigned.append(' --');
    } else {
        $assigned.append(' ');
    }

    // update # of in progress
    $in_progress = $task_summary.find('.in-progress');
    $in_progress.html(data.user.in_progress);

    if (data.user.in_progress > data.team_avg.in_progress) {
        $in_progress.append(' ');
    } else if (data.user.in_progress === data.team_avg.in_progress) {
        $in_progress.append(' --');
    } else {
        $in_progress.append(' ');
    }

    // update # of in review
    $in_review = $task_summary.find('.in-review');
    $in_review.html(data.user.in_review);

    if (data.user.in_review > data.team_avg.in_review) {
        $in_review.append(' ');
    } else if (data.user.in_review === data.team_avg.in_review) {
        $in_review.append(' --');
    } else {
        $in_review.append(' ');
    }

    // update # of overdue
    $overdue = $task_summary.find('.overdue');
    $overdue.html(data.user.overdue);

    if (data.user.overdue > data.team_avg.overdue) {
        $overdue.append(' ');
    } else if (data.user.overdue === data.team_avg.overdue) {
        $overdue.append(' --');
    } else {
        $overdue.append(' ');
    }

    $(document).foundation('tooltip', 'reflow');
});


texts:
def fib_m_through_n(m, n):
    """(number, number) -> list

    A function which returns a list containing the mth through the nth
    fibonacci numbers.

    SHOULD BE MODIFIED IN THE FUTURE so it will remember values already computed,
    so when it is called again it reuses that information
    """
    fib_list = [0, 1, 1]
    a, b, c = 1, 1, 0  #why can I do three variable assignments here...
    count = 0
    while count <= n:
        c = a + b; a = b; b = c #...but not here?
        fib_list.append(c)
        count += 1
    print(fib_list[m : n])

fib_m_through_n(0, 17)

I have a few questions about this:

The first is general: are there any clear pythonic violations here, any obvious improvements to style?

The second is included in some of the comments.  Why can I get away with assigning three variables in one line here: a, b, c = 1, 1, 0

but not here:  c = a + b; a = b; b = c

If I try to do this: c, a, b = a + b, b, c

Then I get an incorrect output.

After analyzing the mistake and trying to imagine how things look from the function's POV, it still seems to me like doing three variable assignments in a row should work, assuming that when the function runs it just reads this line from left to right.

Finally, as noted in the section just after the docstring, I want to turn this into a generator.  I have read about generators and understand them a bit, but I don't know how to implement one here.


texts: C program to write 5 lines to a file then print the lines except the second line

texts:
This will read 5 lines into a file from stdin, then print all the lines except the second one.

I used an array because I'm not sure how to do dynamic memory allocation.

#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 1024

void write_to_file(const char *s);
void print_file(const char *s);

int main(void){
    const char file_name[] = "text";
    write_to_file(file_name);
    print_file(file_name);

    return 0;
}

void write_to_file(const char *s){
    FILE *in_file;
    if((in_file = fopen(s, "w")) == NULL){
        perror(s);
        exit(EXIT_FAILURE);
    }

    char buffer[MAX_SIZE];
    for(int i = 0; i < 5; ++i){
        fgets(buffer, sizeof(buffer), stdin);
        fputs(buffer, in_file);
    }

    fclose(in_file);
}

void print_file(const char *s){
    FILE *in_file;
    if((in_file = fopen(s, "r")) == NULL){
        perror(s);
        exit(EXIT_FAILURE);
    }
    int c;
    int flag = 0;
    while((c = fgetc(in_file)) != EOF){
        printf("%c", c);
        if((flag == 0) && (c == '\n')){
            while((c = fgetc(in_file)) != '\n'){
                /*skip the second line*/
            }
            flag = 1;
        }
    }
}