texts: Avoiding repetition when using the "snprintf idiom" to write text

texts:
I'm writing a function to stringify a nested struct. I'm using snprintf to pre-calculate how much space I'll need to allocate.

The problem is, it's extremely repetitious, and will only get worse if I ever need to add more fields to any of the structs. The duplication also creates more of an opportunity for accidental asymmetrical changes.

Is there an idiomatic way of reducing the duplication?

The repetitious code:

char* stringify_state(State* state) {
    Pet* p = state->pet;
    Settings* s = state->settings;

    char* format_string = "%lld %f %f %f %f %f %f %f %f %f %f";

    size_t len = snprintf(NULL, 0, format_string,
                          state->last_update_time,
                          p->health, p->max_health, p->satiation, p->max_satiation,
                          s->milliseconds_per_tick, s->hunger_pain_per_tick, s->hunger_per_tick, s->satiated_heal_per_tick,
                          s->pain_per_wrong_answer, s->satiation_per_right_answer);

    char* buff = malloc(len + 1);

    if (buff) {
        snprintf(buff, len + 1, format_string,
                 state->last_update_time,
                 p->health, p->max_health, p->satiation, p->max_satiation,
                 s->milliseconds_per_tick, s->hunger_pain_per_tick, s->hunger_per_tick, s->satiated_heal_per_tick,
                 s->pain_per_wrong_answer, s->satiation_per_right_answer);

        return buff;

    } else {
        return NULL;
    }
}

Context (Not what I'm asking about, but feel free to mention anything):

#include <time.h>
#include <stdlib.h>
#include <stdio.h>

typedef struct {
    double health;
    double satiation;

    double max_health;
    double max_satiation;

} Pet;

void init_pet(Pet* pet, double max_health, double max_satiation) {
    pet->max_health = max_health;
    pet->max_satiation = max_satiation;

    pet->health = max_health;
    pet->satiation = max_satiation;

typedef struct {
    double milliseconds_per_tick;

    double hunger_pain_per_tick;
    double hunger_per_tick;

    double satiated_heal_per_tick;

    double pain_per_wrong_answer;
    double satiation_per_right_answer;

} Settings;

void init_settings(Settings* s,
                   double ms_per_tick,
                   double hung_pain_per_tick, double hung_per_tick,
                   double sat_heal_per_tick,
                   double pain_per_wrong, double sat_per_right) {

    s->milliseconds_per_tick = ms_per_tick;

    s->hunger_pain_per_tick = hung_pain_per_tick;
    s->hunger_per_tick = hung_per_tick;

    s->satiated_heal_per_tick = sat_heal_per_tick;

    s->pain_per_wrong_answer = pain_per_wrong;
    s->satiation_per_right_answer = sat_per_right;
}

typedef struct {
    time_t last_update_time;
    Pet* pet;
    Settings* settings;

} State;

void init_state(State* state, Pet* pet, Settings* settings, time_t t) {
    state->pet = pet;
    state->settings = settings;

    state->last_update_time = t;
}

A test main:

int main() {
    Pet pet;
    init_pet(&pet, 100, 100);

    Settings settings;
    init_settings(&settings, 91, 82, 73, 64, 55, 46);

    State state;
    init_state(&state, &pet, &settings, 0);

    char* str = stringify_state(&state);

    if (str) {
        printf("%s", str);

        free(str);
    }
}

Prints

0 100.000000 100.000000 100.000000 100.000000 91.000000 82.000000 73.000000 64.000000 55.000000 46.000000


texts:
There is a application with a very slow query (listed below), and I have to optimize to run faster. The truth is that I don't know where to start. Any help? Thanks!

SELECT DISTINCT v.order_ANC,
                v.order_ANC2,
                f.codi_arxiu,
                f.nom_arxiu,
                f.codi_grup,
                f.codi_fons_refe,
                f.codi_fons,
                f.nom_fons,
                f.any_ini,
                f.any_fi,
                f.cronologia,
                SUM (num_uni_imatges) AS num_uni_imatges,
                SUM (unitats_text) AS unitats_text,
                SUM (unitats_notext) AS unitats_notext
  FROM (  SELECT f.codi_arxiu,
                 f.nom_arxiu,
                 f.codi_grup,
                 f.codi_fons_refe,
                 f.codi_fons,
                 f.nom_fons,
                 f.any_ini,
                 f.any_fi,
                 f.cronologia,
                 SUM (CASE WHEN u.num_imatges > 0 THEN 1 ELSE 0 END) AS num_uni_imatges,
                 COUNT (u.codi_unitat) AS unitats_text,
                 0 AS unitats_notext
            FROM ianc_fons f
            JOIN ianc_unicat u ON ( f.codi_arxiu = u.codi_arxiu AND f.codi_fons = u.codi_fons )
           WHERE     1 = 1
                 AND u.anc_unicat_id IN
                        (SELECT DISTINCT u.anc_unicat_id
                           FROM ianc_unicat u
                          WHERE     1 = 1
                                AND u.codi_arxiu = '1'
                                AND u.codi_grup = 'ANC'
                                AND u.codi_fons = 1)
        GROUP BY f.codi_arxiu,
                 f.nom_arxiu,
                 f.codi_grup,
                 f.codi_fons_refe,
                 f.codi_fons,
                 f.nom_fons,
                 f.any_ini,
                 f.any_fi,
                 f.cronologia
        UNION
          SELECT f.codi_arxiu,
                 f.nom_arxiu,
                 f.codi_grup,
                 f.codi_fons_refe,
                 f.codi_fons,
                 f.nom_fons,
                 f.any_ini,
                 f.any_fi,
                 f.cronologia,
                 SUM (CASE WHEN u.num_imatges > 0 THEN 1 ELSE 0 END) AS num_uni_imatges,
                 0 AS unitats_text,
                 COUNT (u.nt1_unitat) AS unitats_notext
            FROM ianc_fons f
            JOIN ianci_unicats u ON (     f.codi_arxiu = u.nt1_codi_arxiu
                                      AND f.codi_fons = u.nt1_codi_fons )
           WHERE     1 = 1
                 AND u.nt1_id IN
                        (SELECT DISTINCT u.nt1_id
                           FROM ianci_unicats u
                          WHERE     1 = 1
                                AND u.nt1_codi_arxiu = '1'
                                AND u.codi_grup = 'ANC'
                                AND u.nt1_codi_fons = 1)
        GROUP BY f.codi_arxiu,
                 f.nom_arxiu,
                 f.codi_grup,
                 f.codi_fons_refe,
                 f.codi_fons,
                 f.nom_fons,
                 f.any_ini,
                 f.any_fi,
                 f.cronologia
       ) AS f
LEFT JOIN v_ianc_arxius_order v ON ( f.codi_arxiu=v.codi_arxiu )
GROUP BY v.order_ANC,v.order_ANC2,f.codi_arxiu, f.nom_arxiu, f.codi_grup, f.codi_fons_refe,
         f.codi_fons, f.nom_fons, f.any_ini,  f.any_fi, f.cronologia
ORDER BY v.order_ANC,v.order_ANC2,f.nom_arxiu, f.nom_fons


texts:
I'm learning Scala and functional programming. Can I make it more functional?

class Student(val firstname: String, val lastname: String) {
  override def toString: String = firstname + " " + lastname
}
class ClassRoom {
  var rows: List[Array[Student]] = List[Array[Student]]()
  var total: Int = _
  def addRow(row: Array[Student]) = {
    rows = row :: rows
    total += row.length
  }
  def print = rows.foreach(r => r.foreach(println))
}


texts:
So I recently applied to this job for iOS Developer and was invited to complete the following code challenge:

As a next step, please complete this coding exercise in order to proceed with our interview process. If you do well & pass, you will be connected to a Software Engineer to discuss your exercise for an hour zoom video call. Take as much time as needed.
Problem statement:
Please write an (Android/iOS) app that retrieves the data from https://fetch-hiring.s3.amazonaws.com/hiring.json. This will return a json array of items. Using this list of items, display all the items grouped by "listId" to the UI. Sort the results first by "listId" then by "name" when displaying. Filter out any items where "name" is blank or null. The final result should be displayed to the user in an easy-to-read list."

My solution is here.
View Controller is as follows:
import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tableData[section].count
}

@IBOutlet weak var dataTableView: UITableView!
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "DataViewCell", for: indexPath) as? DataCell
    cell?.textSpace.text=tableData[indexPath.section][tableIndices[indexPath.section][indexPath.row]]
    return cell!
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "List ID: "+String(section+1)
}

func numberOfSections(in tableView: UITableView) -> Int {
    return tableData.count
}

var tableData: [[Int:String]]=[[:]]
var tableIndices: [[Int]]=[[]]

override func viewDidLoad() {
    super.viewDidLoad()

    URLSession.shared.dataTask(with: URL(string: "https://fetch-hiring.s3.amazonaws.com/hiring.json")!)
                 {
                     data,response,error  in

                    let json=try? JSONSerialization.jsonObject(with: data!, options: []) as! [[String:Any]]

                    for items in json!
                    {
                        if(type(of: items["name"]!) != NSNull.self && items["name"]! as! String != "")
                        {
                            let listID=Int(String(describing: items["listId"]!))!

                            while(self.tableData.count < listID)
                            {
                                self.tableData.append([:])
                                self.tableIndices.append([])
                            }

                            self.tableIndices[listID-1].append(Int(String(describing: items["id"]!))!)
                            self.tableData[listID-1][Int(String(describing: items["id"]!))!       ]=items["name"]! as! String
                            self.tableIndices[listID-1].sort()

                        }
                    }

                     DispatchQueue.main.async {
                        self.dataTableView.delegate=self
                        self.dataTableView.dataSource=self
                        self.dataTableView.reloadData()

                     }

                 }.resume()

}

}

Two days after submitting, I got the following feedback:

The exercise featured a lot of Swift code that forced unwrapping instead of using nil safe paradigms such as let or guard, and the items displayed in the list would have benefited from a struct or class defining the object to better separate the business logic from the view controller.

Are they being too nit picky here, or is my code really that screwed up?


texts:
Problem spec from CareerCup.

Given two strings, return boolean True/False if they are only one edit apart. Edit can be insert/delete/update of only one character in the string. Eg.

True

xyz,xz
xyz,xyk
xy,xyz
False

xyz,xyz
xyz,xzy
x,xyz

module Strings.OneLetter where

import qualified Data.Text as T

oneLetter :: T.Text -> T.Text -> Bool
oneLetter s1 s2
  | s1 == s2 = False
  | max_l > (min_l + 1) = False
  | max_l == min_l = diff_size == 1
  | otherwise = diff_size == 0
  where
    length_s1 = T.length s1
    length_s2 = T.length s2
    max_l = max length_s1 length_s2
    min_l = min length_s1 length_s2
    diff_size = length $ filter (\(a,b) -> a /= b) zipped
    zipped = T.zip s1 s2

So, I used Text instead of String, hoping I could take advantage of fusion. I have the following questions and my initial attempt to answer them.

What is the time complexity of oneLetter?

\$0(m+n)\$, where \$m\$ is the length of s1 and \$n\$ is the length of s2

what is the space complexity of oneLetter?

I'm thinking due to laziness it's \$O(1)\$, only two Chars are in memory at any one time, or two Ints. But I'm hazy on why. If this is wrong, please articulate why. If I'm right, and my reasoning is wrong or incomplete, please say why.

