texts: Go through every pixel of an image and then dispose of it

texts:
I'm a little confused as to whether implementing the Dispose method serves a purpose in this code. It never gets referenced by any other class in my project, so should I simply get rid of it or should I make an explicit call to Dispose when releasing the bitmap image?

namespace ImageProcessor
    {
        /// <summary>
        /// A bitmap class that allows fast x, y access
        /// </summary>
        public unsafe class UnsafeBitmap
        {
            Bitmap source;
            int width;
            BitmapData bmpData = null;
            IntPtr baseLine = IntPtr.Zero;
            BGRA* pCurrentPixel = null;
            Point size;
            internal bool locked = false;

            /// <summary>
            /// Create an instance from an existing bitmap
            /// </summary>
            /// <param name="src">The source bitmap</param>
            public UnsafeBitmap(Bitmap src)
            {
                source = src;
                GraphicsUnit units = GraphicsUnit.Pixel;
                RectangleF boundsF = src.GetBounds(ref units);
                size = new Point((int)boundsF.Width, (int)boundsF.Height);
            }

            public Bitmap Bitmap
            {
                get { return (source); }
                set { source = value; }
            }

            /// <summary>
            /// Lock bitmap data
            /// </summary>
            public void LockBitmap()
            {
                try
                {
                    GraphicsUnit units = GraphicsUnit.Pixel;
                    RectangleF boundsF = source.GetBounds(ref units);
                    Rectangle bounds = Rectangle.Round(boundsF);

                    // For a standard BMP, each individual scan line needs to be a multiple
                    // of 4 bytes, so when we have a 24 bit image (3 bytes per pixel),
                    // we need to allow for padding at the end of every scan line
                    // to bring it up to a multiple of 4.
                    width = (int)boundsF.Width * sizeof(BGRA);
                    if (width % 4 != 0)
                        width = 4 * (width / 4 + 1);

                    // Lock the bitmap's bits
                    bmpData = source.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

                    // Get the address of the first line
                    //pBase = (Byte*)bmpData.Scan0.ToPointer();
                    baseLine = bmpData.Scan0;
                    locked = true;
                }
                catch(Exception)
                {
                    throw;
                }
            }

            /// <summary>
            /// Unlock bitmap data
            /// </summary>

            public void UnlockBitmap()
            {
                try
                {
                    source.UnlockBits(bmpData);
                    bmpData = null;
                    baseLine = IntPtr.Zero;
                    locked = false;
                }
                catch (Exception)
                {
                    throw;
                }
            }

            public void Dispose()
            {
                source.Dispose();
            }

            public Point GetSize
            {
                get { return size; }
            }

            public BGRA* this[int x, int y]
            {
                get
                {
                    return (BGRA*)(baseLine + y * width + x * sizeof(BGRA));
                }
            }
        }

Any other comments are welcome.


texts:
My code takes a starting position (which must be completed) and a list of updates (each element of which is optional). It then projects future positions, using the appropriate value from each update, if present, or using a formula otherwise.

I'm looking for ways to reduce code duplication, especially as the real data structures will be substantially larger.

In particular:

Is there a better way for the type system to express the fact that ResultForDate is the same structure as InputForDate but with all option values replaced by the underlying types?
Can the duplication be removed from the repetitive code which checks for the existance of an input, uses it if possible and uses a formula otherwise? Perhaps using a monad?

module Demo

open System

type InputForDate = { Date: DateTime; AssetValue: option<float>; InterestRate: option<float> }
type ResultForDate = { Date: DateTime; AssetValue: float; InterestRate: float }

let projection (startingInput: ResultForDate) (futureInputs: InputForDate list) =
    let project (previousYear: ResultForDate) (input: InputForDate) : ResultForDate =
        {
            Date = input.Date;
            AssetValue =
                match input.AssetValue with
                | Some x -> x
                | None -> previousYear.AssetValue * (1.0 + previousYear.InterestRate) ;
            InterestRate =
                match input.InterestRate with
                | Some x -> x
                | None -> previousYear.InterestRate
        }
    List.scan project startingInput futureInputs

// example of use

let startingInput = { ResultForDate.Date = new DateTime(2012, 12, 31); AssetValue = 100.0; InterestRate = 0.05 };

let futureInputs = [
    { InputForDate.Date = new DateTime(2013, 12, 31); AssetValue = Some 110.0; InterestRate = Some 0.04 };
    { Date = new DateTime(2014, 12, 31); AssetValue = None; InterestRate = Some 0.03 };
    { Date = new DateTime(2015, 12, 31); AssetValue = None; InterestRate = None } ]

let result = projection startingInput futureInputs


texts:
I'm implementing an auxiliary global function which has to check whether a given string has correct format (i.e., it begins with a letter and only contains letters, numbers or the "_" character).

This function, named ok_tret, will be used in the methods of a couple classes and will help ensure that the attributes are initialized with correct words and the rest of the methods are getting correct words as parameters.

The classes will be used in situations in which incorrect inputs are not frequent. They'll only happen when the user misspells the word, or by ignorance. So my guess is there will be two errors per read at worst.

My first ok_tret proposal returns a bool that tells us whether the given word is correct. This means we'll have to do the cin in the class method and then pass the word to the function. If there's error, then we'll have various function calls, until eventually the functions returns true.

const char *err4 = "ERROR. Init again.";

// Check correctness, return corresponding bool.
bool ok_tret(const string& nom) {
    if (not ((nom[0] >= 'a' and nom[0] <= 'z') or
        (nom[0] >= 'A' and nom[0] <= 'Z'))) {
        cout << err4 << endl;
        return false;
    }
    for (unsigned int i = 1; i < nom.length(); ++i) {
        if (not ((nom[i] >= '0' and nom[i] <= '9') or
            (nom[i] >= 'A' and nom[i] <= 'Z') or
            (nom[i] >= 'a' and nom[i] <= 'z') or nom[i] == '_')) {
                cout << err4 << endl;
                return false;
        }
    }
    return true;
}

The next proposal also does the cin, so in order to get a correct word there's no need for various function calls.

// Check correctness and cin until nom contains a correct word. Iterative.
void ok_tret(string& nom) {
    bool P = true;
    while (P) {
        if ((nom[0] >= 'a' and nom[0] <= 'z') or
            (nom[0] >= 'A' and nom[0] <= 'Z')) {
            for (unsigned int i = 1; P and i < nom.length(); ++i)
                if (not ((nom[i] >= '0' and nom[i] <= '9') or
                    (nom[i] >= 'A' and nom[i] <= 'Z') or
                    (nom[i] >= 'a' and nom[i] <= 'z') or nom[i] == '_'))
                    P = false;
        } else P = false;
        P = !P;
        if (P) {
            cout << err4 << endl;
            cin >> nom;
        }
    }
}

Finally a recursive solution, obviously there will be multiple function calls:

// Check correctness and cin until nom contains a correct word. Recursive.
void ok_tret(string& nom) {
    if (not ((nom[0] >= 'a' and nom[0] <= 'z') or
        (nom[0] >= 'A' and nom[0] <= 'Z'))) {
            cout << err4 << endl;
            cin >> nom;
            ok_tret(nom);
            return;
    }
    for (unsigned int i = 1; i < nom.length(); ++i) {
        if (not ((nom[i] >= '0' and nom[i] <= '9') or
            (nom[i] >= 'A' and nom[i] <= 'Z') or
            (nom[i] >= 'a' and nom[i] <= 'z') or nom[i] == '_')) {
                cout << err4 << endl;
                cin >> nom;
                ok_tret(nom);
                return;
        }
    }
}

I wanted to know:

Which proposal looks more natural?
Given the context in which the code will be used, there's no meaningful runtime difference between proposals. But... come on, which one would you choose and why?
If number of errors could be arbitrary (0 to a billion), which one would you choose and why?


texts:
I've written a script in vba to parse table from any website if the html elements are not encrypted in javascript. There is a table index in my script in which inputting the right number it is possible to parse any preferable table. Any input on this will be highly appreciated.

Sub GetTabularContent()
    Dim elem As Object, trow As Object
    Dim S$, R&, C&

    With New ServerXMLHTTP
        .Open "GET", "http://www.basketball-reference.com/players/a/", False
        .send
        S = .responseText
    End With

    With New HTMLDocument
        .body.innerHTML = S

        For Each elem In .getElementsByTagName("table")(0).Rows
            For Each trow In elem.Cells
                C = C + 1: Cells(R + 1, C) = trow.innerText
            Next trow
            C = 0: R = R + 1
        Next elem
    End With
End Sub


texts: Retrieving the count of users with complete and incomplete profiles

texts:
Problem

I have to display the count of total users with Incomplete and Complete Profiles.
Incomplete Profiles are those which will have 4 fields of String type. Other than that all are Complete Profiles.

Here is my model class fields:

@Id
private String id;
private String[] imageIds;
private String concerns;
private String summary;
private String likings;
private String occupation;
private String religion;
private String education;
private String height;
@GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)
private double[] location;
private INTERESTS[] interests;
private String fcmId;
private List connections;
private List declined;
private List pending;

Code I have written:

In MySQL I can apply a direct query which is similar to:

Select count(*) from X where a is NULL or b IS NULL -- > ForIncompleteProfiles

Select count(*) from X where a IS NOT NULL or b IS NOT NULL -- > For CompleteProfiles

But here, I have used the findAll() method to retrieve all users in a List of User and then check for each user using if user.getA() or user.getB() or any one of the fields is null. If yes, count for Incomplete Profiles else count for Complete Profiles.

Can anyone let me know if this is a correct way and if not, how I can apply the query to efficiently retrieve data?

@RequestMapping(value = "/showCount", method = RequestMethod.GET)
public Map showConnections(HttpServletResponse response) {
    int pageSize=2000;
    Page<User> users=null;
    int page=0;
    int countInComplete=0;
    int countComplete=0;
    Map hm=null;
    do {
        users = userService.getAllUsers(new PageRequest(page,pageSize));
        for (User user : users) {
             hm=new HashMap();
            hm.put(user.getId(),user.getConnections().size());
            hm.put(user.getId(),user.getPending().size());
            hm.put(user.getId(),user.getDeclined().size());
        }
        page++;
    }while (users.hasNext());

    return hm;
}


texts: Showing object's data on GUI and HTML without accessors and mutable objects

texts:
I have been searching for a solution to show data of class with three assumptions:

Class Employee is not responsible for showing itself
Class Employee does not expose its data with getters
Classes responsible for showing data are immutable

So I created Employee class with its View interface:

public final class Employee {

  private String name;
  private String salary;

  public interface View {
    View addData(String name, String value);
    void show();
  }

  public void showOn(View view) {
    view.addData("Name", name.toString())
        .addData("Salary", salary.toString())
        .show();
  }
}

And two classes to show it to user. HTML:

final class HtmlPage implements Employee.View {
  private final String content;

  public HtmlPage() {
    content = "";
  }

  public HtmlPage(String str) {
    content = str;
  }

  @Override
  public Employee.View addData(String name, String value) {
    String newData = "\t
";
    newData += name;
    newData += "	";
    newData += value;
    newData += "
\n";

    HtmlPage updated = new HtmlPage(content + newData);
    return updated;
  }

