texts: Is there any way to condense my code so it does not take up so many lines?

texts:
I'm writing my program in python and have it working properly, but it's over 500 lines of code. I think there is a way I can condense my code, but I'm not sure how I should do it
Here's an example of some of my code:
def click():
    if clicked1.get() == "app1":
        os.startfile(r"C:\Users\red\Desktop\app1")
        i = 0
        while i < 20:
            try:
                app.connect(title_re=".*app1")
                break
            except pywinauto.findwindows.ElementNotFoundError:
                time.sleep(1)
                i += 1
        app1 = app.top_window()
        app1.move_window(x1, y1)
        time.sleep(.5)
        app1.maximize()
    if clicked1.get() == "app2":
        os.startfile(r"C:\Program Files (x86)\app2")
        i = 0
        while i < 20:
            try:
                app.connect(title_re=".*app2")
                break
            except pywinauto.findwindows.ElementNotFoundError:
                time.sleep(1)
                i += 1
        app1 = app.top_window()
        app1.move_window(x1, y1)
        time.sleep(.5)
        app1.maximize()

I basically have about 20 of those if statements for each different
application and for each different clicked (1-4). Is there any way I can shrink my code so it doesn't take up so many lines? Perhaps using variables?


texts: MySQL proliferation of subqueries and left joins

texts:
I have the following query:

 $sql = "SELECT p.id, p.fname, p.mname, p.surname, p.consultant_id,
                e.address,
                ph.number,
                a.street, a.street_more, a.city, a.country,
                co.label as 'nationality',
                msap.label as 'module'
        FROM per_person AS p
        LEFT JOIN (
            SELECT person_id, number
            FROM per_phone
            WHERE is_primary = 1
        ) AS ph ON p.id = ph.person_id
        LEFT JOIN (
            SELECT person_id, address
            FROM per_email
            WHERE is_primary = 1
        ) AS e ON p.id = e.person_id
        LEFT JOIN (
            SELECT person_id, street, street_more, city, country
            FROM per_address
            WHERE is_primary = 1
        ) AS a ON p.id = a.person_id
        LEFT JOIN (
            SELECT person_id, module
            FROM per_sap
        ) AS sap ON p.id = sap.person_id
        LEFT JOIN (
            SELECT id as 'country_id', iso_code, label
            FROM meta_country
        ) AS co ON p.nationality = co.country_id
        LEFT JOIN (
            SELECT id as 'sap_id', short_code, label
            FROM meta_sap
        ) AS msap ON sap.module = msap.sap_id
        WHERE is_deleted IS NULL
        ORDER BY fname ASC
        LIMIT ".$index.", ".$per_page.";";

At the moment it takes about 0.078 sec / 0.000 sec for the query to complete (it is limited to take 10 records for each query call).

How would you recommend me to better structure my query so that the execution time can be shortened. Each of those table have (on average) ~ 2000 rows. And all of them are indexed based on the primary_key (id of the table) and FK of the referenced table.


texts:
I have a method which works perfectly. It removes an element from an array. Now i would like to have a clean and simple code.

private void removeUserFromGroup(baseClass[] member)
{
    try
    {
        this.ExHandling = null;
        searchPathMultipleObject groupSearchPath = new searchPathMultipleObject();
        groupSearchPath.Value = "CAMID(\":" + this.DataViewModel.GroupModel.SelectedGroup + "\")";

        propEnum[] props = { propEnum.defaultName, propEnum.searchPath, propEnum.members };

        // get the current group membership.
        group cognosGroup = (group)this.LogonModel.CBICMS.query(groupSearchPath, props, new sort[] { }, new queryOptions())[0];
        if (cognosGroup.members.value.Length > 0)
        {
            for (int y = 0; y < cognosGroup.members.value.Length; y++)
            {
                //check if member[y] is the one that need to be deleted
                if (cognosGroup.members.value[y].searchPath.value == member[0].searchPath.value)
                {
                    int lenght = cognosGroup.members.value.Length - 1;

                    baseClass[] newMembers = new baseClass[lenght];
                    int index = 0;
                    baseClass obj = null;
                    // go trough group
                    for (int i = 0; i <= lenght; i++)
                    {
                        if (i != y)
                        {
                            //create user
                            obj = cognosGroup.members.value[i];
                            newMembers[index] = obj;
                            index++;
                        }
                        else
                        {
                            this._messageText = "*Successfully removed " + this.RemoveUsername.ToLower() + " from " + this.DataViewModel.GroupModel.SelectedGroup;
                        }
                    }
                    cognosGroup.members = new baseClassArrayProp();
                    cognosGroup.members.value = newMembers;
                    this.LogonModel.CBICMS.update(new baseClass[] { cognosGroup }, new updateOptions());
                    y--;
                    Log4NetLogger.Logger.Info("Successfully removed: " + this.RemoveUsername.ToLower() + " from " + this.DataViewModel.GroupModel.SelectedGroup);
                    return;
                }
                else
                {
                    this._messageText = "*" + this.RemoveUsername.ToLower() + " is not a user from " + this.DataViewModel.GroupModel.SelectedGroup;
                }
            }
        }
        else
        {
            Log4NetLogger.Logger.Error(this.DataViewModel.GroupModel.SelectedGroup + " is empty");
            return;
        }
    }
    catch (Exception ex)
    {
        Log4NetLogger.Logger.Error("Error: ", ex);
    }
}

I know it doesn't look good and it isn't coded as if the person who ends up maintaining my code is a violent psychopath who knows where I live. So now I want to have a "clean" code. Can anyone help me and give me some tips?

Thanks!


texts:
I've started to write a form data handler class in PHP. Can you please review it and point out any mistakes or logic errors, or perhaps if a method can be written in a better way?

define('VALIDATION_ERR', ' couldn`t be validated.');
define('REQUIRED_ERR', ' is required.');
define('PASSWORD_ERR', 'Password and Confirm Password do not match.');

class DataValidator {

protected $errorMsg;
protected $errorFlag;

public function __construct(){
    $this->errorMsg = array();
    $this->errorFlag = 0;
} // constructor

public function checkRequiredData( $dataArray , $requiredFields = NULL ){
    if( count($dataArray) > 0 ){
        if( $requiredFields != NULL ){
            foreach( $dataArray as $key => $val ){
                if( array_key_exists( $key , $requiredFields ) ){
                    $format = $requiredFields[$key];
                    if( !empty($val) && $format != 'none' ){
                        if( !($this->dataFormatCheck($val, $format)) ){
                            $msg = $key . VALIDATION_ERR ;
                            $this->setErrorMsg($msg);
                            $this->errorFlag = 1;
                        }
                    }
                    else{
                        $msg = $key . REQUIRED_ERR;
                        $this->setErrorMsg($msg);
                        $this->errorFlag = 1;
                    }
                }
            }
        } // requiredFields array IF
        else{
            foreach( $dataArray as $key => $val ){
                if( empty($val) ){
                    $msg = $key . REQUIRED_ERR;
                    $this->setErrorMsg($msg);
                    $this->errorFlag = 1;
                }
            }
        }
    } // requiredFields count IF
    else{
        $msg = "data array is empty";
        $this->setErrorMsg($msg);
        $this->errorFlag = 1;
    }

    if( $this->errorFlag == 0 ){
        return true;
    }
    else{
        return false;
    }
} // checkRequiredData

public function getErrorMsg( $last = '' ){
    if( $last == 'last' ){
        return end($this->errorMsg);
    }
    else{
        return $this->errorMsg;
    }
} // getErrorMsg

public function setErrorMsg( $msg ){
    array_push( $this->errorMsg, $msg );
} // setErrorMsg

public function dataFormatCheck( $data , $format ){
    // use switch or if else?
    switch( $format ){
        case 'text' :
            $return = true; // will be implemented later
            break;

        case 'email' :
            $return = $this->checkEmail($data);
            break;

        case 'numeric' :
            $return = $this->checkNumeric($data);
            break;

        case 'alphanumeric' : // will be implemented later
            $return = true;
            break;

        case 'password' :
            $return = $this->checkPassConfirm($data);
            break;

        case 'image'    : // will be implemented later
            $return = true;
            break;

        case 'none' : // will be implemented later
            $return = true;
            break;
    }
    return $return;
} // dataFormatCheck

public function checkAlpha( $data ){
     // will be implemented later
} // check alphabets

public function checkEmail( $data ){
    return filter_var($data, FILTER_VALIDATE_EMAIL);
} // check email

public function checkNumeric( $data ){
    return is_numeric( $data );
} // check Numbers

public function checkAlphaNumeric( $data ){
     // will be implemented later
} // check Alpha Numerics

public function checkPassConfirm( $pass , $cPass ){
    if( $pass != $cPass )
        return false;
    else
        return true;
}

}


texts: Python: Exception handling in a logic gate

texts:
I'm learning about Python and am going through the OO-stage where I'm building a set of logic-gate classes.

To make the logic more resilient, I only want the user to be able to enter a value of 0 or 1 for the pin value in my binary class. I've currently done this by implementing a try/except in the getPin function, but I noticed I wasn't able to add something like:

except(ValueError) or (pinVal != 0 and pinVal != 1)

In the same line (you can, but it ignores the logic after the "or"), so I broke out the numeric checks in the else statement afterward.

Is this the best way to do this? Or is there a way to merge these two together? The fact that I have the identical line:

pinVal = self.invalidPinInput(self.getPin, pin)

Gives me some pause.

Full class code is below:

class BinaryGate(LogicGate):

    def __init__(self,n):
      super(BinaryGate,self).__init__(n)
      self.pinA = self.getPinA()
      self.pinB = self.getPinB()

    def invalidPinInput(self, method, pin):
      print("Invalid input, value must be set to 0 or 1. Please enter 0 or 1.")
      return method(pin)

    def getPin(self, pin):
      try:
        pinVal = int(input("Enter Pin " + pin + " input for gate "+ str(self.getLabel()) +"-->"))
      except(ValueError):
        pinVal = self.invalidPinInput(self.getPin, pin)
      else:
        if(pinVal != 0 and pinVal != 1):
          pinVal = self.invalidPinInput(self.getPin, pin)
      return pinVal

    def getPinA(self):
      return self.getPin("A")

    def getPinB(self):
      return self.getPin("B")


texts: Character pattern replacement using gsub, loops, and data.table

texts:
I was trying to see if data.table could speed up a gsub pattern matching function over a list.

Data for reprex. It's a list of 3 data frames with some asterisks placed here and there. Each data frame is 6500 rows, 2 columns, and generally representative of my actual data. My data does have multiple columns per data frame that need to be looped over, which is why I'm using the mapply.

library(data.table)
library(microbenchmark)
    df1 <- data.frame(name = rep(LETTERS, 250), code = rep(letters, 250), stringsAsFactors = FALSE)
df1$name[df1$name == "D" | df1$name == "F" | df1$name == "L"] <- "foo*"
df1$code[df1$code == "d" | df1$code == "f" | df1$code == "l"] <- "*foo"
df2 <- data.frame(name = rep(LETTERS, 250), code = rep(letters, 250), stringsAsFactors = FALSE)
df2$name[df2$name == "A" | df2$name == "R" | df2$name == "T"] <- "foo*"
df2$code[df2$code == "a" | df2$code == "r" | df2$code == "t"] <- "*foo*"
df3 <- data.frame(name = rep(LETTERS, 250), code = rep(letters, 250), stringsAsFactors = FALSE)
df3$name[df3$name == "C" | df3$name == "Q" | df3$name == "W"] <- "foo*"
df3$code[df3$code == "c" | df3$code == "q" | df3$code == "w"] <- "*f*oo"