What if I changed from Text to String?

I don't think the time complexity changes, but how does this change the space complexity?


texts:
This is a follow-up to:

Pointer handle - follow-up
Pointer class/handle

Please review my pointer class.

template<typename T>
class Ptr {
public:
    Ptr(T* t, int s = 1) : sz{s<1 ? throw std::logic_error("Invalid sz parameter") : s} {
        sz = s;
        p = new T[sz];
        std::copy(t,t+sz,p);
    }

    Ptr(const Ptr& t) : Ptr(t.p, t.sz) { }

    Ptr& operator=(Ptr copy) {
        std::swap(copy.sz, sz);
        std::swap(copy.p, p);
        return *this;
    }

    Ptr(Ptr &&t) :p{t.p}, sz{t.sz} {
        t.p = nullptr;
        t.sz = 0;
    }

    Ptr& operator=(Ptr &&t) {
        std::swap(t.p,p);
        std::swap(t.sz,sz);
        return *this;
    }

    T& operator*() {
        check_range(index);
        return p[index];
    }

    T& operator[](int i) {
        check_range(i);
        return p[i];
    }

    T* get() const {
        return p;
    }

    void operator+=(int i) {
        check_range(index+i);
        index += i;
    }

    void operator-=(int i) {
        operator+=(-i);
    }

    Ptr operator+(int i) {
        Ptr old{*this};
        old += index+i;
        return old;
    }

    Ptr operator-(int i) {
        return operator+(-i);
    }

    Ptr& operator++() {
        operator+=(1);
        return *this;
    }

    Ptr operator++(int) {
        Ptr old{p+index};
        operator++();
        return old;
    }

    Ptr& operator--() {
        operator-=(1);
        return *this;
    }

    Ptr operator--(int) {
        Ptr<T> old{p+index};
        operator--();
        return old;
    }

    ~Ptr() {
        delete[] p;
    }

private:
    T* p;
    int sz;
    int index = 0;

    void check_range(int i) {
        if (i < 0 || i > sz-1) {
            throw std::out_of_range("out of range");
        }
        if (p+i == nullptr) {
            throw std::out_of_range("null pointer");
        }
    }

};


texts: Creating simulated items sold at a store into a hash

texts:
I am writing code that creates a hash for a store that has an item, price, and sku.  The hash is inserted into an array.  I also create another hash based on the sku that holds the amount of inventory for that item.  I am new to Ruby and am looking for ways to improve my code.

 class SimStore
      def item_info
        random = Random.new
        price = random.rand(1.00 ... 75.00).round(2)
        item = 1.times.map { RandomWord.nouns.next }
        sku_random = Random.new
        sku = sku_random.rand(1000 ... 1000000)
        sum_store_hash = {:item => item, :price => price, :sku => sku}
      end

  def stock array_items_stock
    stock_hash = {}
    array_items_stock.each do |inventory|
       random = Random.new
       quantity = random.rand(10 ... 100)
       stock_hash[inventory[:sku]] = quantity
     end
    stock_hash
  end
end

items = 15;
array_items = []
hash_inventory = []
while items > 0
  items = items - 1
  sim_store = SimStore.new
  items_hash = sim_store.item_info
  array_items.push(items_hash)
end

hash_inventory = sim_store.stock array_items


texts: Read employee number and salary (exercise to use static keyword)

texts:
WAP to create a class called Employee having empid and salary as data members and salary as data members. Create objects of this class and count no. of employees working in an organization using static keyword.

This is my solution for the above question. Is it correct way of doing this? I am a beginner so I would appreciate your help. Let me know of my mistakes.

    import java.util.*;
    class Employee{
private int empid;
private int salary;
private static int count;

private void setValue(int empid,int salary){
this.empid=empid;
this.salary=salary;
count++;
}

private void getValue(){
System.out.println("EmpId = "+empid);
System.out.println("Salary ="+salary);
System.out.println("Number of employees: = "+count);
}

public static void main(String[] args)
{
    Scanner kb=new Scanner(System.in);
    Employee e=new Employee();
    int id,sal;
    System.out.println("Enter Employee Id: ");
    id=kb.nextInt();
    System.out.println("Enter Salary: ");
    sal=kb.nextInt();
    System.out.println("The Values entered are :");
    e.setValue(id,sal);
    e.getValue();
    Employee e1=new Employee();
    System.out.println("Enter Employee Id: ");
    id=kb.nextInt();
    System.out.println("Enter Salary: ");
    sal=kb.nextInt();
    System.out.println("The Values entered are :");
    e1.setValue(id,sal);
    e1.getValue();
}}


texts: Print output one word per line - K&R Exercise 1-12

texts:
When writing this code I found myself getting more and more complex. When I got to the solution I trimmed the excess parts I'd thought I needed from before, but didn't actually need. The example of wc.c had some definitions for IN and OUT. Why didn't I need those for writing this example?

If there are any bugs or improvements I can make, let me know.

include <stdio.h>

/* prints its input one word per line */
main()
{
  int c;

  c = 0;
  while ((c = getchar()) != EOF) {
     if (c == ' ')
      putchar('\n');
     else
       putchar(c);
  }
}


texts: Convert length of time to appropriate unit

texts:
I have a time, in seconds, which has the possibility to be very large. I wish to convert said time into the "appropriate" rounded, readable format.

I already have code which achieves this, however it's not very efficient (and contains a whole bunch of magic numbers):