  @Override
  public void show() {
    System.out.println("
\n" + content + "
");
  }
}

and GUI:

import javax.swing.*;
import java.awt.*;
class OutputWindow implements Employee.View {

  private final JComponent panel;

  public OutputWindow() {
    this.panel = new JPanel();
  }

  public OutputWindow(JComponent panel) {
    this.panel = panel;
  }

  @Override
  public Employee.View addData(String name, String value) {
    panel.add(new JLabel(name));
    panel.add(new JLabel(value));

    return this;
  }

  @Override
  public void show() {
    JFrame outputFrame = new JFrame("Okienko do wypisania danych");
    outputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    outputFrame.getContentPane().add(this.getJComponent());
    outputFrame.pack();
    outputFrame.show();
  }

  JComponent getJComponent() {
    panel.setLayout(new GridLayout(3, 2));
    return panel;
  }
}

Here is the usage:

public static void main(String[] args) {
    Employee Piotr = new Employee();

    OutputWindow outputWindow = new OutputWindow();
    Piotr.showOn(outputWindow);

    Employee Ewelina = new Employee();

    HtmlPage htmlPage = new HtmlPage();
    Ewelina.showOn(htmlPage);
}


texts:
I know that the DBContext represents a session (Unit-Of-Work and Repository) with the database, however I an unsure as to when I should have a different DBContext. Currently, I have a separate DBContext for each table with a single DBSet for each DBContext.

Something like this (Blogs and Posts are in the same database):

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
}

public class PostContext : DbContext
{
    public DbSet<Post> Posts { get; set; }
}

I'm not sure why I had a separate DBContext. I think that it is a sample I followed that was like this. However, I recently found that I get an exception when trying to do queries involving both contexts:

  The specified LINQ expression contains references to queries that are
  associated with different contexts.

So, it seems that the obvious solution is for a single DBContext and multiple DBSets:

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

Is there any guideline for when to use different DBContexts and the pros and cons of each approach?


texts:
This is my attempted solution to cracking the coding interview exercise 3.5.  Looking for any feedback on coding style or the algorithm anywhere I can improve really.

The problem specification is as follows.

  Write a program to sort a stack such that the smallest items are on the top.  You can use an additional temp stack, but you may not copy the elements into any other data structure (such as an array).  The stack supports push, pop, peek and isEmpty.

MyStack.java

package problem_2_8;

import java.util.ArrayList;
import java.util.EmptyStackException;

public class MyStack<T extends Comparable<T>> {

    private static class StackNode<T extends Comparable<T>> {
        T data;
        StackNode<T> next;

        StackNode(T data){
            this.data = data;
        }
    }

    private StackNode<T> top = null;
    private int size;

    public MyStack(){}

    public int size(){
        return size;
    }

    T pop(){
        if(top == null) throw new EmptyStackException();
        T item = top.data;
        top = top.next;
        size--;
        return item;
    }

    void push(T data){
        StackNode<T> node = new StackNode<T>(data);
        if(top != null){
            node.next = top;
        }
        top = node;
        size++;
    }

    T peek(){
        if(top == null) throw new EmptyStackException();
        return top.data;

    }

    boolean isEmpty(){
        return size == 0;

    }

    void sortStack(){
        MyStack<T> tempStack = new MyStack<T>();

        while(!isEmpty()){
            tempStack.insertToSortedStack(this, pop());
        }

        while(!tempStack.isEmpty()){
            push(tempStack.pop());
        }
    }

    void insertToSortedStack(MyStack<T> auxStack, T item){
        int countPops = 0;
        while(!isEmpty() && item.compareTo(peek()) < 0){
            auxStack.push(pop());
            countPops++;
        }
        push(item);

        for(int i = 0; i < countPops; i++){
            push(auxStack.pop());
        }

    }

    void printStack(){
        StackNode<T> current = top;
        ArrayList<String> stackAsString = new ArrayList<String>();
        while(current != null){
            stackAsString.add(current.data.toString());
            current = current.next;
        }
        System.out.println("Top -> " + String.join(", ", stackAsString));
    }

}

I ran the code as follows to test that the sorting works as expected.

Main.java

package problem_2_8;

public class Main {

    public static void main(String[] args) {
        MyStack<Integer> myStack = new MyStack<Integer>();
        myStack.push(5);
        myStack.push(7);
        myStack.push(11);
        myStack.push(5);
        System.out.println("Stack before sorting: ");
        myStack.printStack();
        myStack.sortStack();
        System.out.println("Stack after sorting: ");
        myStack.printStack();

        MyStack<String> myStackOfStrings = new MyStack<String>();
        myStackOfStrings.push("x");
        myStackOfStrings.push("c");
        myStackOfStrings.push("y");
        myStackOfStrings.printStack();
        myStackOfStrings.sortStack();
        myStackOfStrings.printStack();
    }
}


texts:
I wrote this entirely from scratch without any Googling/reading as part of an ongoing effort to improve my problem-solving skills.

Also, please note that the focus for my project was the problem solving steps rather than the code itself, which is why I have the comments. It is also why I manually set up the BST (this helped me visualize the problem in order to solve it). However, I am indeed asking for a code review.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Node {
      int data;
      struct Node* left;
      struct Node* right;
      struct Node* parent;
   } node;
bool checkBST(node *root){

    //Step 1, check if the node is not null *******
    //Step 2, check if left child exists **********
    //Step 3, if left child exists, compare its data to the root/current node's data and make sure that it is SMALLER **********
    //step 4, if the data is smaller, proceed, else return false ***********
    //step 5, if the root's right child exists, compare its data to the root/current node's data and make sure it is BIGGER *********
    //step 6, if the data is bigger, proceed, else return false *******

    //step 7, recurse *****
    //step 8, return true *****

    if(root == NULL){
        printf("root is null!\n");
        return false;
    }

    if(root->left != NULL){
        printf("root data: %d\nleft data: %d\n",root->data,root->left->data);
        if(root->data < root->left->data){
            printf("Not a BST: left is bigger\n");
            return false;
        }
        checkBST(root->left);
    }

    if(root->right != NULL){
        printf("root data: %d\nright data: %d\n",root->data,root->right->data);
        if(root->data > root->right->data){
            printf("Not a BST: right is smaller\n");
            return false;
        }
        checkBST(root->right);
    }

    return true;
}

int main(){
    node *n1, *n2, *root, *n4, *n5, *n6;

    n1 = malloc(sizeof(node));
    n2 = malloc(sizeof(node));
    root = malloc(sizeof(node));
    n4 = malloc(sizeof(node));
    n5 = malloc(sizeof(node));
    n6 = malloc(sizeof(node));

    //Set up data values
    n1->data = 10;
    n2->data = 20;
    root->data = 30;
    n4->data = 15; //modified this node to test for negative outcome
    n5->data = 50;
    n6->data = 60;

    //Set up children/parents
    root->parent = NULL;
    root->left = n2;
    root->right = n4;
    n1->left = NULL;
    n1->right = NULL;
    n2->parent = root;
    n2->left = n1;
    n2->right = NULL;
    n4->parent = root;
    n4->left = NULL;
    n4->right = n5;
    n5->parent = n4;
    n5->left = NULL;
    n5->right = n6;
    n6->parent = n5;
    n6->left = NULL;
    n6->right = NULL;

if(checkBST(root) == true){
    printf("This is a BST!");
}

    return(EXIT_SUCCESS);
}


texts: Getting a key's value in a nested dictionary

texts:
I just found a now deleted question on Stack Overflow and solved the problem. The OP was asking for a way to get all the values contained by all 'PLU' keys. I solved it this way but because I am a newbie in python I was wondering if it would be an optimal/better way of doing this, maybe using iterators, I don't know.

Result should be:

234
32
33
334
61

def getPLU(data):
    for item in data:
        if type(data[item]) == dict:
            getPLU(data[item])
        else :
            if item == 'PLU':
                print (data[item])

    pass

def Main():
    times = 0
    Menu = {
      'PLU' : '234',
      'Salad': {
        'salad': {
            'ceaser':{
                'PLU': '32'
            },
            'italian':{
                'PLU': '33'
            }
        }
      },
      'Dessert': {
        'cookie': {
          'PLU': '334',
          'NAME': 'cookie ',
        }
      },
      'Appetizer': {
        'extra sauce': {
          'PLU': '61',
          'NAME': 'extra sauce',
        }
      }
    }
    getPLU(data=Menu)
    #print (getPLU(Menu))

if __name__ == '__main__':
    Main()


texts:
I am using Java to modify remote files in different machines by ssh. At the same time, only one thread is allowed to modify the file in one machine.

I implement the logic like this:

public boolean executeCmd(String ip, String command, String file) throws Exception
{

    final String file = ip + " " + file;
    final String fileLock = file.intern();

    synchronized (fileLock)
    {
        logger.debug(Thread.currentThread().getName() + " " + fileLock + " get the lock");

        SSHClient sshClient = new SSHClient();

        // code to ssh to modify the file.

        logger.debug(Thread.currentThread().getName() + " " + fileLock + " release the lock");
    }
}

Then this function is called in tasks for multi-threads. Is this method satisfied for the purpose?  I tested it for some simple cases and it seems to work OK.

At first, I lock the file using shell like this:

lockdir="$1.lock"
while ! mkdir "$lockdir" >/dev/null 2>&1
do
    echo "another process is running, wait..."
    sleep 10
done

trap 'rm -rf "$lockdir"' 0

There is a problem about this way. If the shell exits unexpectedly, the $lockdir will not be deleted, and it becomes a "deadlock".

I can't solve the problem so I lock the file using Java to ensure only one thread is modifying the same file.


texts:
I have designed a very basic perceptron (single layer neural network) that has been mostly successful in learning basic linearly separable problems.

The perceptron in defined as a class with different functions for training and running it and is mostly constructed with lists.

from math import tanh
from random import randint

class perceptron():

    def __init__(self, n_inputs): # initialize random weights and settings

        self.inputs = []
        self.outputs = [0]
        self.weights_in = []
        self.weights_out = []

        self.training_speed = 0.1

        for a in range(n_inputs): self.inputs.append(0)

        for c in range(n_inputs): self.weights_in.append(randint(0,9)/10)

        self.weights_out.append(randint(0,9)/10)

    def run(self, input_): # single forward loop through perceptron

        for e in range(len(self.inputs)): # assign inputs

            self.inputs[e] = input_[e]

        total = 0

        for f in range(len(self.weights_in)): # calculate node value

            total += self.inputs[f] * self.weights_in[f]

        first = tanh(total) # activation function
        output = []

        for g in range(len(self.outputs)): # calculate outputs

            output.append( tanh( first * self.weights_out[g] ) )

        return output, first

    def train(self, input_, expected_output): # tarin perceptron with known data

        test = self.run(input_)
        guess = test[0]
        errors_in = []
        error = []

        for h in range(len(self.weights_in)): # find error for each input

            errors_in.append( (guess[0]- test[1]) - expected_output )

        for i in range(len(self.weights_out)): # find error for each output

            error.append( guess[0] - expected_output )

        for j in range(len(self.weights_out)): # change output weights

            self.weights_out[j] = ( self.weights_out[j] - error[j] * test[1] * self.training_speed )

        for k in range(len(self.weights_in)): # change input weights

            self.weights_in[k] = ( self.weights_in[k] - errors_in[k] * input_[k] * self.training_speed )

        print(error) # print the total error