df <- list(df1, df2, df3)
dt <- lapply(df, as.data.table)

In this example, I am trying to remove any * symbols from character strings. First function was just using an mapply and gsub. It deletes any *, looping over elements. Second was an attempt to do it using the data.table library.

mapply.remove.asterisk = function(x){
  df2 <- data.frame(mapply(gsub, "\\*", "", x, perl = TRUE))
  colnames(df2) <- colnames(x)
}

dt.remove.asterisk = function (x) {
  x[, lapply(.SD, function(x) gsub("\\*", "", x, perl = TRUE))]
}

Testing them out doesn't show a big difference, but the mapply is slightly slower.

mapgsubtest = function(x) {
  df.test <- lapply(x, mapply.remove.asterisk)
}

dtgsubtest = function(x) {
  dt.test <- lapply(x, dt.remove.asterisk)
}

microbenchmark(mapgsubtest(df), dtgsubtest(dt), neval = 100)

Unit: nanoseconds
            expr     min      lq       mean  median      uq      max neval
 mapgsubtest(df) 7161991 7388846 7780101.83 7483794 7651907 27860732   100
  dtgsubtest(dt) 6759663 6991926 7181127.95 7109710 7275418 10102686   100
           neval       0       0      12.26       0       1      902   100

Is there something I'm doing within data.table that could be improved? I tried to see if a few things sped everything up, like having * only at the end of strings (only foo*), using an end of string regex anchor $, and setting an index key. Nothing changed noticeably.


texts: Customizing output in accordance to the input

texts:
I wanted to know if I overdid it and maybe could have kept this code simpler and cleaner. I need to execute this assignment:

Write a program called multi_input.cpp that prompts the user to enter
several integers in any combination of octal, decimal, or hexadecimal,
using the 0 and 0x base suffixes; interprets the numbers correctly,
and converts them to decimal form. Then your program should output the
values in properly spaced columns like this:
      0x4 hexadecimal converts to     67 decimal
     0123 octal       converts to     83 decimal
       65 decimal     converts to     65 decimal

Now the code compiles and does what it's intended to do, but I still need to get into that programmer state of mind where you keep only the stuff that really matters, to the last letter (thus keeping the code simple, succinct and efficient). Showing me what I can get rid of and revise would bring me closer to achieving this.
#include"..\..\Header.h"

void print_number(const string& concatenation, const string& type) {
    istringstream s(concatenation);
    int number = 0;
    if(type == "hexadecimal") s >> hex >> number;
    if (type == "octal") s >> oct >> number;
    else s >> number;
    cout << concatenation << '\t' << type << "\tconverts to " << dec << number << " decimal.\n";
}

int main() {
    while (cin) {
        string da;
        cin >> da;
        if (da[0] == '0') {
            if (da[1] == 'x') print_number(da, "hexadecimal");
            else print_number(da, "octal");
        }
        else print_number(da, "decimal");
    }
    system("pause");
    return 0;
}

Header contains these lines (just in case):
    #include <algorithm>
#include <cmath>
#include <vector>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>

using namespace std;

void error(const string& a) {
    throw runtime_error(a);
}


texts:
The basic idea of the code is that agents come into the world, they age and then die. I want to keep track of who is dead and who is alive. Eventually, they will do more things but I think there should be a lot of things I am not doing best practice on. I assume I'm doing something wrong with "Global" as well.

# Classes

class Agent(object):
    def __init__(self, identification, productivity, wealth, preferences, age, health, alive, sex):
        self.identification = identification
        self.productivity = productivity
        self.wealth = wealth
        self.preferences = preferences
        self.age = age
        self.health = health
        self.alive = alive
        self.sex = sex
    def description(self):
        print("My id is", self.identification)
        print("My age is", self.age)

def Create_agents():
    global id
    alive.append(Agent(id,100,20,"blue",30,0,True,True ))
    id += 1

# functions
def Initialize():
    for x in range(3):
        Create_agents()

def Death():
    temp = alive.copy()
    for agent in temp:
        if agent.age>30:
            agent.alive = False
            print("Death of", agent.identification)
            dead.append(agent)
            alive.remove(agent)

def Time_skip():
    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%SKIPPING TIME%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
    global year
    year += 1
    print("The new year is", year)
    for agent in alive:
        agent.age +=1
    Create_agents()
    Death()

# Values
alive = []
dead = []
id = 0
year = 0
Initialize()

# Testing
for agent in alive:
    agent.description()

Time_skip()

for agent in alive:
    agent.description()

The output is:

My id is 0
My age is 30
My id is 1
My age is 30
My id is 2
My age is 30
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%SKIPPING TIME%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The new year is 1
Death of 0
Death of 1
Death of 2
My id is 3
My age is 30


texts: Cross-post from SO-  Palindrome finding function

texts:
I didn't know this site existed before now... awesome!

I just made a thread here:  https://stackoverflow.com/questions/8511620/c-palindrome-finder-optimization

#include <iostream>
#include <ostream>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;

bool isPal(string);

int main()
{
    vector<string> sVec;
    vector<string> sWords;
    vector<string> sTwoWords1;
    vector<string> sTwoWords2;
    char myfile[256]="/home/Damien/Test.txt";
    ifstream fin;
    string str;
    fin.open(myfile);
    if(!fin){
        cout << "fin failed";
        return 0;
    }
    while(fin){
        fin >> str;
        sWords.push_back(str);
        if(!fin){
            break;
        }
        if(isPal(str)){
            sVec.push_back(str);
        }
        else{
            getline(fin, str);
        }
    }
    reverse(sVec.begin(), sVec.end());
    for(int i =0; i < sVec.size(); i++){
        cout << sVec[i] << " is a Palindrome " <<endl;
    }

    // Test 2
    for(int i=0; i<sWords.size(); i++)
    {
        for(int j=(i+1); j<sWords.size(); j++){
            str = sWords[i]+sWords[j];
            if(isPal(str)){
                sTwoWords1.push_back(sWords[i]);
                sTwoWords2.push_back(sWords[j]);
            }
        }
    }
    fin.close();
    for(int i=0; i<sTwoWords1.size();i++){
        cout << sTwoWords1[i] << " and " << sTwoWords2[i] << " are palindromic. \n";
    }
    return 0;
}
bool isPal(string& testing) {
    return std::equal(testing.begin(), testing.begin() + testing.size() / 2, testing.rbegin());
}

About optimizing some code, assuming that I take the revision to my isPal function, what else can I do to optimize the hell out of my code?

Thanks a lot for any / all recommendations!

Wordfile:  http://www.filedropper.com/ospd3


texts:
I have a method which relies heavily on object supplied by third party APIs. Below is my working code, is there any scope of improvement?

public LineItem getLineItem(
      String networkId, String lineItemId) throws ApiException_Exception {
    LineItem lineItem = null;
    session.setCode(networkId);
    LineItemServiceInterface lineItemService = servicesInterface.lineItemService(dfpSession);
    StatementBuilder statementBuilder =
        new StatementBuilder()
            .where("id = " + lineItemId.trim())
            .orderBy("id ASC")
            .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);
    LineItemPage lineItemPage =
        lineItemService.getLineItemsByStatement(statementBuilder.toStatement());
    if (lineItemPage != null && lineItemPage.getResults() != null) {
      lineItem = lineItemPage.getResults().get(0);
    }
    return lineItem;
  }

Every type used above belongs to third party code. I also need to know the good strategy to handle exceptions?

Update 1

One frequent issue I encounter and I am sure many if us will is that there is usually references to the third party type LineItem is sprinkled everywhere in the code base. Is this a good practice to leave it like that or should I wrap that type into my own type and use that instead?

Reference code here.


texts:
This code implements an algorithm for calculation of chemical schemes. This code looks strange but now I have no idea how to refactor it. Can you give your feedback?

eps=0.001;

s1=new Source(1000,0.17);
mx=new Mixer(1000);
mb=new Mem(0.15,0.95);
sp=new Splitter(0.80);
s2=new Sink();
s3=new Sink();

mx.in1=s1.out1;
mx.in2=sp.out2;
mb.in1=mx.out1;
sp.in1=mb.out2;
s3.in1=sp.out1;
s2.in1=mb.out1;

for (i=0;i<50;i++){
    mx.calc();
    mb.calc();
    sp.calc();
}

function Stream(v,c){
    this.v=v||null;
    this.c=c||null;
    this.selfCheck=false;
    this.Show=function(){//how to add default values?
        return "volume="+this.v+",conc="+this.c+",selfCheck:"+this.selfCheck+"; ";
    }
}

function Source(v,c){
    this.out1=new Stream(v,c);
    this.calc=function(){};
}
function Sink(){
    this.in1=null;
    this.calc=function(){};
}

function Mixer(fixedV){
    this.fv=fixedV;
    this.in1=null;
    this.in2=null;
    this.out1=new Stream();
    this.calc=function(){
        this.out1.v=this.fv;//||this.in1.v+this.in2.v;
        this.in2.v=this.in2.v||0;
        this.in2.c=this.in2.c||0;
        this.in1.v=this.out1.v-this.in2.v;
        this.out1.c =(this.in1.v*this.in1.c+this.in2.v*this.in2.c)/this.out1.v;
        this.out1.selfCheck=Math.abs
        ((this.in1.v*this.in1.c+this.in2.v*this.in2.c)-(this.out1.v*this.out1.c))<eps;
    }
}

function Splitter(kS){
    this.in1=null;
    this.ks=kS||0.05;
    this.out1=new Stream();
    this.out2=new Stream();
    this.calc=function(){
        this.out1.v=this.in1.v*(1-this.ks);
        this.out2.v=this.in1.v*(this.ks);
        this.out1.c=this.in1.c;
        this.out2.c=this.in1.c;
    }

}

function Mem(kV,kC) {
    this.kv = kV||0.15;
    this.kc = kC||0.95;
    this.in1 = null;
    this.out1 = new Stream();
    this.out2 = new Stream();
    this.calc = function () {
        this.out1.v = this.in1.v * this.kv;
        this.out1.c = this.in1.c * (1 - this.kc);
        this.out2.v = this.in1.v * (1 - this.kv);
        this.out2.c = (this.in1.v * this.in1.c - this.out1.v * this.out1.c) / this.out2.v;
        this.out1.selfCheck = this.out2.selfCheck = Math.abs
        (this.in1.v * this.in1.c - (this.out1.v * this.out1.c + this.out2.v * this.out2.c)) < eps;

    }
}


texts:
Using JSX syntax I wrote a function that takes either a float or an integer as a parameter and returns a formatted string. I'd like any feedback for refactoring the code.

const moneyFormat = (float) => {
  let answer = [];
  let firstHalf;
  let secondHalf;

  // check if whole number
  if (float % 1 === 0) {
    float = Math.trunc(float);
    firstHalf = float.toString();
    secondHalf = '.00';
  } else {
    float = float.toFixed(2);
    const splitNumArr = float.split('.');
    firstHalf = splitNumArr[0];
    secondHalf = '.' + splitNumArr[1];
  }

  let everyThree = 0;
  // push chars into answer array
  for (let i = firstHalf.length - 1; i >= 0; i--) {
    answer.push(firstHalf[i]);
    everyThree += 1;
    // insert space for every three chars
    if (everyThree % 3 === 0) {
      answer.push(' ');
    }
  }
  // reverse array and add secondHalf
  answer = answer.reverse().join('') + secondHalf;
  return answer;
}