String readable = decayTime + " minutes";
if(decayTime > 60)
{
    decayTime /= 60;
    readable = decayTime + " hours";

    if(decayTime > 24)
    {
        decayTime /= 24;
        readable = decayTime + " days";

        if(decayTime > 365)
        {
            decayTime /= 365;
            readable = decayTime + " years";

            if(decayTime > 1000000)
            {
                decayTime /= 1000000;
                readable = decayTime + "mn years";

                if(decayTime > 1000)
                {
                    decayTime /= 1000;
                    readable = decayTime + "bn years";
                }
            }
        }
    }

Apart from switching out the magic numbers, I can't personally think how to make it better.

What would be a better approach to this, or is there something in-built which could help?


texts: Zero-initializing large dynamically allocated arrays of double

texts:
Arrays of double can be zero-initialized with the { 0 } initializer, which works even on systems that have a binary representation of 0.0 that is not all bits zero. While the IEEE 754 representation of floating point zero is all bits zero, the C Standard makes no guarantees about the representation of floating point numbers.

Large dynamically allocated arrays of integer types can be zero-initialized by  using calloc(), but this method is not portable for floating point types, since calloc() initializes all bits to zero. Assigning a value of 0.0 to each individual double in the segment using a loop seems grossly inefficient.

I wrote the code for the function calloc_d() to solve this problem. The function takes the size_t argument nmemb, and returns a zero-initialized segment of memory large enough to hold nmemb doubles. If there is an allocation error, the function returns NULL. The caller is of course responsible for deallocation.

After using malloc() to allocate the required amount of memory, the first bytes are assigned the value of 0.0. Then memmove() is used to copy the bytes of the first zero, then the bytes of the first two zeros, and so on until at least half of the memory has been initialized. Finally, the remaining memory is initialized to 0.0 by copying bytes from the first half.

The code works, and has no obvious issues, as far as I can tell. I am interested in any comments about shortcomings of this approach, or shortcomings of my code, and suggestions for improvement. I would also be interested in suggestions for alternative, possibly more efficient methods.

I have included the function in a working program below. MAXCOUNT doubles are allocated for, initialized, and displayed. The value of MAXCOUNT is currently set to 100, but I have tested it for values up to 1000000.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXCOUNT 100      // number of doubles to allocate for

double * calloc_d(size_t nmemb);

int main(void)
{
    double *dbl_store = calloc_d(MAXCOUNT);
    size_t i;

    for(i = 0; i < MAXCOUNT; i++) {
        if (i % 10 == 0) putchar('\n');
        printf("%-8.4f", dbl_store[i]);
    }
    putchar('\n');

    free(dbl_store);

    return 0;
}

double * calloc_d(size_t nmemb)
{
    double *ret;
    double *next;         // pointer to beginning of uninitialized segment
    size_t alloc_bytes = sizeof(*ret) * nmemb;
    size_t init_sz;       // size of initialized segment

    ret = malloc(alloc_bytes);
    next = ret;

    if (ret) {
        ret[0] = 0.0;
        init_sz = sizeof(*ret);
        ++next;

        while (init_sz < (alloc_bytes + sizeof(*ret)) / 2) {
            memmove(next, ret, init_sz);
            init_sz *= 2;
            next = ret + init_sz / sizeof(*ret);
        }
        memmove(next, ret, alloc_bytes - init_sz);
    }

    return ret;
}


texts:
i do have two dimentional array of data in php.

I do want to add another column with constant to that array for passing tabular data to next program.

i am iterating and adding manually. What can be alternate code?

my code:

            if( is_array( $arrSource )){
                foreach( $arrSource as &$dataRow){
                    foreach( $arrColumn as $k=>$v)
                        $dataRow[$k] = $v;
                }
                unset( $dataRow );
            }


texts:
I have an abstract class Entity in my code, which requires a reference to an instance of EntityData to operate. (EntityData provides basic information about the type of the entity).
In the design of my program, every type of entity would have its own class that extends Entity, and thus would have to provide EntityData that would describe and be shared between all of the instances of that that entity class.
EntityData itself is an immutable class that is built like a multiton (similar to Java's enum). It has a private constructor, and its instances are revealed as readonly static fields.

An example of how EntityData would look:

sealed class EntityData
{
    public static readonly EntityData Table = new EntityData(250, 60);
    public static readonly EntityData Chair = new EntityData(120, 25);

    public readonly int Cost;
    public readonly int Weight;

    private EntityData(int cost, int weight)
    {
        Weight = weight;
        Cost = cost;
    }
}

I can think of two simple ways to deal with this, but I am uncertain which one I should go with.

First one is to add a reaodnly field to Entity and request is via the constructor, so Entity would look like this:

abstract class Entity
{
    private readonly EntityData data;

    protected Entity(EntityData data)
    {
        this.data = data;
    }
}

While an extending class, Table for example, would look like this:

sealed class Table: Entity
{
    public Table() : base(EntityData.Table) {}
}

The second option would be to add an abstract, protected property (getter only) to Entity. In this case Entity would look like this:

abstract class Entity
{
    protected abstract EntityData Data { get; }
}

While the extending class Table would look like this:

sealed class Table : Entity
{
    protected override EntityData Data
    {
        get { return EntityData.Table; }
    }
}

Thus internally, Entity would simply use the property instead of a field.

The performance differences are probably in the realm of micro-optimization, but I would still like to take them into consideration.

The first way obviously increases the size of any Entity object.
The first way also forces all the extending types to define their constructors and call the base constructor or will simply increase the number of parameters in the already existent constructor.

The second way doesn't increase the size of objects, and (to me) look shorter and slightly more concise.
Performance-wise however, benchmarking showed that a virtual method call is much slower than accessing a field.
It is also less obvious that such a property is a dependency of Entity, something the first way makes perfectly clear.

As there's no clear-cut answer here, I would simply love to have a few opinions on the matter, and which of the two ways you find 'better'.
Thanks in advance.

(Please no responses about how this is in the realm of micro optimization and thus I shouldn't waste my time with it. I simply find this interesting.)


texts:
My first ever attempt at Go. Writing a small app. It takes a property file and uses it to populate a Config object.
After adding the first property of the Config object (dateformat) I realised that the code was looking horrible and would only get worse as I added more properties.

Please help me simplify, how should this be done? Why is my go-code always looking this horrible? :)

// Config holds the properties and values used for configuration
type Config struct {
    dateFormat string
}

// DefaultConfig is the set of configuration values used if none other is given.
var DefaultConfig = Config{"2006-01-02"}

// FromFile returns the configuration to use for did
func FromFile(path string) (c Config, e error) {
    c = DefaultConfig
    if lines, err := File2lines(path); err == nil {
        for _, line := range lines {
            prop, val, propErr := propertyOf(line)
            if propErr == nil && prop == "dateformat" && ValidDateFormat(val) {
                format, formatErr := ToGoDateFormat(val)
                if formatErr == nil {
                    c.dateFormat = format
                }
            } else if propErr != nil {
                e = propErr
            }
        }
    } else if err != nil {
        e = err
    }
    return
}

func propertyOf(str string) (key, val string, err error) {
    split := strings.Split(strings.TrimSpace(strings.TrimRight(str, "\n")), "=")
    if len(split) == 2 {
        return split[0], split[1], nil
    }
    return "", "", fmt.Errorf(fmt.Sprintf("String '%s' cannot be read as property.", str))
}

The code expect a file which has the following property:

dateformat=yyyymmdd

ValidDateFormat just checks if the given value is valid.
ToGoDateFormat converts any given format to valid golang date format
File2lines reads a file and returns its lines


texts:
I've put together a simple application in order for me to learn sqlite and OOP in PHP. The application basically outputs two random words, e.g. "Angry Badger", from two database tables, one called Animals & the other named Adjectives. At present both tables contain the same columns (but could change in future).

The code uses an interface, iWord with two methods to be implemented by their concrete classes (Animal, Adjective). The database object has been passed in on the constructors so I can create some unit tests later.

If I were to introduce a new class, fruit, with the same methods: getRandomItem() & listRandomItems($numerOfItems) I would need to create the another DB table, class, implement the same DB error handling and processing of data. This doesn't feel correct.

An alternative may be to combine the database tables into one and have one class that I pass in an item to lookup, e.g. animal, fruit, adjective, & dynamically build the SQL.

Any recommendations or patterns that I should be following?

Please note: this is test code for learning & not for production use ;)

<?php

interface iWord
{
    public function getRandomItem();
    public function listRandomItems($numerOfItems);
}

class Animal implements iWord
{
    private $database;

    public function _construct(PDO $pdo)
    {
        $this->database = $pdo;
    }

    public function getRandomItem()
    {
        $rAnimal = NULL;
        try
        {
            $query = $this->database->prepare("SELECT animalName FROM animal ORDER BY RANDOM() LIMIT 1;");
            $query->execute();
            $sqlres1 = $query->fetch(PDO::FETCH_OBJ);
            $rAnimal = $sqlres1->animalName;
        }
        catch (PDOException $ex)
        {
            echo $ex->getMessage();
        }
        return $rAnimal;
    }

    public function listRandomItems($numerOfItems)
    {
        // not yet implemented
        throw new Exception('Not Implemented');
    }
}

class Adjective implements iWord
{
    private $database;

    public function _construct(PDO $pdo)
    {
        $this->database = $pdo;
    }

    public function getRandomItem()
    {
         // exception handling required
         $query = $this->database->prepare("SELECT adjective FROM adjectives ORDER BY RANDOM() LIMIT 1;");
         $query->execute();
         $sqlres2 = $query->fetch(PDO::FETCH_OBJ);
         return $sqlres2->adjective;
     }

    public function listRandomItems($numerOfItems)
    {
        throw new Exception('Not Implemented');
    }
}

try {
    $pdo = new PDO("sqlite:c:/htdocs/mydb.sqlite");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
    echo $e->getMessage();
}

$adj = new Adjective($pdo);
$rAdjective = $adj->getRandomItem();
$anm = new Animal($pdo);
$rAnimal = $anm->getRandomItem();

echo $rAdjective . " " . $rAnimal;

unset($pdo);


texts:
I have php cookie based login system on my website using below given code. I want to know that whether this login system is secure or not, Whether it can be hacked in any way?

<?php
session_start();
if(isset($_SESSION["userid"]))
{
 header("location:index.php");
}
include( $_SERVER['DOCUMENT_ROOT'] . '/conndb.php' );

if(isset($_POST["login"]))
{
 if(!empty($_POST["member_name"]) && !empty($_POST["member_password"]))
 {
  $name = mysqli_real_escape_string($conn, $_POST["member_name"]);
  $password = mysqli_real_escape_string($conn, $_POST["member_password"]);
$stmt_check = $conn->prepare("SELECT * FROM userz WHERE email =? AND pass = ? AND active ='1'");
$stmt_check->bind_param("ss", $name, $password);
$stmt_check->execute();
$stmt_check->store_result();
$numberofrows = $stmt_check->num_rows;

if(($numberofrows) > 0){

    setcookie ("member_login",$name,time()+ (10 * 365 * 24 * 60 * 60));
    setcookie ("member_password",$password,time()+ (10 * 365 * 24 * 60 * 60));
    $_SESSION["userid"] = $name;
   header("location:index.php");

} else {

   $message = "Invalid Login OR Email not Verified";
}

$stmt_check->close();

 }
 else
 {
  $message = "Both are Required Fields";
 }
}
?>

Besides this code, below piece of code is placed on each page to check whether the user is already logged in or not.

 <?php
    session_start();
    if (empty($_SESSION['userid'])) {
        header('Location: users/login.php');
        exit;
    }
    ?>


texts: Calculate XOR of many consecutive and non-consecutive numbers

texts:
question:

answer(start,length)

#start is the starting number of the matrix
 #length is number of rows.

example 1:

answer(0,3)

0 1 2 /
3 4 / 5
6 / 7 8

where the answer is 2 (by using  XOR (^) checksum is 0^1^2^3^4^6 == 2.)
example 2:

answer(17,4)

17 18 19 20 /
21 22 23 / 24
25 26 / 27 28
29 / 30 31 32

which produces the checksum 17^18^19^20^21^22^23^25^26^29 == 14.

All numbers are between 0 and 2000000000 inclusive, and the length of checkpoint line will always be at least 1.

input

(int) start = 0
(int) length = 3

Output:

(int) 2

Inputs:

(int) start = 17
(int) length = 4

Output:

(int) 14

my code:

def answer(start,length):
    num = start
    temp_len = length
    j = 0
    result = 0
    while num < (num+(length*length)) and temp_len > 0:
        #if required condition is not satisfied (when it reaches '/' in every row)
        if j == temp_len:
            j = 0
            num += length - temp_len
            temp_len -= 1
        #if required condition is satisfied
        else:
            j += 1
            #calculating XOR
            result ^= num
            num += 1
     return result


texts: Determining possible triangle from lengths of line segments

texts:
This Codility challenge is to take an array of integers representing lengths of line segments, and determine whether or not it is possible to choose three distinct segments to form a triangle.  (The sum of the lengths of any two sides must exceed the length of the remaining side.)  Assume that A contains at most one million ints.

Complexity requirements:

Expected worst-case time complexity is O(n log(n));
Expected worst-case space complexity is O(n), not counting the input array A itself.

This is my solution:

import java.util.Arrays;
class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 6
        int n = A.length;

        if (n>1000000000) return -1;

        Arrays.sort(A);
        int p=0;
        int q=p+1;
        int r=q+1;
        for (;r<n;p++,q++,r++){
            if(A[p]+A[q]>A[r] && A[q]+A[r]>A[p] &&  A[r]+A[p]>A[q])
               return 1;
        }
        return 0;
    }
}

I don't how to achieve 100% correctness. I get only 93%.


texts: Managing and referencing items in an immutable store