I hope to be able to join multiple of these in the future to make a multi-layer network, but as it is now it runs very slow. I used a loop to train the perceptron by generating random numbers, calculating the true answer and passing it into the training function of the network.

Does anyone know of a way to make it more efficient when training? I have looked at different training speeds, but the faster i make it using that, the less accurate it will be.


texts: Is ThreadPool QueueUserWorkItem best option for handling event?

texts:
I have a WinForms application that has value change event coming from ble device.
The event can be hit from more than one device also one device can send a notification to event in every 4 secs. averagely so I am adding device data to a queue to use data after that. This method works but after a while stops working. Is ThreadPool the best option to handle this kind of situation?

protected void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs eventArgs)
    {
        ThreadPool.QueueUserWorkItem((x)=>
        {

            GattCharacteristic characteristic = sender;
            string data = GetByteData(characteristic.Service.Device.BluetoothAddress).Result;
            queue.Enqueue(new EventDataModel { IOData = characteristic, IOKey = characteristic.Service.Device.BluetoothAddress.ToString() });

        });

    }


texts:
I have implemented a function to produce a 32-bit checksum of a file using the following method: checksum = word_1 + word_2 + ... + word_n, where word_i is the 32-bit words the file consists of.

Here are several questions I'm very interested about:

Is the way I read file word by word correct or there is a better way? (I aim not to read the whole file at once because it can be very large.)
Are there any problems with chosen data types such as uint32_t, unsigned and so on?
Have I got the right way to handle a file that isn't N*4 bytes in size? For example, for 7 bytes file I'm just setting 0-8 bits into 0 to avoid using an accidental value. Or I should set 24-31 bits into 0?

Here is the code I have so far:

void execute(std::ifstream& file)
{
    const size_t WORD_SIZE = sizeof(uint32_t);

    file.seekg(0, ios::end);
    auto sizeInBytes = file.tellg();

    file.seekg(0);
    uint32_t checksum = 0U; // ???
    if(auto sizeInEntireWords = sizeInBytes / WORD_SIZE)
    {
        for(int i = 0; i < sizeInEntireWords; i++)
        {
            uint32_t word;
            file.read(reinterpret_cast<char*>(&word), WORD_SIZE); // ???
            checksum += word;
        }
    }

    if(auto additionalSizeInBytes = sizeInBytes % WORD_SIZE)
    {
        uint32_t word;
        file.read(reinterpret_cast<char*>(&word), WORD_SIZE);
        word &= (~0U << (WORD_SIZE - additionalSizeInBytes * 8)); // ???
        checksum += word;
    }

    cout << checksum << endl;
}


texts: More concise way to sum elements of columns in R

texts:
Is there a more efficient/concise way to add the elements of these columns? Basically the D-# codes are error code for documents, and the Q# codes are classes of error.

##Summary columns##
errorarray$Q1 <- errorarray$"D-03" + errorarray$"D-06" + errorarray$"D-07" + errorarray$"D-14" + errorarray$"D-15" + errorarray$"D-16"
errorarray$Q2 <- errorarray$"D-01" + errorarray$"D-02" + errorarray$"D-04" + errorarray$"D-05"
errorarray$Q3 <- errorarray$"D-08" + errorarray$"D-09" + errorarray$"D-10" + errorarray$"D-11" + errorarray$"D-12" + errorarray$"D-13" + errorarray$"D-17" + errorarray$"D-18" +  errorarray$"D-19"

Thank you


texts:
Imagine you can't use the standard functions for time calculation or anything alike. You have to start from scratch as it is the case on embedded systems.
Thus I came with the following code to determine the seconds, minutes, hours, days, months and years from unix timestamp. Tested the code, works for everything I threw at it so far, but wonder if there is a better way to do it without using the standard functions
#include <iostream>

int main(int argc, char* argv[])
{
    /* Subtract 2 years to start on leaping year, later add 1972 instead. */
    auto now = std::atoi(argv[1]) - 63072000;
    auto days = (now / 86400);
    auto hours = (((now - days * 86400) / 3600) % 24);
    auto minutes = ((((now - days * 86400) - hours * 3600) / 60) % 60);
    auto seconds = (((((now - days * 86400) - hours * 3600) - minutes * 60)) % 60);

    /* Get number of 4years to accomodate for leap years */
    auto q_years = (days / 1461);

    /* Recalculate the number of years */
    auto years = q_years * 4 + (days - (q_years * 1461)) / 365;

    /* Deterimne no. of days in the current year */
    auto days_last = (days - (q_years * 1461)) % 365;
    static uint8_t days_in_month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    /* Fix for leap year */
    if (years % 4 == 0)
    {
        days_in_month[1] = 29;
        days_last++;
    }

    /* Retrace current month */
    int month = 0;
    while (days_last > days_in_month[month])
    {
        days_last -= days_in_month[month++];
    }

    printf("Year: %d, Month: %d\n", 1972 + years, month + 1);
    printf("Days: %d, Hours: %d, Minutes: %d, Seconds:%d\n", days_last, hours, minutes, seconds);

    return 0;

}

yes, the code is in c++ but I'll be rewriting it to C afterwards - basically letting go of auto.

What I am not looking at is code readability error checking (what if argv does not have 2 el.) et cetra. I am purely looking for a better algo to get the job done.


texts: Construct a tree given pre and inorder or post and inorder

texts:
I want you to pick my code apart and give me some feedback on how I could make it better or simpler. For a full tree (all nodes with 0 or 2 children) it works deterministically:

public class Construct {

    private TreeNode root;

    private static class TreeNode {
        TreeNode left;
        TreeNode right;
        int item;

        public TreeNode(TreeNode left, TreeNode right, int item) {
            this.left = left;
            this.right = right;
            this.item = item;
        }
    }

    public void treeFromPreOrderAndInorder(int[] pre, int[] inorder) {
        if (pre == null || inorder == null) {
            throw new IllegalArgumentException("Your tree is not accurate");
        }
        if (pre.length != inorder.length) {
            throw new IllegalArgumentException("Your tree is not accurate");
        }
        // should this be overloaded + testing.
        root =  treeFromPreOrderAndInorder(pre, 0, inorder, 0, inorder.length - 1);
    }

    /**
     * Private functions are not overloaded.
     * Check binary0.
     */
    private TreeNode treeFromPreOrderAndInorder(int[] pre, int pos, int[] inorder, int lb, int hb) {
        if (lb > hb) return null;

        // step 1: fetch parent
        int parent = pre[pos];
        // step 2: fetch position
        int parentPosInorder;
        for (parentPosInorder = lb; parentPosInorder <= hb; parentPosInorder++) {
            if (inorder[parentPosInorder] == parent) {
                break;
            }
        }

        if (parentPosInorder > hb) {
            throw new IllegalArgumentException("Your tree is not accurate");
        }

        // proof in diagram : https://bitbucket.org/ameyapatil/pointstonote/commits/a3137e1e5c9f40f28c53b9c62e27f0e8bf81a000
        int numElemsInLeftSubTree = parentPosInorder - lb;

        /**
         * Basically absolutely same as construct Balanced BST from sorted array
         * with this extra junk to be added.
         */
        int leftParentPosPre = pos + 1;
        // proof in diagram : https://bitbucket.org/ameyapatil/pointstonote/commits/458d044f96226e8df1c47775dbe3c8c5ad9ecce4
        int rightParentPosPre = pos + numElemsInLeftSubTree + 1;

        // step 3: recurse
        TreeNode node = new TreeNode(null, null, parent);
        node.left = treeFromPreOrderAndInorder(pre, leftParentPosPre, inorder, lb, parentPosInorder - 1);
        node.right = treeFromPreOrderAndInorder(pre, rightParentPosPre, inorder, parentPosInorder + 1,  hb);

        return node;
    }


texts: Suggestions for better oop designs with real example (file services)

texts:
I'm watching Uncle Bob to improve code maintainability and readability.

I've built a system in which can upload various file formats. Bellow I've posted the pdf one.

The below code works perfect but I need help if there is a way to improve code design and quality.

Any suggestion is welcome.

I use an abstract class FileServices:

abstract class FileServices
{
    protected $file;
    protected $fileName;

    public function __construct($file)
    {
        $this->file = $file;
        $this->fileName = pathinfo($this->file->getClientOriginalName(), PATHINFO_FILENAME);
        $this->setNewFileNameIfExist();
        $this->saveToDB();
        $this->saveToServer();
    }

    public function saveToServer()
    {
        $path = $this->path;
        $realNameWithExtension = $this->fileName  . $this->fileExtension;
        Storage::put($path . $realNameWithExtension, File::get($this->file));
    }

    abstract function saveToDB();
    abstract function setNewFileNameIfExist();
}

And PDF child class:

class PDF extends FileServices
{
    protected $fileExtension = '.pdf';
    protected $path = 'public/pdf/';

    public function saveToDB()
    {
        $newFile = new \App\PDF();
        $newFile->title = $this->fileName . $this->fileExtension;
        $newFile->save();
    }

    public function setNewFileNameIfExist()
    {
        $counter = 0;
        $realName = $this->fileName;
        $allPDF = \App\PDF::all();
        foreach ($allPDF as $pdf) {
            if($pdf->title === $this->fileName . $this->fileExtension) {
                while($pdf->title === $this->fileName . $this->fileExtension) {
                    $this->fileName = $realName . '(' . $counter . ')';
                    $counter++;
                }
            }
        }
    }

}

In the client:

$file = $request->file('pdf');
new PDF($file);

Many thanks to @tim for his answer.


texts: Search and Replace (FreeCodeCamp intermediate algorithm scripting)

texts:
I completed this challenge Search and Replace and passed the tests:

  Perform a search and replace on the sentence using the arguments provided and return the new sentence.

  First argument is the sentence to perform the search and replace on.

  Second argument is the word that you will be replacing (before).

  Third argument is what you will be replacing the second argument with (after).

  Note

  Preserve the case of the first character in the original word when you are replacing it. For example if you mean to replace the word "Book" with the word "dog", it should be replaced as "Dog".

  Example