console.log(moneyFormat(2310000.159897)); // '2 310 000.16'
console.log(moneyFormat(1600)); // '1 600.00'


texts:
Looking for code review, suggestions for improvement, best practices etc.

  Given N leaves numbered from 1 to N . A caterpillar at leaf 1, jumps from leaf to leaf in multiples of Aj (Aj, 2Aj, 3Aj).
  j is specific to the caterpillar. Whenever a caterpillar reaches a leaf, it eats it a little bit.. You have to find out how many leaves, from 1 to N, are left uneaten after all K caterpillars have reached the end. Each caterpillar has its own jump factor denoted by Aj, and each caterpillar starts at leaf number 1.

  Input:
  The first line consists of a integer T denoting the number of testcases. T test cases follow. Each test case consists of two lines of input. The first line consists of two integers: N, which denotes the number of leaves; and K, which denotes the number of caterpillars. Second line of each test case consists of K space seperated integers denoting the jumping factor of caterpillars.

  Example:

Input:
1
10 3
2 3 5
Output: 2

  Explanation: Testcase1: The leaves eaten by the first caterpillar are
  (2, 4, 6, 8, 10). The leaves eaten by the second caterpilllar are (3,
  6, 9) The leaves eaten by the third caterpilllar are (5, 10)
  Ultimately, the uneaten leaves are 1, 7 and their number is 2

class CatterpillarDetails{
    int leaves;
    public int getLeaves() {
        return leaves;
    }

    ArrayList<Integer> caterpillarOrder;

    public void setCaterpillarOrder(int order) {
        caterpillarOrder.add(order);
    }

    public ArrayList<Integer> getcaterpillarOrder() {
        return caterpillarOrder;
    }

    int noOfCatterpillar;
    public int getNoOfCatterpillar() {
        return noOfCatterpillar;
    }

    int result;

    public int getResult() {
        return result;
    }

    public void setResult(int result) {
        this.result = result;
    }

    CatterpillarDetails(int leaves, int noOfCaterpillar)
    {
        this.leaves = leaves;
        this.noOfCatterpillar = noOfCaterpillar;
        this.caterpillarOrder = new ArrayList<Integer>(noOfCaterpillar);
    }
}

public class Catterpillar {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int testcase = sc.nextInt();
        CatterpillarDetails[] detailsObj = new CatterpillarDetails[testcase];
        for(int i = 0 ; i < testcase ; i++)
        {
            int leaves = sc.nextInt();
            int noOfCatterpillar = sc.nextInt();
            detailsObj[i] = new CatterpillarDetails(leaves,noOfCatterpillar);

            boolean[] eaten = new boolean[leaves];
            for(int j = 0 ; j < noOfCatterpillar ; j++) {
                int catterpillarOrder = sc.nextInt();
                detailsObj[i].setCaterpillarOrder(catterpillarOrder);

                for(int k = 1 ; k <= leaves ; k++)
                {
                    if(catterpillarOrder*k > leaves)
                        break;
                    else
                    {
                        eaten[(catterpillarOrder*k)-1] = true;
                    }
                }
            }
            detailsObj[i].setResult(calculateNotEaten(eaten));
        }
        for(int i = 0 ; i < testcase ; i++)
        {
            System.out.println(detailsObj[i].getResult());
        }
    }

    private static int calculateNotEaten(boolean[] eaten) {
        int count = 0;
        for(Boolean i : eaten)
        {
            if(!i)
            {
                count++;
            }
        }
        return count;
    }
}


texts: Project Euler 25 - x-digit Fibonacci Number

texts:
I have solved the Problem 25 of the Euler Project:

  The Fibonacci sequence is defined by the recurrence relation:

  \$\qquad F_n = F_{n−1} + F_{n−2}\$, where \$F_1 = 1\$ and \$F_2 = 1\$.

  Hence the first 12 terms will be:

  \$\qquad F_1 = 1\$

  \$\qquad F_2 = 1\$

  \$\qquad F_3 = 2\$

  \$\qquad F_4 = 3\$

  \$\qquad F_5 = 5\$

  \$\qquad F_6 = 8\$

  \$\qquad F_7 = 13\$

  \$\qquad F_8 = 21\$

  \$\qquad F_9 = 34\$

  \$\qquad F_{10} = 55\$

  \$\qquad F_{11} = 89\$

  \$\qquad F_{12} = 144\$

  The 12th term, F12, is the first term to contain three digits.

  What is the first term in the Fibonacci sequence to contain 1000
  digits?

It was pretty easy to get the result, but i also wanted a solution that is fast and well coded.

The solution of this has two major problems:

It is not possible to save a value of 1000 digits in a standard data type (like long)
Getting the length of the number

The first problem was very easy to solve with the BigInteger structure.

For the second problem i would like to provide the code first:

public class EulerHelper
{
    private readonly int digits;

    public EulerHelper(int digits)
    {
        this.digits = digits;
    }

    private List<BigInteger> RecentNumbers { get; } =
        new List<BigInteger>(new[] {new BigInteger(0), new BigInteger(1)});

    private BigInteger Fibonacci(int n)
    {
        if (RecentNumbers.Count > n)
        {
            return RecentNumbers[n];
        }

        for (var counter = RecentNumbers.Count; counter <= n; counter++)
        {
            var fibCounter = RecentNumbers[counter - 1] + RecentNumbers[counter - 2];
            RecentNumbers.Add(fibCounter);
        }

        return RecentNumbers[n];
    }

    public int NumberWithNDigits()
    {
        var counter = 1;
        while (IsXDigitsLong(Fibonacci(counter)))
        {
            counter++;
        }

        return counter;
    }

    public bool IsXDigitsLong(BigInteger number)
    {
        var calculatedLength = GetLength(number);
        return calculatedLength < digits;
    }

    private int GetLength(BigInteger number)
    {
        if (number == 1)
        {
            return 1;
        }

        return (int) Math.Floor(BigInteger.Log10(number) + 1);
    }
}

The above code is the final one. But before IsXDigitsLong was a "string-length-compare":

public bool IsXDigitsLong(BigInteger number)
{
    return number.ToString().Length < digits;
}

The final implementation is around 3.8 times faster as the string one which was a big win of performance.

The main looks like this:

static void Main(string[] args)
{
    Stopwatch sw = Stopwatch.StartNew();
    var executer = new EulerHelper(1000);
    var result = executer.NumberWithNDigits();
    sw.Stop();

    Console.WriteLine($"The result is {result}");
    Console.WriteLine($"Execution time: {sw.ElapsedTicks}");
    Console.ReadKey();
}

Results (Benchmark)

I have done some very rudamentary benchmarks between the .ToString() and the GetLength() implementation:

Method          Time in StopWatch ticks
ToString()      568476
GetLength()     143699


texts: Ruby code forces the answer using a loop and a branch to guess my favorite ice cream flavor

texts:
I'm writing very simple programs. "Crawl before you walk..." they say.

How could I clean this up? And/or simplify?

While I am very new, technical lanquage is necessary because it helps me learn the lessons I need to learn

puts "What is my favorite ice cream flavor?"

ice_cream_1 = gets.chomp.capitalize

while ice_cream_1 != "Vanilla"
   puts "Wrong answer; what is my favorite ice cream flavor?"

   my_favorite_ice_cream_flavor = gets.chomp.capitalize

   if my_favorite_ice_cream_flavor == "Vanilla"
      break
   end
end

puts "Now that's my jam"


texts:
This question is everywhere, and I looked at many answers. A lot suggest using mysql_real_escape_string but that isn't an option, since it's depreciated now.

Being a rookie at PHP/SQL and especially when it comes to security, I can only hope some of you may be able to help out here. I know for a fact that some of these procedures I already use contribute to security.

As an example: I didn't use :pname before when defining query_params, which caused SQL to interpret submissions like 'values'; drop table dbname; as actual commands. One thing that did save me from the command not being executed is the conversion of spaces to underscores.

search_submit.php

<?php
$pname=str_replace(' ','_',strtolower($_GET['pname']));
require 'connection.php';
  if(isset($_GET['pname'])){

  if(preg_match("/\w/i", $_GET['pname'])){
   $query="SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE   SCHEMA_NAME = :pname;";
           $query_params = array(
             ':pname' => str_replace(' ','_',strtolower($_GET['pname']))
        );
   $prep=$conn->prepare($query);
   $result=$prep->execute($query_params) or die("failed!");
   $row = $prep->fetch();
        if($row)
        {
            die("Exists");
        }
        else{
            echo("doesn't");
        }
  }
  }
  else{
  echo  "
Error
";
  }
?>

index.html

<form  method="get" action="search_submit.php"  id="searchform">
  <input  type="text" name="pname">
  <input  type="submit" name="input" value="Search">

As of right now everything appears to be working perfectly, and any sneaky submissions are simply interpreted as text. But I am a very paranoid person.


texts:
I would like your comments on my code in C++ (C++98 + Boost)

I have written some code to use the functors with the boost::range::for_each algorithm.
My main problem was to add some "external" parameters to the functor that are not in the vector on which I am using a for_each loop.

In main() we have:

std::vector<Person> vec;
vec.reserve(MAX_SIZE);
std::map<std::string, int> result;
FillPersons(vec);
boost::range::for_each(vec,Treatment(&result));

The functor is:

struct Treatment {
    Treatment(std::map<std::string, int> *p_result):result_(p_result){}
    void operator ()(Person &person)
    {
        if (NULL != result_)
        {
            int age = person.getAge();

            if (age < AGE_LOW_LEVEL)
            {
                age += 2;
            }
            else if ((age >= AGE_LOW_LEVEL) && (age < AGE_HIGH_LEVEL))
            {
                age += 1;
            }
            else if (age >= AGE_HIGH_LEVEL)
            {
                age -= 5;
            }
            result_->insert(std::pair<std::string, int> (person.getName(), age));
        }
    }
    private:
    std::map<std::string, int> *result_;
    Treatment(const std::map<std::string, int> &);
    Treatment& operator=(const Treatment&);
};

Is there any other way to do that better or is it good?
How would it be using lambdas?
How would it be in C++11?

For your information, the Treatment function is naive because my focus was only on adding external parameters to the functors.


texts: Access an associative array value given an array of keys in PHP

texts:
I have an object which stores an app configuration in an associative array, as this:

[
  'Database' =>
    [
      'DB_SERVER' => 'localhost'
      'DB_NAME' => 'adbname'
      'DB_USER' => 'theuser'
      'DB_PASS' => 'thepass'
    ]
]

And a function, get(), which receives a variable number of arguments and returns the configuration value for this parameters. For example, Config::get('Database','DB_PASS') will return 'thepass'.

This is an excerpt of the code:

class Config
{
    protected static $values;

    ...

    public static function get()
    {
        $val = &self::$values;
        $argList = func_get_args();
        for ($i = 0; $i < count($argList); $i++) {
            $val = &$val[$argList[$i]];
            if(empty($val)) break;
        }
        return (is_null($val)?"":$val);
    }
}

Is there a more elegant / efficient way of accessing the value?


texts:
I'm currently making a game using C++. I eventually needed a logger, but I wasn't satisfied with any of the existing solutions. After a while, I wrote my own header called log.h:

