texts: Ensuring that events raised by system.diagnostics process class happen in the parent thread

texts:
I'm quite new to threading primitives in C# and was hoping you might be able to suggest improvements to this. I need to ensure that the XXX call below happens within the calling thread (XXX is a foreign call into a thread-unsafe library), so I used a queue here. It seems a bit like there should be a better primitive for this. Maybe delegates are applicable somehow? I don't understand delegates.

I also have to wonder if I've gotten this whole scheme right in the first place! Maybe there's a deadlock I'm not seeing. Threading is so tricky.

As an additional restriction, it's very important that this works on .NET 3.5.

    public void RunProc(AutoResetEvent killSubProc)
    {
        using (Process process = new Process())
        {
            var timeout = 8000;
            var channel = new Queue<string> {};

            process.StartInfo.FileName = "blah.exe";
            process.StartInfo.Arguments = @"stuff";

            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.EnableRaisingEvents = true;

            using (AutoResetEvent channelWaitHandle = new AutoResetEvent(false))
            {
                process.OutputDataReceived += (sender, e) => {
                    if (e.Data != null)
                    {
                        lock (channel) { channel.Enqueue("STDOUT"); channel.Enqueue(e.Data); }
                        channelWaitHandle.Set();
                    }
                };
                process.ErrorDataReceived += (sender, e) =>
                {
                    if (e.Data != null)
                    {
                        lock (channel) { channel.Enqueue("STDERR"); channel.Enqueue(e.Data); }
                        channelWaitHandle.Set();
                    }
                };
                process.Exited += (sender, e) =>
                {
                    lock (channel) { channel.Enqueue("EXIT"); }
                    channelWaitHandle.Set();
                };

                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                bool running = true;
                while (running)
                {
                    int idx = WaitHandle.WaitAny(new WaitHandle[] {killSubProc, channelWaitHandle});
                    if (idx == 0)
                    {
                        process.Kill();
                        running = false;
                    }
                    else
                    {
                        lock (channel)
                        {
                            while (channel.Count > 0)
                            {
                                var item = channel.Dequeue();
                                XXX(item);

                                if (item == "EXIT")
                                {
                                    running = false;
                                }
                            }
                        }
                    }
                }
            }
        }
    }


texts:
How could I improve this algorithm? The goal is to organize matches between sport teams such that:

Each team affront each other
A minimum number of team should start a match after just finishing one

The interesting part is here:

myPerm [] _ = [[]]
myPerm xs threshold = [x:ys | x <- xs,
                    ys <- take nbToKeep $
                            filter
                              (\ts -> price ts <= threshold)
                              (myPerm (delete x xs) threshold)]

It is a way to remove from the enumeration of permutations all sub-sequences not being good enough. Even with this, the problem for 6 teams is very long to resolve.

Here is the complete program:

import System.Environment
import Data.Ord
import Data.List

-- The number of items we keeps to only search
-- from bests local results
nbToKeep :: Int
nbToKeep = 10

type Match = (Int,Int)
type MatchSequence = [Match]

-- Give all sport matches in the form
-- (1,2) => match between Team 1 and Team 2
all_matches :: Int -> MatchSequence
all_matches n = [ (x,y) | x <- [1..n], y <- [1..n], x < y ]

-- A price function for sequence of matches
-- 0 if no team make a match just after finishing one
-- Possible with 5 teams not for 3 and 4
price :: MatchSequence -> Int
price ((x,y):((z,t):rest))
    | x==z = 1 + price ((z,t):rest)
    | x==t = 1 + price ((z,t):rest)
    | y==z = 1 + price ((z,t):rest)
    | y==t = 1 + price ((z,t):rest)
    | otherwise = price ((z,t):rest)
price _ = 0

-- Simple adjoin the price to a MatchSequence
addPrices :: MatchSequence -> (Int,MatchSequence)
addPrices xs = (price xs, xs)

-- Instead of listing _all_ permutations
-- Just keep the one such that its subsequece price
-- is under the threshold
myPerm [] _ = [[]]
myPerm xs threshold = [x:ys | x <- xs,
                    ys <- take nbToKeep $
                            filter
                              (\ts -> price ts <= threshold)
                              (myPerm (delete x xs) threshold)]

-- Keep the best one under some threshold
find_best_under n threshold = take nbToKeep $
                                sortBy (comparing fst) $
                                    map addPrices ( myPerm (all_matches n) threshold)

isNonEmpty [] = False
isNonEmpty _ = True

-- Try to test with the minimal threshold (0)
-- Then repeat until a solution is found for some threshold
find_best n = head $ filter isNonEmpty $ map (find_best_under n) [0..]

showMatchSequence :: MatchSequence -> String
showMatchSequence [] = []
showMatchSequence ((team1,team2):[]) = show team1 ++ "-" ++ show team2
showMatchSequence ((team1,team2):xs) = show team1 ++ "-" ++ show team2 ++ "   " ++ showMatchSequence xs

showResult :: (Int,MatchSequence) -> String
showResult (score,xs) = show score ++ " collisions: " ++ showMatchSequence xs

main = do
    args <- getArgs
    mapM_ (putStrLn . showResult) $ find_best (read (head args)::Int)

I know I do a linear number of computation using price, while, I shouldn't need it if I integrate the price computation inside the myPerm function.

I take all advice, concerning not only style but also sytactic optimisations. For example, I am pretty sure I could have used a Monad to find the first n for which there is a solution.


texts: Reading from a file and connect all data in one big data than to use generators

texts:
Is there better way to read from a file and connect all data in one big data than to use generators?

At the moment, I do the following:

use generators to read data from files.
use NumPy to pack all files in 3D array.
use pandas to stack it to 2D array so readable for next operations (e.g. plotting).

In my example:

I split reading from file operations generators in 2 modules, and have a third module for reading names (file is not connected with others generators_module). In the last separate file I import that generators_modules, and make arrays with NumPy, then pandas.

In the code of modules I use os.walk to read from files, regex to read only that data which is needed.

In the code of making arrays with NumPy, pandas:

I enter variable parameters needed to get data with generator_modules
I pass from generators to array with code:

xdata=np.array( [(float(line['PRESSURE']), float(line['CURVE'])) for line in dt_cols] )

I have four python files, as below:

module1 (gen_enter):

import re, matplotlib as mpl, matplotlib.pyplot as plt, os, fnmatch

def gen_find(filepat,top):
    for path, dirlist, filelist in os.walk(top):
        for name in fnmatch.filter(filelist,filepat): yield os.path.join(path,name)

def gen_open(filenames):
    for name in filenames:
        if name.endswith(".XL"): yield open(name)
        else: pass

def gen_get(sources):
    for s in sources:
        for item in s:  yield item

def gen_grep(pattern, fileparse):
    for line in fileparse:
        inputlines = line[:].strip().replace(';',' ')
        if pattern.search(inputlines):  yield inputlines
        else: pass

def field_map(dictseq,name,func):
    for d in dictseq:
        d[name] = func(d[name])
        yield d

module2 (gen_returnlines):

from gen_enter import *

def lines_from_dir(filepat, dirname):
    findnames = gen_find(filepat, dirname)
    openfiles = gen_open(findnames)
    getlines = gen_get(openfiles)
    #patlines = gen_grep(pattern, getlines)
    return getlines

module3 (gen_shownames):

import re, matplotlib as mpl, matplotlib.pyplot as plt, os, fnmatch

def gen_shownames(filepat,top):
    for path, dirlist, filelist in os.walk(top):
        for name in fnmatch.filter(filelist,filepat): yield name

The main code:

import numpy as np, pandas as pd, os, fnmatch, re
from pylab import *
from gen_returnlines import *
from gen_shownames import *

def dict_cols(lines):
        groups = (patlines.match(line) for line in getlines)
        tuples  = (group.groups() for group in groups if group)
        colnames = ('PRESSURE','CURVE')
        line = (dict(zip(colnames,t)) for t in tuples)
        line = (field_map(line,"PRESSURE", lambda s: float(s)))
        line = (field_map(line,"CURVE",float))
        return line

dir='C:\\Users\\REDHOOD\\workspace\\Politechnika_python\\\silniki\\files' #note: all files from ../files/
pattern = re.compile(r'(\d{3}\.\d{1})\D*(\d{3}\.\d{1})\D*')
pats = '(\d{3}\.\d{1})\D*(\d{3}\.\d{1})\D*'
patlines = re.compile(pats)

if __name__ == '__main__':
    names = gen_shownames('*', dir)
    getlines = lines_from_dir('*',dir)
    dt_cols = dict_cols(getlines)

xdata = np.array( [(float(line['PRESSURE']), float(line['CURVE'])) for line in dt_cols] )
xrdata = np.reshape(xdata,(17,360,2))

datapanel = pd.Panel(
                  xrdata,
                  items=[k for k in names],
                  )

datapaneldf = datapanel.to_frame()       #pressure na curve -> 360 stopni


texts: Generating sequence that uses the previous outcome for the current

texts:
I do not like to use while loops in Ruby. I was wondering how I can generate a "squared sequence" (e.g., squares the first input, then squares the outcome, etc.) in a more idiomatic Ruby way than this one:

value = 2
while value < 10000
    puts value = value**2
end

# => 4
#    16
#    256
#    65536

I have a suspicion that there is a way/method to do this, but I do not know which one. I hope someone can point me in the right direction.


texts: A server response written in node/express/mongodb: does this look right?

texts:
This is my very very very first attempt to write anything meaningful in node. The client side is a simple form that has login, workspace, and simply saves them onto the database. It would have been a 5-liner in PHP!

My question really is: does this code look sane/good? I am trying to avoid using async.js for now, just because I want to get my hands dirty a little to start with.

A few notes:

I want to check if workspace and user names are taken first, but I want to check for BOTH in case they are taken
There is still a slight race condition here: what two users submit different usernames and same workspace names at the same time? OK it's unlikely, but one of them will end up failing (one of them will be workspace-less). How would you address it? Simply deleting the user just created? Or...?
There is a lot of indentation here. I know that it's a known issue with node... I cannot really use "return" as a trick to interrupt execution, because it's often used in an anonymous function context. So...
I sometimes go next("Bad error here"). I plan on writing an error handler in Connect to handle these (I will probably log things onto the database).

Here we go...

// Helper function. The javascript on the other side calls this with Ajax, and expects
// a hash with "response" (can be OK or ERRORS) and a "errors" vector
var serverResponse = function(res, errors){
  if(errors.length){
    res.json( { response: 'ERRORS', errors: errors } , 200)
    console.log("Sent ERROR");
  } else {
    res.json( { response: 'OK' } , 200)
    console.log("Sent OK");
  }
}