  myReplace("Let us go to the store", "store", "mall") should return "Let us go to the mall".

I was hoping to simplify my code. Is there a more concise way to write this program that would end up being cleaner and faster than the current code?

function myReplace(str, before, after) {
  let newStr = str.split(' ');
  for (var a=0; a < str.length; a++) {
    if(before === newStr[a]) {
      str = str.replace(before, after);
    }
    if (before[0] === before[0].toUpperCase()) {
      var swap = after[0].toUpperCase() + after.slice(1);
      str = str.replace(before, swap)
    }
  }
  return str;
}

console.log(myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped"));


texts: Function that multiplies all numbers between "a" and "b" with do loop

texts:
I'm making a function that multiplies all numbers between an "a" input and a "b" input with do loop. If you please, check my function and say what's wrong since I don't know loops very well in Scheme.

(define (pi-function x y)
  (let ((result y))
    (do ((limI x (+ x 1)))
        ((= limI y) result)
      (set! result (* result limI)))))


texts: How to put a lot of information in the class?

texts:
I have such a problem:

I'm parsing a lot of HTML files with Simple HTML DOM Parser, that's why I need to use three foreachs to parse the necessary information from it -> I am getting a lot of information and now I have three arrays which keep it. I think that it's dumb to keep the code like that and I want to keep the information in the class.

How can I do it in a right way? I really need your advice to have a good code in the future

Here is the code with three arrays:

if(count($infos->find('.products-list-item')))
{
    foreach ($infos->find('.products-list-item product-label, .products-list-item .products-list-item__brand, .products-list-item .products-list-item__type,.products-list-item .price') as $item_info)
    {
        $item_info_arr[] = $item_info->plaintext;
        $i=0;
    }

    foreach ($infos->find('.products-list-item__img') as $img)
    {
        $src_arr[] = $img->src;
    }

    foreach ($infos->find('.products-list-item .products-list-item__sizes') as $sizes_info)
    {
        while($size = $sizes_info->children($k++))
        {
            $sizes_arr[] = $size->plaintext;
        }

        $k=0;
    }

} else {echo "not found";}

But what can I do, then?


texts: Vectorizing matrix operation instead of for loop in circular matrices

texts:
I have a vector \$X_k\$ and a matrix \$Y_{k,j}\$, where \$k \in \{1,\dots,K\}\$ and \$j \in \{1, \dots, J\}\$. They are circular, meaning that $$\eqalign{X_{k+K} &= X_k \\ Y_{k+K,j} &= Y_{k,j} \\ Y_{k,j+J} &= Y_{k,j}}$$

I want to compute a \$ZX\$ vector and \$ZY\$ matrix according to the equations $$\eqalign{ZX_k &= -X_{k-1}(X_{K-2}-X_{K+1})-X_k \\ ZY_{k,j} &= -Y_{k,j+1}(Y_{k,j+2}-Y_{k,j-1})-Y_{k,j}+X_k}$$

Currently, I'm doing this through a loop, where first I compute the edge cases (for \$ZX\$, \$k = 1, 2, K\$; for \$ZY\$, \$j = 1, J, J-1\$). And for the others, I use the equations above.

I'm wondering if this calculation can be vectorized. Here is the example code.

import numpy as np

np.random.seed(10)
K = 20
J = 10

# initial state (equilibrium)
x = np.random.uniform(size=K)
y = np.random.uniform(size=(K*J))
y = y.reshape(K,J)

# zy
zy = np.zeros((K*J))
zy = zy.reshape(K,J)

# Edge case of Y
for k in range(K):
    zy[k,0] = -y[k,1]*(y[k,2]-y[k,J-1])-y[k,0]+ x[k]
    zy[k,J-1] = -y[k,0]*(y[k,1]-y[k,J-2])-y[k,J-1]+ x[k]
    zy[k,J-2] = -y[k,J-1]*(y[k,0]-y[k,J-3])-y[k,J-2]+ x[k]

    # General Case of Y
    for j in range(1,J-2):
        zy[k,j] = -y[k,j+1]*(y[k,j+2]-y[k,j-1])-y[k,j]+ x[k]

# zx
zx = np.zeros(K)

# first the 3 edge cases: k = 1, 2, K
zx[0] = -x[K-1]*(-x[1] + x[K-2])  - x[0]
zx[1] = - x[0]*(-x[2] + x[K-1])- x[1]
zx[K-1] = -x[K-2]*(-x[0] + x[K-3]) - x[K-1]

# then the general case for X
for k in range(2, K-1)
    zx[k] = -x[k-1]*(-x[k+1] + x[k-2]) - x[k]

print(zx)
print(zy)

I suspect that is possible to optimize with matrix operations but not sure if it is possible without the loops (at least for the edge cases).

Any suggestion of how to improve the performance?


texts: Selecting one form to be visible using jQuery

texts:
I'm new to jQuery but have managed to get it working the way I want. The problem is, it's a bit convoluted and could easily get out of hand if I add more options.

I am trying to show and hide divs based on a user's dropdown selection. I've made a JSFiddle with where I am so far, but I think it could do with some streamlining.

I'd like to be able to add five more dropdown options, with five more divs to show or hide. Will I need to hide each of them individually, or is there a way to say "if the div id is not the value selected, then hide it"?

I'm using CF7 to build the form.

$(function() {
    $("select").change(function() {

        if ($(this).val() == "I have a query") {
            $("#cf-query").show("slow");
            $("#cf-booking").hide("slow")

        } else if ($(this).val() == "I would like to book") {
            $("#cf-booking").show("slow")
            $("#cf-query").hide("slow")

        } else {
            $(".cf-section").hide("slow");
        }
    });
});

What is the nature of your enquiry*:

<select id="cf-dd-nature">
    <option value="">--</option>
    <option value="I have a query">I have a query</option>
    <option value="I would like to book">I would like to Book</option>
</select>

Query

First Name:

Surname*:

Email Address*:

Telephone number*:

Booking

First Name:

Telephone number*:


texts: Unroll for loop as macro to make array unmutable

texts:
I wrote these lines of rust yesterday. It turns 27 bits from a 32 bit integer into a 3x9 byte array, but my gut feeling is this should be done without having a mutable variable ans.

pub fn u32_to_preformated_vector(image:u32) ->[[u8;9];3] {
  let mut ans:[[u8; 9]; 3]= [[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]];
  let image = !image;
  for i in 0..27 {
     ans[i/9][i%9] = 1 & (image >> i) as u8;
  }
  ans
}

What would make the cleanest code here? A macro or some iterator magic?


texts:
I'm using X.PagedList for paging functionality in my application.  The code I have works fine but when I return larger sets of data it seems like it could be faster.  Is there anything I can do to my code to have it perform more efficiently?

Controller Code

var employees = _service.GetEmployeesByOffice(region, area, office).OrderBy(e => e.FullName);
var model = Mapper.Map<IEnumerable<Employee>,IEnumerable<EmployeesViewModel>>(employees).ToPagedList(page, 20);

var viewModel = new EmployeeListingView
{
    EmployeeViewModel = model,
    // Additional...
};

return View(viewModel);

Service Call

public IEnumerable<Employee> GetEmployeesByOffice(string region, string area, string office)
{
    var query = _context.Employees.AsQueryable();

    if (!String.IsNullOrEmpty(region))
        query = query.Where(e => e.Region == region);

    if (!String.IsNullOrEmpty(area))
        query = query.Where(e => e.Area == area);

    if (!String.IsNullOrEmpty(office))
        query = query.Where(e => e.Office == office);

    return query;
}

Razor Page

@Html.PagedListPager((IPagedList)Model.EmployeeViewModel, page => Url.Action("Index", new { area = Model.SelectedArea, office = Model.SelectedOffice, page }))


texts:
below is the code that i created as a POC towards an implementation for 2 excel file comparison (cell by cell)

This was just to test the logic, which works as expected, however i found out that for big data (hundreds of rows and columns) this approach using excel object is very time consuming. Approx time taken for comparing 130 rows and 248 columns was about 10 mins.

Is there any way that i can optimize this

Note: " the code is at basic level" kindly answer towards optimization only

The Code is as below

Dim a()
Dim b()
x = 0
file1 = InputBox("Enter the first file")
file2 = InputBox("enter the second file")

'create FSO and check if the file exist
Set fso = CreateObject("Scripting.FileSystemObject")
 if (fso.fileExists(file1)) and (fso.fileExists(file2)) then
  MsgBox "The file exists"
Else
  MsgBox "The file doesn't exists"
  ErrCount = 1
End if

if Errcount <> 1 then
 'Create excel object for both the files and compare
  Set objExcel = CreateObject("Excel.Application")
 'Iterate from worksheets for both the file
  Set objFile1 = objExcel.Workbooks.Open(file1)
  objFile1Count = objFile1.Worksheets.count

  Set objFile2 = objExcel.Workbooks.Open(file2)
  objFile2Count = objFile2.Worksheets.count
 End if

'sheet should be same
 if objFile1Count <> objFile2Count then
   ErrCount = 1
 End if
' Loop through the sheets
  if ErrCount <> 1 then
      For cnt = 1 to objFile1.Sheets.count
        Set file1Sheet = objFile1.Sheets(cnt)
        Set file2Sheet = objFile2.Sheets(cnt)
        'Check the sheet name
        if file1Sheet.Name <> file2Sheet.Name then
          ErrCount = 1
          Exit For
        Else
          'File 1
          file1RC = file1Sheet.usedrange.rows.count
          file1CC = file1Sheet.usedrange.columns.count
          'File 2
          file2RC = file2Sheet.usedrange.columns.count
          file2CC = file2Sheet.usedrange.columns.count

          'Iterate file
            For i = 2 to file1RC
              For j = 1 to file1CC
                      ReDim Preserve a(x)
                      ReDim Preserve b(x)
                      a(x) = Trim(file1Sheet.Rows(i).columns(j).value)
                      b(x) = Trim(file2Sheet.Rows(i).columns(j).value)
                      file2getRC = i &"," &j
                      file1getRC = i &"," &j

                      'Check compare and add color
                       File1Val = a(x)
                       File2Val = b(x)

                       if File1Val = File2Val then
                          'do nothing as the values matches
                       Else
                          RNC = split(file1getRC, ",")
                          Col = RNC(1)
                          Row = RNC(0)
                          Col = CInt(Col)

                          ty = file1Sheet.Rows(Row).Cells(1, Col).value
                          file1Sheet.Rows(Row).Cells(1, Col).Interior.ColorIndex = 6
                          file2Sheet.Rows(Row).Cells(1, Col).Interior.ColorIndex = 6
                          objFile1.Save
                          objFile2.Save
                       End if
                      x=x+1
              Next
            Next
           End if
        Next
  MsgBox "it works"
Else
  MsgBox "No file added or cancelled"
    End if


texts: Faster way to parse file to array, compare to array in second file, write final file

texts:
I currently have an MGF file containing MS2 spectral data (QE_2706_229_sequest_high_conf.mgf). The file template is here, as well as a snippet of example:

BEGIN IONS
TITLE=File3249 Spectrum10594 scans: 11084
PEPMASS=499.59366 927079.3
CHARGE=3+
RTINSECONDS=1710
SCANS=11084
104.053180 3866.360000
110.071530 178805.000000
111.068610 1869.210000
111.074780 10738.600000
112.087240 13117.900000
113.071150 7148.790000
114.102690 4146.490000
115.086840 11835.600000
116.070850 6230.980000
... ...
END IONS

This unannotated spectral file contains thousands of these entries, the total file size is ~150 MB.
I then have a series of text files which I need to parse. Each file is similar to the format above, with the first column being read into a NumPy array. Then the unannotated spectra file is parsed for each entry until a matching array is found from the annotated text files input.

(Filename GRPGPVAGHHQMPR)

       m/z              i matches
 104.05318        3866.4
 110.07153      178805.4
 111.06861        1869.2
 111.07478       10738.6
 112.08724       13117.9
 113.07115        7148.8
 114.10269        4146.5
 115.08684       11835.6
 116.07085        6231.0

Once a match is found, an MGF annotated file is written that then contains the full entry information in the unannotated file, but with a line that specifies the filename of the annotated text file that matched that particular entry. The output is below:

BEGIN IONS
SEQ=GRPGPVAGHHQMPR
TITLE=File3249 Spectrum10594 scans: 11084
PEPMASS=499.59366 927079.3
... ...
END IONS

There may be a much more computationally inexpensive way to parse. Given 2,000 annotated files to search through, with the above large unannotated file, parsing currently takes ~ 12 hrs on a 2.6 GHz quad-core Intel Haswell CPU.

import numpy as np
import subprocess as sp
import sys
from pyteomics import mgf, auxiliary

def main():
    pep_files = []

    if (len(sys.argv) > 0):
        spec_in = sys.argv[1]
    else:
        print 'Not enough Command Line Arguments!'

    path = '/DeNovo/QE_2706_229_sequest_high_conf.mgf'
    print spec_in
    pep_files.append(spec_in)

    for ann_spectra in pep_files:
        seq = ann_spectra[:ann_spectra.find('-') - 1]
        print seq
        a = np.genfromtxt(ann_spectra, dtype=float, invalid_raise=False, usemask=False, filling_values=0.0, usecols=(0))
        b = np.delete(a, 0)

        entries = []

        with mgf.read(path) as reader:
            for spectrum in reader:
                if np.array_equal(b, spectrum['m/z array']):
                    entries.append(spectrum)
                    file_name = 'DeNovo/good_training_seq/{}.mgf'.format(ann_spectra[:-4])
                    with open(file_name, 'wb') as mgf_out:
                        for entry in entries:
                            mgf_out.write('BEGIN IONS')
                            mgf_out.write('\nSEQ={}'.format(seq))
                            mgf_out.write('\nTITLE={}'.format(entry['params']['title']))
                            mgf_out.write('\nPEPMASS={} {}'.format(entry['params']['pepmass'][0], entry['params']['pepmass'][1]))
                            mgf_out.write('\nCHARGE={}'.format(entry['params']['charge']))
                            mgf_out.write('\nRTINSECONDS={}'.format(str(entry['params']['rtinseconds'])))
                            mgf_out.write('\nSCANS={}'.format(entry['params']['scans']))
                            mgf_out.write('\n')
                            p = np.vstack([entry['m/z array'], entry['intensity array']])
                            output = p.T
                            np.savetxt(mgf_out, output, delimiter=' ', fmt='%f')
                            mgf_out.write('END IONS')

if __name__ == '__main__':
    main()

The Python script is used with command line arguments with the following bash script:

for f in *.txt ; do python2.7 mgf_parser.py "$f"; done

This was used to be able to only parse a given number of files at a time. Suggestions on any more efficient parsing methods?


texts: PHP MySQLi Prepared Statements: Can this select query be hacked/injected?

texts:
i want to know can this be hacked/injected?

$stmt = $mysqli->prepare("SELECT * FROM myTable WHERE name = ?");
$stmt->bind_param("s", $_POST['name']);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0) exit('No rows');
while($row = $result->fetch_assoc()) {
  //do some stuff
}
var_export($ages);
$stmt->close();


texts:
I came across a situation where I needed code to run every n invocations of a method.  Specifically, I was clearing out massive amounts of data and needed to hint to the VM that it should run garbage collection.  My solution was a little more condensed than this, but this class offers reuseability and ensures accurate counts.

public class ExecutionLimiter {
    private final AtomicInteger ai = new AtomicInteger(0);
    private final Runnable task;
    private final int runEvery;