#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
#include <fstream>
#include <sstream>

class Logger {
    private:
        std::string logFileName = "log.txt";
        bool print = true;
        bool save = true;

        void log(std::string s, std::string i) {
            time_t cuT;
            struct tm *loT;
            time(&cuT);
            loT = localtime(&cuT);

            std::stringstream ss;
            ss << std::setw(2) << std::setfill('0') << loT->tm_hour << ':';
            ss << std::setw(2) << std::setfill('0') << loT->tm_min << ':';
            ss << std::setw(2) << std::setfill('0') << loT->tm_sec;
            ss << i << s << "\n";

            if(save) {
                std::ofstream of;
                of.open(logFileName, std::ios_base::app | std::ios::out);
                of << ss.rdbuf();
            }
            if(print) {
                std::cout << ss.str();
            }
        }
    public:
        void configure(std::string logFileName_, bool print_, bool save_) {
            this->print = print_;
            this->save = save_;
            this->logFileName = logFileName_;
        }

        void note(std::string s) {
            log(s, " NOTE: ");
        }

        void error(std::string s) {
            log(s, " ERROR: ");
        }

        void warn(std::string s) {
            log(s, " WARNING: ");
        }
};

My library can print the current time as well as other information to the console and save this data into a file. But I did a couple of benchmarks and it turns out that my logging program is a lot slower compared to the normal std::cout.
Since speed is crucial for games, I wanted to ask whether there are ways to optimize my program or, if necessary, to improve it.


texts: Refactoring string incrementing and duplicating function

texts:
I wrote this script and got what I wanted from it. However I'm looking for input on ways I can improve the function.

My goal was to scrape a bunch of image links from a website I'd like to rebuild. I wanted to use webscraper but the image links were coded into the CSS instead of the HTML mark up.

Hence I had difficulty getting the web scrapper to find and collect said links.
Luckily while looking at them, I was able to discern their structure and pattern into 4 formats and came up with the following script to duplicate and iterate through each format to get my links.

Beside the 1st group (which is comprised of 40 images), each image (n) is part of a group (x) of 12 and there are 170 groups in total. Something I had to consider while writing the script is that each image number starts with a "00" prefix and "000" for the group number. So they had to be removed as you increment through the tens(for images) and hundreds(for groups).

let loop = 0;
for (; loop < 155; loop++) {
let n = 00;
let x = 000;
str1 = "https://site.com/content/2018/02/"; /* groups 1-155*/
str2 = "https://site.com/content/2019/07/"; /* groups 156-167*/
str3 = "https://site.com/content/2019/11/"; /* group 168*/
str4 = "https://site.com/content/2020/03/"; /* groups 169-171*/
ext = ".jpg"
z = "0";
zz ="00";
        if (loop > 0 ) {
        x+=loop;
    console.log('one loop ' + loop );
    if(x >= 9){
        var zz = "00".replace('00','0');
    }
    if(x >= 99){
        var zz = "00".replace('00','');
    }
  }
      while (n <= 11) {
        if(n >= 9){
        var z = "0".replace('0','');
        }
        n++;
    console.log(str1 + zz + x + "_" + z + n + ext);
  }
}


texts: Generating and re-using unique, sequential, positive integers

texts:
(re-posting from StackOverflow as this is more of a review)

In the past, I've often encountered the following problem and so far my go-to solution was to combine a counter with a hashtable (with open-addressing).

The only operations I need to implement are the following:

next: generates a new integer or re-uses a previously freed one
free: frees a previously generated integer
size: returns the number of generated integers (excluding those who have been freed and not yet re-used)

Here's some working code that I use very often when this case pops up.

class IdGenerator
{
    typedef std::uint64_t Id;

public:
    IdGenerator():
        total_ids_(0)
    {
    }

    Id next()
    {
        Id id;
        if (available_ids_.empty())
        {
            id = total_ids_;
            ++total_ids_;
        }
        else
        {
            auto it = available_ids_.begin();
            id = *it;
            available_ids_.erase(it);
        }
        return id;
    }

    void free(Id id)
    {
        available_ids_.insert(id);
    }

    Id size() const
    {
        return total_ids_ - available_ids_.size();
    }

private:
    std::unordered_set<Id> available_ids_; // usually, I use open-adressing here
    Id total_ids_;
};

While this code generally brings good performance, I've always wondered if there was a faster way of doing this.


texts:
I have written a program in Python 3 for the INTEST problem on Codechef (included in question). The program is taking a lot of time (55.76s) in Python 3. The same code takes almost 1/10 of the time time (4.97s) in C.

  The purpose of this problem is to verify whether the method you are
  using to read input data is sufficiently fast to handle problems
  branded with the enormous Input/Output warning. You are expected to be
  able to process at least 2.5MB of input data per second at runtime.

  Input

  The input begins with two positive integers \$n\$ \$k\$ (\$n, k\le10^7\$). The next
  \$n\$ lines of input contain one positive integer \$t_i\$, not greater than
  \$10^9\$, each.

  Output

  Write a single integer to output, denoting how many integers \$t_i\$ are
  divisible by \$k\$.

  Example

  Input:

7 3
1
51
966369
7
9
999996
11

  Output:

4

My questions are:

How is it that the Python 3 code is taking so much time or which line of code specifically is taking the most time?
Any modifications that can speed up the code?

My CodeChef submissions with time and code.

import sys
__author__ = 'Gourav Chawla'
"""
    Problem Code: INTEST
    Problem URL: http://www.codechef.com/problems/INTEST
    Compatability: Python 3.x
"""

n, k = input().split()
n = eval(n)
k = eval(k)

inputVar = 0
count = 0

# inputVar = [eval(x) for x in input().split()]

inputVar = list(map(int, sys.stdin.readlines()))

for i in inputVar:
   if i % k == 0:
       count += 1

print(count)


texts: A simple queue implementation in Haskell

texts:
I'm a member of a discord channel and sometimes people post simple coding exercises for fun. This time the exercise was:

Implement the following operations of a queue using stacks.

push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty

Example:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false

I didn't implement it using stacks because I don't know of any that are in the standard Haskell library but
I came up with this Solution:

data Queue a = Empty | Value a (Queue a) deriving (Show, Eq, Read)

push :: a -> Queue a -> Queue a
push x Empty             = Value x Empty
push x (Value a pointer) = Value a (push x pointer)

pop :: Queue a -> Maybe (a, Queue a)
pop Empty             = Nothing
pop (Value a pointer) = Just (a, pointer)

peek :: Queue a -> Maybe a
peek Empty       = Nothing
peek (Value a _) = Just a

empty :: Queue a -> Bool
empty Empty = True
empty _     = False

I'm currently trying to understand Haskell better and was wondering if there was a more idiomatic Solution.


texts: Python Boto Script - Sorting based on date

texts:
I had a question regarding my code which downloads a file from S3 with the highest (most recent) timedated filename format:

YYYYMMDDHHMMSS.zip

from boto.s3.connection import S3Connection
from boto.s3.key import Key
import sys
conn = S3Connection('____________________', '________________________________________')
bucket = conn.get_bucket('bucketname')
rs = bucket.list("FamilyPhotos")

for key in rs:
    print key.name

keys = [(key,datetime.strptime(key.name,'%Y%m%d%H%M%S.zip')) for key in rs]
sorted(keys, key = lambda element : element[1])
latest = keys[0][1]
latest.get_contents_to_filename()

I havent done a lot of python before so I would really appreciate some feedback.


texts:
Based on my question here, I have updated my query to take user input so it can be a generic query:

DECLARE @location AS nvarchar(max) = ##location:string##;
SELECT u.Id [User Link], u.Reputation, u.Location
FROM Users u
WHERE lower(u.Location) LIKE lower('%' + @location + '%')
ORDER BY 'Reputation' DESC

Is there something I should be doing differently, or is this good?


texts: Find most significant bit without bitshifts

texts:
I am trying to find the most significant bit of unsigned number without using any bitshifts. This is what I have come up with, which looks very naive but it's very simple:

template<typename T>
constexpr uint8_t find_msb(const T& a_variable)
{
    static_assert(std::is_unsigned<T>::value, "Variable must be unsigned");

    constexpr uint8_t number_of_bits = std::numeric_limits<T>::digits;
    const std::bitset<number_of_bits> variable_bitset{a_variable};

    for (uint8_t msb = number_of_bits - 1; msb >= 0; msb--)
    {
        if (variable_bitset[msb] == 1)
            return msb + 1;
    }
    return 0;
}

In C++17 this is a valid constexpr function and it appears it just vanishes into thin air with gcc, even with -O0: https://godbolt.org/z/pKI8fj.

But the non constexpr version is more involved: https://godbolt.org/z/eyj2bO.

In my use case I can use the constexpr version so it's not a big deal. How can I improve this code while maintaining readability and also without using any "smart" tricks and/or bitshifting?


texts:
I'm not the greatest at writing tests yet and I'm starting a new OSS project for learning and as part of it I want to tackle being more effective at writing tests, more specifically quality tests. I think I write a lot of tests that don't bring much value except maintenance pain sometimes.

Can I improve these tests?

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using FakeItEasy;
using HaywireMQ.Server.Channel;
using HaywireMQ.Server.MessageStore;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoFakeItEasy;

namespace HaywireMQ.Server.Tests
{
    /// <summary>
    /// Tests for HaywireServer
    /// </summary>
    [TestClass]
    public class HaywireServerTests
    {
        private IFixture fixture;

        public HaywireServerTests()
        {
        }

        [TestInitialize]
        public void Initialize()
        {
            fixture = new Fixture().Customize(new AutoFakeItEasyCustomization());
        }

        [TestMethod]
        public void Should_use_defaults_without_ModuleCatalog()
        {
            // Given
            var target = new HaywireServer();

            // When
            target.Start();

            // Then
            Assert.AreEqual<Type>(target.MessageStore.GetType(), typeof(InMemoryMessageStore));
            Assert.AreEqual<Type>(target.MessageChannel.GetType(), typeof(InMemoryMessageChannel));
        }

        [TestMethod]
        public void Should_use_ModuleCatalog()
        {
            // Given
            var catalog = new ModuleCatalog();
            var messageStore = fixture.CreateAnonymous<IMessageStore>();
            var messageChannel = fixture.CreateAnonymous<IMessageChannel>();
            catalog.MessageStores.Add(messageStore);
            catalog.MessageChannels.Add(messageChannel);
            var target = new HaywireServer(catalog);

            // When
            target.Start();

            // Then
            Assert.AreEqual<Type>(target.MessageStore.GetType(), messageStore.GetType());
            Assert.AreEqual<Type>(target.MessageChannel.GetType(), messageChannel.GetType());
        }

        [TestMethod]
        public void Should_create_MessageQueue()
        {
            // Given
            var catalog = new ModuleCatalog();
            var messageStore = fixture.CreateAnonymous<IMessageStore>();
            var messageChannel = fixture.CreateAnonymous<IMessageChannel>();
            catalog.MessageStores.Add(messageStore);
            catalog.MessageChannels.Add(messageChannel);
            var target = new HaywireServer(catalog);

            List<string> ids = new List<string>() {"test"};

            A.CallTo(() => messageStore.GetQueues()).Returns(ids);

            // When
            target.Start();

            // Then
            A.CallTo(() => messageStore.GetQueues()).MustHaveHappened();
            Assert.AreEqual<int>(target.MessageQueues.Count, 1);
            Assert.AreEqual<string>(target.MessageQueues[0].Id, "test");
        }
    }
}