texts:
I have some things (I'll call them Items) that can either be passed around directly or referred to by reference. For the items that are referred to, there is a storage from which the items can be obtained.
My problem is that I want to keep the storage immutable, but I can't figure out how to do so elegantly. It seems that to work with the items and the storage at the same time, every method has to accept the existing storage as input and then output an updated storage alongside the item. This is how this looks in code:
sealed trait Item

case class ItemRef(id: String) extends Item

case class ItemDef(propA: String, propB: Boolean) extends Item

type ItemStore = Map[String, ItemDef]

def makeItem(rawItemData: Map[String, String], itemStore: ItemStore): (Item, ItemStore) = {
  val id = generateItemId(data) // Some unique ID for this item

  if(shouldItemDefBeUsed(data)) { // Ie, is the item small or simple?
    (buildItemDef(data), this)
  } else if(data contains id) { // Avoid building the complex def unless needed
    (ItemRef(id), this)
  } else {
    val itemDef = buildItemDef(data)
    (ItemRef(id), this.copy(items = items + (id -> itemDef)))
  }
}

In the code above, makeItem is really annoying to use since it has to take the store as input and returns two outputs:
val initialStore: ItemStore = Map.empty[String, ItemDef]
val (itemA, storeWithA) = makeItem(itemAData, initialStore)
val (itemB, storeWithAAndB) = makeItem(itemAData, storeWithA)

Besides being annoying to use, this is also error prone:
val store: ItemStore = Map.empty[String, ItemDef]
val (itemA, storeWithA) = makeItem(itemAData, store)
val (itemB, storeWithAAndB) = makeItem(itemAData, store) // !! Forgot to use updated store

And it's not very readable to make a collection of items:
def makeItems(rawItemsData: List[Map[String, String]], itemStore: ItemStore): (List[Item], ItemStore) = {
  rawItemsData.foldLeft(List.empty[Item], itemStore)({case ((items, store), currentItemData) =>
    val (currentItem, updatedStore) = makeItem(currentItemData, store)
    (items :+ currentItem, updatedStore)
  })
}

Is there a better pattern for doing this? I feel like there must be some cleaner way that doesn't involve returning tuples and taking extra arguments, but I'm just not seeing it.


texts:
Below is the implementation of MO algorithm for summing the sub array given the range as input.
As MO algorithm is a offline query it is given a list of ranges as input.

Below code calculates the result using MO algorithm and compares the result with expected output by directly summing the sub array.

MO algorithm first divides the whole array in sqrt(len of array) blocks and then divides the queries based on blocks. It sorts the input queries based on blocks and then based on the right parameters if the block number is same. It uses two pointers which moves left and right based on input query. The main intention of the algorithm is to reduce the movements of the pointers.

import collections
import math

def cmp(a, b):
    if a > b:
        return 1
    elif a < b:
        return -1
    return 0

def compare(a, b):
    def bin(x):
        return x[0]/r
    result = cmp(a, b)
    if result:
        return result
    return cmp(x[1], y[1])

a   = [1, 1, 2, 1, 3, 4, 5, 2, 8];
r = math.sqrt(len(a))
d_query = {0:[0, 5], 1:[5, 8], 2:[2, 4], 3:[5, 6]}
od = collections.OrderedDict(sorted(d_query.items(), compare, key= lambda x: x[1]))
print(od)

l = r = 0
cur_sum = 0
cur_l = 0
cur_r = -1
result = {}
for key, value in od.items():
    l = value[0]
    r = value[1]
    while cur_r < r:
        cur_r += 1
        cur_sum += a[cur_r]
    while cur_r > r:
        cur_sum -= a[cur_r]
        cur_r -= 1
    while cur_l < l:
        cur_sum -= a[cur_l]
        cur_l += 1
    while cur_l > l:
        cur_l -= 1
        cur_sum += a[cur_l]
    result[key] = cur_sum

for (k1,v1), (k2, v2) in zip(d_query.items(),result.items()):
    if k1 != k2 or v1 == v2:
        print("failed")
        break
print(result)


texts: 'do { statement; } while(0)' against 'statement' when writing C macro?

texts:
Which one of the following is preferrable and why when writing C macro?

Type 1

#define I2C_START()                 I2C_WAIT_IDLE(); SSP1CON2bits.SEN  = 1

Type 2

#define I2C_START()               \
    do                            \
    {                             \
        I2C_WAIT_IDLE();          \
        SSP1CON2bits.SEN  = 1;    \
    }while(0)

One of my colleagues prefers Type 1 while I prefer Type 2. So when both of us work in a project, both of the types are seen throughout the project.


texts:
I wrote this Console.Write function to use in my applications where I need to easily color-code output.

Example syntax would be:

Console.WriteLine("<f=red>this is in red");
Console.WriteLine("<b=gray><f=white>This is white on gray. <f=green>This is green on gray. <b=darkmagenta>This is green on dark magenta. <b=d>This is green on default.");

Which results in this...

I'm looking for a general review of the code.

//github.com/BenVlodgi/CommandHelper
public static class Console
{
    private static Regex _writeRegex = new Regex("<[fb]=\\w+>");

    public static void WriteLine(string value, int? cursorPosition = null, bool clearRestOfLine = false)
    {
        Write(value + Environment.NewLine, cursorPosition, clearRestOfLine);
    }

    public static void Write(string value, int? cursorPosition = null, bool clearRestOfLine = false)
    {
        if (cursorPosition.HasValue)
            System.Console.CursorLeft = cursorPosition.Value;

        ConsoleColor defaultForegroundColor = System.Console.ForegroundColor;
        ConsoleColor defaultBackgroundColor = System.Console.BackgroundColor;

        var segments = _writeRegex.Split(value);
        var colors = _writeRegex.Matches(value);

        for (int i = 0; i < segments.Length; i++)
        {
            if (i > 0)
            {
                ConsoleColor consoleColor;
                // Now that we have the color tag, split it int two parts,
                // the target(foreground/background) and the color.
                var splits = colors[i - 1].Value
                    .Trim(new char[] { '<', '>' })
                    .Split('=')
                    .Select(str => str.ToLower().Trim())
                    .ToArray();

                // if the color is set to d (default), then depending on our target,
                // set the color to be the default for that target.
                if (splits[1] == "d")
                    if (splits[0][0] == 'b')
                        consoleColor = defaultBackgroundColor;
                    else
                        consoleColor = defaultForegroundColor;
                else
                    // Grab the console color that matches the name passed.
                    // If none match, then return default (black).
                    consoleColor = Enum.GetValues(typeof(ConsoleColor))
                        .Cast<ConsoleColor>()
                        .FirstOrDefault(en => en.ToString().ToLower() == splits[1]);

                // Set the now chosen color to the specified target.
                if (splits[0][0] == 'b')
                    System.Console.BackgroundColor = consoleColor;
                else
                    System.Console.ForegroundColor = consoleColor;
            }

            // Only bother writing out, if we have something to write.
            if (segments[i].Length > 0)
                System.Console.Write(segments[i]);
        }

        System.Console.ForegroundColor = defaultForegroundColor;
        System.Console.BackgroundColor = defaultBackgroundColor;

        if (clearRestOfLine)
            ClearRestOfLine();
    }

    public static void ClearRestOfLine()
    {
        int winTop = System.Console.WindowTop;
        int left = System.Console.CursorLeft;
        System.Console.Write(new string(' ', System.Console.WindowWidth - left));
        System.Console.CursorLeft = left;
        System.Console.CursorTop--;
        System.Console.WindowTop = winTop;
    }
}


texts: Finding a key from values (which are list) in dict

texts:
I have a dictionary:

x = {'a': [1, 2, 3], 'b': [4, 5, 6]}

and I have to extract a key based on an input. For example assume it is 3, so my output should be 'a'.

Here's my code:

x = {'a': [1, 2, 3], 'b': [4, 5, 6]}

n = 3

output = [k for k, v in x.items() if n in v]

print(output[0])

Can it be done more efficiently?

Elements in the lists are unique, i.e. the value 3 will only be in one list.


texts: Using vswprintf( ... ) to create wchar_t* with variable argument list

texts:
I am using c++17 and wide characters.
I have created a function to create a wchar_t* using a variable number of parameters ...
#include <stdarg.h>

// the caller will free the memory
wchar_t* GetMessage( const wchar_t* format, ... )
{
  va_list args;
  va_start(args, format);

  // get the size of the final string
  const auto size = vswprintf(nullptr, 0, format, args);

  // create the buffer
  const auto buffSize = size + 1;
  const auto buffer = new wchar_t[buffSize];
  memset(buffer, 0, buffSize * sizeof(wchar_t) );

  // create the string
  vswprintf_s(buffer, buffSize, format, args);

  va_end(args);

  // all done
  return buffer;
}

Can you suggest a more efficient, standard, way of achieving the above?


texts: Get minimum of each group based on hour criteria using pandas

texts:
I have a requirement which I posted in SO. However, I have already written code and works fine. I request your review to know whether it is fool proof/elegant and efficient. Please find the details here in SO post Question in SO

my code

df['time_1']= pd.to_datetime(df['time_1'])
s=pd.to_timedelta(24,unit='h')-(df.time_1-df.time_1.dt.normalize())
df['tdiff'] = df.groupby(df.time_1.dt.date).time_1.diff().shift(-1).fillna(s)
df['t_d'] = df['tdiff'].dt.total_seconds()/3600
df['hr'] = df['time_1'].dt.hour
df['date'] = df['time_1'].dt.date
df['day'] = pd.DatetimeIndex(df['time_1']).day

# here I get the freq and cumsum of each val for each day and each hour.Since sort = 'False', timeorder is retained as is

temp_1 = pd.DataFrame(df.groupby(['subject_id','date','hr','val'], sort=False)['t_d'].agg({'cumduration':sum,'freq':'count'}).reset_index())

# here i remove the `hour` component and sum the value duration in same day but different hours (for example `5` was in 12th hour and 13th hour. we sum them)

temp_2 = pd.DataFrame(temp_1.groupby(['subject_id','date','val'], sort=False)['cumduration'].agg({'sum_of_cumduration':sum,'freq':'count'}).reset_index())

# Later, I create a mask for `> 1` hr criteria

mask = temp_2.groupby(['subject_id','date'])['sum_of_cumduration'].apply(lambda x: x > 1)
output_1 = pd.DataFrame(temp_2[mask].groupby(['subject_id','date'])['val'].min()).reset_index()

# I check for `< 1 ` hr records here

output_2 = pd.DataFrame(temp_2[~mask].groupby(['subject_id','date'])['val'].min()).reset_index()

# I finally check for `subject_id` and `date` and then append

output = output_1.append(output_2[~output_2['subject_id'].isin(output_1['subject_id'])])

output


texts: Least significant digit (LSD) radix sort of strings

texts:
I am learning string algorithms and wrote this C example based on a Java example I found online.  Any feedback relating to style, code clarity, whether it is generic enough to be re-used, interface, etc, etc would be very much appreciated.

/*
 Demonstration of least significant digit (LSD) radix sort of strings
 Specifically UK vehicle registration numbers
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define PLATELENGTH 7
#define ALPHABET 36

/* Characters must be uppercase or digits */
void lsd_string_sort(char* a[], const int length, int string_size) {
   int R = ALPHABET;
   int W = string_size;
   const int N = length;
   char id = 0;
   char** aux = (char**)malloc(length * string_size);

   for(int d = W-1; d >= 0; d--) {
      int* count = (int*)calloc(R+1, sizeof(int));
      /* whether character or digit */
      id = (*(a[0]+d) >= '0' && *(a[0]+d) <= '9') ? '0' : 'A';
      /* Compute frequency counts */
      for(int i = 0; i < N; i++)
         count[*(a[i]+d) - id + 1]++;
      /* transform counts to indices */
      for(int r = 0; r < R; r++)
         count[r+1] += count[r];
      /* distribute to temp array */
      for(int i = 0; i < N; i++)
          aux[count[(*(a[i]+d) - id)]++] = a[i];
      /* copy back to original array */
      for(int i = 0; i < N; i++)
         a[i] = aux[i];

      free(count);
   }
   free(aux);
}

int main() {

   /* in real application would use re-sizing array */
   char* plates[1000] = {0};

   int arr[10] = {0};
   char plate[16];  /* extra space just in case */
   int n = 0;
   printf("Please enter list of UK registration plates (skip spaces between registration numbers)\n");
   while(scanf("%s", &plate) == 1) {
      plates[n++] = strdup(plate);
   }

   printf("List before sorting\n");
   for(int i = 0; i < n; i++)
      printf("%s\n", plates[i]);

   lsd_string_sort(&plates[0], n, PLATELENGTH);

   printf("List after sorting\n");
   for(int i = 0; i < n; i++)
      printf("%s\n", plates[i]);

   while(n > 0)
      free(plates[--n]);

   return 0;
}


texts: Factory class that uses reflection to instantiate objects by class name

texts:
In this SO post Dynamically choose class from string  Alexander Platonov creates a Function on the fly and then uses Application.Run() to instantiate an Object by it's class name. Eureka Reflection in VBA!!  How evil! How inspiring!! So that began my journey into the darkness.

My quest for power over Reflection spawn the ReflectionFactory class.  The default instance of this class modifies itself by adding clauses to a Select Case.  This allows me to instantiate the Objects by their class names using the New keyword.

IAnimal:Interface

Option Explicit

Public Function Speak() As String
End Function

Dog:Class

Option Explicit
Implements IAnimal

Public Function Speak() As String
    Const Phrase As String = "Ruff Ruff Ruff"
    Debug.Print TypeName(Me); " says:"; """"; Phrase; """"
    Application.Speech.Speak Phrase
    Speak = Phrase
End Function

Private Function IAnimal_Speak() As String
    Speak
End Function

Cat:Class

Option Explicit
Implements IAnimal

Public Function Speak() As String
    Const Phrase As String = "Meow Meow Meow"
    Debug.Print TypeName(Me); " says:"; """"; Phrase; """"
    Application.Speech.Speak Phrase
    Speak = Phrase
End Function

Private Function IAnimal_Speak() As String
    Speak
End Function

ReflectionFactory:Class

Attribute VB_Name = "ReflectionFactory"
Attribute VB_PredeclaredId = True

Option Explicit
Private Const InsertAfter As String = "'" & "@Case ClassName InsertAfter"
Private Const vbext_ct_ClassModule As Long = 2

Public Sub AddClasses(ParamArray ClassNames() As Variant)
    Dim StartLine As Long
    Dim ClassName

    With getCodeModule
        For Each ClassName In ClassNames
            If Not .Find("Case*New " & ClassName, 1, 1, 1, 1, , , True) Then
                .Find InsertAfter, StartLine, 1, 1, 1
                .InsertLines StartLine + 1, getClassNameCase(CStr(ClassName))
            End If
        Next
    End With
End Sub

Public Sub Build()
    Dim VBComp As Object
    For Each VBComp In ThisWorkbook.VBProject.VBComponents
        If VBComp.Type = vbext_ct_ClassModule Then
            AddClasses VBComp.Name
        End If
    Next
End Sub

Private Function getCodeModule() As Object
    Set getCodeModule = ThisWorkbook.VBProject.VBComponents(TypeName(Me)).CodeModule
End Function

Private Function getClassNameCase(ByVal ClassName As String) As String
    getClassNameCase = vbTab & vbTab & "Case " & Chr(34) & ClassName & Chr(34) & ": Set CreateObject = New " & ClassName
End Function

Public Property Get CreateObject(ByVal ClassName As String) As Object
    Select Case ClassName
    '@Case ClassName InsertAfter
        Case "IAnimal": Set CreateObject = New IAnimal
        Case "MasterFactory": Set CreateObject = New MasterFactory
        Case "Dog": Set CreateObject = New Dog
        Case "Cat": Set CreateObject = New Cat

    End Select
End Property

Test

Sub ThisIsTooFun()
    Dim kitty As IAnimal, puppy As IAnimal, Animal As IAnimal
    ReflectionFactory.Build

    Set kitty = ReflectionFactory.CreateObject("Cat")
    Set puppy = ReflectionFactory.CreateObject("Dog")
    Set Animal = ReflectionFactory.CreateObject(Choose(WorksheetFunction.RandBetween(1, 2), "Cat", "Dog"))

    kitty.Speak
    puppy.Speak
    Animal.Speak
End Sub

Results

In truth, I will probably never use it but boy was it fun to get it working!!!

I'm still interested in your feedback.  Do you think that it has any real world applications?  Hmmm...  Java Bean too outdated. VBA Bean for use in a Visual Bean Application.


texts:
I have the following code, made in C language, which reproduces the functionality of the mv (move) command from linux. The problem is that the code is very inefficient. How I can optimize or make the code more efficient without changing the structure too much?

#include    <limits.h>
#include    <fcntl.h>
#include    "ourhdr.h"
#include    <sys/stat.h>
#include    <dirent.h>
int main(int argc,char *argv[])
{
    if(argc!=3)
    {
        printf("<Sintaxa> <fisier sursa> <fisier destinatie> \n");
        exit(1);
    }
    int ren1,ren2;
    struct stat buf1;
    struct stat buf2;
    lstat(argv[2],&buf1);
    lstat(argv[1],&buf2);
    char src[PATH_MAX];
    strcpy(src,argv[1]);
    char dst[PATH_MAX];
    strcpy(dst,argv[2]);
    int src_size = (int)strlen(src);
    int dst_size = (int)strlen(dst);
    dst[dst_size] = '/';
    dst[dst_size + 1] = '\0';
    dst_size++;
    int i;
    int index=0;
    int index1=src_size;
    while(--index1>0)
    {
        if(src[index1]=='/')
        {
            index1=0;
        }
        else
            index++;
    }
    for (i = src_size-index-1; i < src_size; i++)
    {
        dst[dst_size++] = src[i];
    }
    dst[dst_size] = '\0';
    if (access(src,F_OK)==-1)
    {
        err_ret("%s: cannot stat '%s'", argv[0],argv[1]);
        return -1;
    }
    if(S_ISDIR(buf1.st_mode))
    {
        if(((S_ISDIR(buf2.st_mode))&&(!(opendir(argv[1]))))||(!(opendir(argv[2]))))
        {
            err_quit("%s: cannot move '%s' to '%s': Permission denied \n", argv[0],argv[1],dst);
        }
        ren1=rename(src,dst);
        if(ren1!=0)
        {
            err_quit("Error: unable to move the file");
        }
    }
    else
    {
        ren2=rename(argv[1],argv[2]);
        if(ren2!=0)
        {
            err_quit("Error: unable to rename the file ");
        }
    }
}

The code above works fine but is way to inefficient


texts:
I'm trying to compare two lists of floating point data and see if they might have come from different underlying distributions. The two samples are a before and after, so by comparing the two I thought I could detect whether any change occurred between the two timeframes.

To do this I'm using the two-sample Kolmogorov-Smirnov test. I have the following function which calculates the core statistic used in the test:

def kolmogorov_smirnov(data1, data2):
    """
    Given two lists of data, finds the two-sample Kolmogorov–Smirnov statistic
    """
    data1 = sorted(data1)
    data2 = sorted(data2)

    index1 = 0
    index2 = 0

    ks_stat = 0

    while index1 < len(data1) and index2 < len(data2):
        if data1[index1] == data2[index2]:
            index1 += 1
            index2 += 1

        elif data1[index1] < data2[index2]:
            index1 += 1

        elif data1[index1] > data2[index2]:
            index2 += 1

        ks_stat = max(ks_stat, abs(index1/len(data1) - index2/len(data2)))

    return ks_stat

I realise that I can also shorten the while loop like so:

while index1 < len(data1) and index2 < len(data2):
    if data1[index1] <= data2[index2]:
        index1 += 1

    if data1[index1] >= data2[index2]:
        index2 += 1

    ks_stat = max(ks_stat, abs(index1/len(data1) - index2/len(data2)))

Which version should I use? Also, is there anything worth pointing out about the main code?


texts: My attempt at Dijkstra's Algorithm in Python 3

texts:
I am practicing my coding at HackerRank. The exact problem statement can be found here, but to summarize, it is finding the distances of the shortest path from a starting node to every other node in a non-directional graph where every edge is weighted 6. If a node is unreachable, the distance is -1. The nodes are named 1 to n. If you want an example, please see the provided one in the link.

To solve this, I googled an explanation of Dijkstra's Algorithm and tried my best to implement it (I am new to graph problems). My program passes 6/7 of the test cases, but it times out on the 7th. I improved some small inefficiencies, but it wasn't enough. Please advise me on how I may make the following faster:

def shortest (start, nodes, adj):
    unique = [] #this part is pretty standard for this Algorithm I think
    distance = [float('inf')]*nodes
    for i in range(1, nodes+1):
        if (len(adj[i-1])>0):
            unique.append(i)
    distance [start-1] = 0
    while (len(unique)>0):
        minDist = float('inf')
        for i in unique:
            if (distance[i-1] <= minDist):
                minDist = distance[i-1]
                distIndex = i
        current = distIndex #sets the current node as the closest unvisited node
        unique.remove(current)
        for i in adj[current-1]: #updates the distance of each neighbour of the current node
                neigh = i
                temp = 6 + distance[current-1] #edges are 6
                if temp < distance[neigh-1]:
                    distance[neigh-1] = temp
    return distance

q = int(input()) #each test case contains multiple problems, so just consider one iteration

for i in range(q):
    a = [] #for input purposes
    b = [] #for output purposes
    node = 0
    edge = 0

    #start of input
    node, edge = list(map(int, input().strip().split())) #the input begins with the number of nodes and edges in the graph
    for j in range(edge):
        a.append(list(map(int, input().strip().split()))) #reading the edges, which are all inputted next
    starting = int(input()) #reading the starting node
    #end of input

    adj = [[] for x in range(node)] #the adjacency matrix
    for j in a: #making the adjacency matrix from the inputted edges
        adj[j[0]-1].append(j[1])
        adj[j[1]-1].append(j[0])
    for j in adj:
        j = list(set(j)) #someone warned that the problematic test case gives the same edge many times, so this is to remove duplicates

    b = shortest(starting, node, adj)

    #formatting the output to what the question required
    b.remove(0)
    for i in range(len(b)):
        if b[i] == float('inf'):
            b[i] = -1
    print (" ".join(str(e) for e in b))

If it helps, I 'purchased' the test case which is timing out.


texts: Transforming a byte array into an array of byte arrays with F#

texts:
This code is intended to be used with an image manipulation library that I'm working on, and the goal is to take the raw byte[] data from an image, and transform it into a 2D array where each position on the array has a value corresponding to the pixel coordinates of the image.

Comments concerning how to do this faster or more aligned with F# standards, or concerning style and formatting, are very much appreciated. I'm still learning F# so I need all the help I can get.

let Transform2D (pArrayWidth:int) (pArray:byte[]) =
    let tHeight = pArray.Length / pArrayWidth
    let tImageArray = Array.zeroCreate<byte[]> tHeight

    let mutable tStart = 0
    let mutable tFinish = tStart + pArrayWidth - 1        // 0 indexed array

    for tRowIndex in [ 0 .. tHeight ] do
        tImageArray.[tRowIndex] <- pArray.[tStart .. tFinish]
        tStart <- tStart + pArrayWidth
        tFinish <- tFinish + pArrayWidth

    tImageArray


texts: how can I improve the check name file part

texts:
/**
 * Upload has a limit of 10 mb
 * @param string $dir $_SERVER['DOCUMENT_ROOT']
 * @param string $path Path do you want to upload the file
 * @param string $filetype jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx|ppt|pptx
 * @param array $_FILES An associative array of items uploaded to the current script via the HTTP POST method.
 * @return string ?$fileName:False
 */
function uploadFiles($dir, $path, $filetype) {
    $dir_base = "{$dir}{$path}";
    $dateadded = date('ynj_Gis-');
    $rEFileTypes = "/^\.($filetype){1}$/i";
    $MAXIMUM_FILESIZE = 10 * 1024 * 1024;

// UPLOAD IMAGES
    $isFile = is_uploaded_file($_FILES['file']['tmp_name']);
    if ($isFile) {
        $safe_filename = $dateadded . preg_replace(array('/\s+/', '/[^-\.\w]+/'), array('_', ''), trim($_FILES['file']['name']));
        if ($_FILES['file']['size'] <= $MAXIMUM_FILESIZE && preg_match($rEFileTypes, strrchr($safe_filename, '.'))) {
            $isMove = move_uploaded_file($_FILES['file']['tmp_name'], $dir_base . $safe_filename);
        }
    }
    if ($isMove) {
        return $safe_filename;
    } else {
        return false;
    }
}

How can I improve the name check part or another things?


texts:
I've got this simple ring/circular buffer class:

template<class T, size_t sz>
class CircularBuffer {

    std::array<T, sz> buffer;
    size_t head;
    size_t tail;
    bool isFull;

public:
    CircularBuffer() :
        head{0},
        tail{0},
        isFull{false} {
    }

    void put(T item) {
        buffer[head] = item;
        head = (head + 1) % sz;
        if (isFull) {
            tail = (tail + 1) % sz;
        }
        isFull = head == tail;
    }

    T get() {
        auto result = buffer[tail];
        tail = (tail + 1) % sz;
        isFull = false;
        return result;
    }

    bool empty() const {
        return tail == head;
    }

    size_t capacity() const {
        return sz;
    }

    size_t size() const {
        if (isFull)
            return sz;

        if (head >= tail)
            return head - tail;

        return sz + head - tail;
    }
};

And I was looking for clarification on a few things, to take advantage of C++ features.

First, the new constexpr keyword, what here, if anything should I apply it to? (I'm assuming the size_t size() const member function could use it? Anything else?)

Second, all of these member functions are quite small, should they be inlined?

Third, in the T get() member function, I do auto result = buffer[tail];, should I use auto& instead, or any other versions? (or even just T/T&?) Should that be a const as it's not modified within the function, and only potentially modified once a copy is returned via the functions return parameter.

Any other feedback is welcome!


texts: Implementation of Javascript Classes and Inheritance

texts:
I've created a simple Javascript library to be able to create "classes" and extend them defining instance and static methods and variables.

It consists in a simple function Class with two methods: create and extend.

var Class = function(){};

Class.extend = function(obj){

    var Extended = function(){};

    for(var key in this.prototype){
        Extended.prototype[key] = this.prototype[key];
    }

    for(var key in obj){
        Extended.prototype[key] = obj[key];
    };

    Extended.prototype.constructor = Extended;

  for (var key in this) {
    Extended[key] = this[key];
  };

  return Extended;
};

Class.create = function(constructor){
    var created = new this();
    for(var key in constructor){
        created[key] = constructor[key];
    }
    return created;
};

Here there's an example of what the library is able to do:

var Model = Class.extend({
    fields: {},
    save: function(){
        return "saving a model at " + Model.url;
    },
    destroy: function(){
        return "destroying...";
    }
});

Model.url = "http://localhost";

Model.all = function(){
    return "all from " + Model.url;
};

Model.find = function(id){
    return "finding by " + id;
};

var User = Model.extend({
    fields: {
        username: "default username",
        password: "default password",
    },
    logout: function(){
        return "logged out " + this.fields.username;
    },
    destroy: function(){
        return this.logout() + " and account destroyed!";
    }
});

User.url = Model.url + "/users";

User.all = function(){
    return "overriding parent! all from " + User.url;
}

User.findByUsername = function(username){
    return "finding by username: " + username;
};

And I've created a js fiddle to test the example  http://jsfiddle.net/R6jGe/

There's no way to call a parent instance method or variable.

how do you think the library could be improved?


texts:
I'm using a index system to say:

On index i use:

<?php core::doPage(); ?>

Core code is:

<?php
class core
{
    public static function doPage()
    {
        if(!isset($_GET["page"]) || empty($_GET) || !is_string($_GET["page"]))
        {
            if(!include_once('./_pages/index.php')) die("404 - File not found.");
        }
        else
        {
            $_GET["page"] = substr($_GET["page"], 0, -4);
            $pages = array_map(function($x) { return str_replace(".php", "", basename($x)); }, glob("./pages/*.php"));
            if(in_array($_GET["page"], $pages))
            {
                if(!include_once("./_pages/{$_GET["page"]}.php")) die("404 - File not found.");
            }
            else
                if(!include_once('./_pages/404.php')) die("404 - File not found.");
        }
    }
}
?>

Any tweak suggestions or is this code fairly secure? Not exploitable?


texts:
Just getting up to speed in Ramda, I have implemented this:

var R = require('ramda');
var divisibleBy = (b) => R.compose(R.equals(0), R.flip(R.modulo)(b))
var fizzbuzz =  R.map(R.cond([
  [R.both(divisibleBy(3), divisibleBy(5)), R.always('FizzBuzz')],
  [divisibleBy(3), R.always('Fizz')],
  [divisibleBy(5), R.always('Buzz')],
  [R.T, R.identity]
]));

console.log(fizzbuzz(R.range(1,101)))

Can I improve this, or is there a more canonical way of doing this in Ramda?


texts:
I have dataframe like this:

date        tableName                attributeName
2019-03-29  [order as o, costumer]   [costumer.customerID, o.orderID]
2019-03-30  [customer c, payment]    [payment.paymentID, c.firstName]
...

I have a function that map the tableName to attribute, like this:

import pandas as pd
import re
def countTableAttribute(dataFrame, tableName, attributeName):
    a       = (dataFrame[tableName].values.tolist())
    r       = re.compile(r'\b(as|\s)\b',re.IGNORECASE)
    alias   = list((x,n) for x in range(len(a)) for n in a[x] if bool(r.search(n)))
    df3     = (pd.DataFrame(dataFrame[tableName].values.tolist(), index=dataFrame.index).stack().str.split(' as | ', expand=True)).dropna()
    if alias != []:
        d   = dict(zip(df3[1], df3[0]))
    else:
        d   = dict(zip(df3[0], df3[0]))
    dfs     = pd.DataFrame(columns=[-1,0,1])
    for i in range(len(dataFrame)):
        for x in dataFrame[attributeName][i]:
            if not '.' in x:
                ser = pd.Series([dataFrame['date'][i],dataFrame[tableName][i][0], x], index=dfs.columns)
                dfs = dfs.append(ser, ignore_index=True)
            else:
                ser = pd.Series([dataFrame['date'][i],x.split('.')[0], x.split('.')[1]], index=dfs.columns)
                dfs = dfs.append(ser, ignore_index=True)
    dfs.columns         = ['Date','tableName','attributeName']
    dfs['tableName']    = dfs['tableName'].replace(d)
    dfs                 = dfs.groupby(['Date','tableName','attributeName'], sort=False).size().reset_index(name='Count')
    return dfs

so the output is like this:

   date        tableName   attributeName  count
2019-03-29     order       orderID          1
2019-03-29     costumer    customerID       1
2019-03-30     customer    firstName        1
2019-03-30     payment     paymentID        1

But as this is my first try, I need an opinion about what I've tried, because my code runs slow.

Thank you


texts:
I've just created my first plugin, but I think I've written too much bloated code. Could you point me to the right direction?

$.fn.replaceme = function() {

    function add_essentials(element) {
        var native_btn = element;
        native_type = native_btn.attr('type');

        native_btn.each(function() {
            var n_btn = $(this);
            n_btn.next('label').addClass('label-replacement');
            n_btn.wrap('

');
            n_btn.parent('.input-container').append('
');
        });
    }

    function replace_default_action(element) {
        var input = element;
        group = input.attr('name');

        $('input[name="' + group + '"]').each(function() {

            var input_select = $(this);
            if (input_select.is(':checked')) {
                input_select.siblings('.input-replacement').addClass('selected');
            } else {
                input_select.siblings('.input-replacement').removeClass('selected');
            }
        });
    }

    function label_action(element) {
        element.prevAll('.input-container').children('.styled-input').prop('checked', 'checked').trigger('change');
    }

    function live_check() {
        $('.styled-input:checked').each(function() {
            $(this).siblings('.input-replacement').addClass('selected');
        });
    };

    return this.each(function() {

        var $this = $(this);

        add_essentials($this);
        live_check();

        $('body').on('change', '.styled-input', function() {
            replace_default_action($this);
        });

        $('body').on('click', '.label-replacement', function() {
            label_action($this);
        });
    });
}

$('.styled-input').replaceme();


texts: Query string substitutions for links on a page

texts:
If the current page URL has an argument 'myid1' or 'myid2' in the querystring, for each link in my webpage with class 'rewrite', I want the link href's querystring to be replaced by the current page URL's querystring. I'm using the code given below. Since I'm new to javascript, I'm not sure if its optimized. I want it to execute as fast as possible.

Hyperlink


texts: Create a two dimensional int array and find the smallest and biggest member along with the indexes

texts:
From a CS Diploma course question set:

Create a two dimensional array of ints, fill it with any random integers. Now find the minimum and maximum number, also find the index of those numbers.

I was not sure what they meant by "fill it with any random integers". Should I just use my imagination? Since I wasn't sure, I opted for using rand().
My Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>

int main (void) {
    int array[10][10];

    srand((unsigned int)time(NULL));

    struct Nums {
        int num,
            i,
            j;
    } min, max;

    min.num = INT_MAX;
    max.num = 0;

    for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++) {
            array[i][j] = rand();
            if (array[i][j] > max.num) {
                max.num = array[i][j];
                max.i = i;
                max.j = j;
            }
            if (array[i][j] < min.num) {
                min.num = array[i][j];
                min.i = i;
                min.j = j;
            }
        }
    printf("Max number: %d, row: %d, column: %d\n", max.num, max.i, max.j);
    printf("Min number: %d, row: %d, column: %d\n", min.num, min.i, min.j);
    return 0;
}

I did not go through the loop twice, i.e. I checked for the max and min numbers while filling up the array, is that the wrong approach considering the question?
Also is there any easier way to achieve the same result?
Thank you.


texts:
Originally, I had everything in the base method #read_wall(). I'm not sure what happened with the array, but when I tried:

array = result + second + third + fourth. I was left with data from only the original result. So I created this working disaster. Can you please help me refactor this?

   # Gets the user's Wall
      def read_wall(fbuserid)
         result ||= graph.get_connections(fbuserid, 'feed')
      end

  def second_wall(fbuserid)
     result ||= graph.get_connections(fbuserid, 'feed')
     second ||= result.next_page
  end

  def third_wall(fbuserid)
       result ||= graph.get_connections(fbuserid, 'feed')
       second ||= result.next_page
       third ||= second.next_page
  end

  def fourth_wall(fbuserid)
        result ||= graph.get_connections(fbuserid, 'feed')
        second ||= result.next_page
        third ||= second.next_page
        fourth ||= third.next_page
   end

  # Collects your friends' wall Posts and puts the IDs into an array
  def get_post_ids(fbuserid)
     x ||= read_wall(fbuserid)
     var = []
     for i in 0..25
        if find_nil(x, [i,'id']).nil? == false
           var << x[i]['id']
        end
     end

     second_wall ||= second_wall(fbuserid)
       for i in 0..25
          if find_nil(second_wall, [i,'id']).nil? == false
             var << second_wall[i]['id']
          end
       end

      third_wall ||= third_wall(fbuserid)
        for i in 0..25
           if find_nil(third_wall, [i,'id']).nil? == false
              var << third_wall[i]['id']
           end
        end

      fourth_wall ||= fourth_wall(fbuserid)
         for i in 0..25
            if find_nil(fourth_wall, [i,'id']).nil? == false
                 var << fourth_wall[i]['id']
            end
         end

      @get_post_ids = var
  end


texts: Simple Python module to test dictionaries

texts:
I have some hardware for which I have a driver for which I have a library which can be used to easily configure and probe the device. Now I want to add support for this library to python because the management interface runs on a web server with a Python back-end, and I want to make the device manageable from the web interface, so it'll be easier if the back-end Python code can speak "directly" to the hardware.

Only issue is that I'm not certain about the ownership semantics in Python (2.7 if it matters, but I suspect that these semantics haven't changed much in 3.x), and this particular device needs to have very long uptime so I want to make sure I'm understanding the reference semantics correctly.

While the primary goal is to make sure I don't have any reference leaks, actually understanding the reference counting system is important to me. So if I'm unnecessarily releasing a reference, then that's interesting to know as well.

Specifically I'm wondering:

I assume that in get_conf() I don't need to incref the dict object when it's returned?  (I read somewhere that C functions act as regular scopes so new objects are deref'd when the function returns—is this accurate, and does this apply to returned objects?)
In set_conf(), do I need to decref the tmpstr? (Related to the point above). Let's say I create tmpstr once, and then reuse it and I don't decref it, will it be decref'd once the function returns?

I'm wondering if I have gotten references figured out correctly.

#include <stdbool.h>

#include <Python.h>

static PyObject *get_conf(PyObject *self, PyObject *args);
static PyObject *set_conf(PyObject *self, PyObject *args);

static PyMethodDef Methods[] = {
    {"get_conf", get_conf, METH_NOARGS,
     "Get configuration as a dictionary."},
    {"set_conf", set_conf, METH_VARARGS,
     "Set configuration from a dictionary."},
    {NULL, NULL, 0, NULL}        /* Sentinel */
};

bool g_enabled = true;
long g_val = 42;

PyMODINIT_FUNC initmyfoo(void)
{
  PyObject *m;

  m = Py_InitModule("myfoo", Methods);
  if(m == NULL) {
    return;
  }
}

static PyObject *get_conf(PyObject *self, PyObject *args)
{
  PyObject *dict;
  PyObject *b;

  dict = PyDict_New();
  if(dict == NULL) {
    /* should set exception before returning NULL! */
    return NULL;
  }

  if(g_enabled) {
    b = Py_True;
  } else {
    b = Py_False;
  }
  PyDict_SetItemString(dict, "enabled", b);
  PyDict_SetItemString(dict, "num_foo", PyLong_FromLong(42));

  return dict;
}

static PyObject *set_conf(PyObject *self, PyObject *args)
{
  PyObject *dict;
  PyObject *tmpstr;

  if(!PyArg_ParseTuple(args, "O", &dict)) {
    return NULL;
  }

  tmpstr = PyString_FromString("enabled");
  if(PyDict_Contains(dict, tmpstr) == 1) {
    PyObject* b;

    b = PyDict_GetItemString(dict, "enabled");
    if(PyObject_IsTrue(b)) {
      puts("enabling!");
      g_enabled = true;
    } else {
      puts("disabling!");
      g_enabled = false;
    }
  }
  Py_DECREF(tmpstr);

  tmpstr = PyString_FromString("num_foo");
  if(PyDict_Contains(dict, tmpstr) == 1) {
    PyObject* i;
    long val;

    i = PyDict_GetItemString(dict, "num_foo");
    if(PyInt_Check(i)) {
      long val;

      val = PyInt_AsLong(i);
      printf("setting num_foo=%u\n", (unsigned)val);

      g_val = val;
    } else {
      /* ToDo: Not a number exception */
      return NULL;
    }
  }
  Py_DECREF(tmpstr);

  Py_RETURN_NONE;
}


texts: Finding the middle day of a month, given any day within that month

texts:
Given a date, need to find the middle day of that day's month, or if there are an even number of days (with no exact middle day), the day should be the closest day to the middle of the month on the second half of the month.

For example, if the date given is August 2 (a month with 31 days), the middle day returned should be Aug 16.
If the date given is September 28 (a month with 30 days), the middle date returned should be 16 (15 would be closest day to middle in first half of month, 16 would be closest day to middle in second half of month).

Here's the code. Any better way to accomplish this with only version 2.4 and higher standard library and core?

#ruby 2.4.2
#require 'date'
def middleOfMonth(d)
  advancedMonth = d.next_month
  lastDayOfPreviousMonth = (Date.new(advancedMonth.year, advancedMonth.month, 1) - 1).day
  exactMiddle = lastDayOfPreviousMonth.to_f / 2
  actualMiddle = exactMiddle.floor + 1
  actualMiddle
end


texts:
I have a basic switch statement that executes some code on expectedValue and givenValue. The code to execute is guided by the variable actionToApply. This leaves one more variable that is fieldTypeName. This essentially guides the code in to casting the values to the type defined by fieldTypeName - if needed.

I was hoping to have the switch block reviewed/refactored - if possible have the casting refactored away into another method that handles casting dynamically on the fly based on fieldTypeName. Then it can cast expectedValue and givenValue to the correct types making the switch statement code less repetitive and have less duplication.

At compile time we have the values as strings and we have the type to CastTo as a string too. I am open to using the dynamic keyword here if someone is brave enough.

Naturally as more types are added to the DB the below switch statement is going to grow and break a few SOLID principles along the way.

private bool Run(string actionToApply, string fieldTypeName, string expectedValue, string givenValue)
{
    switch (actionToApply)
    {
        case "HasValue":
            return !string.IsNullOrWhiteSpace(givenValue) && givenValue != expectedValue;

        case "EqualTo":
            return givenValue == expectedValue;

        case "NotEqualTo":
            return givenValue != expectedValue;

        case "Greater Than":
            if (fieldTypeName == "int")
            {
                var one = Convert.ToInt32(givenValue);
                var two = Convert.ToInt32(expectedValue);
                return one > two;
            }
            if (fieldTypeName == "double")
            {
                var one = Convert.ToDouble(givenValue);
                var two = Convert.ToDouble(givenValue);
                return one > two;
            }
            return false;
        case "Or":
            var orArrayValues = expectedValue.Split(new[] { SplitOperatorForOr }, StringSplitOptions.None);
            return orArrayValues.Any(x => x == givenValue);
        case "Less Than":
            if (fieldTypeName == "int")
            {
                var one = Convert.ToInt32(givenValue);
                var two = Convert.ToInt32(expectedValue);
                return one < two;
            }
            if (fieldTypeName == "double")
            {
                var one = Convert.ToDouble(givenValue);
                var two = Convert.ToDouble(givenValue);
                return one < two;
            }
            return false;

        case "Range":
            var given = Convert.ToInt32(givenValue);
            var rangeArrayValues = expectedValue.Split(new[] { SplitOperatorForRange }, StringSplitOptions.None);
            if (fieldTypeName == "int")
            {
                var rangeA = (int)Convert.ChangeType(rangeArrayValues[0], typeof(int));
                var rangeB = (int)Convert.ChangeType(rangeArrayValues[1], typeof(int));
                return given > rangeA && given < rangeB;
            }
            if (fieldTypeName == "double")
            {
                var rangeA = (double)Convert.ChangeType(rangeArrayValues[0], typeof(double));
                var rangeB = (double)Convert.ChangeType(rangeArrayValues[1], typeof(double));
                return given > rangeA && given < rangeB;

            }
            return false;
    }
    return false;
}


texts:
I am trying to self study algorithms and this is my attempt at topological sort using Tarjan's version of DFS. It runs correctly for the graph I included. Can someone tell me if this is correct and if/what optimizations I can make?

graph = {
'A':['C'],
'B': ['C', 'D'],
'C': ['E'],
'D': ['F'],
'E': ['F'],
'F': ['G'],
'G': [],
}

def topological_sort(graph):
    visited, stack = set(), []

    for vertex in graph:
        handle_vertex(graph, vertex, visited, stack)

    print(stack)

def handle_vertex(graph, vertex, visited, stack):
    if vertex not in visited:
        visited.add(vertex)

    for neighbors in graph[vertex]:
        if neighbors not in visited:
            handle_vertex(graph, neighbors, visited, stack)

    if vertex not in stack:
       stack.insert(0, vertex)
    return stack

print(topological_sort(graph))


texts:
I need to search a large repository of files for a specific resource, and return it only if it is used or not.

It is working as expected, but it is very time consuming. To search for 50 resource names takes around 200 seconds. I have many more than 50.

I found this question that helped a bit, but I was wondering if there is anything else I can do to speed it up.

$searchList = Get-ChildItem -r *.cs -OutBuffer 1000000
$usedIcons = @()

foreach ($name in $testNames) {
    $pattern = "Resources."+$name
    $found = $searchList | Select-String -Pattern $pattern -SimpleMatch -Quiet
    if($found -eq $true){
        Write-Host $name
        $usedIcons += $name
    }
}


texts: replace a text from emacs buffer to insert it vertically with emacs lisp script

texts:
I just found this post with vim (https://stackoverflow.com/questions/704130/can-i-transpose-a-file-in-vim) and i just wanted to do the same thing with elisp by creating a little script to reordenate all the characters from a buffer text into a vertical position.

As the post said, the original buffer might be:

THE DAY WAS LONG
THE WAY WAS FAST

and it would become:

TT
HH
EE

DW
AA
YY

WW
AA
SS

LF
OA
NS
GT

I write this little emacs script to first read each buffer lines in a list (removing spaces), and after using a zip function to transpose each characters between lists, and at the end iterate my list to print it in x columns.

(require 'subr-x)
(defun read-buffer-lines (buf)
  (let ((lines '()))
    (with-current-buffer buf
      (save-excursion
        (goto-char (point-min))
        (while (not (eobp))
          (if (not (string-equal "" (buffer-substring (point) (point-at-eol))))
              (push
               (delete " " (delete "" (split-string
                                       (string-trim (buffer-substring (point) (point-at-eol)))
                                       "")))
                  lines)
              )
            (beginning-of-line 2))
        (erase-buffer) ;; clean buffer
        (nreverse lines)
        ))))

(defun zip_list (lst)
  (let ((res))
    (while (-none? 'null lst)
      (setq res (cons (mapcar 'car lst) res))
      (setq lst (mapcar 'cdr lst)))
    (nreverse res)
    ))

(let* ((buf "*scratch*")
       (a (zip_list (read-buffer-lines buf))))
  (with-current-buffer buf
    (while a
      (progn
        (insert (mapconcat 'identity (car a) ""))
        (newline)
        (setq a (cdr a))))))


texts:
I'm working on a fluent interface builder that takes:

an array of strings, each of which becomes a key to an object that is a function that follows the fluent interface pattern
a terminator function which when called breaks the chain and does something else

I'm looking for some advice on how to improve this.

var Twitter = require('twit');

var secrets = require("./secrets/secrets");
var fs = require("fs");
var Twit = require('twit')

    var T = new Twit({
      consumer_key: secrets.consumer_key,
      consumer_secret: secrets.consumer_secret,
      access_token: secrets.access_token,
      access_token_secret: secrets.access_token_secret,
      timeout_ms: 60 * 1000,  // optional HTTP request timeout to apply to all requests.
    });
    function fluentBuilder(options, terminator) {
      let locals = options.reduce((opt, e) => {
        opt[e] = null;
        return opt;
      }, {});
      var methods = options.reduce((opt, e) => {
        opt[e] = (val) => {
          if (val) {
            locals[e] = val;
            return opt;
          } else return locals[e];

        }
        return opt;
      }, {});
      methods.locals = locals;
      methods["execute"] = terminator;
      return methods;
    }

    var geocode = fluentBuilder(["lat", "long"],
      function () {
        var self = this;
        return new Promise(resolve => {
          T.get("geo/reverse_geocode", self.locals, function (err, data, results) {
            resolve(data);
          });
        });
      });
      //calls to lat and long are stored on the self.locals variable which is passed to the Promise callback.
      geocode.lat("34.0406")
        .long("-84.2031")
        .execute()
        .then(data => {
          console.log(data);
        });


texts: Finding strongly connected components in a directed graph using Kosaraju's algorithm

texts:
I'm working through Stanford's algorithms course on edX.
One of the programming assignments is to find strongly connected components using Kosaraju's algorithm, on a graph with ~875,000 vertices. My implementation is the most basic translation from the textbook's pseudo code into Python, and it works fine on smaller graphs, so I think it's correct.
With Python's default recursion limit of 1000 it reaches the limit.
I've tried sys.setrecursionlimit(1000000), but that doesn't help, and instead I get "Process finished with exit code -1073741571" which is a stack overflow.
G = {}
for i in range(1, 875715):
    G[i] = [0] #Each dictionary entry is a list. The first element of the list is 0 if the vertex is unexplored, otherwise 1.
for l in open('SCC.txt'):
    items = list(map(int, l.split()))
    G[items[0]].append(items[1])

Grev = {} #The same graph, with the edges reversed.
for i in range(1, 875715):
    Grev[i] = [0]
for l in open('SCC.txt'):
    items = list(map(int, l.split()))
    Grev[items[1]].append(items[0])

def TopoSort(G): #Topological sort on the reversed graph.
    for v in G:
        if G[v][0] == 0:
            DFStopo(G, v)

def DFStopo(G, s):
    G[s][0] = 1
    global orderedVertexList #The order in which to run DFS and assign SCCs.
    for v in G[s][1:]:
        if G[v][0] == 0:
            DFStopo(G, v)
    orderedVertexList.insert(0, s)

def Kosaraju(G, Grev):
    TopoSort(Grev)
    global numSCC
    for v in orderedVertexList:
        if G[v][0] == 0:
            numSCC = numSCC + 1
            DFSSCC(G, v)

def DFSSCC(G, s):
    G[s][0] = 1
    global SCC
    SCC.append(numSCC) #The submission only requires the size of the five largest SCCs, so order doesn't matter.
    for v in G[s][1:]:
        if G[v][0] == 0:
            DFSSCC(G, v)

numSCC = 0
orderedVertexList = []
SCC = []

Kosaraju(copy.deepcopy(G), copy.deepcopy(Grev))
```


texts: Determine what hazard type does the building belong using GeoDjango Intersects

texts:
Below is my query to identify what hazard type does the buildings belong:

def floodhazard_tbl(request):
    if request.method == "GET":
        reference_high = FloodHazard.objects.filter(hazard='High')
        reference_medium = FloodHazard.objects.filter(hazard='Medium')
        reference_low = FloodHazard.objects.filter(hazard='Low')

        #get all ids based on filter
        ids_high = reference_high.values_list('id', flat=True)
        ids_medium = reference_medium.values_list('id', flat=True)
        ids_low = reference_low.values_list('id', flat=True)

        # create a list
        k = []
        response_high = []
        response_medium = []
        response_low = []
        bldg_id_high = []
        bldg_ids_high = []
        bldg_id_medium = []
        bldg_ids_medium = []
        filtered_bldg = []

        # this code is results a messy JSON data that need underscore.js to manipulate
        # in order for us to use datatables
        for myid in ids_high:
            getgeom = FloodHazard.objects.get(id=myid).geom
            response_high = PolyStructures.objects.filter(geom__intersects=getgeom).values(
                'brgy_locat', 'municipali').annotate(counthigh=Count('brgy_locat'))
            bldg_id_high = filter(None,response_high.values_list('id',flat=True))
            bldg_ids_high = bldg_ids_high + bldg_id_high
            k.append(response_high)

        for myid in ids_medium:
            getgeom = FloodHazard.objects.get(id=myid).geom
            response_medium = PolyStructures.objects.exclude(id__in=bldg_ids_high).filter(geom__intersects=getgeom).values(
                'brgy_locat', 'municipali').annotate(countmedium=Count('brgy_locat'))
            bldg_id_medium = filter(None,response_medium.values_list('id',flat=True))
            bldg_ids_medium = bldg_ids_medium + bldg_id_medium
            k.append(response_medium)

        filtered_bldg = bldg_ids_medium + bldg_ids_high

        for myid in ids_low:
            getgeom = FloodHazard.objects.get(id=myid).geom
            response_low = PolyStructures.objects.exclude(id__in=filtered_bldg).filter(geom__intersects=getgeom).values(
                'brgy_locat', 'municipali').annotate(countlow=Count('brgy_locat'))
            k.append(response_low)

        #to_json = list(k for k,_ in itertools.groupby(k))
        result = []
        for d in chain.from_iterable(k):
            result.append(d)

        return HttpResponse(list(json.dumps(result)), content_type='application/json')

I have this method (algo):

After the response_high query, I get all the building that DID NOT intersect to the HIGH type of hazard and so on and exclude it in the next query (intersects) to avoid duplication (because there is a tendency that the building will intersect to the hazard polygon several times).

The code works but the response is slow, take 6 seconds to show the output.
As it is messed up, any optimization "technique" is appreciated.


texts:
I came across the following piece of code in a UI application I need to maintain.

int tool_unhex( char c )
{
    return( c >= '0' && c <= '9' ? c - '0'
        : c >= 'A' && c <= 'F' ? c - 'A' + 10
        : c - 'a' + 10 );
}

void unescape2QString(const char *sOrg, QString & str)
{
/*
 * Remove URL hex escapes from s... done in place.  The basic concept for
 * this routine is borrowed from the WWW library HTUnEscape() routine.
 */
    char* s = (char*)sOrg;
    unsigned short w = 0;

    str = "";

    for ( ; *s != '\0'; ++s ) {
        if ( *s == '%' ) {
            if(*(s+1) == 'u')
            {
                s++;
                if ( *++s != '\0' ) {
                    w = (wchar_t) (tool_unhex( *s ) << 12);
                }
                if ( *++s != '\0' ) {
                    w += (wchar_t) (tool_unhex( *s ) << 8);
                }
                if ( *++s != '\0' ) {
                    w += (wchar_t) (tool_unhex( *s ) << 4);
                }
                if ( *++s != '\0' ) {
                    w += (wchar_t) tool_unhex( *s );
                }

                str += QString::fromUtf16(&w, 1);
            }
        }
        else
        {
            str += QString::fromAscii(s, 1);
        }
    }
}

Isn't QString immutable?  The comment says it's changing in place, but isn't each str += creating a new QString?
Is this the most optimized way of doing this?

It looks like the function is trying to implement HTUnEscape() from w3.org, with UTF16 strings.


texts: Class that implements a queue using two stacks

texts:
I am looking for a review of my code that implements a MyQueue class which implements a queue using two stacks.

public class MyQueue<T> {
  Stack<T> stackNewest, stackOldest;

  public MyQueue() {
    stackNewest = new Stack<T>();
    stackOldest = new Stack<T>();
  }

  public int size() {
    return stackNewest.size() + stackOldest.size();
  }

  public void add(T value) {
    // push ont stackNewest, which always has the newest elements on top
    stackNewest.push(value);
  }

  // move elements from stackNewest into stackOldest. this is usually done so that operations can be done on stackOldest
  private void shiftStacks() {
    if (stackOldest.isEmpty()) {
      while (!stackNewest.isEmpty()) {
        stackOldest.push(stackNewest.pop());
      }
    }
  }

  public T peek() {
    shiftStacks(); // ensure stackOldest has the current elements
    return stackOldest.peek(); // retrieve the oldest item
  }

  public T remove() {
    shiftStacks(); // ensure stackOldest has the current elements
    return stackOldest.pop(); // pop the oldest item
  }
}


texts: File selection button for Jupyter notebook

texts:
Background

This is a feature that I have wanted to see in Jupyter notebook for quite some time. I'm sure that others have built similar things but I haven't been able to find them on SO, Github, CodeReview or the rest of the searchable internet.

Approach

I used ipywidgets.Button as a base class and added a traitlet called files. This traitlet receives a list of files as strings from tkinter.filedialog.askopenfilename. When the button is clicked the file dialog pops up the user selects files and then can access that list of strings as an attribute/traitlet on the button instance.

import traitlets
from ipywidgets import widgets
from IPython.display import display
from tkinter import Tk, filedialog

class SelectFilesButton(widgets.Button):
    """A file widget that leverages tkinter.filedialog."""

    def __init__(self):
        super(SelectFilesButton, self).__init__()
        # Add the selected_files trait
        self.add_traits(files=traitlets.traitlets.List())
        # Create the button.
        self.description = "Select Files"
        self.icon = "square-o"
        self.style.button_color = "orange"
        # Set on click behavior.
        self.on_click(self.select_files)

    @staticmethod
    def select_files(b):
        """Generate instance of tkinter.filedialog.

        Parameters
        ----------
        b : obj:
            An instance of ipywidgets.widgets.Button
        """
        # Create Tk root
        root = Tk()
        # Hide the main window
        root.withdraw()
        # Raise the root to the top of all windows.
        root.call('wm', 'attributes', '.', '-topmost', True)
        # List of selected fileswill be set to b.value
        b.files = filedialog.askopenfilename(multiple=True)

        b.description = "Files Selected"
        b.icon = "check-square-o"
        b.style.button_color = "lightgreen"

Example Usage

Displaying the button

my_button = SelectFilesButton()
my_button # This will display the button in the context of Jupyter Notebook

Retrieving the file list from the button.

# In a different cell of the same Jupyter Notebook You can access the file list by using the following:
my_button.files

Questions

These are just some suggestions.

1) Does this work on your machine? If so throw me an upvote! If not please specify what versions you are working with so I can extend.

2) Are there any general overall improvements that can be made?

3) Is there any redundancy that I missed?

4) Does this code follow best practices?


texts:
Some time ago I wrote a little property class for a then abandoned project. I just stumbled over it again and I would like to know if the design is using good, efficient C++.

#pragma once

#ifndef NO_THREAD_SAFETY
#include <atomic>
#endif

template<typename T1>
class Property {
public:

#ifndef NO_THREAD_SAFETY
    typedef std::atomic<long> PropertyID;
    typedef std::atomic<T1>   PropertyValue;
#else
    typedef long              PropertyID;
    typedef T1                PropertyValue;
#endif

    Property(T1 value): value(value), id(id_count++) {
    }
    Property(): value(), id(id_count++) {
    }
    Property(const Property &rhs): id(id_count++) {
        value = static_cast<T1>(rhs.value);
    }
    Property(Property &&rhs): value(std::move(rhs.value)), id(id_count++) {
    }

    const Property &operator=(const Property &rhs) {
        value = std::move(static_cast<T1>(rhs.value));
        return *this;
    }
    const Property &operator=(const T1 &rhs) {
        value = rhs;
        return *this;
    }
    const Property &operator=(T1 &&rhs) {
        value = std::move(rhs);
        return *this;
    }

    bool operator==(const Property &rhs) const {
        return value == rhs.value;
    }
    bool operator==(const T1 &rhs) const {
        return value == rhs;
    }
    bool operator< (const Property &rhs) const {
        return value < rhs.value;
    }
    bool operator< (const T1 &rhs) const {
        return value < rhs;
    }
    void set(const T1 &value) {
        this->value = value;
    }

    T1 get() const {
        return value;
    }
    operator T1() const {
        return value;
    }
    PropertyID getID() const {
        return id;
    }

private:

    PropertyValue value;
    PropertyID id;
    static PropertyID id_count;
};

template<typename T1>
typename Property<T1>::PropertyID Property<T1>::id_count (0);


texts: Function to remove duplicated elements from an Array

texts:
Task is to have a function which takes an array. Then removes elements from the array which are contained more then one time. Finally returns an array with only unique elements.

Here's my solution:

// Duplicates : 4 (3 times), 5, 9 (3 times) => Sum: 5 too much !
let withDuplicates = [1, 2, 3, 4, 4,
  4, 5, 5, 6, 7,
  8, 9, 9, 9, 10
];
let withoutDuplicates = [];

// -- The actual function ------------------

function removeDuplicates(arr) {
  return arr.reduce((unique, current) => {

    if (!unique.includes(current)) {
      unique.push(current);
    }

    return unique;
  }, []);
}

// ----------------------------------------

withoutDuplicates = removeDuplicates(withDuplicates);

console.log(withDuplicates);
console.log('Length:', withDuplicates.length);
console.log(withoutDuplicates);
console.log('Length:', withoutDuplicates.length);

Using reduce() was what came to my mind for solving the task.
And the code has become already quite tight.

Nevertheless: Is there a better solution?