    public ExecutionLimiter(Runnable task, int runEvery){
        this.task = task;
        this.runEvery = runEvery;
    }

    public boolean tryRun(){
        synchronized(ai){
            if(ai.incrementAndGet() != runEvery) return false;
            ai.set(0);
        }
        task.run();
        return true;
    }

    public static void main(String... args) throws InterruptedException{
        AtomicInteger example = new AtomicInteger(0);
        ExecutorService service = Executors.newWorkStealingPool(5);
        ExecutionLimiter limiter = new ExecutionLimiter(example::incrementAndGet, 10);

        int invocations = 100;

        for(int i=0;i<invocations;i++){
            service.submit(()->{
                try{
                    Thread.sleep(Math.round(Math.random() * 1000));
                }catch(InterruptedException ignore){}
                if(limiter.tryRun())
                    System.out.println(Thread.currentThread().getName() +
                            ": Successfully ran: value is " + example.get());
            });
        }

        service.shutdown();
        service.awaitTermination(invocations, TimeUnit.SECONDS);
    }
}

I can't help but feel that something like this exists already in Java, but I haven't been able to find it.  The closest I've come is CyclicBarrier, but I don't want to hang my threads while incrementing.

A few concerns:

Is AtomicInteger overkill for this class?  Would it be better to use an int and synchronize on a lock Object?
Should I be synchronizing AtomicInteger to perform the incrementAndGet-and-set, or is there a better way to go about this?

The main is just for demonstration.


texts:
It's been one month I do programming in python. Hence, my experience is a bit limited. Here is what I've done so far. The program is only filtering OTC market data according to certain features. Could anyone be able to refactor and improve the performance of  the following code? Is it possible to use a single class here?

import pandas as pd
import requests
import json
import csv

token = {
    "access_token": "abcdefghijklmnopABCDEFGHIJKLMNOP1",
    "api_server": "https://api05.iq.questrade.com/",
    "expires_in": 1800,
    "refresh_token": "QrStUvWxYz_0123456789abcdefgHIJK",
    "token_type": "Bearer"
}

uri = "{}v1/symbols?names=".format(token.get('api_server'))
headers = {'Authorization': 'Bearer {}'.format(token.get('access_token'))}

# Reformat the CSV file to keep only the symbols
path = 'OTCBB.csv'
df = pd.read_csv(path,  usecols=['Symbol'])
df['Symbol'] = df['Symbol'].map(lambda x: x.lstrip('.OB').rstrip('.OB'))
df.to_csv(path, index=False)

def batch(batch_size=100, count=0):
    """
    Build chunks of batch_size by default =100
    """

    with open(path, 'r') as csvfile:
        rows=[row.strip('\n') for row in csvfile]

        result = []
        string = ''

        for index, row in enumerate(rows[1:]):
            if count >= batch_size or index == len(rows[1:])-1:
                result.append(string)
                string = ''
                count = 0

            if count == 0:
                string = ''.join((string,row))
            else:
                string = ','.join((string,row))

            count += 1
    return result

batch = batch()
def symbolIds():
    """
    Get the OTC symbolIds
    """

    another_listing = []
    for i in batch:
        rt = requests.get(''.join((uri,i)), headers=headers)
        another_listing.extend(rt.json().get('symbols'))

    return [element['symbolId'] for element in another_listing]

symbolIds = symbolIds()
def batch_symbolIds(batch_size=100, count=0):
    """
    Build symbolIds chunks
    """

    batch_symbolIds = []
    string = ''

    with open(path, 'r') as csvfile:
        rows=[row.strip('\n') for row in csvfile]
        for index, row in enumerate(symbolIds[1:]):
            if count >= batch_size or index == len(rows[1:])-1:
                batch_symbolIds.append(string)
                string = ''
                count = 0

            if count == 0:
                string = ''.join((string, str(row)))
            else:
                string = ','.join((string, str(row)))

            count += 1
    return batch_symbolIds

batch_symbolIds = batch_symbolIds()
def raw_output():
    """
    Gathering information, i.e., volume, bid, ask, bidsize, asksize
    """

    result = []
    uri2 = "{}v1/markets/quotes?ids=".format(token.get('api_server'))

    for elem in batch_symbolIds:
        rt = requests.get(''.join((uri2, elem)), headers=headers)
        result.extend(rt.json().get('quotes'))

    return result

raw_output = raw_output()
def filtering_otc_stocks():
    """
    Filter the OTC market data according to
    certain features, i.e. volume, BAS, bid, ask, ...
    """

    for elem in raw_output:
        try:
            chg = (elem['lastTradePrice'] - elem['openPrice']) / elem['openPrice']*100
        except:
            chg = 0

        elem.update({"% chg": chg})

    columns = ["symbol", "% chg", "volume", "bidPrice", "bidSize", "askPrice", "askSize", \
               "lastTradePrice", "lastTradeSize", "lowPrice", "highPrice", "openPrice"]

    df = pd.DataFrame(raw_output, columns=columns)
    df = df.loc[(df["lastTradePrice"] <= 5) & (df["lastTradePrice"] >= 0.001)] #LastPrice must be less or equal to 5$
    df = df.loc[(df.volume >= 500000) & (df.volume <= 50000000)]
    df = df.sort_values('% chg', ascending=False)
    df.to_csv('OTCList.csv', index=False)

if __name__ == "__main__":
    filtering_otc_stocks()


texts: Place div's of different heights in a responsive parent div

texts:
Can somebody help me with optimizing this code? I'd like to have some control about placement. Masonry doesn't do the job in that way.

What I have done now is to create some sets of columns. For different screen width one of the column sets will be active. Big screens have 3 columns middle screens 2 and small screens one one column. The columns are filled with several divs with the same width but different heights.

In this case the html loads double content, which is turned off by css.

Can somebody help me to find a way to avoid double content?

At the moment of writing it is in use by [www.pcsupportaanhuis.nl][1]

 #l_wrapper_topic_left {
    margin: 0;
    margin-right: 2%;
    padding: 0;
    width: 32%;
    float:left;
    overflow: auto;
    clear: both;
    display: inline;
    }

   #l_wrapper_topic_middle {
    margin: 0;
    margin-right: 2%;
    padding: 0;
    width: 32%;
    float:left;
    overflow: auto;
    display: inline;
   }

   #l_wrapper_topic_right {
    margin: 0;
    padding: 0;
    width: 32%;
    float: right;
    overflow: auto;
    display: inline;
  }

   #m_wrapper_topic_left {
    display: none;
  }

  #m_wrapper_topic_right {
    display: none;
  }

   #s_wrapper_topic {
    display: none;
  }

   .incolumn {
    margin-bottom: 4%;
  }

  @media only screen and (max-height: 480px)
    and (max-width: 531px) and (orientation: landscape) {
    #m_wrapper_topic_left {
        margin: 0% 2% 0% 0%;
        padding: 0;
        width: 49%;
        float:left;
        overflow: auto;
        clear: both;
        display: inline;
      }

         #m_wrapper_topic_right {
          margin: 0;
         padding: 0;
        width: 49%;
        float: right;
        overflow: auto;
        display: inline;
       }

       #l_wrapper_topic_left {
         display: none;
        }

       #l_wrapper_topic_middle {
        display: none;
       }

       #l_wrapper_topic_right {
        display: none;
    }

      .incolumn {
        margin-bottom: 4%;
      }
   }

   <?php include('topics/t1.php'); ?>

   <?php include('topics/t4.php'); ?>

   <?php include('topics/t2.php'); ?>

   <?php include('topics/t3.php'); ?>

   <?php include('topics/t1.php'); ?>

   <?php include('topics/t3.php'); ?>

   <?php include('topics/t4.php'); ?>

   <?php include('topics/t2.php'); ?>

   <?php include('topics/t1.php'); ?>

   <?php include('topics/t2.php'); ?>

   <?php include('topics/t3.php'); ?>

   <?php include('topics/t4.php'); ?>