texts:
Could someone review the following code?

class PigLatin

  attr_accessor :phrase
  ending = "ay"

  def initialize the_phrase
    @phrase = the_phrase
  end

  def translate
    translated_phrase = String.new
    words = @phrase.split
    words.each do |word|
      puts word
      if vowel_is_first word
        translated_phrase +=  translate_with_vowel(word)
      else
        translated_phrase += translate_with_consonant(word)
      end
    end

    clean_up translated_phrase
  end

  def vowel_is_first test_word
    true if test_word[0] =~ /aeiou/ #will this make false since 0??
    false
  end

  def translate_with_vowel word
    word + "-" + ending + " "
  end

  def translate_with_consonant word
    return word + "-way " if word.size <= 2
    split_location = word =~ /a|e|i|o|u/
    word_array_length = word.size - 1

    first_segment = word[split_location,word_array_length]
    second_segment = "-" + word[0,split_location-1] + word[split_location-1]  + "ay" + " "

    first_segment + second_segment
  end

  def clean_up to_be_cleaned
    to_be_cleaned = to_be_cleaned[0..to_be_cleaned.size-2]
    to_be_cleaned.capitalize
  end
end

I'm sure it could use some work as I'm just getting going in Ruby, so anything and everything would be helpful. The clean-up function, I think, could especially use work.  It gets the job done, but w/o it there is always a space at the end, and str.strip wasn't getting the job done.


texts: Get user and users of ancestors of a model instance if it has `organizationmember` attribute or else only user of the instance in Django

texts:
I have the following models:
class Client(BaseModel):
    #other fields
    engineers = models.ManyToManyField(Engineer, null = True, blank = True, related_name='clients')

class OrganizationMember(MPTTModel):
    designation = models.CharField(max_length = 100, blank = True)
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.SET_NULL)

Now I would like to get all engineers of a client instance and check if each engineer has an organizationmember instance or not.
Then if they belong to some organization then I should get_ancestors of that organizationmember and then the users.
If they do not have any organizationmember then just get the user of that engineer instance.
For this I have written a method in Client model as below:
class Client(BaseModel):

    def get_users_from_engineers(self):
        users_in_organization = []
        users_outside_organization = []

        engineers = self.engineers.all()
        if engineers:
            for engineer in engineers:
                user = engineer.user
                if hasattr(user, "organizationmember"):
                    users_in_organization += [orgmember.user for orgmember in user.organizationmember.get_ancestors(include_self=True)]
                else:
                    users_outside_organization.append(user)

Now this code is working correctly but I am sure that I can use django filters here instead of two for loops and optimize this code. But I do not know how.
For eg:
OrganizationMember.objects.filter(user__engineer__in=self.engineers.all())

can be used to get all the organizationmembers of the engineers of that particular client instance. But I need the users of those organizationmembers.
Also if I use get_ancestors on multiple engineers then more than one engineer might have the same ancestor thereby adding the same person more than once in the users_in_organization list. How can I rectify this if I use django filters?
Edit:
In the method get_users_from_engineers I can also use as follows:
users_outside_organization = list(User.objects.filter(engineer__in=engineers, organizationmember__isnull=True)

But I do not know how to get the users_in_organization values as stated above using django orm methods.
Note: This is my first question in codereview. I do not know if this question should be asked here or in stackoverflow since I already have a working code. Anyway I have asked the same question in stackoverflow also. Please feel free to correct me regarding the same.


texts: Python script to query REST API and write to database

texts:
I wrote the following sample script for learning purposes:

import requests
import json
import pyodbc
import os
import sys

source_url = 'https://jsonplaceholder.typicode.com/posts/'

query_posts_response = requests.get(source_url)

if (query_posts_response.status_code == 200):
    posts = json.loads(query_posts_response.content.decode('utf-8'))

db_connection = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
    "Server=(local);"
    "Database=sandbox;"
    "Trusted_Connection=yes;")

sys_devnull = open(os.devnull, 'w')
sys_stdout_original = sys.stdout
sys.stdout = sys_devnull

db_cursor = db_connection.cursor()

for post in posts:
    db_cursor.execute("INSERT INTO dbo.Posts(id, title) VALUES (?, ?)", post['id'], post['title'])

db_connection.commit()
db_connection.close()

sys.stdout = sys_stdout_original

I'm grabbing content from a REST API, and I'm inserting it into a relational table.

I write scripts in other languages, but this is my first Python script. I don't know what I don't know. I'm looking for a critique. I realize I was lazy on the database call and didn't create an exception handler. That said, is this the generally accepted way to interface with a REST endpoint and interact with a database?

Concerning output of db_cursor.execute(), see the following:


texts:
I'm trying to develop some templates for common PHP tasks I've been dealing with. One of which is a general image file upload handler.

So far I'm using the following reusable code which seems to be working fine without any noticeable bug:

<?php

    if ( !isset($_POST['submit']) ) {
        goto page_content;}

    if ( $_FILES['file_upload']['error']===4 ) {
        echo 'No file uploaded';
        goto page_content;}

    if ( $_FILES['file_upload']['error']===1 || $_FILES['file_upload']['error']===2 ) {
        echo 'File exceeds maximum size limit';
        goto page_content;}

    if ( $_FILES['file_upload']['error']!==0 ) {
        echo 'Failed to upload the file';
        goto page_content;}

    if ( !is_uploaded_file($_FILES['file_upload']['tmp_name']) ) {
        echo 'Failed to upload the file';
        goto page_content;}

    require_once('imageResize.php');
    $err = imageResize($_FILES['file_upload']['tmp_name'], 'random.png' );
    if ( $err !== 0 ) {
        echo 'Invalid image format';
        goto page_content;}

    echo 'Image uploaded successfully';

    page_content:
?>
<form action="filename.php" method="POST" enctype="multipart/form-data">

    <input type="hidden" name="MAX_FILE_SIZE" value="1000000">
    <input type="file" name="file_upload" accept="image/*">
    <input type="submit" name="submit">

</form>

Additional file imageResize.php:

<?php
    // image resize
    function imageResize($source, $target){

        $size = getimagesize($source);
        if ($size === false) {return 1;} // invalid image format

        $sourceImg = @imagecreatefromstring(@file_get_contents($source));
        if ($sourceImg === false) {return 2;} //invalid image format

        $width = imagesx($sourceImg);
        $height = imagesy($sourceImg);
        $sidelenght = min($width,$height);
        $targetImg = imagecreatetruecolor(100, 100);
        imagecopyresampled($targetImg, $sourceImg, 0, 0, ($width-$sidelenght)/2, ($height-$sidelenght)/2, 100, 100, $sidelenght, $sidelenght);
        imagedestroy($sourceImg);
        imagepng($targetImg, $target);
        imagedestroy($targetImg);

        return 0;
    }
?>

Some main characteristics of this code are:

provides messages for the most common errors that can happened during the upload process
it allows the client to upload an image file up to 1Mb size
resizes all images to a standard 100x100 px size
save all images to a standard PNG format

Questions

Is this code safe? Or are there any vulnerability that could be exploited by an malicious client? In this case, how can I solve it?
To avoid several nested if-then-else conditions (which can become hard to read), I'm currently using goto (which can become a bad control structure practice). Is there a better alternative?


texts: Implementation of a Resizing Array Queue

texts:
Below is a problem from Sedgewick's Algorithms and my solution. Any thoughts or suggestions for improvement would be much appreciated.

  Develop a class that implements the queue abstraction with
  a fixed-sized array, and then extend your implementation to use array
  resizing.

package chapter_1_3_bagsQueuesStacks;

import java.util.Arrays;
import java.util.Iterator;

// Exercise 1.3.14 | pg. 163
public class ArrayQueue<E> implements Iterable<E> {
    private E[] a = (E[]) new Object[1];
    private int head;
    private int tail;
    private int N;

    public boolean isEmpty() {
        return N == 0;
    }

    private boolean isFull() {
        return N == a.length;
    }

    public int size() {
        return N;
    }

    private void resize(int cap) {
        E[] temp = (E[]) new Object[cap];
        int curr = head;
        for (int i = 0; i < N; i++) {
            temp[i] = a[curr];
            if (curr == a.length-1) {
                curr = 0;
            } else {
                curr++;
            }
        }
        a = temp;
    }

    public void enqueue(E element) {
        if (isFull()) {
            resize(a.length*2);
            head = 0;
            tail = N-1;
        }

        if (isEmpty()) {
            head = tail = 0;
        } else if (tail == a.length-1) {
            tail = 0;
        } else {
            tail++;
        }

        a[tail] = element;
        N++;

    }

    public E dequeue() {
        if (isEmpty())
            throw new RuntimeException();

        E element = a[head];
        a[head] = null;
        N--;

        if (head == a.length-1) {
            head = 0;
        } else {
            head++;
        }

        if (N == a.length/4) {
            resize(a.length/2);
            head = 0;
            tail = N-1;
        }

        return element;
    }

    @Override
    public Iterator<E> iterator() {
        return new ArrayIterator();
    }

    private class ArrayIterator implements Iterator<E> {

        int curr = head;

        @Override
        public boolean hasNext() {
            return a[curr] != null;
        }

        @Override
        public E next() {
            E element = a[curr++];
            return element;
        }

    }

    @Override
    public String toString() {
        String formatStr = "HEAD: %s - TAIL: %s - %s";
        return String.format(formatStr, this.head, this.tail, Arrays.toString(this.a));
    }

}


texts:
I currently have the following working code. I am looking for some suggestion with best practices and perhaps a better way to accomplish my goal.

Goal: - in short - Have a generic data interface as a single data access point to different data sources.

Concern: My current code is working fine but I have to call GetRepository() in each method inside my test class to access the desire instance of the data source repository.

Code Snippet:

public class GenericRepository : IGenericRepository
{
   public T GetRepository<T>()
    {
        string typeName = typeof(T).ToString();
        if (string.IsNullOrEmpty(typeName))
            return default(T);

        Type repoType = Type.GetType(typeName);
        object repoInstance = Activator.CreateInstance(repoType);
        return (T)(object)repoInstance;
    }
    // more code...
}

Usage:

public class MyTestClass
{
    IGenericRepository repo = new GenericRepository();

    private void DoThis()
    {
       IFileRepository repoA = repo.GetRepository<FileRepository>();
       // now I can call repository A interface methods like this repoA.SomeMethod()
    }

    private void DoThat()
    {
        ISQLRepository repoB = repo.GetRepository<SQLRepository>();
        // now do something with repository B interface methods like this repoB.SomeMethod()
    }
}

I thought of an alternative way to do this but it has its own drawbacks as well.

Implement the interface methods in both IGenericeRepository and as well as the interface I inherited.
Implement the methods for inherited interface inside IGenericRepository and put it in each different region and end up with a massive page of code

Thoughts? Comments? Suggestion?
-- I personally think the first option is a better choice but wonder if there are better ideas or maybe there is something wrong with my implementation.

Alternative Code

public class GenericRepository : IGenericRepository, IFileRepository, ISQLRepository
{
   public FileRepository fileRepo { get; set; }
   public SQLRepository sqlRepo { get; set; }

   public GenericRepository()
   {
       fileRepo = new FileRepository();
       sqlRepo = new SQLRepository();
   }
    // more code...
}

Alternative Usage

public class MyTestClass
{
    IGenericRepository repo = new GenericRepository();