// The actual call
exports.nonApiRegister = function(req, res, next){

  // ***** UNINDENTED ON PURPOSE: artificial delay
  setTimeout(function(){
  // *****

  var errors = [];
  var Workspace = mongoose.model("Workspace");
  var User = mongoose.model("User");

  User.findOne( { login: req.body.login}, function(err, docs){

    // Log database error if it's there
    if(err){
      next("Database error fetching user"); // TODO: add error handler
    } else {
      // If the user exists, add it to the error vector BUT keep going
      if(docs){
        errors.push({ field:'login', message: 'Login name taken, sorry!' } );
      }
      Workspace.findOne({ name: req.body.workspace }, function(err, docs){
        if(err){
          next("Database error fetching workspace");
        } else {
          if(docs){
            errors.push( {field: "workspace", message: "Workspace taken, sorry!"} );
          }

          if(errors.length != 0){
            serverResponse(res, errors);
          } else {

            //
            // AT THIS POINT, UNLESS SOMETHING JUMPS ON US, both user and workspace are available
            //

            // User doesn't exist: create it
            var u = new User();
            u.login = req.body.login;
            u.password = req.body.password[0];
            u.workspaceIds = [];

            u.save( function(err) {
              if(err){
                next("Database error saving user");
              } else {
                var w = new Workspace();
                w.name = req.body.workspace;
                w.activeFlag = true;
                w.ownerUserId = u._id;
                w.countryId = null;
                w.save( function(err){
                  if(err){
                    next("Database error saving workspace. WATCH OUT: user " + u.login + " doesn't have a workspace!");
                  } else{
                    serverResponse(res, errors);
                  }
                })
              }
            })
          }
        }
      })
    }
  });

  //
  } , 500); // Artificial timeout
  //
}


texts: Wrapping the classList API to add/remove array of classes

texts:
I've written a function that wraps the classList API, allowing you to pass an array of classes to add/remove, or the variable arguments already supported by classList.

The methods are the following:

var flatten = function(array) {
    return Array.prototype.concat.apply([], array);
};

var classMethod = function(method) {
    return function(element /*, classes... */) {
        return flatten(Array.prototype.slice.call(arguments, 1)).forEach(function(klass) {
            element.classList[method](klass);
        });
    }
};

var addClass = classMethod('add');
var removeClass = classMethod('remove');

Usage:

var elem = document.querySelector('.box');

addClass(elem,     'class1');
addClass(elem,     'class2', 'class3');
addClass(elem,    ['class2', 'class3']);

removeClass(elem,  'class1');
removeClass(elem,  'class2', 'class3');
removeClass(elem, ['class2', 'class3']);

I'm wondering if there's some better way to implement this function, say without using the forEach call and instead using Function.prototype.apply, but I get a TypeError: Illegal invocation when trying to refactor this into, say:

var classMethod = function(method) {
    return function(element /*, classes... */) {
        element.classList[method].apply(element, flatten(Array.prototype.slice.call(arguments, 1)));
    }
};

Is it possible to write this more succinctly, whilst keeping all of the use cases?


texts:
I wrote up a small script to calculate the answer to Project Euler Problem 5:

  2520 is the smallest number that can be divided by each of the numbers
  from 1 to 10 without any remainder.

  What is the smallest positive number that is evenly divisible by all
  of the numbers from 1 to 20?

I'm wondering if this algorithm can be improved or made more efficient:

def divisible_by(num, den_set):
    if not den_set: return True
    elif not num % den_set.pop():
        return divisible_by(num, den_set)
    else: return False

def smallest(den_count):
    i = 1
    den_set = list(range(1, den_count))
    while not divisible_by(i, den_set):
        den_set = list(range(1, den_count))
        i += 1
    return i

print smallest(20)


texts: Using boost::mpi to take the Euclidean norm of a vector

texts:
I am learning MPI (via boost::mpi) and wrote this program that takes the euclidean norm of a 1-D vector (represented as an array here.) I want to make sure that I am using boost::mpi properly, in terms of both functions used and the way the code is parallelized.

The sample below is the program with just the norm functionality; it takes no input from the user and always uses the same seed for consistency reasons. Another limitation is that the vector size must be evenly divisible into the MPI world size.

I appreciate any comments and am thankful for your time.

#include <boost/mpi.hpp>
#include <chrono>
#include <cmath>
#include <iostream>
#include <numeric>
#include <random>
#include <utility>
#include <vector>

int main() {
  boost::mpi::environment env;
  boost::mpi::communicator world;
  //unsigned long TWIST_SEED = std::chrono::system_clock::now().time_since_epoch().count();
  unsigned long TWIST_SEED = 2;
  unsigned long VECT_SIZE = 10;
  double *main_vector = new double[VECT_SIZE];
  if (world.rank() == 0) {
    std::mt19937 generator(TWIST_SEED);
    std::uniform_real_distribution<double> dis(-222222.22, 222222.22);
    for (int i = 0; i < VECT_SIZE; i++) {
      main_vector[i] = dis(generator);
    }
  }
  int n_bar = VECT_SIZE / world.size();
  if (world.rank() == 0) {
    if (VECT_SIZE <= 10) {
      std::cout << "Your vector is small enough to output. It is: \n{";
      for (int i = 0; i < VECT_SIZE; i++) {
        if (i == VECT_SIZE - 1) {
          std::cout << main_vector[i];
        } else {
          std::cout << main_vector[i] << ", ";
        }
      }
      std::cout << "}" << std::endl;
    }
  }
  double *local_vector = new double[n_bar];
  boost::mpi::scatter(world, main_vector, local_vector, n_bar, 0);
  std::vector<double> dot;
  double local_dot = 0.0;
  for (int i = 0; i < n_bar; i++) {
    local_dot += local_vector[i] * local_vector[i];
  }
  boost::mpi::gather(world, local_dot, dot, 0);
  if (world.rank() == 0) {
    std::cout << "The norm is " << sqrt(std::accumulate(dot.begin(), dot.end(), 0.0)) << std::endl;
  }
  delete[] main_vector;
  return 0;
}


texts:
I'm working through some exercises to sharpen my Ruby skills. The following code is how I solved this particular question. I'd like to know what other developers think of this solution. I'm self taught, which means: I'm not getting any feedback as I learn, so I just want to make sure that I'm learning the right way to do things. And I'd like to get a gauge of what professional developers think of my code.

  Ranking System
  [1-terrible] [2-not good] [3-ok] [4-good] [5-very good]

Is the answer code elegant? (score and feedback)
What tips can you suggest to improve the answer?
How's the readability of the code? (score and feedback)
Can you suggest a simpler and alternative answer?

Ruby

class Book
  def title
    @title
  end

  def title=(title)
  special_words = %w(and in the of a an)
  formatted_title = []

    @title = title.split.each_with_index do |w,i|
      case
      when i == 0
        formatted_title << w.capitalize

      when i > 0 && !special_words.include?(w)
        formatted_title << w.capitalize

      when special_words.include?(w)
        formatted_title << w
      end
    end

  @title = formatted_title.join(" ")
  end
end

Rspec

describe Book do

  before do
    @book = Book.new
  end

  describe 'title' do
    it 'should capitalize the first letter' do
      @book.title = "inferno"
      @book.title.should == "Inferno"
    end

    it 'should capitalize every word' do
      @book.title = "stuart little"
      @book.title.should == "Stuart Little"
    end

    describe 'should capitalize every word except...' do
      describe 'articles' do
        specify 'the' do
          @book.title = "alexander the great"
          @book.title.should == "Alexander the Great"
        end

        specify 'a' do
          @book.title = "to kill a mockingbird"
          @book.title.should == "To Kill a Mockingbird"
        end

        specify 'an' do
          @book.title = "to eat an apple a day"
          @book.title.should == "To Eat an Apple a Day"
        end
      end

      specify 'conjunctions' do
        @book.title = "war and peace"
        @book.title.should == "War and Peace"
      end

      specify 'prepositions' do
        @book.title = "love in the time of cholera"
        @book.title.should == "Love in the Time of Cholera"
      end
    end

    describe 'should always capitalize...' do
      specify 'I' do
        @book.title = "what i wish i knew when i was 20"
        @book.title.should == "What I Wish I Knew When I Was 20"
      end

      specify 'the first word' do
        @book.title = "the man in the iron mask"
        @book.title.should == "The Man in the Iron Mask"
      end
    end
  end
end


texts:
I've written this little countdown script to count until the end of our school days.

Now, that was written quickly, badly remembering modulo from a few years ago, and I don't think that's very optimized.

I thought about updating only the seconds and check if it needs to update the minute too, etc. But it wouldn't be accurate as setTimeout is not (depending if the browser lags, etc).

(function() {
    //the variable block here seems kinda weird, but whatever toots your horn
    var el = document.getElementById('countdown'),
        endDate = new Date('March 30, 2012 18:10:00'),
        curDate,
        diff,
        days,
        hours,
        minutes,
        seconds,
        tmp,
        countdown,
        //added Math.floor. this is already a shortcut, might as well make it a double one
        pad = function(number) { return (number < 10 ? '0' : '') + Math.floor(number) },

        //calculate these constants once, instead of over and over
        minute = 60 * 1000,
        hour = minute * 60,
        day = hour * 24

    ;(function tick() {
        curDate = new Date()
        //you want the absolute value of this, not of individual calculations using this
        diff = Math.abs(new Date(curDate.getTime() - endDate.getTime()))
        days = diff / day

        tmp = diff % day
        hours = tmp / hour

        tmp = tmp % hour
        minutes = tmp / minute

        tmp = tmp % minute
        seconds = tmp / 1000

        //parseInt was redundant
        countdown = pad(days) + ':' + pad(hours) + ':' + pad(minutes) + ':' + pad(seconds)

        if ( 'textContent' in el ) {
            el.textContent = countdown
        }
        else {
            el.innerText = countdown
        }

        //dont't use arguments.calle, it's deprecated
        //simply use a named function expression
        setTimeout(tick, 1000)
    }())
}())