texts: Programs for different language learning - Python

texts:
I've created a program for my own purposes in three different languages, Perl, Python, and Ruby. Each program will be posted in with their own tag but I will add links to them through on each post. The program itself is very simple, all it does is ask the user about three different languages which are saved into an array, it then prompts the user to choose a language that runs through an if statement, and if the user chooses the language they're writing in it then takes a random language from the array and outputs it.

See also Perl

See also Ruby

Python:

import random

def welcome():
    choices = ["Perl", "Python", "Ruby"]
    lang = 3
    print "Welcome, to the test script, this will test what language you would like to learn.. In order to find out these choices, write this same definition in all three different languages\n"
    print "There are", lang, "languages to choose from please pick one\n"
    user_choice = raw_input(choices)
    if user_choice == "Ruby":
        print("You have chosen Ruby!\n")
    elif user_choice == "Perl":
        print("You have chosen Perl!\n")
    else:
        print("You're already writing in Python!! Let me choose for you! ")
        print random.choice(["Perl", "Ruby"])
welcome()

Creating this program in Python was actually fairly easy, it was my second program I've ever written in Python and reminds me a lot of Ruby. However I kept getting an error while running it due to the fact that I didn't import random, after figuring this out I found out that I had to write out each language's name instead of making it random from the array.. Also Python ended up being the shortest maxing out at 22 lines, I will be adding the execution time of the program shortly.

I also have some questions about Python:

In Python is there a equivalent to Ruby's puts?
In the function print random.choice(["Perl", "Ruby"]) is there a way I can pull from the array instead of having to write out language names


texts: Write to a new, modified Excel file from an original one

texts:
I noticed that I've a HUGE bottleneck in this following function of mine. I can't see how to make it faster.

These are the profiling test results(keep in mind that I'm using a PyQt GUI so times can be stretched):

cProfile Results

def write_workbook_to_file(self, dstfilename):
    self.populaterownumstodelete()
    # actual column in the new file
    col_write = 0
    # actual row in the new file
    row_write = 0
    for row in (rows for rows in range(self.sheet.nrows) if rows not in self.row_nums_to_delete):
        for col in (cols for cols in range(self.sheet.ncols) if cols not in self.col_indexes_to_delete):
            self.wb_sheet.write(row_write, col_write, self.parseandgetcellvalue(row, col))
            col_write += 1
        row_write += 1
        col_write = 0

I ran a cProfile profiling test and write_workbook_to_file() resulted the slowest function in all my application. parseandgetcellvalue() isn't a problem at all.


texts: Doubly-linked list program with delete functions

texts:
I'm starting to learn Java (started with C++), and still getting to get used to the syntax and whatnot. For practice, I made a doubly-linked list program. Is there any way this could be improved at all, or is this okay code?

// Doubly Linked-List Practice
package doublylinkedlist;

public class DoublyLinkedList {

node head, tail;

class node // Creates node class
{
    double num;
    node next;
    node prev;
    public node()
    {
        num = 0;
        next = null;
        prev = null;
    }
    public node (double p)
    {
        num = p;
        next = null;
        prev = null;
    }
}

public void append(double x) // Appends data to list
{
    node p = new node(x);
    if (head == null) // Creates head node if empty list
    {
        head = p;
        tail = p;
        return;
    }

    p.prev = tail; // Skips to end of list and appends
    tail.next = p;
    tail = p;

    return;
}

public void showF() // Displays list forward
{
    for (node q = head; q != null; q = q.next)
        System.out.print(q.num + " ");
    System.out.println();

}

public void showR() // Displays list in reverse
{
    for (node q = tail; q != null; q = q.prev)
        System.out.print(q.num + " ");
    System.out.println();
}

public double findAvg()
{
    double mean = 0, total = 0;
    int i = 0;

    for (node p = head; p != null; p=p.next)
    {
        total += p.num;
         ++i;
    }

    return(mean = total/i);
}

public void delete(double x) // Deletes a single node
{
    node p = new node(x);
    node temp = head;
    node pre, nex;

    if (head.num == p.num) // If head node needs to be removed
    {
        head = head.next;
        return;
    }

    while (temp != null) // If a node in between is to be deleted
    {
        if (p.num == temp.num)
        {
            System.out.println("Node found! Deleting " + x + "...");
            temp.prev.next = temp.next;
            temp.next.prev = temp.prev;
            return;
        }
        else temp = temp.next;
    }

    if (tail.num == p.num) // If tail is to be deleted
    {
        tail = tail.prev;
        return;
    }

}

public void deleteMore(double x) // Removes all nodes of certain key
{
    node temp = head;

    if(head == null) // If list is empty
    {
        System.out.println("Empty list!");
        return;
    }

    while (head != null && head.num > x) // If head node needs to be deleted
    {
        head = head.next;
        head.prev = null;
        temp = head;
    }

    while(temp !=null) // Every remaining occurrence to be removed
    {
        if(temp.num > x)
        {
            if (temp.num == tail.num) // If tail node needs to be removed
            {
                tail = tail.prev;
                tail.next = null;
                temp = tail;
            } else
            {
                temp.prev.next = temp.next;
                temp.next.prev = temp.prev;
            }
        }
        temp = temp.next;
    }
}

public static void main(String[] args) {
    DoublyLinkedList myList = new DoublyLinkedList();
    double[] arr = {600.0, 100.0,  10.0,  15.0,  20.0,  200.0,  30.0,  40.0,  300.0, 350.0, 400.0, 500.0};

    for (int i = 0; i < arr.length; ++i)
        myList.append(arr[i]);

    System.out.println("Here's your list foreward...");
    myList.showF();
    System.out.println("Average = " + myList.findAvg());
    System.out.println("Removing all excess averages...");
    myList.deleteMore(myList.findAvg());
    System.out.println("Here's your revised list");
    myList.showF();
    System.out.println("And here's your list in reverse");
    myList.showR();
    System.out.println("Removing 30, just because I can");
    myList.delete(30.0);
    myList.showF();
}

}


texts: Most concise Python radix function using functional constructions?

texts:
The problem with computing a radix using a non-imperative style of programming is you need to calculate a list of successive quotients, each new entry being the quotient of the last entry divided by the radix. The problem with this is (short of using despicable hacks like log) there is no way to know how many divisions an integer will take to reduce to 0.

I'm fine with doing this with a generator :

def rep_div(n,r):
        while n != 0:
                yield n
                n /= r

But I don't like this for some reason. I feel there must be a clever way of using a lambda, or some functional construction, without building a list like is done here :

def rep_div2(n,r):
        return reduce(lambda v,i: v+[v[-1]/r],question_mark,[n])

Once the repeated divisions can be generated radix is easy :

def radix2(n,r):
        return map(lambda ni: ni % r,(x for x in rep_div(n,r)))

So my question is : is it possible to rewrite rep_div as a more concise functional construction, on one line?


texts: A Timer Construct to Simplify Timing Blocks of Code

texts:
This is fairly simple, so I'm just looking for ideas on anything that can be cleaned up, places it can be extended, and suggestions regarding style/naming (I'm terrible at naming).

It allows you to write something like:

object TimerTest extends App {
        import Timers._

        val time: Long = TimeBlock { timer =>

                println("Starting...")
                println(timer.interTime)

                val s = (0 to 500000).foldRight(0)(_+_)
                println(timer.interTime)

                val s2 = (0 to 100000).foldRight(0)(_*_)
                println(timer.interTime)

                val s3 = (0 to 100000).foldRight(0)((x, y) => x + y * y + x)

        }

        println("Final Time: " + time)
}

Timer.scala:

object Timers {
    case class Timer(startTime: Long = new Date().getTime) {
        private def curMs: Long = new Date().getTime

        //Shortcut to start a new timer using a previous one
        def restart: Timer = Timer(curMs)

        //Doesn't actually stop it, because it's immutable
        //  Returns the amount of time since the Timer was started
        def stop: Long = curMs - startTime

        //To be used in a TimeBlock to get an intermediate time
        def interTime: Long = stop

        //Same as stop, but also returns a new Timer that starts where the
        // previous one ended
        def lap: (Long, Timer) = { val curTime = curMs
            (curTime - startTime, Timer(curTime))
        }
    }

    //Convenience class to help manage starting/stopping
    //  It supplies the internal timer to check intermediate times
    //    within the block
    case class TimeBlock(body: Timer => Unit) {
        val t = Timer()
        body(t)

        def stop = t.stop
    }

    //Same as the other TimeBlock, but simpler
    //  Doesn't supply the timer, so you can't check intermediate times
    class SimpleTimeBlock(body: => Unit) {
        val t = Timer()
        body

        def stop: Long = t.stop
    }
    object SimpleTimeBlock {
        def apply[A](body: => A) =
            new SimpleTimeBlock(body)
    }

    //Implicits to auto-stop TimeBlocks so they return the elapsed time
    implicit def StopLooseTimeBlocks(tB: TimeBlock): Long =
        tB.stop

    implicit def StopLooseSTimeBlocks(tB: SimpleTimeBlock): Long =
        tB.stop

}


texts: Bash on Synology - Delete recycle bin entries over X days old

texts:
Synology NASs have a Task Scheduler that allows you to schedule deletion of files over X days old from recycle bins. This feature isn't working for me–running the task results in no files being deleted. The task works if I schedule a full deletion of the recycle bin, but I'd prefer to only delete a file if it sits in the bin for more than X days. As such, I've created this user script to do so. I want to make sure that it deletes exactly as I want.

Only entries within the recycle bin of the specific shared folder /volume1/share1/#recycle/
Only files that are over 60 days old
Not the recycle bin folder itself
Delete empty folders

Script:

deletepath="/volume1/share1/#recycle/"
logpath="/volume1/share2/SynoScripts/logs/deleteOlderThanXDays.txt"
errorpath="/volume1/share2/SynoScripts/errors/deleteOlderThanXDays.txt"
now=`date "+%Y-%m-%d %H:%M:%S"`

echo "" >> $logpath
echo $now >> $logpath

echo "" >> $errorpath
echo $now >> $errorpath

# Delete files
/usr/bin/find $deletepath -type f -mtime +60 -exec rm -v {} \; >>$logpath 2>>$errorpath

# Delete empty folders
/usr/bin/find $deletepath -mindepth 1 -type d -empty -exec rmdir {} \; >>$logpath 2>>$errorpath

Does this script appear to satisfy my requirements?


texts: Generic callback object, but I need the type parameter inside methods

texts:
Inside my android app, I currently have methods that look like below code. Since they all need a callback object that basically does the same thing and I would like to try to eliminate the duplicated code seen below.

The object that gets posted via the mBus.post(response); statement needs to be the specific type.