    private void DoThis()
    {
         // now I can access file repository like this: repo.fileRepo.SomeMethod();
         // now I can access sql repository methods like this: repo.sqlRepo.SomeMethod();
    }

    private void DoThat()
    {
         // now I can access file repository like this: repo.fileRepo.SomeMethod();
         // now I can access sql repository methods like this: repo.sqlRepo.SomeMethod();
    }
}

======
updated:

To provide more context. Below is the solution structure

-- Solution

---- Repository Project (GenericRepository, FileRepository, SQLRepository)

---- IRepository Project (IGenericRepository, IFileRepository, ISQLRepository)

---- MyTestProject Project (MyTestClass)


texts:
I wrote this sparse linked list insert function, and there are nine return statements. Is this a code smell? Is this badly implemented? I fear that it's hard to read, or hard to maintain.

/* NOT BUGS, TESTED AND WORKS CORRECTLY
 * insert an element into a list
 * list is ordered using pos
 * if position pos is already occupied, the value of the node
 * should be updated with val
 * if val=0, then the element should be deleted
 * return 0 if operation is succesfull
 *        1 if malloc failed */
int insert_element(ElementNode_handle *list_handle, int pos, int data)
{
  /*Record the head*/
  ElementNode *current = *list_handle;

  /* If data is 0, stop */
  if (data == 0)
  {
    return 1;
  }

  /* If list is empty, crate new list*/
  if (current == NULL)
  {
    /* Create new list */
    ElementNode *new_node = make_node(pos, data);
    /* Malloc fail check*/
    if (new_node == NULL)
    {
      return 0;
    }
    new_node->data = data;
    new_node->pos = pos;
    *list_handle = new_node;
    return 1;
  }
  /* If head pos == pos, replace and done*/
  if (current->pos == pos)
  {
    current->data = data;
    return 1;
  }
  else if (current->pos > pos)
  {
    /* Create new node between current and next */
    ElementNode *new_node = make_node(pos, data);
    if (new_node == NULL)
    {
      return 0;
    }
    new_node->next = current;
    *list_handle = new_node;
    return 1;
  }
  /*Walk the list, until next hits the end*/
  while (current->next != NULL)
  {
    if (current->next->pos == pos)
    { /* If next pos equals post, replace, done*/
      current->next->data = data;
      return 1;
    }
    else if (current->next->pos > pos)
    {
      /* Create new node between current and next */
      ElementNode *new_node = make_node(pos, data);
      if (new_node == NULL)
      {
        return 0;
      }
      ElementNode *next     = current->next;
      current->next         = new_node;
      new_node->next        = next;
      return 1;
    }
    /*walk the list*/
    current = current->next;
  }
  /* Append to the tail */
  ElementNode *new_node = make_node(pos, data);
  if (new_node == NULL)
  {
    return 0;
  }
  current->next = new_node;
  return 1;
}

=== EDIT ===
Refactored based on @user1118321

/**
 * @brief insert an element into a list
 * @details
 * list is ordered using pos if position
 * pos is already occupied, the value of
 * the node should be updated with data
 * @param p_list_handle Opaque pointer to list
 * @param pos Position to insert
 * @param data data at position
 * @return 0 = success, 1 = failed
 */
int insert_element(ElementNode_handle *p_list_handle, int pos, int data)
{
  /*Record the head*/
  ElementNode *current = *p_list_handle;
  /*Record previous*/
  ElementNode *previous = NULL;
  /*End result*/
  int result = -1;

  if (data == 0)
  {
    delete_element(p_list_handle, pos);
    return 0;
  }

  if (current == NULL)
  {
    return make_list(p_list_handle, pos, data);
  }

  while ((current != NULL) && (result == -1))
  {
    if (current->pos == pos)
    {
      current->data = data;
      result = 0;
    }
    else if (current->pos > pos)
    {
      ElementNode *new_node = make_node(pos, data);
      if (new_node == NULL)
      {
        result = 1;
      }
      if (previous == NULL)
      {
        *p_list_handle = new_node;
      }
      else
      {
        previous->next = new_node;
      }
      new_node->next = current;
      result = 0;
    }
    previous = current;
    current = current->next;
  }
  if (result == -1)
  {
    ElementNode *new_node = make_node(pos, data);
    if (new_node == NULL)
    {
      result = 0;
    }
    previous->next = new_node;
  }
  return result;
}


texts:
Online challenge on Hacker Rank.

  Problem Description

  Alice wrote a sequence of words in CamelCase as a string of letters, S ,
  having the following properties:

  It is a concatenation of one or more words consisting of English
  letters. All letters in the first word are lowercase. For each of the
  subsequent words, the first letter is uppercase and rest of the
  letters are lowercase. Given, print the number of words in  on a new
  line.

  Input Format

  A single line containing string S.

  Constraints

  Output Format

  Print the number of words in string.

  Sample Input

saveChangesInTheEditor

  Sample Output

5

public class Solution {
    private static int solve(String input) {
        int len = input.length();
        if (len == 0) {
            return 0;
        }
        int count = 1;
        for (int i = 0; i < len; i++) {
            char c = input.charAt(i);
            if ('A' <= c && c <= 'Z') {
                count++;
            }
            else if (c == ' ') {
                break;
            }
        }
        return count;
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s = in.next();
        System.out.println(solve(s));
    }
}


texts: Script for a multi-user webapp database connection

texts:
I have the following working script which I use for my database connection for a multi-user webapp. I use a different database for the login, this script is called only after the user is successfully logged in. The login uses PDO.

I would like to know what I can do to

make this more secure
harder to fail

include('.dbinc.cred.inc.php');

try {
$dbh = new PDO('mysql:host=' . HOST_ONE . ';dbname=' . DB_ONE . '', USER_ONE, PASS_ONE);

$statement = $dbh->prepare("SELECT user_db, user_db_pass, user_db_user, user_name FROM databases WHERE user_name = :name");
$statement->execute(array('name' => $_SESSION['user_name']));

foreach ($statement as $row) {
   $user_db = $row['user_db'];
   $user_db_user = $row['user_db_user'];
   $user_db_pass = $row['user_db_pass'];
}

}
  catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$dbh = null;

$sql = new mysqli (HOST_ONE,$user_db_user, $user_db_pass,$user_db);
$sql -> set_charset ( 'utf8' );
if ($sql->connect_errno)
{echo "<script language=JavaScript>location.href='#ajax/account_setup.php';</script> ";}

Is it better to do this in 2 files, one for the user check, then define HOST_TWO and so on and include the first file in the second?

Why am I using PDO and then MySQLi? I do this (weird) thing because the whole app uses mysqli_ at the moment and I'm rewriting everything to PDO atm. But actually I need the MySQLi connection, though.


texts:
I'm looking for general feedback on this module.  Here is what it handles on the page:

This is a private "class" meaning none of its properties are available outside of it.

init is run at run-time.  pre sets up parameters to be sent to the server via ajax and post receives the ajax response.

I can post the code for Class.create if needed, but I wanted to focus on the class itself.

$A.Class.create('private', {
    Name: 'Settings',
    E: {
        save_button:  '#save_button',
        cancel_button:  '#cancel_button',
        se_form: '#se_form'
    },
    init: function () {
        var self = this;
        $(this.E.save_button).on("click", function () {
            $A.Packet.push({model: self.Name});
        });
        $(this.E.cancel_button).on("click", function () {
            Page.flip('fave');
        });
    },
    pre: function (packet) {
        packet.h_token = Storage.getRemembered();
        packet.privacy = this.getSaved();
        packet.state = true;
        return packet;
    },
    post: function (packet) {
        Page.flip('fave_custom');
        return packet;
    },
    getSaved: function () {
        var form_elements = this.E.se_form.elements,
            send_value = '',
            iterator;
        for (iterator = 0; iterator < form_elements.length; iterator++) {
            if (form_elements[iterator].checked) {
                send_value = form_elements[iterator].value;
            }
        }
        return send_value;
    }
});


texts: Name for mconcat implementation for applicative monoid

texts:
I have implemented a function mcollect which is effectively mconcat only for applicative monoids:

mcollect
  :: Applicative f
  => Monoid (f a)
  => [a]
  -> f a
mcollect = mconcat . fmap pure

However I am not overly keen on the name mcollect, an alternative name in the spirit of mconcat is amconcat which I am not keen on either. Looking on Hoogle there does not appear to be anything like this in any libraries, that I can find. Does something like this exist somewhere already, I've just missed it? Is there a better name for this function?


texts:
I have this working code that selects which method to call based on values in
the parameter:

@Override
public Iterator<DBObject> __find(DBObject ref, DBObject fields,
        int numToSkip , int batchSize , int limit, int options){
    Preconditions.checkNotNull(ref, "Reference object can't be null");

    LOG.info("Reference object=" + ref);

    DBObject query = (DBObject) ref.get("$query");
    DBObject orderby = (DBObject) ref.get("$orderby");

    // Remove special fields
    dataCleansing(ref);

    if (query != null){
        LOG.info("Query object=" + query);
        if (orderby != null){
            LOG.info("Sort object=" + orderby);
            Iterator<DBObject> it = _store.getSortedObjectsLike(query, orderby);
            return it;
        } else {
            Iterator<DBObject> it = _store.getObjectsLike(query);
            return it;
        }
    } else {
        if (orderby != null){
            LOG.info("Sort object=" + orderby);
            Iterator<DBObject> it = _store.getSortedObjects(orderby);
            return it;
        } else { // query and ordeby are both null
            Iterator<DBObject> it = _store.getObjects();
            return it;
        }
    }
}

I really think there's some way to better address this selection of functions than just plain if-else statement.

As conditions might grow and more objects passed for condition checking. Is there an "elegant" way to deal with this kind of "choose which method to execute based on parameters values and existence" ?


texts:
Please comment on this.

class MinHeap<T> where T: IComparable
    {
        List<T> elements;

        public MinHeap()
        {
            elements = new List<T>();
        }

        public void Add(T item)
        {
            elements.Add(item);
            Heapify();
        }

        public void Delete(T item)
        {
            int i = elements.IndexOf(item);
            int last = elements.Count - 1;

            elements[i] = elements[last];
            elements.RemoveAt(last);
            Heapify();
        }

        public T PopMin()
        {
            if (elements.Count > 0)
            {
                T item = elements[0];
                Delete(item);
                return item;
            }
            //relook at this - should we just throw exception?
            return default(T);
        }

        public void Heapify()
        {
            for (int i = elements.Count - 1; i > 0; i--)
            {
                int parentPosition = (i+1) / 2 - 1;
                parentPosition = parentPosition >= 0 ? parentPosition : 0;

                if (elements[parentPosition].CompareTo(elements[i])>1)
                {
                    T tmp = elements[parentPosition];
                    elements[parentPosition] = elements[i];
                    elements[i] = tmp;
                }
            }
        }
    }


texts: 0/1 knapsack algorithm implementation with possibilities vector