About the semicolons missing: it is a deliberate choice as I find this more readable (the ; right before the (function() is because it is the only edge case where the semicolon insertion doesn't work correctly).


texts: Extracting lines from a file, the smelly way

texts:
I have a section of code I use to extract an event log out of a large text file. It works well, it's just my use of list(itertools.takewhile(...)) that feels a little sketchy to me.

Is there a nicer way of doing this?

import itertools

testdata = '''
Lots of other lines...
Really quite a few.

*************
* Event Log *
*************
Col1  Col2  Col3
----- ----- -----
1     A     B
2     A     C
3     B     D

Other non-relevant stuff...
'''

def extractEventLog(fh):
    fhlines = (x.strip() for x in fh)
    list(itertools.takewhile(lambda x: 'Event Log' not in x, fhlines))
    list(itertools.takewhile(lambda x: '-----' not in x, fhlines))
    lines = itertools.takewhile(len, fhlines) # Event log terminated by blank line
    for line in lines:
        yield line # In the real code, it's parseEventLogLine(line)

Expected output:

>>> list(extractEventLog(testdata.splitlines()))
['1     A     B', '2     A     C', '3     B     D']


texts: Fill an array with last non-zero element to the end in PHP

texts:
I need to fill an array with the last non-zero value.

Points of note I guess are that the array will either have all 0 values or end with 0 values.

Please review my code below.

<?php

$array = [1, 1, 5, 4, 0, 0];
$array2 = [0, 0, 0, 0, 0, 0];

function padArray($array) {
    $length = count($array) - 1;
    for ($i = $length; $i >= 0; $i--) {
        if($array[$i] != 0) {
            for ($j = $i; $j < count($array); $j++) {
                $array[$j] = $array[$i];
            }
            break;
        }
    }
    return $array;
}

var_dump(padArray($array));
var_dump(padArray($array2));

//should output [1,1,5,4,4,4]
//should output [0,0,0,0,0,0]


texts:
In an interview, I was asked to write code to produce this output:

    T
   TE
  TES
 TEST
 EST
 ST
 T

The code I wrote was:

#include<iostream>
int main() {
char* a[] = {"t","e","s","t","\0"};
int k=0, i,j;
for(i=0; i<4; i++) {
    while(k<3) {
        cout<<" ";
        k++;
    }
    k=i+1;
    for(j=0; j<=i; j++) {
        cout<<a[j];
    }
    cout<<"\n";
}
for(i=1; i<4; i++) {
    for(j=i; j<4; j++) {
        cout<<a[j];
    }
    cout<<"\n";
}
return 0;
}

I think the code is not precise also the complexity is really a lot more that what I expected.

How can I improve this code in terms of time and space complexity?

I was wondering if additional sets of eyes could spot potential errors. Also, any stylistic or performance improvement suggestions would be appreciated


texts: Function to remove element from an array

texts:
Below function takes an array, an element to be deleted and returns a new array minus the indicated element. Can this be optimized some how? How good is it generally?

public static int[] sbSample(int a[],int i){

    int size=0;
    int b[]=new int[a.length]; // provide length of new array
    for(int k=0;k<a.length;k++){    // iterate over elements of passed array
        if(!(a[k]==i)){    // search for elements other than to be deleted in passed array

            b[size]=a[k];     // store those arrays in new declared array
            size++;    // increment counter
        }
    }
    for(int k=0;k<size;k++){
        System.out.println(b[k]);
    }
    return b;
}


texts: Computing an approximate value of Pi via Monte Carlo method in Java with streams

texts:
I have this short program that attempts to compute an approximate value of \$\pi\$:

package net.coderodde.fun;

import java.awt.geom.Point2D;
import java.util.Arrays;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * This class computes an approximate value of Pi.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Feb 23, 2018)
 */
public class MonteCarloPiComputer {

    /**
     * The default radius of the simulated circle.
     */
    private static final double DEFAULT_RADIUS = 0.5;

    /**
     * The random number generator.
     */
    private final Random random;

    public MonteCarloPiComputer(Random random) {
        this.random =
                Objects.requireNonNull(
                        random,
                        "The input random number generator is null.");
    }

    public MonteCarloPiComputer() {
        this(new Random());
    }

    /**
     * Computes an approximate value of Pi via a Monte Carlo method. The method
     * creates {@code samples} random points, computes the percentage of all
     * points within the radius from the center of the simulated square and
     * multiplies it by {@code 4.0}.
     *
     * @param samples the number of points to create.
     * @param radius  the radius of the simulated circle.
     * @return an approximate value of Pi.
     */
    public double computeApproximateValueOfPi(int samples, double radius) {
        Point2D.Double center = new Point2D.Double(radius, radius);
        double squareSideLength = 2.0 * radius;
        long numberOfPointsWithinCircle =
            IntStream.range(0, samples)
                     .mapToObj(
                             (i) -> {
                                 return new Point2D.Double(
                                         squareSideLength * random.nextDouble(),
                                         squareSideLength * random.nextDouble());
                             })
                     .filter((point) -> {
                         return point.distance(center) < radius;
                     }).count();

        return (4.0 * numberOfPointsWithinCircle) / samples;
    }

    /**
     * Computes an approximate value of Pi via a Monte Carlo method with default
     * radius.
     *
     * @param samples the number of points to create.
     * @return an approximate value of Pi.
     */
    public double computeApproximateValueOfPi(int samples) {
        return computeApproximateValueOfPi(samples, DEFAULT_RADIUS);
    }

    public static void main(String[] args) {
        MonteCarloPiComputer computer = new MonteCarloPiComputer();

        for (int samples = 100_000; samples <= 1_000_000; samples += 100_000) {
            double approximation =
                    computer.computeApproximateValueOfPi(samples);
            double percentage = approximation / Math.PI;
            System.out.print(String.format("%7d: ", samples));
            System.out.print(String.format("%10f", approximation));
            System.out.println(
                    String.format(
                            ", percentage from exact Pi: %10f",
                            (100.0 * percentage)));
        }
    }
}

Critique request

I would like to hear any comments and improvement suggestions.


texts:
The text of a website is checked in a given time period. If there are any changes a mail is sent. There is a option to show/mail the new parts in the website. What could be improved?

#!/usr/bin/env python3
import urllib.request, hashlib, time, html2text, smtplib, datetime, argparse

class urlchange:
    def __init__(self, url):
        self.url = url
        self.urlhash = self.createhash()
        self.content = self.getcontent()
        date = datetime.datetime.now().strftime( "%d.%m.%Y %H:%M:%S" )
        print(date+": Start Monitoring... hash: "+self.urlhash)

    def getcontent(self):
        #Try to get data
        try:
            urldata = urllib.request.urlopen(self.url).read().decode("utf-8","ignore")
            urldata = html2text.html2text(urldata)
        except:
            print("Can't open url: ", self.url)
        return urldata

    def createhash(self):
        #create hash
        urldata = self.getcontent().encode("utf-8")
        md5hash = hashlib.md5()
        md5hash.update(urldata)
        return md5hash.hexdigest()

    def comparehash(self):
        date = datetime.datetime.now().strftime( "%d.%m.%Y %H:%M:%S" )
        if(self.createhash() == self.urlhash):
            print(date+": Nothing has changed")
            return False
        else:
            print(date+": Something has changed")
            if(not args.nodiff):
                print(self.diff())
                if(not args.nomail):
                    try:
                        sendmail("Url has changed!","The Url "+self.url+" has changed at "+date+" .\n\nNew content:\n"+self.diff())
                    except:
                        sendmail("Url has changed!","The Url "+self.url+" has changed at "+date+" .")
            elif(not args.nomail):
                sendmail("Url has changed!","The Url "+self.url+" has changed at "+date+" .")
            return True

    def diff(self):
        #what has chaged
        start, end = 0, 0
        newcontent = self.getcontent()
        #start of changes
        for i,j in enumerate(self.content):
            if(i<len(newcontent) and j != newcontent[i]):
                start=i
                break
        #end of changes
        for i,j in enumerate(reversed(self.content)):
            if( (len(newcontent)-(i+1))>0 and j != newcontent[len(newcontent)-(i+1)]):
                end=len(newcontent)-i
                break
        return newcontent[start:end]

def sendmail(subject,message):
    try:
        server = smtplib.SMTP("smtp.server.com",587)
        server.set_debuglevel(0)
        server.ehlo()
        server.starttls()
        server.login("email@server.de","password")
    except:
        print("Can't connect to the SMTP server!")

    date = datetime.datetime.now().strftime( "%d.%m.%Y %H:%M:%S" )
    msg = "From: email@server.de\nSubject: %s\nDate: %s\n\n%s""" % (subject, date, message)

    server.sendmail("email@server.de","email2@server.de",msg)
    server.quit()
    print(date+": email was sent")

parser = argparse.ArgumentParser(description="Monitor if a website has changed.")
parser.add_argument("url",help="url that should be monitored")
parser.add_argument("-t","--time",help="seconds between checks (default: 600)",default=600,type=int)
parser.add_argument("-nd","--nodiff",help="show no difference",action="store_true")
parser.add_argument("-n","--nomail",help="no email is sent",action="store_true")
args = parser.parse_args()

url1 = urlchange(args.url)
time.sleep(args.time)
while(True):
    if(url1.comparehash()):
        break
    time.sleep(args.time)

Improved code at: Email a notification when detecting changes on a website - follow-up


texts: Extract data from a DBMS, create a CSV dump and transfer it to an FTP server

texts:
First of all, my code does work as expected at least to some extent. The intention of the program is to extract data from a DBMS in order to create a CSV dump and transfer it to an FTP server.

My two issues:

The functions of the class seem to be bloated with self.-references. How can that be optimized? Or is that the way it ought to be? It looks overloaded to me.
The population of the plist-variable (first call of if __name__ == '__main__':) has been done very ineptly. The main function does not exit the program if the number of arguments does not equal 2. How can this be achieved respectively or be done better?

import cx_Oracle
import re
import os
import csv
import sys
import getopt
import ftplib
import ntpath

#os.environ['NLS_LANG'] = "en_US.ISO8859-1"
#os.environ['NLS_LANG'] = ".UTF8"

def main(argv):
    inputfile = ''
    outputfile = ''
    usage = 'test.py -i <inputfile> -o <outputfile>'
    flist = []
    try:
        opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
    except getopt.GetoptError:
        print usage
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'test.py -i <inputfile> -o <outputfile>'
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg
        elif len(sys.argv) != 2:
            print usage
            sys.exit(2)
    flist.append(inputfile)
    flist.append(outputfile)
    return flist

class Extractor(object):

    def __init__(self, iput, oput):
        self.oracle_server = "my_oracle_server"
        self.oracle_password = "my_oracle_password"
        self.oracle_port = "1521"
        self.oracle_sid = "MYSID"
        self.oracle_user = "MYUSER"
        self.ftp_server = 'my_ftp_psw'
        self.ftp_user = 'my_ftp_user'
        self.ftp_passwort = 'my_ftp_passwort'
        self.sql_file = os.path.join(os.getcwd(),iput)
        self.csv_file = os.path.join(os.getcwd(),oput)
        self.dsnStr = cx_Oracle.makedsn(self.oracle_server, self.oracle_port, self.oracle_sid)
        self.connection = cx_Oracle.connect(user=self.oracle_user, password=self.oracle_password, dsn=self.dsnStr)
        self.cursor = self.connection.cursor()

    def execute_sql(self, file):
        self.f = open(file)
        self.sql_statement = self.f.read()
        self.cursor.execute(self.sql_statement)

    def extract_from_db(self):
        self.column_list = [i[0] for i in self.cursor.description]
        self.columns = ';'.join(self.column_list)
        with open(self.csv_file,'w') as outfile:
            outfile.write(self.columns+"\n")
            writer = csv.writer(outfile, delimiter =";")
            for row in self.cursor:
                writer.writerow(row)

    def transfer_file(self):
        print "Transferring " + self.csv_file + " ..."
        self.session = ftplib.FTP(self.ftp_server, self.ftp_user, self.ftp_passwort )
        self.file = open(self.csv_file,'rb')
        self.session.storlines('STOR ' + ntpath.basename(self.csv_file), self.file)     # send the file
        self.file.close()
        self.session.quit()
        print "Complete."

if __name__ == '__main__':
    plist=main(sys.argv[1:]) # very inept, doesn't not exit as intended when number of arguments does not equal 2
    ext = Extractor(plist[0], plist[1])
    ext.execute_sql(ext.sql_file)
    ext.extract_from_db()
    ext.cursor.close()
    ext.connection.close()
    ext.transfer_file()


texts:
I'm looking for optimized code with faster execution time. This writes CSV to parquet with the max size of 64 MB chunks.

we are trying to concatenate the csv file contents being written as an parquet file until the parquet file size reaches 64MB

The loop would continue to run until reads all the csv files content being concatenated being written as parquet format

import pandas as pd
import uuid
import boto3

s3 = boto3.client('s3')
out_path='s3://ahshan/parquet-out/'
ssize=64*1024*1024

def get_s3_keys(bucket, prefix):

    """Get a list of keys in an S3 bucket."""
    resp = s3.list_objects_v2(Bucket=bucket, Prefix=prefix)
    files=[]
    for obj in resp['Contents']:
      str_key = obj['Key']
      files.append(str_key.split('\n'))
#      print(files)
    return files

def lambda_handler(event,context):
    counter=0
    count=0
    cond=False
    extension = 'csv'
    all_filenames = get_s3_keys('ahshan','csvfiles/csvtemp/')
#    print (all_filenames)
    df = []
    sizedf =0
    cond=False
    flat_list = [item for sublist in all_filenames for item in sublist]
    flatl= [ item for item in flat_list if '.csv' in item]
    print(' shiva pre :', flatl)
    for f in flatl:
        ipd = pd.read_csv('s3://ahshan/'+f)
        sizedf += ipd.size
        print(sizedf, ":", ssize)
        if sizedf > ssize:
            pd.concat(df).to_parquet(out_path+str(uuid.uuid1())+'.parq', compression='gzip')
            sizedf = 0
            df = []
            cond=True
        else:
            df.append(ipd)
            cond=False

    if not cond:
        print('hello')
        pd.concat(df).to_parquet(out_path+str(uuid.uuid1())+'.parq', compression='gzip')
```


texts: Method to delegate command to other methods

texts:
Since I am working alone on this, I would like someone who would take a look and point out any mistakes or things I could have done better.
My questions:

How could I improve this big switch statement?
Is there any obvious beginner flaws?

The executeModeration is a method I call when a command is an moderation command. The command.parameters[0] contains the parameters a commmand needs to be executed
const executeModeration = async (command, channel) => {
  switch (command.command)  {
    case "ban":
      if(command.parameters[0])
        await moderation.ban(channel, command.parameters[0], command.parameters[1] !== undefined ? command.parameters[1] : '');
      break;
    case "unban":
      if(command.parameters[0])
        await moderation.unban(channel, command.parameters[0]);
      break;
    case "timeout":
      if(command.parameters[0])
        await moderation.timeout(channel, command.parameters[0], command.parameters[1] !== undefined ? command.parameters[1] : 300, command.parameters[2] !== undefined ? command.parameters[2] : '');
      break;
    case "emoteonly":
      await moderation.emoteonly(channel);
      break;
    case "emoteonlyoff":
      await moderation.emoteonlyoff(channel);
      break;
    case "followersonly":
      await moderation.followersonly(channel,command.parameters[0] !== undefined ? command.parameters[0] : 30);
      break;
    case "followersonlyoff":
      await moderation.followersonlyoff(channel);
      break;
    case "r9kbeta":
      await moderation.r9kbeta(channel);
      break;
    case "r9kbetaoff":
      await moderation.r9kbetaoff(channel);
      break;
    case "slow":
      await moderation.slow(channel, command.parameters[0] !== undefined ? command.parameters[0] : 30);
      break;
    case "slowoff":
      await moderation.slowoff(channel);
      break;
    case "subscribers":
      await moderation.subscribers(channel);
      break;
    case  "subscribersoff":
      await moderation.subscribersoff(channel);
      break;
    case  "mod":
      if(command.parameters[0])
        await moderation.mod(channel, command.parameters[0]);
      break;
    case  "unmod":
      if(command.parameters[0])
        await moderation.unmod(channel, command.parameters[0]);
      break;
    case  "vip":
      if(command.parameters[0])
        await moderation.vip(channel, command.parameters[0]);
      break;
    case  "unvip":
      if(command.parameters[0])
        await moderation.unvip(channel, command.parameters[0]);
      break;
    case  "clear":
      await moderation.clear(channel);
      break;
    case  "host":
      if(command.parameters[0])
        await moderation.host(channel, command.parameters[0]);
      break;
    case  "unhost":
      await moderation.unhost(channel);
      break;
    case  "commercial":
      if(command.parameters[0])
        await moderation.commercial(channel, command.parameters[0]);
      break;
  }


texts:
I'm extracting the first letter (not symbol) of a string using Unicode characters, with French words/sentences in mind.

I have implemented it like this:

def lettrine(text):
    first = next((c for c in text if c.isalpha()), "")
    return first

assert lettrine(u":-)") == u""
assert lettrine(u"Éléphant") == u"É"
assert lettrine(u"\u03b1") == u"α"
assert lettrine(u":-)") == u""
assert lettrine(u"") == u""

Do you think there is a better solution? Would isalpha work just as well on both Python 2.7 and 3.5?


texts:
This is a very simple function, but it gets run on a roughly 10ms interval, so I'm looking for ways to improve it. The first obvious thing is that it has to run the comparisons nearly every time as it starts with the lowest probabilities first. Is there a way I can reverse that without breaking it, or a way I can generally improve the performance of this function to achieve the same end result?

function find_coin() {
    var roll = Math.random() * 100;

    if (roll < 0.01)
        currency['platinum']++;
    else if (roll < 0.1)
        currency['gold']++;
    else if (roll < 1)
        currency['silver']++;
    else if (roll < 10)
        currency['bronze']++;
};


texts:
How to choose the dark mode properly?
  {isDarkMode ? <ImageBackground source={require('../Images/bgndDark/bgGradient.png')} style={styles.container}>
    <Charter isDarkMode />
  </ImageBackground > : <Charter isDarkMode={false} />
  }

Just feels wrong to duplicate "Charter"?


texts:
I needed a way to make a CLI based script a bit secure. So, I thought of the following workflow:

the client will get the MAC of the user, sha256 it and put it in a file at a specific location
then in my program, I'm also doing the same thing, check to see if the sha256 of the MAC is present in the file (and if it matches) then let the user use the script.
more, that text file will have multiple lines in it (but the only one that maters is the first one)

I'm aware that this might not be the best option for securing a script, but the client said ("do this to make it a bit harder for somebody else to use it").

import hashlib
import sys

from uuid import getnode

def get_mac():
    """return the MAC address of a specific machine"""
    return bytes(str(getnode()), 'utf-8')

def hash_mac():
    """hash the MAC using sha256 algorithm"""
    return hashlib.sha256(get_mac()).hexdigest()

def main():
    with open('uid_file.cfg') as uid_file:
        first_line = uid_file.readline().replace('\n', '')

        if str(hash_mac()) in first_line and len(str(hash_mac())) == len(first_line):
            print('Match MAC and execute program here\n')
        else:
            print('MAC does not match! Exiting...')
            sys.exit(0)

if __name__ == '__main__':
    main()

Any advice on what could go wrong or alternatives / good practices are welcome.


texts:
I have a function which goes through every name in an object. This object has an array parameter materials which holds other objects. Those objects have the same array parameter which hold more objects and so on.

My code lines 3-5 just repeat while adding .material and another variable. Also the code will only go into an object's name four layers down or else I have to keep repeating more code.

How can I cut down on this mess?

var itemList = function(x) {
    console.log(x.materials[0].name);
    for (var i = 1; i < x.materials.length; i++) {
    console.log(x.materials[i].name);
       if (x.materials[i].build !== "BasicFactory" && i !== 0) {
           for (var j = 1; j < x.materials[i].materials.length; j++) {
               console.log(x.materials[i].materials[j].name);
               if (x.materials[i].materials[j].build !== "BasicFactory" && j !== 0) {
                   for (var k = 1; k < x.materials[i].materials[j].materials.length; k++) {
                   console.log(x.materials[i].materials[j].materials[k].name);
                   if (x.materials[i].materials[j].materials[k].build !== "BasicFactory" && j !== 0) {
                       for (var l = 1; l < x.materials[i].materials[j].materials[k].materials.length; l++) {
                       console.log(x.materials[i].materials[j].materials[k].materials[l].name);
                    }
                }
              }
            }
        }
    }
}
};


texts:
I've created a program for my job that unlocks spreadsheet files quickly and efficiently. What we use to have to do before this program is we'd have to go into the system, search for the file, kill the users process containing the file, unlock the file, then the user can finally get back into their spreadsheet. With my new program it first cd's into the directory containing the files, you enter the file number "folio", it searches through a list of locked files using shell commands, then unlocks the specific one for the user.

I'm looking for some critique on my work, I would really like to know what I can do better what I did wrong, etc..

Source:

#!/usr/local/bin/ruby

require 'fileutils'

module Kernel
    def ls_grep
        `cd '/my/dir'`
        `ls -la|grep -i .lock`
        puts "Enter Folio #"
        @input_folio = gets.chomp
        lockfile = "/my/dir.~lock.#{@input_folio}.ods#"
        if @input_folio =~ /^\d{7}/
            if File.exist?( lockfile )
                puts "Unlock file?"
                input = gets.chomp.upcase
                if input == 'Y'
                     FileUtils.rm( lockfile )
                     puts "File unlocked."
                else
                    puts "You went through that trouble for no reason..."
                end
            else
                puts <<-EDE.gsub(/^\s*>/, ' ')
                >
                >Lockfile not found for Folio # #{@input_folio}"
                >
                >If the file name doesn't match the folio number, get the file name
                >and use that instead of the Foilio number...
                >
                EDE
                ls_grep
            end
        else
            puts <<-EDF.gsub(/^\s*>/, ' ')
            >
            >What part of 'Folio #' is hard to understand? 7 DIGITS"
            >
            >If the file name doesn't match the folio number, get the file name
            >and use that instead of the Folio number...
            >
            EDF
            ls_grep
        end
    end
end
ls_grep

Example usage:

Enter Folio #
1234567

 Lockfile not found for Folio # 1234567"

 If the file name doesn't match the folio number, get the file name
 and use that instead of the Foilio number...

Enter Folio #
erwe

 What part of 'Folio #' is hard to understand? 7 DIGITS"

 If the file name doesn't match the folio number, get the file name
 and use that instead of the Folio number...

Enter Folio #


texts:
Program to compare if files within two directories are having same content
I followed the approach of getting the list of files under two directories recursively and store it in different list with it is canonical path.

Then using two loops, compared the each file line by line. Below is my code,

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

public class FileCompare
{
    static List<String> dir1_filePath = new ArrayList<String>();
    static List<String> dir2_filePath = new ArrayList<String>();
    static void fetchFiles(File[] arr,int start,int level, List<String> filePath) throws IOException
    {
        if(start == arr.length)
            return;
        if(arr[start].isFile()){
            filePath.add(arr[start].getCanonicalPath());
        }
        else if(arr[start].isDirectory())
        {
            fetchFiles(arr[start].listFiles(), 0, level + 1,filePath);
        }
        fetchFiles(arr,++start, level,filePath);
    }

    public static void main(String[] args) throws IOException
    {
        Scanner s = new Scanner(System.in);
        String directory_one = s.next();
        String directory_two = s.next();
        File dir_one = new File(directory_one);
        File dir_two = new File(directory_two);

        if(dir_one.exists() && dir_one.isDirectory())
        {
            File dir1_files[] = dir_one.listFiles();
            fetchFiles(dir1_files,0,0, dir1_filePath);
        }
        if(dir_two.exists() && dir_two.isDirectory())
        {
            File dir2_files[] = dir_two.listFiles();
            fetchFiles(dir2_files,0,0, dir2_filePath);
        }
        boolean fileEqual;
        for(int i=0;i<dir1_filePath.size();i++){
            for(int j=1; j<dir2_filePath.size();j++){
                fileEqual = compareTwoFiles(dir1_filePath.get(i), dir2_filePath.get(j));
                if(fileEqual){
                    System.out.println(dir1_filePath.get(i) + " and " + dir2_filePath.get(i) + " are Equal");
                }
            }
        }
    }

    private static boolean compareTwoFiles(String file1, String file2) throws IOException {
        BufferedReader reader1 = new BufferedReader(new FileReader(file1));
        BufferedReader reader2 = new BufferedReader(new FileReader(file2));
        String line1 = reader1.readLine();
        String line2 = reader2.readLine();
        boolean areEqual = true;
        while (line1 != null || line2 != null)
        {
            if(line1 == null || line2 == null)
            {
                areEqual = false;
                break;
            }
            else if(! line1.equalsIgnoreCase(line2))
            {
                areEqual = false;
                break;
            }
            line1 = reader1.readLine();
            line2 = reader2.readLine();
        }
        reader1.close();
        reader2.close();
        return areEqual;
    }
}

Is there any other approach to compare the files effectively, instead of using two loops?


texts:
This is my attempt at making a class for dynamic PDO queries in PHP.

The code works, but I would like the hear what I can improve to make it more secure and readable.

class DB

{

    private static $connection;

    public static function setConnection ($connection)

    {

        static::$connection = $connection;

    }

    public static function insert($table, $data = [])

    {

        try {

            $columnsArray = array_keys($data);
            $columnsString = implode(',', $columnsArray);

            $valuesArray = array_values($data);
            $valuesCount = count($valuesArray);

            $valuesPlaceholder = '';
            for ($i=0; $i < $valuesCount; $i++) {
                $valuesPlaceholder .= '?,';
            }
            $valuesPlaceholder = rtrim($valuesPlaceholder, ',');

            $query = "INSERT INTO $table ($columnsString) VALUES ($valuesPlaceholder)";

            $statement = static::$connection->prepare($query);

            $statement->execute($valuesArray);

        } catch (\PDOException $e) {

            die("Insert failed: " . $e->getMessage());

        }

    }

}

Usage example

//setting the connection in app entry point
$config = require_once "config.php";
$dbConnection = Connection::make($config['database']);

DB::setConnection($dbConnection);

//using DB class in a controller
class PostController

{
    //inserting a post to posts table with name and content columns
    public function create()

    {

        $name = $_POST['postName'];
        $content = $_POST['postContent'];

        DB::insert('posts', [

            'name' => $name,
            'content' => $content

        ]);

        return redirect('somewhere');

    }

}


texts: Class derived from TXmlIniFile to save/read to/from XML

texts:
I have created this unit containing a class derived from TXmlIniFile. This class uses the common TCustomInifile methods to write to and read from an XML file. It comes from an idea of Chris Rolliston from his book "Delphi XE2 Foundations" (which I warmly recommend):

unit PAXMLIniFile;

interface

uses
  System.SysUtils,
  System.IniFiles,
  Xml.XmlDoc,
  Xml.XMLIntf,
  Xml.XMLIniFile;

type
  TMyStandaloneXmlIniFile = class(TXmlIniFile)
  strict private
    FDocument: IXMLDocument;
    FFileName: string;
  public
    constructor Create(const AFileName: string);
    procedure UpdateFile; override;
  end;

implementation

constructor TMyStandaloneXmlIniFile.Create(const AFileName: string);
begin
  if FileExists(AFileName) then
    FDocument := LoadXMLDocument(AFileName)
  else
  begin
    FDocument := NewXMLDocument;
    FDocument.Options := FDocument.Options + [doNodeAutoIndent];
  end;
  if FDocument.DocumentElement = nil then
    FDocument.DocumentElement := FDocument.CreateNode('Sections');
  TCustomIniFile(Self).Create(AFileName);
  FFileName := AFileName;
  inherited Create(FDocument.DocumentElement);
end;

procedure TMyStandaloneXmlIniFile.UpdateFile;
begin
  FDocument.SaveToFile(FFileName);
end;

end.

Usage - Here is the test program:

program XMLTest;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils, PAXMLIniFile, Winapi.ActiveX;

var
  MyStandaloneXmlIniFile: TMyStandaloneXmlIniFile;
  MyXmlFile: string;

begin
  try
    CoInitialize(nil);
    MyXmlFile := ChangeFileExt(ParamStr(0), '.xml');
    MyStandaloneXmlIniFile := TMyStandaloneXmlIniFile.Create(MyXmlFile);
    try
      MyStandaloneXmlIniFile.WriteString('Section1', 'Ident1', 'Value1');
      MyStandaloneXmlIniFile.UpdateFile;
    finally
      MyStandaloneXmlIniFile.Free;
    end;
    CoUninitialize;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Does anybody find any flaws in the class or in the usage?


texts: Updating items of one List that match another List

texts:
I'm using VS 2008. I pass a List<T> a using ref, along with another List<T> b.

I need to cycle thru List<T> b, which contains around 200,000 items, and for each item in b, it it matches criteria in a, which contains 100,000 or more items, and update it.

public static void UpdateList(ref List<ExampleT> a, List<ExampleT> b)
{

    var count = 0;
    for (int i = 0; i < b.Count; i++)
    {

        foreach (var z in a.FindAll(x => x.MatchA == b[i].MatchA && x.MatchB == b[i].MatchB))
        {
            z.ToUpdate = b[i].ToUpdate;
            count++;
        }
        if(count >= 10000)
            break;
    }
}

Now, the only reason I added count was so that once 10000 items in a have been updated, the loop will stop, otherwise it will take a very long time to go thru all of the items. Even by limiting it like this, it still takes around 3 min.

For the sake of the example, T in this case is an object similar to the following:

public class ExampleT
{
public string MatchA {get;set;}
public string MatchB {get;set;}
public double? ToUpdate {get;set;} //in List a this will ALWAYS be null until it gets updated in the foreach
}

Is there a way I can make this more efficient?


texts: Extract name, address and phone number from some web pages using multiprocessing

texts:
I've written a script in Python using the multiprocessing module to scrape values from web pages (one page per subprocess). As I'm very new to multiprocessing, I'm not sure whether I did everything in the right way. It works without error, though.

Here goes the full script:

import requests
from lxml.html import fromstring
from multiprocessing import Pool

link = "https://www.yellowpages.com/search?search_terms=coffee&geo_location_terms=Los%20Angeles%2C%20CA&page={}"

def create_links(url):
    response = requests.get(url).text
    tree = fromstring(response)
    for title in tree.cssselect("div.info"):
        name = title.cssselect("a.business-name span")[0].text
        try:
            street = title.cssselect("span.street-address")[0].text
        except IndexError: street = ""
        try:
            phone = title.cssselect("div[class^=phones]")[0].text
        except IndexError: phone = ""
        print(name, street, phone)

if __name__ == '__main__':
    links = [link.format(page) for page in range(1,4)]
    with Pool(4) as p:
        p.map(create_links, links)

Any idea to make it more robust will be highly appreciated.


texts:
For a given file name path, I need to get the folder one level before it. This can be accomplished in ruby with the following code:

File.dirname(File.dirname("/a/b/c.txt"))
 => "/a"

Independently from this exact case, how can I DRY two method calls in sequence?


texts:
After a discussion of which users were from Australia, I wrote my first SQL query to find out:
SELECT u.DisplayName'Display Name', u.Reputation'Rep', u.Location'Location'
FROM Users u
WHERE u.Location LIKE '%Australia%'
ORDER BY 'Rep' DESC

As always, please tell me the good, the bad, and the ugly.
The query can be found here


texts:
I have written this PrimeFactorize utility method in C# (using LINQPad) which works fine, but feels like it is a bit slow, I was wondering what might be improved. Also looking for any criticism not related to efficiency to make the code better.

// Generate prime factors for a number, e.g., input 12 returns 2 2 3
public static IEnumerable<int> PrimeFactorize(int number)
{
    if(IntUtils.IsPrime(number))
    {
        yield return number;
    }
    else
    {
        List<int> primes = IntUtils.GetPrimesBetween(2, number);
        while(!IntUtils.IsPrime(number))
        {
            foreach(var p in primes)
            {
                if(number % p == 0)
                {
                    yield return p;
                    number /= p;
                    break;
                }
            }
        }
        yield return number;
    }
}

As a note, the IntUtils.IsPrime and IntUtils.GetPrimesBetween are two other utility methods I wrote. I am including GetPrimesBetween below. IsPrime has already been reviewed and it is quite fast by itself and can be found on GitHub.

public static List<int> GetPrimesBetween(int min, int max)
{
    var primes = new List<int>();
    for(var i = min; i <= max; i++)
    {
        if(IntUtils.IsPrime(i) && i != 1)
        {
            primes.Add(i);
        }
    }
    return primes;
}

Here is a test run, along with the execution times:

void Main()
{
    var N = 12;
    for(var i = 1; i <= 10; i++)
    {
        Console.Write("Run # {0} | Number to factorize: {1}\nResult: ", i, N);
        foreach(var P in IntUtils.PrimeFactorize(N))
        {
            Console.Write(P + " ");
        }
        // mix up results a bit
        N += N*3 + i;
        Console.WriteLine("\nTime elapsed since start: {0}", Util.ElapsedTime);
    }
}

Results:

Run # 1 | Number to factorize: 12
Result: 2 2 3
Time elapsed since start: 00:00:00.0130129
Run # 2 | Number to factorize: 49
Result: 7 7
Time elapsed since start: 00:00:00.0132697
Run # 3 | Number to factorize: 198
Result: 2 3 3 11
Time elapsed since start: 00:00:00.0133637
Run # 4 | Number to factorize: 795
Result: 3 5 53
Time elapsed since start: 00:00:00.0139543
Run # 5 | Number to factorize: 3184
Result: 2 2 2 2 199
Time elapsed since start: 00:00:00.0183778
Run # 6 | Number to factorize: 12741
Result: 3 31 137
Time elapsed since start: 00:00:00.0528457
Run # 7 | Number to factorize: 50970
Result: 2 3 5 1699
Time elapsed since start: 00:00:00.2867861
Run # 8 | Number to factorize: 203887
Result: 31 6577
Time elapsed since start: 00:00:01.9602979
Run # 9 | Number to factorize: 815556
Result: 2 2 3 7 7 19 73
Time elapsed since start: 00:00:13.5247897
Run # 10 | Number to factorize: 3262233
Result: 3 13 233 359
Time elapsed since start: 00:01:35.3379070

As you can see, starting at Run #6 the times start getting a lot longer very quickly, and by Run # 10 it takes over a minute to get the results.


texts:
I've tried to write a simple timer class that could later be used in games, such as for updating the screen every second. Problem is, I read gettimeofday() was UNIX-specific and unsafe to use as well (that last one I'm not sure about). I know C has a clock() function, but it only has second precision.

Is there a way to get time in a cross-platform way that has millisecond precision at the very least? I know Boost and other libraries exist, but I prefer not to use them for various reasons.

class Timer
{
private:
   bool m_isRunning;
   int m_startTime;
   int m_delayAmount;
   double m_initialDelay;

public:
   Timer(int delayAmount, double initialDelay = 0.0)
   {
      m_delayAmount = delayAmount * 1000;
      m_initialDelay = initialDelay/1000;
   }

   void start()
   {
      m_startTime = getMilliseconds();
      clock_t endwait = clock() + m_initialDelay * CLOCKS_PER_SEC;
      while (clock() < endwait);
      m_isRunning = true;
   }

   void stop()
   {
      m_isRunning = false;
   }

   bool isRunning()
   {
      return m_isRunning;
   }

   bool hasTicked()
   {
      if (getMilliseconds() - m_startTime > m_delayAmount)
      {
         m_startTime = getMilliseconds();
         return true;
      }
      else
      {
         return false;
      }

   }

   int getMilliseconds() const
   {
      timeval t;
      gettimeofday(&t, NULL);
      return (t.tv_sec * 1000000) + t.tv_usec;
   }
};

This is kinda how you would use it. The program just prints a message every second after an initial delay of 3 seconds.

int main (int argc, char * const argv[])
{
   Timer timer(1000, 3000);
   timer.start();
   int i = 1;
   while (timer.isRunning())
   {
      if (timer.hasTicked())
      {
         cout << "tick " << i++ << endl;
      }
   }
}


texts: Binary Search Tree without pass by reference

texts:
Here is a code for BST that I have written , that does not use pass by reference. Help me to find flaws in its design. Also I do not like the function getReqNodes, can it be made more elegant.
#include <iostream>
using namespace std;

struct node {
    int data;
    node* left = nullptr;
    node* right = nullptr;
    node(int d , node *l = nullptr, node *r = nullptr){
        data = d;
        left = l;
        right = r;
    }
};
node* insertVal(node* n, int val) {
    if (n == nullptr) {
        n = new node(val);
        n->data = val;
        return n;
    }
    else if (val < n->data){
        return new node(n->data, insertVal(n->left,val), n->right);
    }
    else if(val > n->data) {
        return new node(n->data, n->left, insertVal(n->right, val));
    }
    else{
        return new node(val, n->left, n->right);
    }
}
int minVal(node* n) {
    if (n == nullptr) return -10000;
    else if (n->left == nullptr) return n->data;
    else return minVal(n->left);
}

node* getReqNodes(node *t, node *q){
    if(q == nullptr){return t;}
    else{
        t = insertVal(t,q->data);
        t = getReqNodes(t,q->left);
        t = getReqNodes(t,q->right);
        return t;
    }
}

node* removeVal(node *n, int v){
    if (n == nullptr){return n;}
    else if(v < n->data){
        return new node(n->data, removeVal(n->left,v), n->right);
    }
    else if(v > n->data){
        return new node(n->data, n->left, removeVal(n->right, v));
    }
    else{
        node *j = n;
        //attaching right subtree to the left subtree
        node *p = getReqNodes(n->left, n->right);
        delete j;
        return p;
    }
}

void printTree(node* n) {
    if (n == nullptr) { return; }
    printTree(n->left);
    cout << n->data << " ";
    printTree(n->right);
}

int main() {
    node* p = nullptr;
    for(int i = 0; i < 15; ++i){
        p = insertVal(p, rand()%15);
    }
    printTree(p);cout<<endl;cout<<endl;
    node *foo = removeVal(p, 149);
    printTree(foo);
    return 0;

}


texts: Calling Stored Procedure "insert query" using EF 6, UOW, and MVC 5

texts:
I'm a beginner in MVC programming, repository, and UOW using Entity framework. I tried to calling my existing SP in my MVC project using UOW and EF.

Here is my code to mapping my SP in myDbContext file:

modelBuilder.Entity<Applicant>().MapToStoredProcedures(
            s => s.Insert(
                i => i.HasName("InsertApplicant")
                .Parameter(fn => fn.First_Name,"FirstName")
                .Parameter(ln => ln.Last_Name,"LastName")
                .Parameter(em => em.Email,"Email")
                .Parameter(tn => tn.Tel_No,"TelNo")
                .Parameter(mn => mn.Mobile_No,"MobileNo")
                .Parameter(vt => vt.Visa_Type,"VisaType")
                .Parameter(lu => lu.LinkedIn_URL,"LinkedInURL")
                .Parameter(ob => ob.Objective, "Objective")
                .Parameter(ac => ac.Active, "Active")));

And, below is the code I used to call the SP on my controller (i don't know if it's right or not):

using (var context = new MyExperienceDbContext())
            {
                var fn = new SqlParameter("@FirstName", entity.First_Name);
                var ln = new SqlParameter("@LastName", entity.Last_Name);
                var em = new SqlParameter("@Email", entity.Email);
                var pn = new SqlParameter("@TelNo", entity.Tel_No);
                var mn = new SqlParameter("@MobileNo", entity.Mobile_No);
                var vt = new SqlParameter("@VisaType", entity.Visa_Type);
                var lu = new SqlParameter("@LinkedInURL", entity.LinkedIn_URL);
                var ob = new SqlParameter("@Objective", entity.Objective);
                var ac = new SqlParameter("@Active", entity.Active);

                context.Database.ExecuteSqlCommand("InsertApplicant @FirstName,@LastName,@Email,@TelNo,@MobileNo,@VisaType,@LinkedInURL,@Objective,@Active ",
                    fn, ln, em, pn, mn, vt, lu, ob, ac);
                return RedirectToAction("Index");
            }

It works fine for me, but I noticed if I delete the mapping's code in myDbContext file everything still works fine. I believe i'm failed to implemented the UOW and repository concept in EF when calling my existing SP, right?
Do you have any idea with my question above or do you have tutorial suggestion to calls SP using UOW and EF in MVC project?


texts: Communication between privileged (function) and non-privileged (GUI) python script on macOS

texts:
Ok, so I am creating my own macOS cleaning app. Something like OnyX but then open-source and python based.

The removal process requires administrative privileges but since I have read that it is usually considered best practice to not run your entire GUI via sudo, I am now in the process of separating the GUI from the actual removal process.

For both aesthetics and security, when I launch the actual deletion process I want to ask the user for his password via macOS's native GUI screen. That way, I can prevent having to store the password in a variable and it just looks & feels better.

In it's most basic form my current setup thus consists of 2 python scripts:

Script1: A non-priviliged GUI (wx-based)
Script2: A priviliged deletion script

Script2 is initiated by Script1, and I need it to communicate back to Script1.

The idea is that if Script2 has to delete for example 100 files it needs to report back after each file so that the wx-Progressbar contained in Script1 can be updated accordingly.

In its most basic and stripped form my current working proof-of-concept looks like this:

Script1

Important: The line with the launch-command is commented out because it somehow messed up the code-layout here on StackExchange, but if you want to tryout the code it should be un-commented.

from pathlib import Path
import subprocess
import sys
import io
import shlex
from threading import Thread
import time

class LaunchDeletionProcess(Thread):

    def __init__(self, nr_of_steps):

        self.nr_of_steps = nr_of_steps
        Thread.__init__(self)

    def run(self):

        #launch_command = r"""/usr/bin/osascript -e 'do shell script "/usr/local/bin/python3.6 -u /path/to/script2 """ + str(self.nr_of_steps) + """\" with prompt "Sart Deletion Process " with administrator privileges'"""
        split_command = shlex.split(launch_command)

        print("Thread 1 started")
        testprogram = subprocess.Popen(split_command)
        testprogram.wait()

class ReadStatus(Thread):

    def __init__(self, nr_of_steps):

        self.nr_of_steps = nr_of_steps
        Thread.__init__(self)

    def run(self):

        print("Thread 2 started")

        check_status_file = Path("/path/to/statusfile.txt")

        while not check_status_file.is_file():
            time.sleep(1)

        if check_status_file.is_file():
            nr = 0

            while nr < self.nr_of_steps:
                time.sleep(1)
                with open("/path/to/statusfile.txt", "r") as status_file:
                    status = status_file.read()
                    print("Current status = ", status)
                nr += 1

        else:
            pass

if __name__ == "__main__":

    nr_of_steps = 100
    thread1 = LaunchDeletionProcess(nr_of_steps)
    thread2 = ReadStatus(nr_of_steps)
    thread1.start()
    thread2.start()

Script2

import time
import sys
import os

nr_of_lines = int((sys.argv)[1])

print("nr of lines = ", nr_of_lines)

for i in range(nr_of_lines):
    with open("/path/to/statusfile.txt", "w") as status_file:
        status_file.write(str(i))
    time.sleep(1)
    print(i)

os.remove("/path/to/statusfile.txt")

sys.exit()

As you might have noticed my current setup uses a textfile to communicate between the two scripts. I am wondering if there is a better (performance wise: so more efficient, etc.), more pythonic, or more secure solution? Like, could I use multithreading for this somehow maybe? Just guessing..

Earlier attempts I've made, made use of stdin & stdout to communicate, but because Script2 is now called via osascript (needed in order to get the native GUI pop-up for administrative privileges) it is run in a non-interactive shell, thus any method using stdout won't work properly.


texts:
I have a 2 classes Armor and Weapon in my game, that inherit from the abstract class Gear:

public class Gear {
    public int price;
    // Other common attributes between armors and weapons
}

public class Weapon : Gear {
    public int damage = 10;
    public int weight = 10;
    public int range = 10;
}

public class Armor : Gear {
    // Defense against different kinds of attack
    public int blunt, slash, ranged;
}

Then I have a class GearButton which is nothing more than a button, with a piece of gear associated. I inherit from this class to create Buttons to Buy, Equip or Upgrade this items, for instance.

This is 2 examples of it:

BuyArmorButton.cs

public class BuyArmorButton : GearButton {

    // ...

    void BuyItem() {
        bool bought = GameSession.Buy((Armor) this.gear);
        if (bought) this.ShowMessage('Buy successful');
    }

    void Update() {
        bool can_buy = GameSession.CanBuy((Armor) this.gear);
        this.EnableButton(can_buy);
    }

    // ...
}

BuyWeaponButton.cs

public class BuyWeaponButton : GearButton {

    // ...

    void BuyItem() {
        bool bought = GameSession.Buy((Weapon) this.gear);
        if (bought) this.ShowMessage('Buy successful');
    }

    void Update() {
        bool can_buy = GameSession.CanBuy((Weapon) this.gear);
        this.EnableButton(can_buy);
    }

    // ...
}

I have added the methods from GameSession, which probably might also need to be tweaked, for this to work.

public static bool Buy(Armor armor) {
    if (!CanBuy(armor)) return false;

    data.money -= armor.price;
    data.armorsPurchased.Add(armor);
    return true;
}

public static bool Buy(Weapon weapon) {
    if (!CanBuy(weapon)) return false;

    data.money -= weapon.price;
    data.weaponsPurchased.Add(weapon);
    return true;
}

public static bool CanBuy(Armor armor) {
    if (data.armorsPurchased.Contains(armor))
        return false;

    if (armor.price > data.money)
        return false;

    return true;
}

public static bool CanBuy(Weapon weapon) {
    if (data.weaponsPurchased.Contains(weapon))
        return false;

    if (weapon.price > data.money)
        return false;

    return true;
}

It kinda feels like a lot of the code duplication, and I thought it could be merged into a BuyGearButton class, but I am not sure how to go about it, because of the up-casting of the Gear classes.

I have pasted the whole files here:

Gear.cs
Weapon.cs
Armor.cs
GameSession.cs
BuyArmorButton.cs
BuyWeaponButton.cs


texts:
I wrote this code about finding the end of file (EOF).  Please review this.

#include<stdio.h>
#include<conio.h>
void main (void)
{
int x,y,m;
for(x=0;x>=0;x++){
    m=scanf("%d %d",&x,&y);
    if (m!=2 || m==EOF){
    break;
    }
    else printf("/%d/%d/\n",x,y);
}
if (feof ( stdin )){
  printf("End of input\n");
}
else if(m!=2){
  printf("There was an error\n");
}
getch();
}


texts:
From what I've read, I should use abstract classes when I want to define behavior for a superclass, and I don't want to instantiate the superclass. So, I'm making a Blackjack game in Java, and I want a BlackjackDealer class and a BlackjackPlayer class. Would it be okay to make these children of a BlackjackPerson  class, since some of the behavior should be the same? An example of behavior that should be the same:

abstract class BlackjackPerson {

   protected Card[] cards;
   public void hit(Card c) {
       // add c to cards
   }

   public abstract void displayHand();
   // print out hand
}

An example of a BlackjackDealer class, with its own implementation of the displayHand method (since a dealer has 1 card hidden):

class BlackjackDealer extends BlackjackPerson {
    public void displayHand() {

        for (Card c : cards) {
            System.out.println(c);
        }
    }
}

This is my first time using inheritance, I just want to know if I'm on the right track.


texts: Using large amounts of if-else statements for playing card numbers

texts:
I have a method that uses a bunch of if-else statements, and I am thinking how I could simplify it.

public static CardNumber decode(String s) {
    if(s == null) {
        return null;
    } else if(s.equalsIgnoreCase(ACE.toString())) {
        return ACE;
    } else if(s.equalsIgnoreCase(TWO.toString())) {
        return TWO;
    } else if(s.equalsIgnoreCase(THREE.toString())) {
        return THREE;
    } else if(s.equalsIgnoreCase(FOUR.toString())) {
        return FOUR;
    } else if(s.equalsIgnoreCase(FIVE.toString())) {
        return FIVE;
    } else if(s.equalsIgnoreCase(SIX.toString())) {
        return SIX;
    } else if(s.equalsIgnoreCase(SEVEN.toString())) {
        return SEVEN;
    } else if(s.equalsIgnoreCase(EIGHT.toString())) {
        return EIGHT;
    } else if(s.equalsIgnoreCase(NINE.toString())) {
        return NINE;
    } else if(s.equalsIgnoreCase(TEN.toString())) {
        return TEN;
    } else if(s.equalsIgnoreCase(JACK.toString())) {
        return JACK;
    } else if(s.equalsIgnoreCase(QUEEN.toString())) {
        return QUEEN;
    } else if(s.equalsIgnoreCase(KING.toString())) {
        return KING;
    } else {
        return null;
    }
}

The whole class is here:

public class CardNumber {
    private final String name;
    private final int value;

    public static final CardNumber ACE_AS_ONE = new CardNumber("A", 1);
    public static final CardNumber TWO = new CardNumber("2", 2);
    public static final CardNumber THREE = new CardNumber("3", 3);
    public static final CardNumber FOUR = new CardNumber("4", 4);
    public static final CardNumber FIVE = new CardNumber("5", 5);
    public static final CardNumber SIX = new CardNumber("6", 6);
    public static final CardNumber SEVEN = new CardNumber("7", 7);
    public static final CardNumber EIGHT = new CardNumber("8", 8);
    public static final CardNumber NINE = new CardNumber("9", 9);
    public static final CardNumber TEN = new CardNumber("10", 10);
    public static final CardNumber JACK = new CardNumber("J", 11);
    public static final CardNumber QUEEN = new CardNumber("Q", 12);
    public static final CardNumber KING = new CardNumber("K", 13);
    public static final CardNumber ACE = new CardNumber("A", 14);

    private CardNumber(String name, int value) {
        this.name = name;
        this.value = value;
    }

    @Override
    public String toString() {
        return name;
    }

    public static CardNumber decode(String s) {
        if(s == null) {
            return null;
        } else if(s.equalsIgnoreCase(ACE.toString())) {
            return ACE;
        } else if(s.equalsIgnoreCase(TWO.toString())) {
            return TWO;
        } else if(s.equalsIgnoreCase(THREE.toString())) {
            return THREE;
        } else if(s.equalsIgnoreCase(FOUR.toString())) {
            return FOUR;
        } else if(s.equalsIgnoreCase(FIVE.toString())) {
            return FIVE;
        } else if(s.equalsIgnoreCase(SIX.toString())) {
            return SIX;
        } else if(s.equalsIgnoreCase(SEVEN.toString())) {
            return SEVEN;
        } else if(s.equalsIgnoreCase(EIGHT.toString())) {
            return EIGHT;
        } else if(s.equalsIgnoreCase(NINE.toString())) {
            return NINE;
        } else if(s.equalsIgnoreCase(TEN.toString())) {
            return TEN;
        } else if(s.equalsIgnoreCase(JACK.toString())) {
            return JACK;
        } else if(s.equalsIgnoreCase(QUEEN.toString())) {
            return QUEEN;
        } else if(s.equalsIgnoreCase(KING.toString())) {
            return KING;
        } else {
            return null;
        }
    }

    public int getValue() {
        return value;
    }
}


texts: reinterpret_cast vs bit shifts for extracting 32-bit integers from bytes, with either endianness

texts:
I've written some simple helper functions that read data types from a vector of bytes (binary files) and having a tough time deciding which route to go.

Method 1 : reinterpret_cast

int32_t read_32s(const std::vector<uint8_t> &buf, const unsigned offset,
                 const bool bswap = false) {
  // Check for out of bounds
  if (offset > buf.size() - sizeof(int32_t)) {
    // error handling
  }
  // Cast the pointer to int32_t and get the first value
  const auto val = reinterpret_cast<const int32_t *>(&buf[offset])[0];
  // Swap bytes if necessary
  if (bswap) {
    return (((val & 0xFF000000) >> 24) | ((val & 0x00FF0000) >> 8) |
            ((val & 0x0000FF00) << 8) | ((val & 0x000000FF) << 24));
  }
  return val;
}

The biggest advantage with this method is probably performance, readability is debatable. This basically compiles down to a single instruction, two if you need to swap the bytes. The problem I have with this is casting like this in modern C++ is frowned upon, and I am unsure how safe it actually is despite bounds checking first. How does alignment work?

Method 2 : classic bit shifts

int32_t read_32s(const std::vector<uint8_t> &buf, const unsigned offset,
                 const bool bswap = false) {
  // Check for out of bounds
  if (offset > buf.size() - sizeof(int32_t)) {
    // error handling
  }
  // Swap bytes if necessary
  if (bswap) {
    return (buf[offset] << 24) | (buf[offset + 1] << 16) |
           (buf[offset + 2] << 8) | buf[offset + 3];
  }
  return (buf[offset + 3] << 24) | (buf[offset + 2] << 16) |
         (buf[offset + 1] << 8) | buf[offset];
}

Very simple bit shifting, about double the instructions as the first method, and can get a bit messy with larger data types. I presume this is the safer solution though, and perhaps more readable.

Is the first method OK, or would you consider it to be poor code in comparison to the second method? Or maybe there's just a better method all together (std::byte?).

Here is a compiler explorer link with both examples.


texts:
I wrote this out of curiosity. It is based on the theory behind Knuth's Algorithm D and is intended to emulate the behavior of the x86 div instruction (though the result is truncated instead of raising an exception for overflow).

I am primarily interested in correctness (it seems to work correctly), and have not yet compared performance with anything simpler.

Two's complement hardware is assumed.

uint64_t div(uint64_t a_lo, uint64_t a_hi, uint64_t b, uint64_t &r)
{
    uint64_t p_lo;
    uint64_t p_hi;
    uint64_t q = 0;

    auto r_hi = a_hi;
    auto r_lo = a_lo;

    int s = 0;
    if(0 == (b >> 63)){

        // Normalize so quotient estimates are
        // no more than 2 in error.

        // Note: If any bits get shifted out of
        // r_hi at this point, the result would
        // overflow.

        s = 63 - bsr(b);
        const auto t = 64 - s;

        b <<= s;
        r_hi = (r_hi << s)|(r_lo >> t);
        r_lo <<= s;
    }

    const auto b_hi = b >> 32;

    /*
    The first full-by-half division places b
    across r_hi and r_lo, making the reduction
    step a little complicated.

    To make this easier, u_hi and u_lo will hold
    a shifted image of the remainder.

    [u_hi||    ][u_lo||    ]
          [r_hi||    ][r_lo||    ]
                [ b  ||    ]
    [p_hi||    ][p_lo||    ]
                  |
                  V
                [q_hi||    ]
    */

    auto q_hat = r_hi / b_hi;

    p_lo = mul(b, q_hat, p_hi);

    const auto u_hi = r_hi >> 32;
    const auto u_lo = (r_hi << 32)|(r_lo >> 32);

    // r -= b*q_hat
    //
    // At most 2 iterations of this...
    while(
        (p_hi > u_hi) ||
        ((p_hi == u_hi) && (p_lo > u_lo))
        )
    {
        if(p_lo < b){
            --p_hi;
        }
        p_lo -= b;
        --q_hat;
    }

    auto w_lo = (p_lo << 32);
    auto w_hi = (p_hi << 32)|(p_lo >> 32);

    if(w_lo > r_lo){
        ++w_hi;
    }

    r_lo -= w_lo;
    r_hi -= w_hi;

    q = q_hat << 32;

    /*
    The lower half of the quotient is easier,
    as b is now aligned with r_lo.

          |r_hi][r_lo||    ]
                [ b  ||    ]
    [p_hi||    ][p_lo||    ]
                        |
                        V
                [q_hi||q_lo]
    */

    q_hat = ((r_hi << 32)|(r_lo >> 32)) / b_hi;

    p_lo = mul(b, q_hat, p_hi);

    // r -= b*q_hat
    //
    // ...and at most 2 iterations of this.
    while(
        (p_hi > r_hi) ||
        ((p_hi == r_hi) && (p_lo > r_lo))
        )
    {
        if(p_lo < b){
            --p_hi;
        }
        p_lo -= b;
        --q_hat;
    }

    r_lo -= p_lo;

    q |= q_hat;

    r = r_lo >> s;

    return q;
}

For convenience, below are the bsr and mul functions used above. The bsr routine comes from this useful site:

int bsr(uint64_t x)
{
    uint64_t y;
    uint64_t r;

    r = (x > 0xFFFFFFFF) << 5; x >>= r;
    y = (x > 0xFFFF    ) << 4; x >>= y; r |= y;
    y = (x > 0xFF      ) << 3; x >>= y; r |= y;
    y = (x > 0xF       ) << 2; x >>= y; r |= y;
    y = (x > 0x3       ) << 1; x >>= y; r |= y;

    return static_cast<int>(r | (x >> 1));
}

uint64_t mul(uint64_t a, uint64_t b, uint64_t &y)
{
    auto a_lo = a & 0x00000000FFFFFFFF;
    auto a_hi = a >> 32;

    auto b_lo = b & 0x00000000FFFFFFFF;
    auto b_hi = b >> 32;

    auto c0 = a_lo * b_lo;
    auto c1 = a_hi * b_lo;
    auto c2 = a_hi * b_hi;

    auto u1 = c1 + (a_lo * b_hi);
    if(u1 < c1){
        c2 += 1LL << 32;
    }

    auto u0 = c0 + (u1 << 32);
    if(u0 < c0){
        ++c2;
    }

    y = c2 + (u1 >> 32);

    return u0;
}


texts: Present database results based on form submission

texts:
When we select the 'info' list in the select field, the article with type 'info' characteristic automatically showed up, and when we select 'Berita' list in the select field, the articles with type 'Berita' characteristic automatically show up.
This is a long script that uses a post method.  Can you help me make it simpler, perhaps using functions?
<form method="post" name="form2">
  <select name="type" id="type">
    <option value="Semua">Semua</option>
    <option value="Berita">Berita</option>
    <option value="Info">Info</option>
  </select>
  <input type="submit" id="type" />
</form>

    <?php
        $i=0;
        $no=0;
            if($_POST['type'] == 'Semua')
            {
                $query_art = mysql_query("SELECT * FROM artikel_tbl ORDER BY id") or die(mysql_error());
            }
            else if ($_POST['type'] == 'Berita')
            {
                $query_art = mysql_query("SELECT * FROM artikel_tbl WHERE type = 'Berita' ORDER BY id") or die(mysql_error());
            }
            else if ($_POST['type'] == 'Info')
            {
                $query_art = mysql_query("SELECT * FROM artikel_tbl WHERE type = 'Info' ORDER BY id") or die(mysql_error());
            }
            else
            {
                $query_art = mysql_query("SELECT * FROM artikel_tbl ORDER BY id") or die(mysql_error());
            }
            while($show=mysql_fetch_array($query_art))
            {
                $no++;
                if(($no%2)==0)
                    $color = '#f2f2f2';
                else
                    $color = '#f9f9f9';
    ?>
  <tr bgcolor="<?php echo $color; ?>" class="rows">
    <input type="checkbox" name="checked<?php echo $i; ?>" value="<?php echo $show['id']; ?>"/>
    <?php echo $no; ?>
    <?php echo $show['judul']; ?>
    <?php echo $show['penulis']; ?>
    <?php echo $show['type']; ?>
    <img src=".././upload/artikel/<?php echo $show['foto']; ?>" width="144" height="88"/>
    <?php echo $show['tanggal']; ?>

<a href="table_artikel.php?edit=<?php echo $show['id']; ?>">

<a href="table_artikel.php?delete=<?php echo $show['id']; ?>" onclick="return confirm('Hapus artikel?')";>

    <?php
        $i++;
        }
    ?>
    <input type="hidden" name="n" value="<?php echo $i; ?>" />


texts: Changing the type of an object inside a method?

texts:
First off, this is not my code.  I'm curious what everyone thinks about changing the type of an object inside of a method then modifying the properties of the cast type. I wanted to use composition to build up a patient, but this is the recommend path.  I'm probably wrong which is why I wanted 3rd party feedback.  Or maybe we just have different coding styles...

    // Person/Patient Builder
public static void BuildUpPersonOrPatient(Person person, Dictionary<string, string> row)
        {
    person.FirstName = row["FirstName"];
    person.LastName = row["LastName"];

    Patient patient = person as Patient;

    if (patient != null)
    {
        patient.PatientID = row["PatientID"];
    }
}

for reference

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Patient : Person
{
    public string PatientID { get; set; }
}

//
//


texts: Optimize Recursive Function to traverse nested DOM nodes

texts:
I wrote a recursive function that traverses nested DOM nodes of the following form:

The recursive function is the following:

function getNestedNodes(node) {
var ary = [];
for(var i = 0; i < node.length; ++i) {
    var myJSONChildren = {};
    if(node[i].childElementCount) {
        var myNode = node[i].children;
        for(var j = 0; j < myNode.length; ++j) {
            for(var k =0, attrs = myNode[j].attributes, l = attrs.length; k < l; ++k) {
                myJSONChildren['tag'] = myNode[j].nodeName;
                myJSONChildren[attrs.item(k).nodeName] = attrs.item(k).nodeValue;
            };
        }
        myJSONChildren['children'] = getNestedNodes(myNode); //Recursive Call
        ary.push(myJSONChildren);
    };
}
return ary;
}

so if I call that function this way:

var links = document.querySelectorAll('a');
getNestedNodes(node);

it returns a JSON array of the following form:

[{
  tag:'a',
  href:"#,
  title:"test",
  children:[{
             tag:"div",
             id:"nested-image",
             children:[{
                        tag:"img",
                        src:"image.jpg"
                       }]
             }]
  }]
}]

However, I think that my function is way too complex, and I know that there must a better way to get the same results.

Any help will be greatly appreciated!


texts: Parsing Addresses with GeoPanda's GeoDataFrame

texts:
Long time reader of Code Review with my first question. I'm self-taught and suspect this code can be improved. The project is really important to me and the team and I could really use the help.

I'm using this as part of a larger script run through the terminal which takes a GeoDataFrame and adds the GPS coordinates as a Point per the specification, and then outputs a GDF again. (I then export it as a geojson file.) So far it's running through ~3500 rows in about 2 hours - which is fine - but I don't think I'm using many coding best practices. I'd like to make it as robust as possible because we have some datasets to run through that are +15000 rows. Does anyone have any feedback on this script?

import pandas as pd
import geopandas as gpd
from shapely.geometry import Point
import geopy as gpy
from geopy.geocoders import GoogleV3
from geopy.extra.rate_limiter import RateLimiter
from geopy.exc import GeocoderTimedOut
from geopy.location import Location

def addressParsing(gdf_obj, delayseconds):
    """
    This takes a whole GeoDataFrame and adds the Geo Coords from the standard address
    before returning the udpated Geodataframe
    """
    # Returned class obj if None
    site = Location("0", (0.0, 0.0, 0.0))

    def do_geocode(address):
        try:
            return geocode_with_delay(address)
        except GeocoderTimedOut:
            return geocode_with_delay(address)

    print(f"starting parser: {gdf_obj.shape}, estimated time: {round(delayseconds * gdf_obj.shape[0] / 60, 2)} min")

    # Initiate geocoder
    geolocator = GoogleV3(api_key=g_api_key)

    # Create a geopy rate limiter class:
    geocode_with_delay = RateLimiter(
        geolocator.geocode,
        error_wait_seconds=delayseconds + 20,
        min_delay_seconds=delayseconds,
        swallow_exceptions=True,
        return_value_on_exception= site
        )

    # Apply the geocoder with delay using the rate limiter:
    gdf_obj['temp'] = gdf_obj['Address'].apply(do_geocode)

    # Get point coordinates from the GeoPy location object on each row, drop z vector data:
    gdf_obj["coords"] = gdf_obj['temp'].apply(lambda loc: tuple(loc.point)[:2] if loc else tuple(site.point)[:2])

    # Create shapely point objects to geometry column:
    gdf_obj["geometry"] = gdf_obj["coords"].apply(Point)

    # Drop intermediate columns
    gdf_obj = gdf_obj.drop(["temp", "coords"], axis=1)

    print("FINISHED - conversion successful - check shape")
    return gdf_obj


texts: MySQL Prepared Statement - Combinging 3 seperate statements in to 1 statement

texts:
I'm currently learning MySQL about prepared statements and I was wondering if this code I've written is the most efficient way.
The process:

There's a query that checks a table called 'websites' for a field called websites_pagecount.
The same query then increments the field by 1. (I haven't done this is the database using auto-increment because there will be more than one row with the same number.)

There's a query that then runs and grabs the new number.

Then another query runs and creates a row in a table called pages and sets the new pagecount number in to the page_id field (again, I haven't used auto-increment on this as there will be more than one row with the same number).

However, it all seems a bit 'cumbersome'.
$mysql['stmt'] = $mysql['conn']->prepare("UPDATE websites SET website_pagecount=website_pagecount+? WHERE website_domain=?");
$mysql['stmt']->bind_param("is", $a = 1, $website['website_id']);
$result = $mysql['stmt']->execute();
$mysql['stmt']->close();

$mysql['stmt'] = $mysql['conn']->prepare("SELECT website_pagecount FROM websites WHERE website_domain = ?");
$mysql['stmt']->bind_param("s", $website['website_id']);
$result = $mysql['stmt']->execute();
//GET ROWS
$result = $mysql['stmt']->get_result();
$pagecount = $result->fetch_assoc();
$mysql['stmt']->close();

$mysql['stmt'] = $mysql['conn']->prepare("INSERT INTO pages (page_id,page_parent, page_title, page_description,page_keywords, website_id, page_layout) VALUES (?,?,?,?,?,?,?)");
$mysql['stmt']->bind_param("issssss",$pagecount['website_pagecount'],$item['parentpage'],$item['pagetitle'],$item['pagedescription'],$item['pagekeywords'],$website['website_id'],$item['pagelayout'] );
$result = $mysql['stmt']->execute();
$mysql['stmt']->close();

The code is used to create a new web page from a web based administration panel. The admin panel can be used to edit multiple websites (depending on which user is logged in) All website information is held in the 'websites' table and all the pages from all the websites are held in the 'pages' table.
Every page has an auto-incrementing unique ID, however they also have a page id relative to the website they belong to. IE (test.com can have pages with ids 1,2 and 3 however testagain.com can also have pages with ids 1,2,3)
The reason for the 'website_pagecount' field is so when a new page is created for a particular website, it counts up in order.
The reason I have done this is because if i used a 'row count' function, for example, to generate the page ID field, and pages with the ID's 1 & 3 got deleted, when a new page was generated it would set the ID to '2' - however that would conflict with the already existing page that has an ID set which was 2.
If there was to be 30-40 pages for a website and pages got deleted and created over time, there would be an awful lot of conflicts eventually per website.


texts:
I am wondering the best way to setup a database class, to remove repeat code by using OOP. This way if I changed how I connect to the database (switch from PDO to sqlsrv driver) I can just change it in 1 file, instead of all the files that use PDO. I've setup a class that I will show below, but I feel like it may be hard to understand if I hired a developer in the future.

Also, would it be better to have pre-built functions for returning specific data (.getFriends())? I also am going to be using mainly stored procedures, which means, should I create specific functions for doing that? Just to make it more clear to a developer? As you can see, I understand how to do all of this, I am just not sure what a good, clean way is.

<?php

$database = new Database;

class Database
{
public $database;

public function __construct()
{
    $this->database = new PDO("sqlsrv:Server=$IP;Database=$DBNAME", "$UsrName", "$Password");
}

// get rows
//Returns rows from specified query. If no bindParams, then pass empty or       undefined variable.
public function selectRows($query, $bindParams, $fetchMode)
{
    $stmt = $this->database->prepare($query);
    $stmt->execute($bindParams);
    return $stmt->fetchAll($fetchMode);
}

// insert row
public function insertRows($query, $bindParams)
{
    try {
        $stmt = $this->datab->prepare($query);
        $stmt->execute();
        return TRUE;
    } catch (PDOException $e) {
        throw new Exception($e->getMessage());
    }
}

// update row
public function updateRows($query, $bindParams)
{
    $this->insertRow($query);
}

// delete row
public function deleteRows($query, $bindParams)
{
    $this->insertRow($query);
}

}

?>


texts:
Here is my first code for a radio player. How to make it stable and secured? Applicable to any "id_wr".
If possible, display the first 7 songs provided by the API...

NRJAudio.fm is not linked to this project, their API is the same as mine (local)

Here is an excerpt of my code, normally it works.

    MURIEL ROBIN

    Les lapins

--- DEV INFOS ---

Start time :

...

End time :

...

Current time :

...


texts: Formatting a list of strings as a comma-separated string

texts:
I'm learning Haskell on my own and I'm following the material of a course.

I would like to know if this is idiomatic Haskell.

asList :: [String] -> String
asList ss = "[" ++ (concat $ intersperse "," ss) ++ "]"


texts:
Please check this program that sorts an integer array.  It doesn't look very efficient.  Please tell me how to correct this.

int temp;
for(int i=0;i<nums.length-1;i++)
{
    if(nums[i]>nums[i+1])// if this is true, swap the value
    {
        temp=nums[i];
        nums[i]=nums[i+1];
        nums[i+1]=temp;
        i=-1;//If there is swap happen, loop will start again from 0th element
    }
}