@Subscribe
public void onLeave(LeaveRequest event) {
    mRailsApi.leave(event.getEmail(), event.getPassword(),
            new Callback<LeaveResponse>() {
                @Override
                public void failure(RetrofitError arg0) {
                    LeaveResponse response = new LeaveResponse();
                    response.setSuccessful(false);
                    mBus.post(response);
                }

                @Override
                public void success(LeaveResponse leaveResponse,
                        Response arg1) {
                    // need to create one since the api just returns a
                    // header with no body , hence the response is null
                    LeaveResponse response = new LeaveResponse();
                    response.setSuccessful(true);
                    mBus.post(response);
                }
            });
}

@Subscribe
public void onGetUsers(GetUsersRequest event) {
    mRailsApi.getUsers(mApp.getToken(), new Callback<GetUsersResponse>() {
        @Override
        public void failure(RetrofitError arg0) {
            GetUsersResponse response = (GetUsersResponse) arg0.getBody();
            response.setSuccessful(false);
            mBus.post(response);
        }

        @Override
        public void success(GetUsersResponse getUsersResponse, Response arg1) {
            getUsersResponse.setSuccessful(true);
            mBus.post(getUsersResponse);
        }
    });
}

Here is what I have come up with so far.  It seems to work but I am wondering if there is a better solution.  One thing that bothers me is, that I have both the type parameter for the class and I am passing in the class to the constructor.  It seems like I should not need to pass in the same info in two different ways.

The method calls become this:

    @Subscribe
    public void onLeave(LeaveRequest event) {
        System.out.println("inside api repo - making leave request");
        LeaveResponse response = new LeaveResponse();
        mRailsApi.leave(event.getEmail(), event.getPassword(),
                new RailsApiCallback<LeaveResponse>(mBus, LeaveResponse.class ));
    }

And this is the callback class :

public class RailsApiCallback<T extends BaseResponse> implements Callback<T> {

    private Bus mBus;
    private Class mType;

    public RailsApiCallback(Bus bus, Class type) {
        super();
        mBus = bus;
        mType = type;
    }

    @Override
    public void failure(RetrofitError retrofitError) {
        T response = (T) retrofitError.getBody();
        response.setSuccessful(false);
        mBus.post(mType.cast(response));
    }

    @Override
    public void success(T convertedResponse, Response rawResponse) {
        T response = null;
        try {
            response = (T) (convertedResponse != null ? convertedResponse : mType.newInstance());
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        response.setSuccessful(true);
        mBus.post(mType.cast(response));
    }
}


texts: Rational class supporting precise numbers

texts:
This is my JavaScript Rational class, similar to other languages' BigFraction class, but with one major difference:

This class doesn't support arbitrarily large rational numbers:

i.e. new Rational(Number.MAX_VALUE + 1) may fail.
However, it supports arbitrarily precise numbers
i.e. new Rational(1, 10).add(new Rational(2, 10)) will be exactly new Rational(3, 10) instead of .3000000000004.

window.Rational = (function() {
  var GCF, LCM;

  // Internal GCF and LCM

  GCF = function(a, b) {
    var temp;
    if (a < 0) a *= -1;
    if (b < 0) b *= -1;
    if (a < b) {
      temp = a;
      a = b;
      b = temp;
    }
    return a % b === 0 ? b : GCF(a % b, b);
  };

  LCM = function(a, b) {
    return Math.abs(a * b) / GCF(a, b);
  };

  function Rational(top, bottom) {
    this.top = top;
    // bottom defaults to 1
    this.bottom = bottom != null ? bottom : 1;
    this.simplify();
  }

  Rational.prototype.add = function(other) {
    var lcm = LCM(this.bottom, other.bottom);
    // If we multiply by lcm
    // it becomes an integer
    // but we round to prevent floating point innacuracies
    var top1 = Math.round(this * lcm);
    var top2 = Math.round(other * lcm);
    return new Rational(top1 + top2, lcm);
  };

  Rational.prototype.subtract = function(other) {
    return this.add(other.multiply(Rational.constants.NEGATIVE_ONE));
  };

  Rational.prototype.multiply = function(other) {
    return new Rational(this.top * other.top, this.bottom * other.bottom);
  };

  Rational.prototype.divide = function(other) {
    return this.multiply(other.reciprocal());
  };

  Rational.prototype.reciprocal = function() {
    return new Rational(this.bottom, this.top);
  };

  Rational.prototype.isLessThan = function(other) {
    return this < other;
  };

  Rational.prototype.isGreaterThan = function(other) {
    return this > other;
  };

  Rational.prototype.isEqualTo = function(other) {
    return this.top === other.top && this.bottom === other.bottom;
  };

  Rational.prototype.valueOf = function() {
    return this.top / this.bottom;
  };

  Rational.prototype.simplify = function() {
    var gcf;
    if (this.top === 0) {
      // No need to calculate GCF because GCF = 0
      this.bottom = 1;
      return;
    }
    if (this.bottom === 0) {
      throw new Error("Cannot have denominator 0");
    }
    gcf = GCF(this.top, this.bottom);
    if (this.top < 0 && this.bottom < 0) {
      // Since GCF doesn't handle negatives
      // if both numerator and denominators are negative
      // we can cancel the negative
      gcf *= -1;
    }
    // If the bottom is less than zero, then move the negative sign to the top
    if (this.bottom < 0 && this.top >= 0) {
      this.top *= -1;
      this.bottom *= -1;
    }
    this.top /= gcf;
    this.bottom /= gcf;
    return this;
  };

  Rational.constants = {
    ZERO: new Rational(0),
    ONE: new Rational(1),
    NEGATIVE_ONE: new Rational(-1)
  };
  return Rational;

})();

Questions:

I think that by doing this * 5 or other * 6, I implicitly call valueOf(). Is that okay? Should I make it explicit (to me, saying this * 5 is clear: multiply this by 5), but I'm not sure in general.
Same as the question above for this < other and this > other.
Can I refactor my GCF and LCM algorithms to take into account negative numbers so that I don't have to handle them as special cases in the simplify function? Right now, they simply make everything positive and return a positive number.


texts: Checking whether a number is a Smith number

texts:
I have created a Java program to check if the number entered by the user is a Smith number (a number whose sum of digits equals the sum of the digits of its prime factorization). The program works fine but takes too long to check numbers like 4937775. How do I reduce the time taken by it to execute?

import java.util.*;
class check
{
    static boolean a;
    static boolean checkprime(long n)
    {
        int i, factors= 0;
        for(i = 1;i<=n ;i++)
        {
            if(n%i==0)
                factors++;
        }
        if(factors == 2)
            return true;
        else
            return false;
    }

    static long sumfinder(long  n)
    {
        long  sum = 0;
        while(n!=0)
        {
            sum = sum + n%10;
            n= n/10;
        }
        return sum;
    }

    static boolean checksmith(long  n)
    {
        long  sum = 0;
        if(checkprime(n)== true)
        {
            System.out.println(n + " is a prime number ");
            return false;
        }
        else
        {
            System.out.println(n + " is not  a prime number ");
            //generate prime factors:
            long  num = n;

            outer:
            for(long  i = 1; i<= num ; i++)
            {
                if(checkprime(i)== true)
                {

                    if(num%i== 0)
                    {
                        sum= sum+ sumfinder(i);
                        num = num/i;
                        i = 1;
                        if (num == 1)
                        {
                            break outer;
                        }
                    }
                }
            }
        }

        System.out.println(sum);
        System.out.println(sumfinder(n));

        if (sumfinder(n)== sum)

            return true;

        else
            return false;
    }

    static void display()throws InputMismatchException
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number");
        long  n = sc.nextInt();
        if(checksmith(n)== true)
        {
            System.out.println("Smith number");

        }
        else
            System.out.println("Not a Smith number");
    }

    public static void main(String [] args)
    {
        display();
    }
}


texts:
I am using the below syntax to color code sales persons data.  The issue that I have is that the datagridview returns roughly 12,000 rows so the coloring syntax takes some extensive time to execute.

Is there a way to optimize this code?

private void datagridview1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    foreach (DataGridViewRow row in datagridview1.Rows)
    {
        if (row.Cells["Jake"].Value == System.DBNull.Value && row.Cells["Jones"].Value == System.DBNull.Value && row.Cells["Lati"].Value == System.DBNull.Value && row.Cells["Venitia"].Value == System.DBNull.Value)
        {
            row.DefaultCellStyle.BackColor = Color.Red;
        }
    }
}
private void PopulateIT()
{
    datagridview1.Visible = true;
    lblNoData.Visible = false;

    string connString = @"Connection String";
    string query = @"SELECT * from tempdata";
    SqlConnection conn = new SqlConnection(connString);
    SqlCommand cmd = new SqlCommand(query, conn);
    conn.Open();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(formattedDT);
    conn.Close();
    da.Dispose();
    datagridview1.DataSource = formattedDT;
    datagridview1.AutoResizeColumns();
}


texts: Fastest way to multiply two byte arrays in Java

texts:
I have two byte arrays that represent unsigned 256-bit values and I want to multiply them resulting into a new value. What is the fastest ways to do this in Java? And are there other factors I should take into account?

This is my current multiply-function:

// two input values
// i.e. each 0x00000000000000000000000000000000000000000000000000000000000000ff
byte[] input1Array = new byte[32];
byte[] input2Array = new byte[32];

BigInteger input1 = new BigInteger(1, input1Array);
BigInteger input2 = new BigInteger(1, input2Array);
BigInteger result = input1.multiply(input2);

byte[] bytes = result.toByteArray();
ByteBuffer data    =  ByteBuffer.allocate(32);
System.arraycopy(bytes, 0, data.array(), 32 - bytes.length, bytes.length);

// expected 0x000000000000000000000000000000000000000000000000000000000000fe01
byte[] resultArray = data.array();

This takes ~1500ms on my PC for 10000000 iterations and something tells me this can be done faster.


texts: Simple way to decrement number within a repeating range

texts:
I currently have a solution to increment numbers within a range:

i % x + 1

Where x is the maximum number in the range and i is the previous number.

It is nice and simple, and gives this array: 1,2,3,4,1,2...

I also need to do this in reverse, which should produce this array: 1,4,3,2,1,4,3...

This is my solution:

i == 1 ? x : (i - 1 % x)

Is there a way to do it without the ternary operator?


texts: Compare a given version number in the form major.minor.build.patch and see if one is less than the other

texts:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

typedef int STATUS;
#define ERROR -1
#define OKAY 0

struct version
{
    unsigned char major;
    unsigned char minor;
    unsigned char build;
    unsigned char patch;
};
STATUS is_less_than(struct version * original, struct version *compared, bool *result)
{
    if(original == NULL || compared == NULL || result == NULL)
    {
        result = NULL;
        return ERROR;
    }
    *result = false;

    if(original->major < compared->major)
    {
        *result = true;
    }
    else if(original->major == compared->major) // else if the major >= major
        {

            if(original->minor < compared->minor)
            {
                *result = true;
            }
            else if(original->minor == compared->minor)
            {
                if(original->build < compared->build)
                {
                    *result = true;
                }
                else if(original->build == compared->build)
                {
                    if(original->patch < compared->patch)
                    {
                        *result = true;
                    }
                    else if(original->patch == compared->patch)
                    {
                        *result = false;
                    }
                }
            }
        }

    return OKAY;

}