texts:
The following code uses dynamic approach to solve 0/1 knapsack problem. (I know the maximum profit function I have used is not as good as the one I have defined here and I still am working on that . Are any optimizations possible for the following code?

#include "algorithms.h"

struct Item {
    int index = 1;
    int profit = 1;
    int weight = 1;
    Item() = delete;
    explicit Item(int i, int _profit, int w) {
        index = i;
        profit = _profit;
        weight = w;
    }
    bool operator<(const Item& item) {
        return this->profit < item.profit;
    }
    bool operator<=(const Item& item) {
        return this->profit <= item.profit;
    }
    bool operator>(const Item& item) {
        return this->profit > item.profit;
    }
    bool operator>=(const Item& item) {
        return this->profit >= item.profit;
    }
    friend std::ostream& operator<<(std::ostream& out, const Item item) {
        out << item.index;
        return out;
    }
};

long weight(const std::vector<Item>& item_list, const std::vector<int>& item_switch) {
    long sum = 0;
    for (int i = 0; i < item_switch.size(); i++) {
        sum += item_switch[i] * item_list[i].weight;
    }
    return sum;
}

long profit(const std::vector<Item>& item_list, const std::vector<int>& item_switch) {
    long sum = 0;
    for (int i = 0; i < item_switch.size(); i++) {
        sum += item_switch[i] * item_list[i].profit;
    }
    return sum;
}

void increment(std::vector<int>& vec) {
    auto it_bit = vec.end();
    it_bit--;
    while (*it_bit == 1) {
        *it_bit = 0;
        if (it_bit == vec.begin()) {
            return;
        }
        it_bit--;
    }
    *it_bit = 1;
}

int main() {
    long M = 25;
    Item i1(1, 10, 9);
    Item i2(2, 12, 8);
    Item i3(3, 14, 12);
    Item i4(4, 16, 14);
    std::vector<Item> items = { i1,i2,i3,i4 };
    std::vector<int> enable(4,0);
    std::vector<std::vector<int>> possible;
    for (int i = 1; i <= 16; i++) {
        if (weight(items, enable) <= M) {
            possible.push_back(enable);
        }
        increment(enable);
    }
    long pr = 0;
    for (int i = 0; i < possible.size(); i++) {
        long temp = profit(items, possible[i]);
        if (temp > pr) {
            pr = temp;
        }
    }
    std::cout << pr;
    return 0;
}

P.S. I did not implement the nice suggestion here regarding creation of objects, as during the assignment submission, I am supposed to make objects at run-time.


texts: How can I make this Euler/RK4 implementation more elegant?

texts:
One of the things that I'm doing to teach myself is converting some numerical methods from existing Python code (they seem to me to lend themselves to functional programming quite well).

I'd like to know how I can improve the general style of my code.
In particular, I feel like I'm overusing brackets, that I should be able to use more inbuilt functions (that I'm not aware of), and that I may be misusing the let statement.

Background

A quick refresher on the terminology I'm using (slightly different to wiki*):

Given a state vector \$\mathbf{x}\$, and a function vector \$\mathbf{f}(\mathbf{x})\$ (which is our system of first order differential equations), we want to iterate using step size \$h\$ until a given target \$t(\mathbf{x})\$ is reached.

*Different in that I don't make the useless distinction between dependent and independent variables that some texts, and wiki, use.

Euler Method

For this method, we use a very simple approximation:

$$
\mathbf{k_1} = \mathbf{f}(\mathbf{x}) \\
\mathbf{x}_{new} = \mathbf{x} + h*\mathbf{k_1}
$$

In the code, I use what is basically a 'reverse map' (ie, apply a list of functions to a single argument) that I found online:

pam :: [a -> b] -> a -> [b]
pam f x = map g f
    where g h = h x

And then we define the euler method itself:

euler :: Fractional a => [([a] -> a)] -> ([a] -> Bool) -> a -> [a] -> [a]
euler fs target h xs
    | target xs = xs
    | otherwise = let k1 = pam fs xs
                      xn = (+.) xs (map (h *) k1)
                  in euler fs target h xn
                  where (+.) = zipWith (+)

RK4 (4th order Runge-Kutta)

For this method, the approximation is a bit more complex:

$$
\mathbf{k_1} = \mathbf{f}(\mathbf{x}) \\
\mathbf{k_2} = \mathbf{f}(\mathbf{x} + \frac{h}{2}\mathbf{k_1}) \\
\mathbf{k_3} = \mathbf{f}(\mathbf{x} + \frac{h}{2}\mathbf{k_2}) \\
\mathbf{k_4} = \mathbf{f}(\mathbf{x} + h*\mathbf{k_3}) \\
\mathbf{x_{new}} = \mathbf{x} + \frac{h}{6}(\mathbf{k_1} + 2*\mathbf{k_2} + 2*\mathbf{k_3} + \mathbf{k_4})
$$

And the code I came up with:

rk4 :: Fractional a => [([a] -> a)] -> ([a] -> Bool) -> a -> [a] -> [a]
rk4 fs target h xs
    | target xs = xs
    | otherwise = let k1 = pam fs xs
                      k2 = pam fs ((+.) xs (map (h / 2 *) k1))
                      k3 = pam fs ((+.) xs (map (h / 2 *) k2))
                      k4 = pam fs ((+.) xs (map (h *) k3))
                      dx = map (h / 6 *) (foldr (+.) (repeat 0) [k1, k2, k2, k3, k3, k4])
                      xn = (+.) xs dx
                  in rk4 fs target h xn
                  where (+.) = zipWith (+)

A very simple set of functions to test this:

target :: (Fractional a, Ord a) => [a] -> Bool
target [x,y] = x >= 1.4

f1 :: Fractional a => [a] -> a
f1 [x,y] = 1

f2 :: Fractional a => [a] -> a
f2 [x,y] = x + 3 * y

Usage example:

euler [f1,f2] target 0.0001 [0,0]

I'm particularly unhappy with the need to define +. for element-wise addition (surely that exists, but Google didn't help me), and the way in which I added the various k values to create dx.

I also feel like I'm declaring too many variables (if that's what they're called?) in the let statement.

Oh, and my brackets are breeding like rabbits.


texts: Bernoulli trials using a condition in a vectorized operation

texts:
I was wondering how to vectorize the following code instead of using the for-loop and still be able to check for a condition.

# n is a numpy array which keeps the 'number of trials' parameter for the binomial distribution
# p is a numpy array which keeps the 'probability of success' parameter for the binomial distribution
# baf is a numpy array that will keep the results from the np.random.binomial() function

baf = np.repeat(np.nan, n.size)
for index, value in enumerate(n):
    if value >= 30:
        baf[index] = np.random.binomial(value, p[index]) / value

My own vectorized solution is:

baf = np.repeat(np.nan, n.size)
indices = np.where(n >= 30)[0]
baf[indices] = np.random.binomial(n[indices], p[indices]).astype(float) / n[indices]

However, I was wondering whether there are other more efficient solutions?


texts: Word VBA function to find a specified heading & return its text as a string

texts:
In this post, I asked for an overall review of a script to auto-generate table captions, because it was running relatively slowly. I've used Debug.Print to isolate the problem, and this function takes the longest (at 16 seconds).

The purpose of the function is to find the heading of a specified style that the selected text falls under. It loops back through each paragraph to see if it's the right style. When it finds it, it returns the paragraph text as a string (which the larger script uses to generate the table caption).

Any suggestions for improvement are welcome, but I'd specifically like performance improvement suggestions, as well as feedback on how long a function like this should take (i.e., is it slow or am I just impatient?)

Public Function FindHeading(strHeadLevel As String) As String
'Gets the heading level as an input and finds the closest heading of that level before the selection.

    Dim rngSelection As Range
    'the initial selection

    Dim rngPrev As Range
    'The current paragraph to be evaluated.

    Set rngSelection = Selection.Range
    Set rngPrev = rngSelection.Previous(wdParagraph, 1)

    'MsgBox (rngPrev.Text)

    Do While rngPrev.Style <> strHeadLevel

        If ActiveDocument.Range(0, rngPrev.Paragraphs(1).Range.End).Paragraphs.Count > 1 Then
            Set rngPrev = rngPrev.Previous(wdParagraph, 1)
            'MsgBox ("rngPrev Style =  " & rngPrev.Style & vbCr & "Text = " & rngPrev.Text)
        Else
            'MsgBox ("Heading not found")
            Exit Do
        End If

    Loop

    If rngPrev.Style = strHeadLevel Then
        FindHeading = rngPrev.Paragraphs(1).Range.Text
    Else
        FindHeading = "No heading found"
    End If

End Function


texts:
i'm trying to build an API wrapper class, that sends requests in a JSON format. the sample request format is something like this:

{
  "items": [
    {
      "brand": "brand",
      "idCategory": "idCategory",
      "idItem": "idItem",
      "attributes": [
        {
          "idUda": "idUda",
          "price": "price"
        },
        {
          "idUda": "idUda",
          "price": "price"
        }
      ],
      "description": "description",
      "skus": [
        {
          "price": {
            "offer": "offer",
            "default": "default"
          },
          "stock": {
            "available": "available",
            "amount": "amount"
          },
          "gtin": "gtin",
          "images": [
            "image",
            "image"
          ],
          "idSku": "idSku",
        }
      ]
    }
  ]
}

my first thought was to create an object for each element of the JSON request that is an array, something like this:

        $attr1 = new Attribute;
        $attr1->setIdUda('xxx')
        ->setPrice('99999');

        $price = new Price;
        $price->setOffer('teste')
        ->setDefault('99.99');

        $stock = new Stock;
        $stock->setAvailable(true)
        ->setAmount('9999');

        $product = new Product;
        $product->setBrand('Apple')
        ->setIdCategory('500')
        ->setIdItem('9999')
        ->setAttributes($attr1)
        ->setDescription('nice product')
        ->setSkus($price);
        ->setSkus($stock);

and each one these objects have a toArray() method, that returns an associative array, eg:

class Price {

        //getters and setters....

            function toArray() {
                return array(
                    'offer' => $this->offer,
                    'default' => $this->default
                )
            }
        }

inside of the Product class all these attributes setters are grouped to form an array so i can convert it to the JSON format later.

class Product {
        //.....
    public function setAttributes(Attribute $attributes) {

        $this->attributes['attributes'][] = $attributes->toArray();
                    return $this;
    }
}

but it still feels like it's highly coupled, because i have to set the key of each one of these arrays, in order to form the JSON data.

What would be the "best" approach to make this code easier to maintain? should i use classes only for some attributes? how should i consider it?


texts:
Recently I made an basic port of the JavaScript Promise construct to Python. Here's the basic code:

class Promise:
    def __init__(self, fn):
        self.value = None
        self.errors = []
        self._state = "unfullfilled"

        def resolve(val):
            if self._state == "settled":
                return
            self.value = val
            self._state = "settled"
        def reject(err):
            if self._state == "settled":
               return
            self.errors.append(err)
            self._state = "settled"
        fn(resolve, reject)

    def catch(self, fn):
        if self.errors:
            for i in self.errors:
                fn(i)
                self.errors.remove(i)
        return self

    def then(self, fn):
        if not self.errors:
            fn(self.value)
        return self

    @staticmethod
    def resolve(val):
        def g(resolve, reject):
            resolve(val)
        return Promise(g)

    @staticmethod
    def reject(val):
        def g(resolve, reject):
            reject(val)
        return Promise(g)

What could I improve in this code?
Besides that, are there any bugs in this code?


texts:
I have some code that has three lists, and it then checks the index of the second list against the index of the first as long as the first list has six elements. The code will then append to the third list if part of a string matches in the index of the first list. If the string does not match, it will append a message. I am hoping to find a better, more Pythonic way of writing my algorithm. Here is my code:
L1 = ["first = 1st","second = 2nd","third = 3rd","fourth = 4th","sixth = 6th",
  "first = A","second = B","third = C","fifth = E","sixth = F",
  "second = W","third = X","fourth = Y","fifth = Z","sixth = AA","first = BB"]