Is there a cleaner way to do this?


texts: Go function to test whether a file exists

texts:
How could one write in a more elegant way that if error is null, the result is true? I really need a bool as returned value.

func existsFile(pPath string) bool {
    _, errStat := os.Stat(pPath)

    if errStat != nil {
        return false
    }
    return true
}


texts:
I have made some jQuery Fallback Support for the CSS Property "background-attachment: local" and I am mainly a CSS developer. I do some jQuery, but I thought I would check to see if I am doing this in the more efficient way, as I may have multiple versions of this on one page.

CODEPEN DEMO

HTML

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

hello

CSS

@import "http://fonts.googleapis.com/css?family=Open+Sans:400,600,700";
* {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
body {
    background: none repeat scroll 0 0 #fff;
    font-family: "Open Sans";
    line-height: 26px;
    margin: 20px;
}

.container {
  position: relative;
  margin-top: 30px;
}

.data-holder {
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
  width: 200px;
  height: 300px;
  overflow: auto;
}

#shadowtop,
#shadowbottom {
  position: absolute;
  left: 0;
  height: 12px;
  width: 180px;
  z-index: 9999;
  display: none;
  background-size: 100% 12px;

}
#shadowtop {
  top: 0;
  background:   radial-gradient(farthest-side at 50% 0, rgba(0,0,0,.15), rgba(0,0,0,0)) 0 100%;
}
#shadowbottom {
  bottom: 0;
  background:   radial-gradient(farthest-side at 50% 100%, rgba(0,0,0,.15), rgba(0,0,0,0)) 0 100%;
}

.block {
  background: #fff;
  border-bottom: 1px solid #f4f4f4;
  padding: 10px;
}
.block:last-child {
  border-bottom: 0 none;
}

jQuery

$(document).ready(function(){
  $('.data-holder').scroll(function(){
    var scrollValue = $(this).scrollTop();
    var elementHeight = $(this).height();
    if(scrollValue == 0){
      $("#shadowtop").fadeOut(200);
      console.log("at top");  //should remove
    } else if (scrollValue == ($(this).get(0).scrollHeight - $(this).height())){
      $("#shadowbottom").fadeOut(200);
      console.log("at bottom"); //should remove
    } else {
      console.log("in middle"); //should remove
      $("#shadowtop").fadeIn(200);
      $("#shadowbottom").fadeIn(200);
    }
  });
  var scrollValue = $('.data-holder').scrollTop();
  if(scrollValue < ($('.data-holder').get(0).scrollHeight - $('.data-holder').height())){
     $("#shadowbottom").show();
  }
});


texts:
Say I have the following SQL:

SELECT
    amount,
    amount*.1,
    (amount*1)+3,
    ((amount*1)+3)/2,
    (((amount*1)+3)/2)+37
FROM table

Instead of repeating that identical code every time, I really want to be able to do something like this:

SELECT
    amount,
    amount*.1 AS A,
    A+3 AS B,
    B/2 AS C,
    C+37 AS D,
FROM table

But this code doesn't work.

So, is there another way to avoid duplication in the working query that I have?


texts: Combine and minimize all .js files in parent folder

texts:
I'd appreciate some feedback on my latest PHP script. It is supposed to work like this:

When obtained, it checks whether the cache is still up-to-date
IF YES, return the cache; IF NOT, reset the cache
Get all JS scripts in the parent directory
Minimize the code
Add it to the cache
Return the cache

// Script combines & minimizes all .js files in the parent folder
// Result is cached until a change to the files is dealt

header('Content-type: application/x-javascript');

$cache_path = 'cache.txt';
$index_path = 'cache-index.txt';

function getScriptsInDirectory(){
    $array = Array();
    $scripts_in_directory = scandir('.');
    foreach ($scripts_in_directory as $script_name) {
        if (preg_match('/(.+)\.js/', $script_name))
        {
            array_push($array, $script_name);
        }
    }
    return $array;
}

function compilingRequired(){
    global $cache_path;
    global $index_path;
    if (file_exists($cache_path) && file_exists($index_path))
    {
        $cache_time = filemtime($cache_path);
        $files = getScriptsInDirectory();
        foreach ($files as $script_name) {
            if(filemtime($script_name) > $cache_time)
            {
                return true;
            }
        }

        $array = explode(PHP_EOL, file_get_contents($index_path));
        foreach($array as $name)
        {
            if (!file_exists($name))
            {
                return true;
            }
        }

        return false;
    }
    return true;
}

function compressScript($buffer) {
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    $buffer = str_replace(array("\r\n","\r","\n","\t",'  ','    ','     '), '', $buffer);
    $buffer = preg_replace(array('(( )+{)','({( )+)'), '{', $buffer);
    $buffer = preg_replace(array('(( )+})','(}( )+)','(;( )*})'), '}', $buffer);
    $buffer = preg_replace(array('(;( )+)','(( )+;)'), ';', $buffer);
    return $buffer;
}

if (compilingRequired())
{
    if (file_exists($cache_path)){
        unlink($cache_path);
        unlink($index_path);
    }

    $scripts_in_directory = getScriptsInDirectory();
    $file_handler = fopen($cache_path, 'w+');
    $cache_handler = fopen($index_path, 'w+');

    foreach ($scripts_in_directory as $name)
    {
        if (strlen(file_get_contents($cache_path)) > 0){
            fwrite($file_handler, str_repeat(PHP_EOL, 2));
        }

        fwrite($file_handler, '/**** ' . $name . ' ****/' . str_repeat(PHP_EOL, 2));
        fwrite($file_handler, compressScript(file_get_contents($name)));
        fwrite($cache_handler, $name . PHP_EOL);
    }

    echo file_get_contents($cache_path);
}
else
{
    echo file_get_contents($cache_path);
}


texts: Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds

texts:
public static void main(String args[]) {
        solution(new Command() {
            @Override
            public void execute() {
                {
                    System.out.println("Hello World");
                }
            }
        }, 1000);

        // java 8
        solution(() -> System.out.println("Hello World"), 1000);
    }

    public static void solution(Command command, int n) {
        new java.util.Timer().schedule(new java.util.TimerTask() {
            @Override
            public void run() {
                command.execute();
            }
        }, n);

    }

    interface Command {
        public void execute();
    }

}

Can my solution be improved? I have used command pattern. Is there a better way to do this?


texts: VueJS to do list - handling clear event on input

texts:
I made a basic to-do list in VueJS, but it feels really clunky and obtuse to me. One of the key things is that if the text input value is empty and the user clicks the button labeled submit then it shows a red error. When you start typing, it goes away. I tried declaring the variables in a different scope but it breaks the application. See full sample below:

// components
Vue.component('todoitem', {
  template: "
Test Item
"
})

// app code
var app = new Vue({
  el: '#app',
  data: {
    todos: [],
    button: {
      text: 'Hide'
    },
    seen: true
  },
  methods: {
    addItem: function() {
      let item = document.getElementById("list-input").value;
      let error = document.getElementById("error");
      if (item == "") {
        error.style.display = "block";
      } else {
        app.todos.push({ text: item });
        error.style.display = "none";
      }
    },
    removeItem: function(index) {
      this.todos.splice(index, 1);
    },
    removeError: function() {
     let item = document.getElementById("list-input").value;
      let error = document.getElementById("error");
     if (item == "") {
        error.style.display = "block";
      } else {
        error.style.display = "none";
      }
    },
    toggleSeen: function() {
      app.seen = !app.seen;
      app.button.text = app.seen ? 'Hide' : 'Show';
    }
  }
});
#app {
  width: 900px;
  padding: 2em;
  margin: 0 auto;
}

.todo-list {
  list-style-type: square;
}

.todo-list__delete {
  display: none;
}

li:hover .todo-list__delete {
  display: inline-block;
}

Add an Item to the list

      {{ todo.text }}
      Delete

  <input v-on:keyup="removeError" type="text" id="list-input">
  <input type="submit" id="list-submit" v-on:click="addItem">
  Please Enter Text

    <todoitem></todoitem>

SEEN

  <button id="hide-seen" v-on:click="toggleSeen">{{ button.text }}</button>

How can I make this better?


texts:
I would like a review on my Console class I made in JavaFX 8. It features the following:

A text field where you can enter input, the input gets copied into the text area.
A text area where you can observe output and see the input.
When you press enter, you send the message.
When you press arrow up, you can go back in history.
When you press arrow down, you can go forward in history.
You can hook an event listener when a message gets sent.

public class Console extends BorderPane {
    protected final TextArea textArea = new TextArea();
    protected final TextField textField = new TextField();

    protected final List<String> history = new ArrayList<>();
    protected int historyPointer = 0;

    private Consumer<String> onMessageReceivedHandler;

    public Console() {
        textArea.setEditable(false);
        setCenter(textArea);

        textField.addEventHandler(KeyEvent.KEY_RELEASED, keyEvent -> {
            switch (keyEvent.getCode()) {
                case ENTER:
                    String text = textField.getText();
                    textArea.appendText(text + System.lineSeparator());
                    history.add(text);
                    historyPointer++;
                    if (onMessageReceivedHandler != null) {
                        onMessageReceivedHandler.accept(text);
                    }
                    textField.clear();
                    break;
                case UP:
                    if (historyPointer == 0) {
                        break;
                    }
                    historyPointer--;
                    runSafe(() -> {
                        textField.setText(history.get(historyPointer));
                        textField.selectAll();
                    });
                    break;
                case DOWN:
                    if (historyPointer == history.size() - 1) {
                        break;
                    }
                    historyPointer++;
                    runSafe(() -> {
                        textField.setText(history.get(historyPointer));
                        textField.selectAll();
                    });
                    break;
                default:
                    break;
            }
        });
        setBottom(textField);
    }

    @Override
    public void requestFocus() {
        super.requestFocus();
        textField.requestFocus();
    }

    public void setOnMessageReceivedHandler(final Consumer<String> onMessageReceivedHandler) {
        this.onMessageReceivedHandler = onMessageReceivedHandler;
    }

    public void clear() {
        runSafe(() -> textArea.clear());
    }

    public void print(final String text) {
        Objects.requireNonNull(text, "text");
        runSafe(() -> textArea.appendText(text));
    }

    public void println(final String text) {
        Objects.requireNonNull(text, "text");
        runSafe(() -> textArea.appendText(text + System.lineSeparator()));
    }

    public void println() {
        runSafe(() -> textArea.appendText(System.lineSeparator()));
    }
}

public final class GUIUtils {
    private GUIUtils() {
        throw new UnsupportedOperationException();
    }

    public static void runSafe(final Runnable runnable) {
        Objects.requireNonNull(runnable, "runnable");
        if (Platform.isFxApplicationThread()) {
            runnable.run();
        }
        else {
            Platform.runLater(runnable);
        }
    }
}

public class WordWrapConsole extends Console {
    public WordWrapConsole() {
        super();
        textArea.setWrapText(true);
    }
}

The calls that modify textArea and textField are wrapped in a GUIUtils.runSafe(), because modifications on JavaFX UI elements may only be done from the JavaFX thread and it is quite common that code from the public methods can run in different threads.