L2 = ["first","second","third","fourth","fifth","sixth"]
L3 = []

#Used in case a list has less than six elements
if len(L1) % 6 != 0:
    L1.append("Missing_Data")

c = 0
for i in L1:
    cont = True
    while cont:
        if L2[c] in i:
            L3.append(i.split("= ")[-1])
            c += 1
            if c < len(L2):
                cont = False
            else:
                c = 0
                cont = False
        else:
            L3.append("Missing_Data")
            c += 1
            if c < len(L2):
                continue
            else:
                c = 0
                break

This code works for what I want it to do but I think its too long. Any help in making this code more Pythonic would be greatly appreciated. Thanks in advance.


texts:
So I'm going to publish this small project on GitHub and I thought I'd better do a makefile for it. The source code consists of

1 Java Class
1 Native JNI module written in C
1 stdlib wrapper object written in C (for LD_PRELOAD)

The purpose of the Makefile is to compile the two shared objects from the C-Source.

Here it is

CC=gcc
CFLAGS=-nostartfiles -fpic -shared -ldl -D_GNU_SOURCE -Wall -Werror
OUT=bld
OUTFILES = $(OUT)/bind.so $(OUT)/bindsetter.so
JNI_AUTO_HEADER=$(OUT)/com_daftdroid_droidlib_bind_ClientBind.h

#Two locations needed to get all the JNI header files
JNI_INCLUDE=/usr/lib/jvm/java-8-oracle/include \
    /usr/lib/jvm/java-8-oracle/include/linux

#Add the includes to the compiler flags
CFLAGS+=$(foreach d, $(JNI_INCLUDE), -I$d)

all: $(OUTFILES)

$(OUTFILES): $(OUT)/%.so: %.c $(JNI_AUTO_HEADER)
    $(CC) $(CFLAGS) -c $< -o $@

$(JNI_AUTO_HEADER): ClientBind.java
    javac ClientBind.java -d $(OUT) -h $(OUT)

.PHONY: clean
clean:
    rm bld/* -rf

So some questions: CC=gcc is this a bit presumptuous? CFLAGS - well these all assume GCC too. What about inflicting -Werror on people - on my computer there are no warnings as it stands.

I hate this: JNI_INCLUDE=/usr.... that is seriously installation dependent. What's a better way of doing this?

I have this header file JNI_AUTO_HEADER that javac can generate from the .java source, so therefore I consider it a build artifact which the makefile is responsible for. Do you agree? Also I've made all of the .so files dependent on JNI_AUTO_HEADER but hey, there's only two of them so I guess it's not worth worrying about.

Also I'm not sure if there's a better way of doing this in my source file:

// This include generated in the build directory at compile time
#include "bld/com_daftdroid_droidlib_bind_ClientBind.h"

(without getting into a much more complex build process)

Any other comments welcome.


texts:
I have started teaching myself MySQL and created a simple application which asks for user input stores it and displays it. Can you guys please let me know if there is something I am doing wrong or any tips on what can be improved? I want to build a student management application which will use a MySQL database and want to make sure I know the basics.

I have a class that holds connection method and closing methods:

import java.sql.*;

public class DBUtil {

// Connecting to database.
public static Connection getConnection() throws SQLException {
String url = "jdbc:mysql://localhost:3306/database";
String user = "root";
String pass = "admin";

Connection connection = DriverManager.getConnection(url, user, pass);
    return connection;
}

// Close database connection.
public static void closeConnection(Connection con) {
    try {
        if(con != null) {
            con.close();
            System.out.println("Database Connection Closed!");
        }
    }catch(Exception e) {
        e.printStackTrace();
    }
}
// Close Prepared Statement.
public static void closePrepStatement(PreparedStatement pStmt) {
    try {
        if(pStmt != null) {
            pStmt.close();
            System.out.println("Prepared Statemet Closed");
        }
    }catch (Exception e) {
        e.printStackTrace();
    }
}
// Close Result Set.
public static void closeResSet(ResultSet rSet) {
    try{
        if(rSet != null) {
            rSet.close();
            System.out.println("Result Set Closed");
        }
    }catch (Exception e) {
        e.printStackTrace();
    }
}
}

This class gets the input, stores it, and displays it:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;

// SQL variables defined
public class Source {
DBUtil dbConnection = new DBUtil();
Scanner input = new Scanner(System.in);
Connection connection = null;
PreparedStatement pStatement = null;
ResultSet rSet = null;

// Constructor
public Source() {
    getInput();
    displayData();
}
// Getting user input and saving to database
private void getInput() {

    System.out.println("What is your name?");
    String fName = input.nextLine();
    System.out.println("What is your second name?");
    String sName = input.nextLine();
    System.out.println("What is your proffesion?");
    String userProff = input.nextLine();

    try {
         connection = DBUtil.getConnection();
         String sqlQuery = "INSERT INTO employees_info (firstname,  secondname, proffesion) VALUES (?, ?, ?)";
         pStatement = connection.prepareStatement(sqlQuery);
         pStatement.setString(1, fName);
         pStatement.setString(2, sName);
         pStatement.setString(3, userProff);
         pStatement.executeUpdate();
         System.out.println("Record saved!");

    }catch(Exception e) {
        e.printStackTrace();
    }finally {
        DBUtil.closePrepStatement(pStatement);
        DBUtil.closeConnection(connection);
    }
}
// Get data from database and display
private void displayData() {
    System.out.println("Current records from the database:");

    try {
        connection = DBUtil.getConnection();
        String sqlQuery = "SELECT * FROM employees_info";
        pStatement = connection.prepareStatement(sqlQuery);
        rSet = pStatement.executeQuery();
        while(rSet.next()) {
            System.out.println("");
            System.out.println("Next Record:");
            System.out.println(rSet.getInt("ID"));
            System.out.println(rSet.getString("firstname"));
            System.out.println(rSet.getString("secondname"));
            System.out.println(rSet.getString("proffesion"));
        }
    }catch (Exception e) {
        e.printStackTrace();
    }finally {
        DBUtil.closeResSet(rSet);
        DBUtil.closePrepStatement(pStatement);
        DBUtil.closeConnection(connection);
    }
}

}


texts: Java recursive sort verification function for a linked list

texts:
It should return true, if there is no element that follow or the following elements are greater than their predecessors.
public class Element {
    private int value;
    private Element next;

    public boolean isSorted(){
        if (this.next == null)
            return true;
        else return (this.value < this.next.value && this.next.isSorted());
    }
}

What do you guys think of it?


texts: Finding difference between date now and last comment

texts:
I want users to wait 9 minutes after their last comment. I have written this code. It works but do you think this is practical? Is there a simpler solution?

$now = new DateTime( date( 'Y-m-d H:i:s' ) );
$lastPost = new DateTime( '2016-01-08 13:16:59' );
$diff = $lastPost->diff( $now );

if ( $diff->format( '%Y-%m-%d %H' ) == '00-0-0 00' ) {
    if ( $diff->format( '%i' ) < 9 ) {
         echo $diff->format( '%i minuts left or ahead' );
    }
}


texts:
My A* Algorithm in C++ is pretty slow. I'm not sure if it is because of a bad implementation or just because I have way too many Nodes (I have a field of 256x256 Nodes). It takes the algorithm about 5 seconds to complete.

I'm using a vector for the open and closed List. For the openList I use std::make_heap to sort the Nodes.

/************
* Method to calculate the shortes path
*
**/
std::vector<Position*> Pathfinding::getShortestPath(MapField* startField, MapField* targetField) {

PathNode* startNode = new PathNode(startField, argosMap);
openList.push_back(startNode);

push_heap(openList.begin(), openList.end(), ComparePathNodePointer());

while(!(openList.empty())){

    make_heap(openList.begin(), openList.end(), ComparePathNodePointer());
    PathNode* currentNode = openList.front();

    pop_heap(openList.begin(), openList.end(), ComparePathNodePointer());

    openList.pop_back();
    make_heap(openList.begin(), openList.end(), ComparePathNodePointer());
    if(*(currentNode->getMapField()) == *targetField){
        Logger::getInstance()->log("Target found");
        return buildpath(currentNode);
    }
    expandNode(currentNode, targetField);
    closedList.push_back(currentNode);
}
return buildpath(startNode);
};

/************
* expands a PathNode and adds it to the openList if it meets the conditions of A*
*
**/
void Pathfinding::expandNode(PathNode* currentNode, MapField* targetField) {

std::vector<PathNode*> children = currentNode->getChildren();
std::vector<PathNode*>::iterator child;

for (child = children.begin(); child != children.end(); child++) {

    Utils::PointerValuesEquals<PathNode> childToFind = {*(child)};

    //check if Node is alreay in closedList
    if(std::find_if(closedList.begin(), closedList.end(), childToFind) == closedList.end()) {
        double actualCost = (*child)->getCostOfField(currentNode)+currentNode->getActualCost();

        //check if Node is already in openList, if so, check if the value is better if it is better, expand the new Node otherwise use the existing Node
        if(!((std::find_if(openList.begin(), openList.end(), childToFind) != openList.end()) && actualCost >= (*std::find_if(openList.begin(), openList.end(), childToFind))->getActualCost())){
            double estimatedCosts = actualCost+(*child)->getCostToTarget(targetField);

            //when Node is already in Openlist update it, if not add the new Node
            if(std::find_if(openList.begin(), openList.end(), childToFind) != openList.end()) {
                (*std::find_if(openList.begin(), openList.end(), childToFind))->setParent(currentNode);
                (*std::find_if(openList.begin(), openList.end(), childToFind))->setActualCost(actualCost);
                (*std::find_if(openList.begin(), openList.end(), childToFind))->setTotalCost(estimatedCosts);

                make_heap(openList.begin(), openList.end(), ComparePathNodePointer());

            } else {
                (*child)->setParent(currentNode);
                (*child)->setActualCost(actualCost);
                (*child)->setTotalCost(estimatedCosts);
                this->openList.push_back(*child);
                push_heap(openList.begin(), openList.end(), ComparePathNodePointer());
                make_heap(openList.begin(), openList.end(), ComparePathNodePointer());
            }
        }
    }
}
};


texts: Efficient way of finding perfect squares

texts:
I was trying to solve a problem which needed you to count the number of perfect squares in the given range:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int isPerfectSquare(int x)
{
    float s = sqrt(x);
    if (fmod(s,1) ==0)
        return 1;
    else
        return 0;
}
int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int testcases;
    unsigned int a,b;
    scanf("%d",&testcases);
    while(testcases--)
        {
        int counter =0;
        scanf("%d %d",&a,&b);
        unsigned int i;
        for(i=a;i<=b;i++)
            {
                int last_digit = i%10;
            if( (last_digit == 2) || (last_digit == 3) || (last_digit == 7) || (last_digit == 8) )
                continue;
            else
            {
                if (isPerfectSquare(i))
                    counter++;
            }
        }
        printf("%d\n",counter);
    }
    return 0;
}

However, this code fails for certain test cases due to a timeout. I found that perfect squares do not end with a 2 or 3 or 7 or 8 so I ignored such values. Yet, I'm unable to solve this problem within the required run time.

I have found similar questions here, but either they were not in C or they didn't have answers that were quite relevant to C.

Could you suggest a way that I can optimize this code so that it could run faster?