texts:
I wrote a basic C++ template to manage shared resources like textures and shaders in a 3D engine. The idea is that the cache itself holds weak references to the resources (through std::weak_ptr) and turns it into strong references (through std::shared_ptr) when the resource is fetched from the cache or constructed if it's not present. As soon as all strong references go out of scope, the given object gets deleted and removed from the cache by a custom deleter. Suggestions/improvements are welcome:

#ifndef PTRCACHE_H
#define PTRCACHE_H

#include <memory>
#include <map>
#include <functional>
#include <mutex>

namespace MyEngine
{
  template<typename Key, typename Val, typename ... Args>
  class PtrCache
  {
  public:
    PtrCache(const std::function<Val*(Args...)>& creator) :
      _creator(creator),
      _mutex(std::make_unique<std::mutex>())
    {}
    PtrCache(const PtrCache& other) = delete;
    PtrCache& operator=(const PtrCache& other) = delete;
    PtrCache(PtrCache&& other) :
      _cache(std::move(other._cache)),
      _creator(std::move(other._creator)),
      _mutex(std::move(other._mutex))
    {}
    PtrCache& operator=(PtrCache&& other)
    {
      if (this != &other) {
        _cache = std::move(other._cache);
        _creator = std::move(other._creator);
        _mutex = std::move(other._mutex);
      }
      return *this;
    }
    /**
    * Returns true if ret was taken from the cache, false otherwise.
    */
    bool getOrCreate(const Key& key, std::shared_ptr<Val>& ret, Args... args)
    {
      std::lock_guard<std::mutex> lock(*_mutex);
      auto it = _cache.find(key);
      if (it != _cache.end()) {
        ret = std::shared_ptr<Val>(it->second); // Construct from weak_ptr
        return true;
      }
      ret = std::shared_ptr<Val>(_creator(args...), [this, key](Val* ptr) { // Construct from creator and pass custom deleter which removes the element from the cache.
        std::lock_guard<std::mutex> lock(*_mutex);
        _cache.erase(key);
        delete ptr;
      });
      _cache[key] = ret;
      return false;
    }
    inline void clear()
    {
      std::lock_guard<std::mutex> lock(*_mutex);
      _cache.clear();
    }
    inline size_t size()
    {
      std::lock_guard<std::mutex> lock(*_mutex);
      return _cache.size();
    }
  private:
    std::map<Key, std::weak_ptr<Val>> _cache;
    std::function<Val*(Args...)> _creator;
    std::unique_ptr<std::mutex> _mutex;
  };
}

#endif

Basic usage example:

PtrCache<std::string, GLTexture, const std::string&> texture_cache([] (const std::string& path) {
  auto tex = SOIL_load_OGL_texture(path.c_str(), SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_COMPRESS_TO_DXT);
  if (tex) {
    return new GLTexture(tex, GL_TEXTURE_2D);
  }
  else {
    throw std::exception((std::string("Could not create texture ") + path).c_str());
    return nullptr;
  }
});

std::shared_ptr<GLTexture> my_texture;
std::string path = "my_texture.png";
texture_cache.getOrCreate(path, my_texture, path);

The only caveat I see is that the user of this class has to ensure that the lifetime of the cache goes beyond the lifetime of any contained managed object. Otherwise, the custom deleter would obviously cause undefined behaviour.


texts: Code Improvement: Copy Regex named capture groups to strongly typed object

texts:
This code works to copy named capture groups of a Regex to the same named properties of a strongly typed object.  However, it's not pretty.  Someone mentioned I should use polymorphism to at least remove the five if statements.

What should I consider when improving this code?  Suggested reading?

// Copies named capture groups in a REGEX to the properties of an object
// if the names match
static public void CopyProperties(Regex regex, Match source, object target)
{
    if (target != null && source != null && source.Success)
    {
        var targetType = target.GetType();
        // only step through non numeric capture names
        foreach (var sourceProp in regex.GetGroupNames()
            .Where(p => !Regex.IsMatch(p, @"^\d+$") &&
            !String.IsNullOrWhiteSpace(p)))
        {
            // does the target property the same as source exist?
            var targetPropName = targetType.GetProperty(sourceProp);
            // if the source and target exist
            if (targetPropName != null &&
                !String.IsNullOrWhiteSpace(source.Groups[sourceProp].Value) )
            {
                var targetPropSetter = targetPropName.GetSetMethod();
                // created a variable for each possible type
                // because I couldn't inline the Convert.ToInt32, etc.
                string sourceValue = source.Groups[sourceProp].Value;
                int? intValue = !Regex.IsMatch(sourceValue,
                                  @"^\d{1,10}$")
                    ? (int?) null
                    : Convert.ToInt64(sourceValue) <= Int32.MaxValue
                        ? Convert.ToInt32(sourceValue)
                        : (int?) null;
                long? longValue = Regex.IsMatch(sourceValue,
                                  @"^\d{1,19}$")
                    ? Convert.ToInt64( sourceValue)
                    : (long?) null;
                bool? boolValue = Regex.IsMatch(sourceValue,
                                  @"^(?i)true$|^(?i)false$")
                    ? Convert.ToBoolean(sourceValue)
                    : (bool?) null;
                decimal? decimalValue = Regex.IsMatch(sourceValue,
                                  @"^\d+\.?\d*$")
                    ? Convert.ToDecimal(sourceValue)
                    : (decimal?) null;
                // multiple if because it didn't like a switch statement
                // I didn't think five micro functions would improve this
                if (targetPropName.PropertyType == typeof(string))
                    targetPropSetter.Invoke(target,
                        new[] { (object) sourceValue });
                if (targetPropName.PropertyType == typeof(Nullable<Int32>))
                    targetPropSetter.Invoke(target,
                        new[] { (object) intValue });
                if (targetPropName.PropertyType == typeof(Nullable<Int64>))
                    targetPropSetter.Invoke(target,
                        new[] { (object) longValue });
                if (targetPropName.PropertyType == typeof(Nullable<Boolean>))
                    targetPropSetter.Invoke(target,
                        new[] { (object) boolValue });
                if (targetPropName.PropertyType == typeof(Nullable<Decimal>))
                    targetPropSetter.Invoke(target,
                        new[] { (object) decimalValue });
            }
        }
    }
}


texts:
This code below converts number from decimal to fraction. I don't know if there's a better way or better methods to do this job so any advice would be appreciated.
const toFraction = (inputNumber) => {
  // Only two digits after decimal point
  inputNumber = inputNumber.toFixed(2);

  // destructure number
  let [int, dec] = inputNumber
    .toString()
    .split(".")
    .map((el) => parseInt(el));

  // Round it up to nearst multiple of 5
  dec = Math.ceil(dec / 5) * 5;

  // Keep Dividing until it's impossible
  const divide = [9, 8, 7, 6, 5, 4, 3, 2];
  let hundred = 100;
  let notOver = true;
  while (notOver) {
    notOver = false;
    for (let num of divide) {
      if (dec % num === 0 && hundred % num === 0) {
        dec /= num;
        hundred /= num;
        notOver = true;
      }
    }
  }
  return int === 0 ? `${dec}${hundred}` : `${int} ${dec}/${hundred}`;
};


texts: High school social network query for friends in common

texts:
This is sourced from the Stanford Coursera self study DB class SQL quizzes:

  Students at your hometown high school have decided to organize their
  social network using databases. So far, they have collected
  information about sixteen students in four grades, 9-12. Here's the
  schema:

Highschooler (ID, name, grade)

  English: There is a high school student with unique ID and a given
  first name in a certain grade.

Friend (ID1, ID2)

  English: The student with ID1 is friends with the student with ID2.
  Friendship is mutual, so if (123, 456) is in the Friend table, so is
  (456, 123).

Likes (ID1, ID2)

  English: The student with ID1 likes the student with ID2. Liking
  someone is not necessarily mutual, so if (123, 456) is in the Likes
  table, there is no guarantee that (456, 123) is also present.

  Database
  here

  Prompt: For each student A who likes a student B where the two are not friends, find if they have a friend C in common (who can introduce
  them!). For all such trios, return the name and grade of A, B, and C.

I would appreciate a brief code review of this working query:

select distinct a.name, a.grade, b.name, b.grade, c.name, c.grade
from highschooler a, highschooler b, highschooler c, likes, friend
where a.id=likes.id1
and b.id=likes.id2
and a.id=friend.id1
and b.id not in (select id2 from friend where a.id=id1)
and b.id in (select id1 from friend where id2=c.id)
and a.id in (select id1 from friend where id2=c.id)


texts: Python program to find the most frequent letter in a text

texts:
Given a text like "Hello World!" the program outputs the most frequent letter, in this case the "l".

If there are two letters with the same frequency, it outputs the first in alphabetical order, for example in the text "One" it outputs "e".

In addition upper and lower letters are counted as the same letter.

How could be this code improved?

def most_frequent_letter(text: str) -> str:

    letters_dict = {}
    text = text.lower()
    text = re.sub("[^a-z]","",text)

    for letter in text:
        if letter in letters_dict:
            letters_dict[letter] += 1
        else:
            letters_dict[letter] = 1

    value_to_key = collections.defaultdict(list)
    for key_letter, frecuency_value in letters_dict.items():
        value_to_key[frecuency_value].append(key_letter)

    letters = list(value_to_key.values())
    frecuencies = list(value_to_key.keys())
    return (sorted(letters[frecuencies.index(max(frecuencies))])[0])


texts: Remove duplicate elements from char array

texts:
This is a method where a char[] will be supplied as an input and it should return an array, but without the duplicate elements. How can this be optimized?

private static char[] getMYCharArray(char[] array) {
        String myArray = "";
        for(int i = 0; i < array.length; i++) {
            if(myArray.indexOf(array[i]) == -1) // check if a char already exist, if not exist then return -1
                myArray = myArray+array[i];      // add new char
        }
        return myArray.toCharArray();
    }


texts: Find all strings matching a giving regex pattern in files in a directory (including all subdirectories)

texts:
#! python3
#   `regexSearch`: Finds all lines matching a given regex in each file in a given folder.
#   Usage:
#       The directory to search and regex to be searched for are provided as a command line arguments.
#       The 1st and 2nd command line arguments are the directory and regex pattern respectively.
#       Script prompts the user to enter the regex.
#       After completion, the user is prompted to continue

import re, sys
from os import path, listdir

def regex_search(regex, directory):
    res, lst = {}, listdir(directory)
    for itm in lst:
        pth = path.join(path.abspath(directory), itm)
        if path.isdir(pth):   res.update(regex_search(regex, pth))    #Recursively traverse all sub directories.
        else:
            print(pth)
            with open(pth) as file:
                tmp = []
                for idx, line in enumerate(file.readlines()):
                    results = regex.findall(line)
                    if results:  tmp.extend([f"Line {idx+1}: {results}"])
                res[pth] = tmp
    return res

if __name__ == "__main__":
    directory, pattern = sys.argv[1:3]
    while not path.isdir(directory):
        print("Error: Please input a valid path for an existing directory:", end = "\t")
        directory = input()
    while True:
        try:
            regex = re.compile(pattern)
            break
        except TypeError:
            print("Error: Please input a valid regex:", end = "\t")
            pattern = input()
        except re.error:
            print("Error: Please input a valid regex:", end = "\t")
            pattern = input()
    matches = regex_search(regex, directory)
    for key in matches:  print(key, "\n".join(matches[key]), sep="\n", end="\n\n")


texts: Using jQuery string replacements to make labels bold

texts:
Instead of having multiple statements like the following, Is it possible to club them into one liner in jQuery?

       var replaced = $("#myContents").html().replace(/Employee:/g,'Employee:');
       $("#myContents").html(replaced);

       var replaced = $("#myContents").html().replace(/SSN:/g,'SSN:');
       $("#myContents").html(replaced);

       var replaced = $("#myContents").html().replace(/DOB:/g,'DOB:');
       $("#myContents").html(replaced);

       var replaced = $("#myContents").html().replace(/Start Date\/Time:/g,'Start Date\/Time:');
       $("#myContents").html(replaced);

       var replaced = $("#myContents").html().replace(/End Date\/Time:/g,'End Date\/Time:');
       $("#myContents").html(replaced);


texts: What can I do better in this ViewModel Creator?

texts:
I'm currently creating a ASP.NET MVC page in C#.

I want to hide everything regarding the creation of our "models" and "viewmodels".

I have seen much of the fancy stuff regarding Dependency Injection as well as Action Filters, Custom Controllers and so on! But the people I work with are pretty new to this so I want it to keep it dead simple, but I still want to avoid all the new statement and keep the controller really lightweight.

Please advise me if I'm doing this the wrong way, and be constructive.

Factory Class

 public class Factory
 {
    public T BuildViewModel<T>() where T : class, new()
    {
        IViewModel<T> iVmInterf = (IViewModel<T>)Activator.CreateInstance<T>();

        return iVmInterf.getViewModel();
    }
 }

IViewModel InterFace

 interface IViewModel<T>
 {
    T getViewModel();
 }

interface IProductViewModel

interface IProductViewModel
{
    int ProductCost { get; }
    string ProductName { get; }
}

class ProductViewModel

class ProductViewModel : IViewModel<ProductViewModel>, IProductViewModel
{
    private int _productCost;
    private string _productName;
    private IProductViewModel interf;

    int IProductViewModel.ProductCost
    {
        get { return _productCost; }
    }

    string IProductViewModel.ProductName
    {
        get { return _productName; }
    }

    ProductViewModel IViewModel<ProductViewModel>.getViewModel()
    {
        return this;
    }
}

Usage in controller

Factory fact = new Factory();
IProductViewModel vmdl = fact.BuildViewModel<ProductViewModel>();


texts: Make binary search tree from sorted array

texts:
Here is my code for converting a sorted array to a binary search tree. Please review and let me know the improvements or some better way of solving this.

/**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }

        // If there is only one element, make it root node and return.
        if (nums.length == 1) {
            TreeNode root = new TreeNode(nums[0]);
            return root;
        }

        // else, find the mid element and the left of it as left and right to
        // right recursively
        else {
            int length = nums.length;
            TreeNode root = new TreeNode(nums[length / 2]);
            int[] numsLeft = Arrays.copyOfRange(nums, 0, nums.length / 2);
            int[] numsRight = Arrays.copyOfRange(nums, (nums.length / 2) + 1, nums.length);
            root.left = sortedArrayToBST(numsLeft);
            root.right = sortedArrayToBST(numsRight);
            return root;

        }

    }


texts:
The following 8088/8086 assembly program tests the modular-sum checksum of a block of data. I suspect it could be tighter; can anyone do it in fewer bytes?

31        xor        ax,ax          ; zero the sum
c0
bb        mov        bx,2000h        ; count 8kb of ROM
00
20
4b        dec        bx             ; start at the top
02        add        al,[bx]        ; add the current byte to the total
07
85        test       bx,bx          ; see if we're at the bottom yet
db
75        jnz        -7             ; loop while not done
f9
84        test       al,al          ; sum should be 0
c0
74        jz         1              ; if sum is good, continue with program
01
f4        hlt                       ; if sum is bad, stop


texts: C program to convert string to floating point

texts:
From K&R:

  Extend atof to handle scientific notation of the form
  123.45e-6
  where a floating-point number may be followed by e or E and an optionally
  signed exponent.

I only added the part that handles the scientific notation. It compiles and works fine. I think it's way too long and could be shortened. I also don't like the names.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_SIZE 20

double atof(const char *s){
    int i;
    for(i = 0; isspace(s[i]); ++i);
        /*skip white space*/

    int sign;
    sign = (s[i] == '-')? -1 : 1; /*The sign of the number*/

    if(s[i] == '-' || s[i] == '+'){
        ++i;
    }

    double value;
    for(value = 0.0; isdigit(s[i]); ++i){
        value = value * 10.0 + (s[i] - '0');
    }

    if(s[i] == '.'){
        ++i;
    }

    double power;
    for(power = 1.0; isdigit(s[i]); ++i){
        value = value * 10.0 + (s[i] - '0');
        power *= 10.0;
    }

    if(s[i] == 'e' || s[i] == 'E'){
        ++i;
    }
    else{
        return sign * value/power;
    }

    int powersign; /*The sign following the E*/
    powersign = (s[i] == '-')? -1 : 1;

    if(s[i] == '-' || s[i] == '+'){
        ++i;
    }

    int power2; /*The number following the E*/
    for(power2 = 0; isdigit(s[i]); ++i){
        power2 = power2 * 10 + (s[i] - '0');
    }

    if(powersign == -1){
        while(power2 != 0){
            power *= 10;
            --power2;
        }
    }
    else{
        while(power2 != 0){
            power /= 10;
            --power2;
        }
    }

    return sign * value/power;
}

int main(void){
    char string[MAX_SIZE];

    fgets(string, sizeof(string), stdin);

    printf("%.9f", atof(string));

    return 0;
}


texts: Associating a string with a derived class

texts:
I am using the following code to get a string that is associated with the class of an instance:

std::string gate =
    dynamic_cast<AND*>(pComponent) != nullptr ? "AND" :
    dynamic_cast<NAND*>(pComponent) != nullptr ? "NAND" :
    dynamic_cast<NOR*>(pComponent) != nullptr ? "NOR" :
    dynamic_cast<NOT*>(pComponent) != nullptr ? "NOT" :
    dynamic_cast<OR*>(pComponent) != nullptr ? "OR" :
    dynamic_cast<XNOR*>(pComponent) != nullptr ? "XNOR" :
    dynamic_cast<XOR*>(pComponent) != nullptr ? "XOR" : ""
;

This works, but I feel like there should be a better way to do this. Perhaps create some kind of map with a reference to the class type of pComponent as key and the related string as value?

All classes (AND, NAND, etc) inherit the same base class, Node. I have been thinking about adding the following code to Node:

virtual std::string get_gate() const = 0;

Then have every derived class implement the method, returning its string and call:

pComponent->get_gate();

Would this solution use memory for every class instance rather than once per class? For example I declare two objects of AND, would both of them allocate memory for the method? Will the compiler do something smart?


texts: Raw filter with ternary operator for html class attribute

texts:
I've been trying to figure out how to stop Twig escape using the following code, which I feel is a little nicer with the succinct ternary operator.

I hope someone can confirm I'm using the correct syntax and if there are any performance issues doing it like this (as well as alternative methods, if any):

<body{{ bodyClass is defined ? (' class="' ~ bodyClass ~ '"')|raw : '' }}>

It seems to work and is the only way I've managed to get proper output so far!

An alternative version can be seen here, using string interpolation (#{} is my current preferred method):

" class=\"#{bodyClass}\""|raw


texts: Session state wrapper, extending an existing application

texts:
I'm adding additional functionality to an existing MVC .net application, and to help prevent or at least reduce repeated reads to the dB I'm dumping a few custom entities in session. I'm limiting what can be stored in session to say a max of 5 objects for now.

Given below is the code and it seems generic enough and works fine locally on my box; any suggestions to improve this and session is In-Proc but if it does get stored in a persistent medium say SQL server then I would need to customize this further - decorate custom object properties w/XML element attributes

public class QuestionModelSessionStateProvider : IQuestionModelSessionStateProvider
{
    const int MaxSize = 5;

    public T GetValue<T>(string key)
    {
        HttpSessionState session = GetSessionState();

        T returnValue = default(T);

        if (session == null) return returnValue;

        if (session["QuestionModelStore"] != null)
        {
            var questionModelStore = (List<KeyValuePair<string, T>>)session["QuestionModelStore"];
            foreach (var t in questionModelStore.Where(t => t.Key.Equals(key)))
            {
                returnValue = t.Value;
            }
        }

        return returnValue;
    }

    public void SetValue<T>(string key, T value)
    {
        HttpSessionState session = GetSessionState();

        if (session == null) return;

        List<KeyValuePair<string, T>> questionModelStore;

        if (session["QuestionModelStore"] == null)
        {
            questionModelStore = new List<KeyValuePair<string, T>> { new KeyValuePair<string, T>(key, value) };
            session["QuestionModelStore"] = questionModelStore;
        }
        else
        {
            questionModelStore = (List<KeyValuePair<string, T>>)session["QuestionModelStore"];
            questionModelStore.Add(new KeyValuePair<string, T>(key, value));
        }

        if (questionModelStore.Count > MaxSize)
        {
            questionModelStore.RemoveAt(0);
        }
    }

    public void RemoveValue<T>(string key)
    {
        HttpSessionState session = GetSessionState();
        int indexToRemoveAt = 0;
        var found = false;
        if (session != null && session["QuestionModelStore"] != null)
        {
            var questionModelStore = (List<KeyValuePair<string, T>>) session["QuestionModelStore"];
            for (var i = 0; i < questionModelStore.Count; i++)
            {
                if (questionModelStore[i].Key.Equals(key))
                {
                    indexToRemoveAt = i;
                    found = true;
                    break;
                }
            }

            if (found)
                questionModelStore.RemoveAt(indexToRemoveAt);
        }
    }

    public void Clear()
    {
        HttpSessionState session = GetSessionState();
        if (session != null)
        {
            session["QuestionModelStore"] = null;
        }
    }

    public int Count<T>()
    {

        HttpSessionState session = GetSessionState();
        if (session != null)
        {
            //return session.Count;
            if (session["QuestionModelStore"] != null)
            {
                var questionModelStore = (List<KeyValuePair<string, T>>)session["QuestionModelStore"];
                return questionModelStore.Count;
            }

        }

        return 0;

    }

    private static HttpSessionState GetSessionState()
    {
        if (HttpContext.Current != null)
            return HttpContext.Current.Session;
        return null;
    }
}


texts:
I am trying to return a value (a.tnAddress) from a custom class based on a lookup (foreach loop).  Depending on the type of transaction, I will need to do the foreach loop based on different properties (sExecID, iMsgSeqNum, orsClOrderID).  I prefer to not have 3 differentforeach` loops just but I am not sure how else to re-write this.

Keep in mind that the code is working fine; I just want to simplify it.

private TreeNode GetNodeAddress(cls_Transactions trPassedInTransaction)
{
    switch (trPassedInTransaction.sMessageType)
    {
        case "Q":
        case "8b":
            foreach (cls_Transactions a in cls_GlobalVariables.transList)
            {
                if (trPassedInTransaction.sExecID == a.sExecID)
                {
                    return a.tnAddress;
                }
            }
            break;
        case "3":
            foreach (cls_Transactions a in cls_GlobalVariables.transList)
            {
                if (trPassedInTransaction.iMsgSeqNum == a.iMsgSeqNum)
                {
                    return a.tnAddress;
                }
            }
            break;
        default:
            foreach (cls_Transactions a in cls_GlobalVariables.transList)
            {
                if (trPassedInTransaction.sClOrderID == a.sClOrderID)
                {
                    return a.tnAddress;
                }
            }
            break;
    }

    return null;
}


texts:
I wanted to see graphically what my programme was doing so I wrote this automatic flowchart generator:

class Object

    def log(previous_method)
        if not DEBUGGING
            return
        end
        repr = if self.class == Enumerator then self.to_a else self end
        if [Array, String].include?(repr.class) and repr.length > 100
            repr = repr.first(20) + [". . ."] + repr.last(20)
        end
        if previous_method.downcase == 'start'
            self.tap {|x| puts """
                   #{repr}
                   """}
        else
            self.tap {|x| puts """
                     |
                     |     #{previous_method}
                     |
                     V

                   #{repr}
                   """}
         end
     end
end

Some testcases:

class Integer
    def is_digits_pow_sum?(exp)
        self                           .log("start")
            .digits                    .log("Digits")
            .map{|x| x**exp}           .log("Each digit to the power of #{exp}")
            .sum                       .log("Sum")
            .equal?(self)              .log("Equals the start? (#{self})")
    end
end

441.is_digits_pow_sum?(3)

Generates the flowchart:

               441

                 |
                 |     Digits
                 |
                 V

               [4, 4, 1]

                 |
                 |     Each digit to the power of 3
                 |
                 V

               [64, 64, 1]

                 |
                 |     Sum
                 |
                 V

               129

                 |
                 |     Equals the start? (441)
                 |
                 V

               false

class String
    def alpha_value
        self                           .log("Start")
            .chars                     .log("Split char by char")
            .map(&:alphabet_position)  .log("Map by position in the alphabet")
            .sum                       .log("Sum")
    end
end

"hellopeople".alpha_value

Gives the flowchart:

               hellopeople

                 |
                 |     Split char by char
                 |
                 V

               ["h", "e", "l", "l", "o", "p", "e", "o", "p", "l", "e"]

                 |
                 |     Map by position in the alphabet
                 |
                 V

               [8, 5, 12, 12, 15, 16, 5, 15, 16, 12, 5]

                 |
                 |     Sum
                 |
                 V

               121


texts: Change the identity from Azure AD to identity of application and return new token

texts:
I use this code to change the identity coming from Azure AD in an identity usable by my application, then i generate a token for this identity and return it in the response headers.

Is this secure? and is it the good way? In particular, call the SignIn method of the AuthenticationManager and handle this in a middleware to generate a token.

Environment

Asp.net-WebAPI with OWIN

Code in startup.cs

Add Azure AD middleware
On validate identity, create a custom identity for the authentified user and signin with this identity

app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
    Audience = ConfigurationManager.AppSettings["ida:Audience"],
    Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
    Provider = new OAuthBearerAuthenticationProvider()
    {
        OnValidateIdentity = async context =>
        {
            if(!context.IsValidated)
                return;

            var userManager = context.OwinContext.Get<UserManager>();
            string email =    context.Ticket.Identity.GetClaimValue(System.Security.Claims.ClaimTypes.Email);
            User user = userManager.GetByEmail(email);

            if(user == null)
            {
                // Create user
            }

            // Create custom identity
            ClaimsIdentity identity = new ClaimsIdentity(AuthenticationTypes.My);
            identity.AddClaim(new Claim(My.ClaimTypes.UserId, user.Id.ToString(CultureInfo.InvariantCulture)));

            // Signal to middleware to treat my custom identity
            context.OwinContext.Authentication.SignIn(identity);

            // validate the identity
            AuthenticationTicket ticket = new AuthenticationTicket(identity, null);
            context.Validated(ticket);
        }
    }
});

Add a custom middleware to handle the signin with my custom identity to create a new token and return it to browser

app.Use((context, next) =>
{
    if(context.Authentication.AuthenticationResponseGrant == null)
        return next();
    if(context.Authentication.AuthenticationResponseGrant.Identity.AuthenticationType != AuthenticationTypes.My)
        return next();

    // Create a token with the custom identity
    AuthenticationTicket ticket = new AuthenticationTicket(context.Authentication.AuthenticationResponseGrant.Identity, null);
    IDataProtector dataProtecter = app.CreateDataProtector(typeof(OAuthBearerAuthenticationMiddleware).Namespace, "Access_Token", "v1");
    TicketDataFormat ticketDataFormat = new TicketDataFormat(dataProtecter);
    string token = ticketDataFormat.Protect(ticket);
    context.Response.Headers.Add("access_token", new string[] { token });
    return next();
});

Add a OAuth bearer authentication middleware to handle my custom token:

app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions()
{
    TokenEndpointPath = new PathString("/token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
    AccessTokenFormat = null,
});


texts: Percentage based drop prize on Mob entity kill

texts:
I have created a simple percentage-based random prize drop for killing certain mobs.
A drop is basically what the player will get in return for killing a mob, as a reward.

So I have a large list of Mobs saved in an XML file which looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<drops>
    <npc id="1">
        <drop item="175" amount="1" chance="0.001" />
        <drop item="174" amount="5" chance="0.013" />
        <drop item="173" amount="1" chance="0.158" />
        <drop item="172" amount="1" chance="0.098" />
    </npc>
</drops>

Basically each NPC has its own ID, so that way we can easily decide what drops does a certain NPC can drop.

So for NPC '1' we have 4 drops, the hardest to get drop is 0.001 (1/1000) and the easiest one is 0.158.

To make the drop system percentage based, I used SecureRandom and the nextFloat() method to generate the base drop rate for the NPC.

After I got the rate, I go through all of the drops that the NPC can drop, and find the drop with the closest drop chance rate to the generated random float rate.

I do this like that:

/**
 * Gets a random drop for NPC by random percentage
 * @param npc       The NPC id
 * @return  The drop details
 */
public Drop getRandomDrop(int npc) {
    List<Drop> drops = this.drops.get(npc);

    /**
     * The random drop rate
     */
    float rate = random.nextFloat();

    /**
     * The closest distance to rate
     */
    float bestDistance = Float.MAX_VALUE;

    // Closest's drop instance
    Drop closest = null;

    for (Drop d : drops) {
        float rt = d.getChance();
        if (rt == rate) {
            return d;
        }

        float distance = Math.abs(rt - rate);
        if (distance < bestDistance) {
            bestDistance = distance;
            closest = d;
        }
    }

    return closest;
}

But I feel that I can make the drops system more accurate, as in this approach is not accurate enough. I need some reviews and suggestions on my approach.


texts:
I'm trying to design a chain of responsibility pattern.
It slightly differ from traditional way when handler does only one action on a request, f.e. handles http response considering status code.
But my handlers have to do two actions. Below is an (dummy) example where handler asks a question first and then writes the user response to some store:
# some object where we keep surname and name
class Request:
    pass

# some outer storage
store = {}

# chain of responsibility implementation

class PersonIdentifier:

    def __init__(self) -> None:
        self.handlers = []

    def add_handler(self, handler):
        if self.handlers:
            self.handlers[-1].set_next_handler(handler)
        self.handlers.append(handler)

    def handle(self, request):
        return self.handlers[0].handle_request(request)

# handlers for chain of responsibility

class BaseHandler:
    handler_name = None

    def __init__(self) -> None:
        self.next_handler = None

    def set_next_handler(self, handler):
        self.next_handler = handler

class SurnameHandler(BaseHandler):
    handler_name = 'surname'
    handler_name_answer = 'surname-answer'
    question = 'Type your surname: '

    def handle_request(self, request):
        if request.handler_name == self.handler_name:
            return self.question
        elif request.handler_name == self.handler_name_answer:
            global store
            store['surname'] = request.surname
            del request.surname
            request.handler_name = 'name'
            return self.next_handler.handle_request(request)
        else:
            return self.next_handler.handle_request(request)

class NameHandler(BaseHandler):
    handler_name = 'name'
    handler_name_answer = 'name-answer'
    question = 'Type your name: '

    def handle_request(self, request):
        if request.handler_name == self.handler_name:
            return self.question
        elif request.handler_name == self.handler_name_answer:
            global store
            store['name'] = request.name

user_request = Request()

chain = PersonIdentifier()
chain.add_handler(SurnameHandler())
chain.add_handler(NameHandler())

# first ask for surname
user_request.handler_name = 'surname'
surname = input(chain.handle(user_request))
user_request.handler_name = 'surname-answer'
user_request.surname = surname

# then ask for name
name = input(chain.handle(user_request))
user_request.name = name
user_request.handler_name = 'name-answer'
chain.handle(user_request)

print(store)

It looks ugly for me. What do I dislike more is using handler_name and handler_name_answer.
May be you could offer nicer way to solve my task?


texts: In-proc event dispatching through IoC container

texts:
Here is the sender and handler interfaces:
public interface ISender
{
    Task SendAsync(object e);
}

public interface IHandler<in TEvent>
{
    Task HandleAsync(TEvent e);
}

So I register in IoC container a sender service implementation, which dispatches events to all the compatible IHandler<in T> implementations. I use Autofac with a contravariance source, but there could be something else:
[Service]
public class Sender : ISender
{
    public Sender(IServiceProvider provider) => Provider = provider;
    IServiceProvider Provider { get; }

    public async Task SendAsync(object e)
    {
        var eventType = e.GetType();
        var handlerType = typeof(IHandler<>).MakeGenericType(eventType);
        var handlerListType = typeof(IEnumerable<>).MakeGenericType(handlerType);
        var method = handlerType.GetMethod("HandleAsync", new[] { eventType });
        var handlers = ((IEnumerable)Provider.GetService(handlerListType)).OfType<object>();
        await Task.WhenAll(
            handlers.Select(h =>
                Task.Run(() => (Task)method.Invoke(h, new[] { e }))
                    .ContinueWith(_ => { })));
    }
}


texts:
I am creating a web page in which I have 4 different numbers which show companies stats. I am using javascript to dynamically show these numbers from 0 to n (where 0 is the starting point of counter and n is the end, I have n=74, n=86, n=285, n =97). I am using javascript to start the counter from 0 to n, everything is working fine, as I am just a beginner in programming so I just want to know how experienced programmers think of this code. is this a good approach for this problem? Can the algorithm efficiency be improved?

//I am invoking this function on scroll but here I have provided the button

function letsCount(){
  var num = document.getElementsByClassName('number');
  var count = 0;
  var id = setInterval(myFunction,1);
  var val = document.getElementById('value');
  function myFunction(){
    if(count == 286 ){ //stop the counter at this value
      clearInterval(id);
    }
    else if(count < 76) { //First (Smallest) value of n
      num[0].innerHTML = count;
      num[1].innerHTML = count;
      num[2].innerHTML = count;
      num[3].innerHTML = count;
      count++;
    }
    else if(count < 87){ // second value of n
      num[1].innerHTML = count;
      num[2].innerHTML = count;
      num[3].innerHTML = count;
      count++;
    }
    else if(count < 98){ // third value of n
      num[2].innerHTML = count;
      num[3].innerHTML = count;
      count++;
    }
    else if(count < 286){ // fourth value of n
      num[2].innerHTML = count;
      count++;
    }
  }
}
button {
   position: absolute;
   top: 30px;
   left: auto;
   right: 30px;
   border: none;
   background-color: black;
   color: white;
   padding: 10px;
   cursor: pointer;
  }
button:hover {
   background-color: crimson;
}

   0

Styles Created

   0

Awards Won

   0

Stores Worldwide

   0

Varities Desinged

 <button onclick = "letsCount()">START</button>


texts: Chunk a large set of characters by a specified set of delimiters and a maximum chunk size

texts:
Problem
I need to be able to grab a subset of characters but ensure that each set doesn't exceed a specified limit and must end with a defined set of characters. For example, say I have an entire book worth of characters, I need to chunk that into a set of 300 characters but ensure that none of those chunks is split mid-sentence.
To put it into pesudo code I basically need:
foreach(var chunk in text.Chunk(x).ButAlsoSplitOnFirst('.', '!', '?', etc...);

My solution
public static class StringExtensions
    {
        public static IEnumerable<string> ChunkWithDelimeters(this string source, int maxChar, params char[] delimeters)
        {
            var sourceSpan = source.AsSpan();
            var items = new List<string>();

            var pointer = 0;
            var lazyPointer = 0;

            while (pointer <= sourceSpan.Length)
            {
                bool foundMatch = false;

                pointer = Math.Min(lazyPointer + maxChar, sourceSpan.Length);

                if (pointer == sourceSpan.Length)
                {
                    items.Add(sourceSpan.Slice(lazyPointer, pointer - lazyPointer).TrimStart().ToString());
                    break;
                }

                for (var j = pointer; j >= lazyPointer; j--)
                {
                    var tempChar = sourceSpan[j];

                    if (delimeters.Contains(tempChar))
                    {
                        foundMatch = true;
                        items.Add(sourceSpan.Slice(lazyPointer, j + 1 - lazyPointer).TrimStart().ToString());
                        lazyPointer = j + 1;
                    }
                }

                if (!foundMatch)
                {
                    items.Add(sourceSpan.Slice(lazyPointer, pointer - lazyPointer).Trim().ToString());
                    lazyPointer = pointer;
                }
            }

            return items;
        }
    }

Benchmarks

source.Length
maxChar
delimiters
Mean (μs)
Error (μs)
StdDev (μs)

7320000
30
'.'
73,622.739
1,412.4035
1,252.0589

439200
30
'.'
4,122.574
68.6392
60.8468

731
30
'.'
5.125
0.0466
0.0436

My question
What is the optimal solution to this problem? Is there any way I can improve the performance of my solution?


texts: Get list of files in directory with exclude option

texts:
This method returns the list of files (absolute path) in a folder (or tree). It allows filtering by extensions or filenames.

The method receives the following parameters:

string path: folder path to scan for files.
string[] exclude: can contain filenames such as "read.me" or extensions such as "*.jpg".
SearchOption searchOption: TopDirectoryOnly to scan only the specified folder or AllDirectories to scan tree folder under the specified path.

The method return files that doesn't appear in exclude array and a) hasn't extension, or b) extension doesn't appear in exclude array.

    public static IEnumerable<string> GetFiles(string path, string[] exclude, SearchOption searchOption = SearchOption.AllDirectories)
    {
        IEnumerable<string> files = Directory.EnumerateFiles(path, "*.*", searchOption);
        var resultFiles = new List<string>();

        if (exclude.Length > 0)
        {
            foreach (var filename in files)
            {
                string extension = Path.GetExtension(filename);

                if (Array.IndexOf(exclude, Path.GetFileName(filename)) >= 0)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(extension) || Array.IndexOf(exclude, "*" + extension) < 0)
                {
                    resultFiles.Add(filename);
                }
            }
        }

        return resultFiles;
    }


texts:
Im inserting data to a PostgreSQL database using the below function.

Im not very happy with the solution for the IF statements to handle the adaptation of Python None to PostgreSQL NULL. Would there be a more elegant solution I would be happy yo know.

Also, I believe I am not being very performant using .execute() method .
Where could i start to convert my function to make usage of .executemany() perhaps.

def insert_into_table(data):
    # print json.dumps(data, indent=4)

    conn = psycopg2.connect(database='testdb', user='postgres', password='password', host='localhost')
    cursor = conn.cursor()
    for i in data:
        # print json.dumps(i, indent=4)
        iso_code = i["iso_code"]

        if i["l_postcode"] is None:
            l_postcode = 'NULL'
        else:
            l_postcode = i["l_postcode"]

        if i["r_postcode"] is None:
            r_postcode = 'NULL'
        else:
            r_postcode = i["r_postcode"]
        link_id = i["link_id"]
        geom = i["geometry"]

        # sql = 'INSERT into data_load VALUES (\'{}\', {}, {},{} , st_geomfromgeojson(\'{}\'))'.format(iso_code, l_postcode, r_postcode, link_id, json.dumps(geom))
        sql = """INSERT into data_load (iso_code, l_postcode, r_postcode, link_id, geom) VALUES ('{}',{},{},{},st_geomfromgeojson(\'{}\'));""".format(iso_code, l_postcode, r_postcode, link_id, json.dumps(geom))
        print sql

        cursor.execute(sql, )
        print sql

    cursor.close()
    conn.commit()

    conn.close()

A json fragment example of the load im trying to load , this example has only 3 objects for the sake of simplicity .

[
    {
        "geometry": {
            "type": "LineString",
            "coordinates": [
                [
                    -91.98979,
                    15.644559999999998
                ],
                [
                    -91.98971,
                    15.645249999999999
                ]
            ]
        },
        "iso_code": "MEX",
        "l_postcode": null,
        "r_postcode": null,
        "link_id": 1186786776
    },
    {
        "geometry": {
            "type": "LineString",
            "coordinates": [
                [
                    -106.77742,
                    28.390159999999998
                ],
                [
                    -106.77806,
                    28.39076
                ]
            ]
        },
        "iso_code": "MEX",
        "l_postcode": null,
        "r_postcode": null,
        "link_id": 818231403
    },
    {
        "geometry": {
            "type": "LineString",
            "coordinates": [
                [
                    -98.89940999999999,
                    18.90605
                ],
                [
                    -98.89926,
                    18.906689999999998
                ]
            ]
        },
        "iso_code": "MEX",
        "l_postcode": null,
        "r_postcode": null,
        "link_id": 1130886811
    }
]


texts: A wrapper for user authentication using cURL in PHP

texts:
So I created a wrapper class to authenticate user via POST HTTP request.
    class Nucleolus
    {
        public const AUTHEN_USER_URL = "localhost:8000/authen/user";

        protected $ch;

        public function __construct(string $token)
        {
            $this->ch = curl_init();
            curl_setopt($this->ch, CURLOPT_URL, self::AUTHEN_USER_URL);
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, [
                "Content-Type: application/json",
                "Authorization: Bearer " . $token,
            ]);
            curl_setopt($this->ch, CURLOPT_POST, 1);
            curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
        }

        public function authenticate(string $username, string $password, string $serverUrl = null)
        {
            $url = $serverUrl ? $serverUrl : $_SERVER['SERVER_NAME'];
            curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode(compact('url', 'username', 'password')));

            return json_decode(curl_exec($this->ch), true);
        }

        public function __destruct()
        {
            curl_close($this->ch);
        }
    }

Then the other developers can do the following.
    $nucleolus = new Nucleolus($token);
    $result = $nucleolus->authenticate($username, $password);

and retrieve result as a PHP array.
Please review.


texts:
Is it recommended to combine two similar methods into one?

public void initialize_board(){
    for(int y = 0; y < board.length; y++){
        for(int x = 0; x < board.length; x++){
            if(x == 0)
                board[x][y] = (char)y;
            else
                board[x][y] = '~';
        }
    }
}

public void display_board(){
    for(int y = 0; y < board.length; y++){
        for(int x = 0; x < board.length; x++){
            System.out.print(board[x][y]);
        }
        System.out.print("\n");
    }
}


texts: How to save image in base64 format as file in secure way?

texts:
My try:

import base64
from django.core.files.base import ContentFile

def form_valid(self, form):
    self.object = form.save(commit=False)
    if self.request.POST.get('image_as_base64', None):
        format, imgstr = self.request.POST.get('image_as_base64').split(';base64,')
        ext = format.split('/')[-1]

        data = ContentFile(base64.b64decode(imgstr))
        file_name = "'temp_name." + ext
        self.object.receipt.save(file_name, data, save=True)

Do you see any security problems?

The value in the frontend is generated in this way (Vue.js method):

 saveMapAsImage() {
    this.printPlugin.printMap('A4Portrait page', 'Miles');
    self = this;
    this.routingMap.on('easyPrint-finished', e => {
        var reader = new window.FileReader();
        reader.readAsDataURL(e.event); // e.event is a Blob object generated via leaflet-easyPrint
        reader.onloadend = function () {
             base64data = reader.result;
             self.image_as_base64 = base64data;
        }
    });
  }

HTML

<input v-model="image_as_base64" type="hidden" id="id_image_as_base64" name="image_as_base64"/>


texts: Simplifying and optimize a concurrent access

texts:
I have code that is accessed by multiple threads.  If by any chance it has a problem, all accessing threads will wait for recovery.  By default, the first thread that fails, will have to recover and all others will have to wait.  When the process is complete, everyone leaves the method.

[TestMethod]
public void RecoveryConcurrentTest()
{
    Task task = Task.Factory.StartNew(() =>
        {
            ManualResetEvent r1 = new ManualResetEvent(false);
            var t1 = new Thread((obj) =>
            {
                AutoRecover();
                r1.Set();
            });

            ManualResetEvent r2 = new ManualResetEvent(false);
            var t2 = new Thread((obj) =>
            {
                AutoRecover();
                r2.Set();
            });

            ManualResetEvent r3 = new ManualResetEvent(false);
            var t3 = new Thread((obj) =>
            {
                AutoRecover();
                r3.Set();
            });

            ManualResetEvent r4 = new ManualResetEvent(false);
            var t4 = new Thread((obj) =>
            {
                AutoRecover();
                r4.Set();
            });
            t1.Start();
            t2.Start();
            t3.Start();
            t4.Start();

            WaitHandle.WaitAll(new WaitHandle[] { r1, r2, r3, r4 });
        });
    task.Wait();
}

private Object _syncRoot = new Object();
private int count;
private bool handled;
public void AutoRecover()
{
    Trace.WriteLine("thread: " + Thread.CurrentThread.ManagedThreadId);
    Interlocked.Increment(ref count);
    Trace.WriteLine("count + 1 = " + count); // not work properly

    lock (_syncRoot)
    {
        Trace.WriteLine("thread: " + Thread.CurrentThread.ManagedThreadId);
        if (handled)
        {
            Trace.WriteLine("handled is true");
        }
        else
        {
            Trace.WriteLine("handled is false");
            Trace.WriteLine("PROCESSING....");
            Thread.Sleep(10000);
            Trace.WriteLine("PROCESSED....");
            handled = true;
            Trace.WriteLine("handled set true");
        }

        Interlocked.Decrement(ref count);
        Trace.WriteLine("count - 1 = " + count);
        if (count == 0)
        {
            handled = false;
            Trace.WriteLine("handled set false");
        }
    }
}

It works well for my tests, but I believe that there are necessary adjustments and that it can be implemented differently.


texts: Two ways to remove duplicates from a list

texts:
The question is - Write a program to remove the duplicates in a list
Here's how I did it-
numbers = [1, 1, 1, 3, 3, 7, 7]
for i in numbers:
    while numbers.count(i) > 1:
        numbers.pop(numbers.index(i))
print(numbers)

Here's how the teacher in the youtube video did it-
numbers = [2, 2, 4, 4, 6, 6]
uniques = []
for number in numbers:
    if number not in uniques:
        uniques.append(number)
print(uniques)

I know both the programs are objectively different in terms of how they do the task and the second program will I reckon consume more memory to create the new list however given the question which is the better approach and for what reasons?


texts: Loop through a worksheet and insert a row with layout when value is true

texts:
I have a code that does a loop through a worksheets, if there is a value 2 inside a cell in column S, then I want to insert a row with a specific layout. I have the code, but it takes ages to complete. I've tried replacing .select function, but because I need a specific layout, I don't know how to avoid this.

LastRowMatchC = Worksheets("Compliance").Cells(Rows.Count, 1).End(xlUp).Row

Dim rngc As Range, rc As Long

Set rngc = Range("S8:S" & LastRowMatchC)

For rc = rngc.Count To 1 Step -1
    If rngc(rc).Value = 2 Then
        rngc(rc + 1).EntireRow.Insert
        rngc(rc + 1).EntireRow.Select

    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent1
        .TintAndShade = 0.599993896298105
        .PatternTintAndShade = 0
    End With
    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
    With Selection.Borders(xlEdgeLeft)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeRight)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    Selection.Borders(xlInsideVertical).LineStyle = xlNone
    Selection.Borders(xlInsideHorizontal).LineStyle = xlNone

    End If
Next rch


texts: Python DictionaryTagger class takes too long to initialize

texts:
With big inspiration from code from different webpages, I have created this DictionaryTagger. My problem is that it takes around 2 sec. to initialize the taggers / class.

When the tagger has been initialized, it only takes a few milliseconds to use the different taggers. I see two different ways to optimize the tagger:

Do the initialize of the tagger in some preload function. This have
to be used through a homepage. If it could be initialize and the stay
in memory all the time.
Rewrite the whole class with eye for performance

class DictionaryTagger(object):

def __init__(self, dictionary_paths):
    files = [open(path, 'r') for path in dictionary_paths]
    dictionaries = [yaml.load(dict_file) for dict_file in files]
    map(lambda x: x.close(), files)
    self.dictionary = {}
    self.max_key_size = 0
    for curr_dict in dictionaries:
        for key in curr_dict:
            #print(key)
            if key in self.dictionary:
                self.dictionary[key].extend(curr_dict[key])
            else:
                self.dictionary[key] = curr_dict[key]
                self.max_key_size = max(self.max_key_size, len(key))

def tag(self, postagged_sentences):
    return [self.tag_sentence(sentence) for sentence in postagged_sentences]

def tag_sentence(self, sentence, tag_with_lemmas=False):
    """
    the result is only one tagging of all the possible ones.
    :type sentence: object
    The resulting tagging is determined by these two priority rules:
        - longest matches have higher priority
        - search is made from left to right
    """
    tag_sentence = []
    n = len(sentence)
    if self.max_key_size == 0:
        self.max_key_size = n
    i = 0
    while i < n:
        j = min(i + self.max_key_size, n)  #avoid overflow
        tagged = False
        while j > i:
            expression_form = ' '.join([word[0] for word in sentence[i:j]]).lower()
            expression_lemma = ' '.join([word[1] for word in sentence[i:j]]).lower()
            if tag_with_lemmas:
                literal = expression_lemma
            else:
                literal = expression_form
            if literal in self.dictionary:
                #print(self.dictionary)
                is_single_token = j - i == 1
                original_position = i
                i = j
                taggings = [tag for tag in self.dictionary[literal]]
                tagged_expression = (expression_form, expression_lemma, taggings)
                if is_single_token:  #if the tagged literal is a single token, conserve its previous taggings:
                    original_token_tagging = sentence[original_position][2]
                    tagged_expression[2].extend(original_token_tagging)
                tag_sentence.append(tagged_expression)
                tagged = True
            else:
                j -= 1
        if not tagged:
            #print(literal)
            tag_sentence.append(sentence[i])
            i += 1

    return tag_sentence


texts:
I had a curl command which I converted using this.

This is the Ruby script:

 rabbitmqctl_url = CONFIG['rabbitmqctl']['url']
 rabbitmqctl_user = CONFIG['rabbitmqctl']['username']
 rabbitmqctl_password = CONFIG['rabbitmqctl']['password']
 uri = URI.parse("#{rabbitmqctl_url}/api/queues")
 request = Net::HTTP::Get.new(uri)
 request.basic_auth(rabbitmqctl_user, rabbitmqctl_password)
 req_options = { use_ssl: uri.scheme == 'https' }
 response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
    http.request(request)
 end
 puts response.body

This is the curl command:

curl -u  username:password  http:localhost 15672/api/queue

This code is very lengthy.


texts:
I am using JUnit, Hibernate and Spring Framework. I wrote a simple test to test whether entity was updated correctly or not.

Is this correct way to test if entity was updated? Could it be done better?

@Test
public void testUpdated(){
    ConfirmationEntity confirmationEntity = confirmationDao.find(1L);
    confirmationEntity.setConfirmationString("0123456789");
    confirmationEntity.setConfirmationStringValidUntil(new LocalDateTime());

    confirmationDao.update(confirmationEntity);

    ConfirmationEntity confirmationEntityUpdated = confirmationDao.find(1L);

    Assert.assertSame(
        "Expected values to be the same.",
        confirmationEntity,
        confirmationEntityUpdated
    );
}


texts: Find maximum in sorted and rotated array

texts:
This is an interview question.
A sorted rotated array is a sorted array which was rotated 0 or more times.

For example: [1,2,3] -> [2,3,1]

Please tell me what do you think about the following (correctness, efficiency, coding conventions) and specifically if I can remove in some way the special handle for array of two elements:

static int findMax(int arr[]) {
    return findMax(arr, 0 , arr.length - 1);
}

static int findMax(int arr[], int low, int high) {
    int middle;

    if (low == high) {
        return arr[low];
    }
    if ( Math.abs(high - low) == 1 ) {
        return Math.max(arr[low], arr[high]);
    }

    middle = (low + high) >> 1;
    if (arr[middle] > arr[middle + 1]) {
        return arr[middle];
    }
    if (arr[low] > arr[middle]) {
        return findMax(arr, low, middle - 1);
    }
    return findMax(arr, middle + 1, high);
}


texts:
I try to implement a (restricted version of) step function in Haskell. A step functions is a function that is constant on a finite number of half intervals, and mempty everywhere else. (equivalently, one can fill those "everywhere else" by half intervals)

This can be modeled as a StepData a b, which stores a list of the half intervals and the associated value for that half interval.
Not all Ord a has a minimum or maximum, I lift it to Bound a, which guaranties it to have a minimum and maximum, this is to make the algorithm clearer.

I implemented eval :: StepData a b -> a -> b to evaluate a step function at a point.

The important part is the ability to make step function a monoid, where <> is defined as pointwise sum of the function. Currently I implemented <> for the StepData a b.

P.S. Whenever I want to find a value, I have to run eval f x. Of course I can define g = eval f, but I can't use <> on the derived function. So I have to pass the data around in order to combine functions, and only call eval when I need to find a value. Are there better ways to handle this?

{-# LANGUAGE NoMonomorphismRestriction #-}

import Data.List
import Data.Monoid

data Bound a = Minimum | Value a | Maximum  deriving (Eq, Ord, Show)

data StepData x y = StepData [(Bound x, Bound x, y)]
    deriving (Show, Eq, Ord)

instance (Ord x, Monoid y) => Monoid (StepData x y) where
  mempty = StepData [(Minimum, Maximum, mempty)]
  mappend (StepData a) (StepData b) = StepData (foldl insertInterval b a)
    where
      insertInterval [] _ = []
      insertInterval ((a',b',y'):xs) (a,b,y)
       | a >= b' = non [(a',b',y')] ++ insertInterval xs (a,b,y)
       | b >= b' = non [(a',a,y'),(a,b',y <> y')] ++ insertInterval xs (b',b,y)
       | b <  b' = non [(a',a,y'),(a,b, y <> y'),(b,b',y')] ++ xs
       where non = filter (\(a,b,_)-> a/=b)

      merge (h@(a,_,y):h'@(_,b',y'):xs)
       | y == y'   = merge ((a,b',y):xs)
       | otherwise = h:merge (h':xs)
      merge x = x

eval (StepData xs) t = y
  where (_,_,y) = head $ dropWhile sol xs
        sol (a,b,y)
         | a<=Value t && Value t<b = False
         | otherwise   = True

fromList xs = StepData (map (\(a,b,y)->(Value a, Value b, y)) xs) `mappend` mempty


texts: Proper way of using the MVC concept - update

texts:
Original question:

Template engine

I updated my files as instructed, and now I require a review.  Please point out the most minute things out to me for me to have better code. Once again, efficiency, elegance, and performance is what I need. Also, please point out places where better code can be used (for places like loading a template, I need to find a better way to load a template).

Model:

<?php
class Model {
    public $params;
    public $site_url;
    public $theme;

    public function __construct($global) {
        $this->site_url = $global['site_url'];
        $this->theme    = $global['theme'];
    }
}

View:

<?php
class View {
    private $model;
    private $controller;

    public function __construct($model, $controller) {
        $this->model      = $model;
        $this->controller = $controller;
    }
    public function createPage($path) {
        $this->content = $model->replaceParams(file_get_contents($path));
        return $this->content;
    }
    public function createParam($key, $value) {
        $model->params['{' . $key . '}'] = $value;
    }
    public function replaceParams($content) {
        foreach($model->params as $key => $value) {
            str_replace($key, $value, $content);
        }
        return $content;
    }
    public function pageExists($path) {
        return file_exists($path);
    }
}

Controller:

<?php
class Controller {
    private $model;

    public function __construct($model) {
        $this->model = $model;
    }
    public function handlePageLoad($page_name) {
        $this->path = $model->site_url . "/app/tpl/skins/" . $model->theme . "/" . $page_name . ".php";
        if($view->pageExists($this->path) === true) {
            $this->content = $view->createPage($this->path);
            return $this->content;
        } else {
            header('HTTP/1.1 404 Not Found');
            return false;
        }
    }

}

Global:

<?php
function autoload($class_name) {
    include "classes/class." . $class_name . ".php";
}
spl_autoload_register('autoload');

$global = array(
    'site_url' = 'http://localhost/Projects/HassanCMS',
    'theme'    = 'v1'
);

$model      = new Model($global);
$controller = new Controller($model);
$view       = new View($model, $controller);

$view->createParam('site_title', 'HassanTech');


texts: JavaFX design writes to static field from constructor

texts:
In JavaFX, the lifecycle of an Application is quite different than Swing. Your constructor must take no arguments so that the Application class can create an instance of your object. Once the instance has been created, it calls start(Stage), which gives you a Stage for you to put your user interface on. This may be fine for some people, but I want to access instance variables of my Application class (which happens to be called LJGM), and the only way I thought I could do this was to have a single, static instance of my LJGM object, and have a static instance() method which returns the instance. Whenever the constructor is called, instance is set to this. There has to be a better way to do this.

public class LJGM extends Application {

    /** The instance of {@link LJGM}. */
    private static LJGM instance;

    /**
     * Gets the only instance of LJGM.
     *
     * @return The instance of LJGM.
     */
    public static LJGM instance() {
        return instance;
    }

    // (other variables here)

    /**
     * Instantiates a new LJGM object.
     */
    public LJGM() {
        LJGM.instance = this;
        // (initialize other variables)
    }

    /*
     * (non-Javadoc)
     *
     * @see javafx.application.Application#start(javafx.stage.Stage)
     */
    @Override
    public void start(Stage primaryStage) throws Exception {
        // (add GUI to the primaryStage here)
    }

    /**
     * Main method.
     *
     * @param args
     *            The arguments to pass to the application.
     */
    public static void main(String[] args) {
        launch(args);
    }
}

Here is the Application Javadoc  in case you need it.


texts:
I have a requirement where I get totalAmount and how much parts to divide that amount into as inputs. For the outputresponse i am using builder pattern and also avoiding null fields. Total amount is a big decimal (if null or less than 0, throw exception) and number of inputs can range between 1-3 (if outside of this range or non numeric, throw exception). I have written this code, but I am not convinced and think there may be a cleaner and better way that is also easy to understand just by looking at the code. Also while splitting, whatever additional cents are left, that would be added to 1st amount.
eg. if 100.01 is total amount that i have to divide into 3 parts, i should get 33.35 for first amount and 33.33 for recurring amounts. Please advise if there is a cleaner and better way to achieve this.
public OutputResponse splitAmount(BigDecimal totalAmount, int divideInto) {
if (!(1 <= divideInto && 3 >= divideInto)) {
            throw new Exception();
        }
        OutputResponse outputResponse;
        if (totalAmount != null && totalAmount.compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal recurringAmounts = null;
            BigDecimal firstAmount = totalAmount;
            if (divideInto > 1) {
                recurringAmounts = totalAmount.divide(BigDecimal.valueOf(divideInto), 2, RoundingMode.FLOOR);
                firstAmount = totalAmount.subtract(recurringAmounts.multiply(new BigDecimal(divideInto - 1)));
            }

            outputResponse = OutputResponse.builder()
                    .firstAmt(firstAmount)
                    .secondPmtAmt(recurringAmounts)
                    .build();

            if (divideInto > 2) {
                outputResponse.setThirdPmtAmt(recurringAmounts);
            }
        } else {
            throw new Exception();
        }
}
```


texts: Extension method to enumerate a hierarchical object

texts:
I have a domain object that I have no control over which itself contains a collection of this same type. This is a classical hierarichal representation like in a tree node hierarchy. I would like to be able to enumerate the whole hierarchy in a single call so I came up with this extension method:

public static class MyObjectExtensions
{
    public static IEnumerable<MyObject> FindAllObjectsRecursive(this MyObject myObject)
    {
        var objects = new List<MyObject>();

        objects.Add(myObject);

        foreach (MyObject innerObject in myObject.Objects)
        {
            objects.AddRange(innerObject.FindAllObjectsRecursive());
        }

        return objects;
    }
}

Unfortunately I am not really satisfied by this method because it would definitely cause issues in a large tree span scenario. So I was wondering if anyone would have a solution for that. I did think of using a parameter for the list but I was thinking there must be a better solution.

Here is how I intend to use this method:

var myObject = new MyObject();
var allObjects = myObject.FindAllObjectsRecursive();

And here is the domain object:

public class MyObject
{
    public IEnumerable<MyObject> Objects { get; set; }
}


texts:
My attempt at writing code to input values of arbitrary bitlength based on a bytearray in Factor. Any comments on the correctness or style would be appreciated.

USING: kernel locals accessors math sequences math.bitwise ;

TUPLE: bitreader bytearray curpos curbit ;
: <bitreader> ( bytearray -- bitreader ) 0 0 bitreader boa ;

: advance ( reader -- reader ) 0 >>curbit [ 1 + ] change-curpos ;

: check-advance ( reader -- reader ) dup curbit>> 8 = [ advance ] when ;

:: readsinglevalue ( bits reader -- result ) reader curpos>> reader bytearray>> nth
                                             reader curbit>> dup bits 1 - + swap bit-range
                                             reader [ bits + ] change-curbit check-advance drop ;

: bitsleft ( reader -- result ) curbit>> 8 swap - ;

DEFER: readbits

:: readmultivalue ( bits reader -- result ) reader bitsleft :> bitsextra
                                            bitsextra reader readsinglevalue
                                            bits bitsextra - reader readbits
                                            bitsextra shift + ;

:: readbits ( bits reader -- result ) reader curbit>> bits + 8 < [ bits reader readsinglevalue ] [ bits reader readmultivalue ] if ;


texts: Natural merge: mergesort that uses already sorted subarrays

texts:
The code bellow is my implementation for the natural merge exercise in Robert Sedgwick's Algorithms book:

  Write a version of bottom-up mergesort that takes advantage of order
  in the array by proceeding as follows each time it needs to ﬁnd two
  arrays to merge: ﬁnd a sorted subarray (by incrementing a pointer
  until ﬁnding an entry that is smaller than its predecessor in the
  array), then ﬁnd the next, then merge them.

def merge(a, lo, mi, hi):
    aux_lo = deque(a[lo:mi])
    aux_hi = deque(a[mi:hi])

    for i in range(lo, hi):
        if len(aux_lo) and len(aux_hi):
            a[i] = aux_lo.popleft() if aux_lo[0] < aux_hi[0] else aux_hi.popleft()
        elif len(aux_lo) or len(aux_hi):
            a[i] = aux_lo.popleft() if aux_lo else aux_hi.popleft()

def find_next_stop(a, start):
    if start >= len(a)-1:
        return start

    stop = start + 1
    if a[start] < a[stop]:
        while(stop<len(a)-1 and a[stop] <= a[stop+1]):
            stop += 1
    else:
        while(stop<len(a)-1 and a[stop] >= a[stop+1]):
            stop += 1

        _stop = stop
        while(start<_stop):
            a[_stop], a[start] = a[start], a[_stop]
            start += 1
            _stop -= 1
    return stop

def natural_merge(a):
    lo = hi = 0
    while(True):
        lo = hi
        mi = find_next_stop(a, lo)
        if lo == 0 and mi == len(a) - 1:
            return
        hi = find_next_stop(a, mi)
        if mi == hi == len(a)-1:
            lo = hi = 0
            continue
        merge(a, lo, mi, hi)

I referenced this answer.


texts:
I would like to detect which is the line-endings type of a file. I wrote this function:

 open my $fh, '<afile.txt';
 seteol($fh);

Here the eol detection subroutine:

 sub seteol {
    my $fh = shift;
    my $byte;
    my $i = 0;
    while (sysread($fh, $byte, 1)) {
        if($byte eq "\n") {
            $/ = "\n";
            return 0;
        }
        elsif($byte eq "\r") {
            sysread($fh, $byte, 1);
            if($byte eq "\n") {
                $/ = "\r\n";
                return 0;
            } else {
                $/ = "\r";
                return 0;
            }
        }
        last if $i++ > 65535;
    }
    return -1;
    seek($fh,0,0);
}

I am wondering if I can do a better job with only core-modules.


texts: Readability of a point-free applicative parser

texts:
I am writing an applicative parser, which you can think of as a minimal Parsec, just to educate myself. I got started with the excellent tutorial from this StackOverflow answer. Here is the relevant code:

type Error = String
newtype Parser a = P { unP :: String -> (String, Either Error a) }

instance Functor Parser where
  fmap f (P st) = P $ \stream -> case st stream of
    (res, Left err) -> (res, Left err)
    (res, Right a ) -> (res, Right (f a))

instance Applicative Parser where
  pure a = P (\stream -> (stream, Right a))
  P ff <*> P xx = P $ \stream0 -> case ff stream0 of   -- produce an f
    (stream1, Left err) -> (stream1, Left err)
    (stream1, Right f ) -> case xx stream1 of          -- produce an x
      (stream2, Left err) -> (stream2, Left err)
      (stream2, Right x ) -> (stream2, Right (f x))    -- return (f x)

orElse :: Parser a -> Parser a -> Parser a
orElse (P f1) (P f2) = P $ \stream0 -> case f1 stream0 of
  (stream1, Left err) -> f2 stream1
  (stream1, Right a ) -> (stream1, Right a)

instance Alternative Parser where
  empty = P $ \stream -> (stream, Left "empty")
  (<|>) = orElse

To make the challenge more interesting, I implemented basically the same code (except that Either is replaced by Maybe) using point-free style and here is what I came up with:

-- A minimal applicative parsing library

module Aarsec where

import Data.Functor
import Control.Applicative
import Control.Monad (join)
import Control.Arrow ((***))

newtype Parser a = Parser { parse :: String -> Maybe (a, String) }

instance Functor Parser where
    fmap f (Parser p) = Parser (fmap (f *** id) . p)

instance Applicative Parser where
    pure x = Parser (Just . ((,) x))
    Parser pf <*> q = Parser (join . fmap g . pf) where
        g (f, input) = parse (fmap f q) input

instance Alternative Parser where
    empty = Parser (const Nothing)
    (Parser p) <|> (Parser q) = Parser (foldl1 (<|>) . (<*>) [p, q] . (: []))

It type-checks just fine and I believe it is correct. I am just curious whether there is anything I can improve regarding readability. I am quite satisfied with the definition of fmap, but those of <*> and <|> do seem a bit cryptic.

Full source


texts:
I am using the JSON output of the MediaWiki API documented here and here, and I have found that for Boolean values, it often returns an empty string if true and omits it if false. Thus, I want to "rationalize" the response.

(Historical context: This was before a new output format was added that uses native JSON true and false.)

My current code to do so (written some months ago) is located in a giant anonymous function:

user = query.users[0];
invalid = typeof user.invalid != "undefined";
missing = typeof user.missing != "undefined";
groups = (typeof user.groups == "object") ? user.groups : [];
editcount = (typeof user.editcount == "number") ? user.editcount : null;
registration = (typeof user.registration == "string") ?
    UserinfoJsParseDate(user.registration) : null;
blocked = typeof user.blockedby != "undefined";
gender = (typeof user.gender == "string") ? user.gender : null;
lastEdited = (typeof query.usercontribs[0] == "object") &&
    (typeof query.usercontribs[0].timestamp == "string") ?
    UserinfoJsParseDate(query.usercontribs[0].timestamp) : null;

I am trying to clean this up, breaking the script's main components into separate functions:

/**
 * Extract relevant information from the server's response.
 * @param data The server's response to the AJAX request
 * @return An object containing the user's information
 */
function processResponse( data ) {
    var query = data.query, info = {};

    if ( query && query.users && query.users[0] ) {
        var user = query.users[0];

        info.invalid = 'invalid' in user;
        info.missing = 'missing' in user;
        info.groups = user.groups || [];
        info.editcount = ( 'editcount' in user ) ? user.editcount : null;
        info.registration = ( 'registration' in user ) ? parseDate( user.registration ) : null;
        info.blocked = 'blockexpiry' in user;
        info.gender = ( 'gender' in user && user.gender != 'unknown' ) ? user.gender : null;

        info.lastEdited = null;
        if ( query.usercontribs && query.usercontribs[0] ) {
            var contribs = query.usercontribs[0];
            if ( contribs.timestamp ) {
                user.lastEdited = parseDate( contribs.timestamp );
            }
        }

    }

    return info;
}

Is this better, or have I just written more messy code?


texts: Enhance the performance of the source code in Java

texts:
I need help to enhance the performance of java source code. The code take txt file that has name, amount and date in form (name) (amount) (date yyyy-mm-dd) separated by spaces. After reading the file the data will be (name) (amount) (date dd/MM/yyyy).

    public static void main(String[] args) throws IOException {

    //we have an lang.ArrayIndexOutOfBoundsException because there is no index 0 in args
    long start = System.currentTimeMillis();
    File inputFile;
    int read;
    char[] charBuffer = new char[1024];
    String token = "";
    int tokenIndex = 0;
    String name = null;
    int year = -1;
    int month = -1;
    int day = -1;
    String amount = null;

    try {
        inputFile = new File(args[0]);
        FileReader reader = new FileReader(inputFile);
        while((read = reader.read(charBuffer)) != -1) {
            for (int i = 0; i < read; ++i) {
                char c = charBuffer[i];
                if (c == '\r' || c == '\n') {
                    if (token.length() != 0) {
                        // read date
                        String date = token;
                        year = Integer.parseInt(date.substring(0, 4));
                        month = Integer.parseInt(date.substring(5, 7));
                        day = Integer.parseInt(date.substring(8, 10));
                        // flush line
                        System.out.print(name.toUpperCase());
                        System.out.print(" ");
                        System.out.print(amount.indexOf('.') == -1 ? true : false);
                        System.out.print(" ");
                        System.out.print(day < 10 ? "0" + day : day);
                        System.out.print("/");
                        System.out.print(month < 10 ? "0" + month : month);
                        System.out.print("/");
                        System.out.print(year);
                        System.out.println();
                        name = null;
                        year = -1;
                        month = -1;
                        day = -1;
                        amount = null;
                        token = "";
                        tokenIndex = 0;
                    }
                }
                else if (c == ' ') {
                    // flush token
                    if (tokenIndex == 0) {
                        // read name
                        name = token;
                        token = "";
                        tokenIndex++;
                    }
                    else if (tokenIndex == 1) {
                        // read amount
                        amount = token;
                        token = "";
                        tokenIndex++;
                    }
                }
                else token = token + c;
            }
        }
    } catch (ArrayIndexOutOfBoundsException e) {System.out.println (e);}
    System.out.println ("Time taken for String in if/else if :"+ (System.currentTimeMillis() - start));
}

I was thinking to separate the nested if-statements because I think its a bad OO code. Any ideas to enhance the code?


texts:
Hi folks:  I posted a SO (https://stackoverflow.com/questions/57541246/optimizing-vba-function-loop) and was told to ask here.

I am starting to think that rather than relay on excel as my data repository, I should create a separate class that holds a variant array that I can then query must faster??

Anyway... here's my question. I hope someone can help.   I agree that searching arrays may be faster but I need this data available across all functions of this sheet.

I am in need to optimizing some VBA which currently works functionally.

Given columns of sequential Dates (column B) and Times (column C), and
Given a time window (T1 and T2), return a range of rows in which dates and times fall within T1 and T2.  For example, I want MIN and MAX price between those two times.

The goal is to build Open/High/Low/Close charts for Excel candlestick charts and the data source has over 260,000 rows of data.

I currently have the following code that

Dim priceRange As Range
startRowNum = GetFirstRow(StartTime)     << THIS TAKE 10 SECONDS
endRowNum = GetLastRow(endTime)         << THIS TAKE 10 SECONDS
Set priceRange = Range(Cells(startRowNum, 4), Cells(endRowNum, 4))
targetRange.Offset(0, 2).Value = Application.WorksheetFunction.Max(priceRange)
targetRange.Offset(0, 3).Value = Application.WorksheetFunction.Min(priceRange)

To find the first row...

Function GetFirstRow(T As Date) As Long

'Starts at FirstRow and returns the first row where the time is greater than T1.

Dim currentRow As Long
Dim CompareTime As Date
Dim CompareDate As Date

currentRow = 4 'Start at row4 due to headers.

Do While (IsDate(Cells(currentRow, 2)))
    CompareDate = Cells(currentRow, 2)
    CompareTime = Cells(currentRow, 3)
    marketTime = CompareDate + CompareTime
  If (marketTime >= T) Then Exit Do
  currentRow = currentRow + 1
Loop

GetFirstRow = currentRow

End Function

GetLastRow is very similar.

My issue is that the GetFirstRow function has to process 49,000 (yes, forty nine thousand) rows, and it takes about 10 seconds.... so it takes "minutes" to complete this run.

Can someone help me optimize this?

Note I Need the date since market data starts the night before.   If this is what is slowing me down, I can filter that as I import the data?


texts: Method for downloading a PDF from a website in Android

texts:
How is this? Any ways to improve?

public void DownloadPDF(Uri uri) {
    downloadProgress.setVisibility(View.VISIBLE);
    downloadComplete.setVisibility(View.INVISIBLE);
    openFile.setText("Wait..."); // My button
    openFile.setEnabled(false);
    if (uri != null) {
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setTitle(pdf + ".pdf");
        request.setDescription("Website: " + pdf);
        request.setMimeType("application/pdf");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        }
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "/SavedPDFs/", pdf + ".pdf");
        manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        downloadId = manager.enqueue(request);
        onComplete = new BroadcastReceiver() {
            public void onReceive(Context ctxt, Intent intent) {
                try {
                    unregisterReceiver(onComplete);
                } catch(IllegalArgumentException e){
                    e.printStackTrace();
                }
                downloadComplete.setVisibility(View.VISIBLE);
                downloadProgress.setVisibility(View.INVISIBLE);
                downloadStatus.setText("Download Complete!");
                updateNumberOfFiles();
                openFile.setText("Open!");
                openFile.setEnabled(true);
            }
        };
        registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }
}


texts: Anything Wrong with This Method of API Versioning Using Flask?

texts:
I'm trying to find a sensible way to structure a REST API written in Flask. I'm new to writing such things and I've not seen this structure used anywhere else, so before I continue I wanted to ask whether this is a decent way of structuring my API code, or if I'm missing something.

I have decided on the following structure, with seperate modules containing flask.Blueprint objects.

src
 ├──api
 │   ├──v1
 │   │  ├──__init__.py
 │   │  └──api_blueprint.py
 │   │
 │   ├──v2
 │   │  ├──__init__.py
 │   │  └──api_blueprint.py
 │   │
 │   ├──__init__.py
 │   │
 .   └──runApi.py

When I need to apply a change to the API, I'll create a new version folder, then import the resource classes from the previous version and override their methods

e.g. src/api/v1/api_blueprint.py contains

import flask
import flask_restful

api_bp = flask.Blueprint('api_v1', __name__)
api = flask_restful.Api(api_bp)

class Vla(flask_restful.Resource):
    def get(self):
        return {'gleep':'glorp'}

api.add_resource(Vla, '/vla')

and src/api/v2/api_blueprint.py - the hypothetical second version of the API - contains a Resource inherited from v1 and has whatever methods required overridden

import flask
import flask_restful
from v1.api_blueprint import Vla

api_bp = flask.Blueprint('api_v2', __name__)
api = flask_restful.Api(api_bp)

class Vla(Vla):
    def get(self):
        return {'gleep':'florp?'}

api.add_resource(Vla, '/vla')

And finally runApi.py

import flask
from v1.api_blueprint import api_bp as api_v1
from v2.api_blueprint import api_bp as api_v2

app = flask.Flask(__name__)
app.register_blueprint(api_v1, url_prefix='/api/v1')
app.register_blueprint(api_v2, url_prefix='/api/v2')

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)

So, in short, is there anything wrong with this method of versioning my API?


texts: Dictionary for locking on unique identifiers without leaking memory

texts:
The following code is greatly inspired on this question and this answer. That answer works quite well for a specific case, but I was looking for a solution that:

could be used more generic (so I can put this in a base library and never have to think about it anymore).
got rid of the Find() and replace it with a O1 dictionary lookup. To be honest I doubt if this would have any performance effect, but it was tickling my OCDs.

I've tried to test it with running about 10 threads and superficially it seems to work. But as concurrency is hard to test and reason about - am I missing something? Any other obvious upgrades?

public class LockDictionary<TKey>
{
    object _RootLock = new object();
    Dictionary<TKey,ItemLock> _KeyToLock = new Dictionary<TKey,ItemLock>();

    public IDisposable Lock(TKey key)
    {
        ItemLock item_lock;

        lock  ( _RootLock )
        {
            item_lock = GetOrCreate(key);
            item_lock._Counter++;
        }

        Monitor.Enter(item_lock);

        return new LockCounter(this, key);
    }

    private ItemLock GetOrCreate(TKey key)
    {
        if ( !_KeyToLock.TryGetValue(key, out var item_lock) )
        {
            item_lock = new ItemLock();
            _KeyToLock.Add( key, item_lock );
        }

        return item_lock;
    }

    private void ReleaseLock(TKey key)
    {
        lock (_RootLock)
        {
            var item_lock = _KeyToLock[key];
            item_lock._Counter--;

            if ( item_lock._Counter == 0 )
                _KeyToLock.Remove(key);

            Monitor.Exit(item_lock);
        }
    }

    private class ItemLock
    {
        public object   _ItemLock   = new object();
        public int      _Counter    = 0;
    }

    private class LockCounter : IDisposable
    {
        LockDictionary<TKey> _Parent;
        TKey _Key;

        public LockCounter(LockDictionary<TKey> parent, TKey key)
        {
            _Parent     = parent;
            _Key        = key;
        }

        public void Dispose()
        {
            _Parent.ReleaseLock(_Key);
        }
    }
}

Update

To clarify; I'm looking for an implementation for the following:

// minimal definition boilerplate
// possibility of using other types as key, like string, long or a struct
static LockDictionary<int> _LockDictionary = new LockDictionary<int>();

// minimal boilerplate for having a separate lock per "groupId"
using ( _LockDictionary.Lock(groupId) )
{
     // can only be run once concurrently per unique groupId
}


texts:
My goal with vervPHP was to create a framework I could create applications in very quickly, without any excessive configuration or over the top framework.

Here's a link to the github, to see more: https://github.com/verv/vervPHP

And now, for some code examples to show how awesome (I think) it is:

index.php:

// Start the session:
session_start();

// Include the framework base:
include_once('framework/verv.php');

// Start the application:
$verv = new verv();

framework/verv.php

class verv {

    // Variables:
    public static $db;
    public static $url;
    public static $rq = array();
    public static $lang = array();
    public static $page = array();
    public static $config = array();
    public static $commands = array();
    public static $framework = array();

    /**
     * Constructor. Do not call manually, unless your module extends verv.
     *
     * @return null
     * @since 1.0
     */
    public function __construct() {
        // Parse the config:
        self::$config = parse_ini_file('config.ini', true);

        // Setup Language:
        self::setLang();

        // Connect to the database if required:
        self::dbConnect();

        // Prepare the request:
        self::setRQ();

        // Load the remaining framework:
        self::loadFramework();

        // Load the appropriate module:
        self::loadModule(self::getCommand(0));

        // Load the template:
        self::loadTemplate();

        // And finally, render the page:
        self::renderPage();
    }

    // More functions follow...

What I'm hoping from a peer review:

How can I improve my code (generally speaking)?
Are there any glaring security holes that I should fix?
I'm wanting to make this open source (for all the help I recieved on SO while making it) so I need to add an open source license to it - one that allows modification (preferrably with attribution) and allows for commercial development.

And yes, I am in the process of improving the actual documentation - it's pretty shocking (particularly the iCommand chaining) at the moment ;)


texts: Make this implementation of counting sort Pythonic

texts:
This is my crude attempt at implementing a counting sort algorithm. My goal is to be able to sort lists of ints, negative and positive. As you can see I've employed such hacks as return res[1:] to get by. I'd appreciate any feedback I can get to make this a more pythonic implementation.

def find_min(a_list):
    min = a_list[0]
    for item in a_list:
        if item < min:
            min = item
    return min

def find_max(a_list):
    max = a_list[0]
    for item in a_list:
        if item > max:
            max = item
    return max

def counting_sort(a_list):
    min = find_min(a_list)
    max = find_max(a_list)

    counts = [0] * (abs(max) + abs(min) + 1)

    for i in range(0, len(a_list), 1):
        counts[a_list[i] - min] += 1

    sum = 0
    for j in range(0, len(counts), 1):
        sum += counts[j]
        counts[j] = sum

    res = [0] * (len(a_list)+1)
    for k in range(0, len(a_list), 1):
        res_index = counts[a_list[k]-min]
        res[res_index] = a_list[k]
        counts[a_list[k]-min] -= 1

    return res[1:]


texts:
I have the following dictionary:

results_dict = {'Current model': {'Recall': 0.77,
  'Precision': 0.1,
  'F1_score': 0.18,
  'Frauds': 94},
 'New model': {'Recall': 0.96,
  'Precision': 0.17,
  'F1_score': 0.29,
  'Frauds': 149}}

What I want is to make a comparison for each metric between the two models, and in case the one belonging to the new model is better, adding +1 to a variable i. So far, I have made this:

recall_new = results_dict['New model']['Recall']
recall_current = results_dict['Current model']['Recall']
precision_new = results_dict['New model']['Precision']
precision_current = results_dict['Current model']['Precision']
F1_new = results_dict['New model']['F1_score']
F1_current = results_dict['Current model']['F1_score']
frauds_new = results_dict['New model']['Frauds']
frauds_current = results_dict['Current model']['Frauds']

i = 0

if recall_new > recall_current or recall_new > (recall_current-(0.1)):
    i+=1
if precision_new > precision_current or precision_new > (precision_current-(0.1)):
    i+=1
if F1_new > F1_current or F1_new > (precision_current-(0.1)):
    i+=1
if frauds_new > frauds_current or frauds_new > int(round(frauds_current*1.2,0)):
    i+=1

The code makes what is intended to do but it is very verbose and repetitive and I was wondering whether it could be simplified or not. Thank you!


texts: Parsing a string with specific pattern into json

texts:
I've a string as an input which is having some specific patterns and I'm trying to parse it into a desired json. Here is my code:

const input = "status:all,applied_date:2019-04-15--to--2019-04-15,screen_status:SR|NS";

    const output = { and: {} };

    const dateSeparator = RegExp("--to--");

    function parseStr(str) {
      const arr = str.split(",");
      for (let i=0; i<arr.length; i++) {
        findPattern(arr[i]);
      }
      console.log(JSON.stringify(output));
    }

    function findPattern(subStr) {
      const subArr = subStr.split(":");
      const newKey = subArr[0].replace("_", ".");
      output["and"][newKey] = {};
      if(dateSeparator.test(subArr[1])) {
        output["and"][newKey]["between"] = subArr[1].split("--to--");
      } else if(subArr[1].split("|").length > 1) {
        output["and"][newKey]["inq"] = subArr[1].split("|");
      } else {
        output["and"][newKey]["eq"] = subArr[1];
      }
    }

    parseStr(input);

I think my approach is very naive and it's not good for complex strings(e.g. deep nesting) and also the logic I've written cannot identify if the given input conform the patterns and will fail if wrong input is provided.

Is there any efficient way to parse strings like these?


texts: Synchronization algorithm for deterministic context switching between threads

texts:
Curious how sqlite3 would handle different race conditions in a multithreaded environment, I created a simple module called deterministic for serializing the execution of multiple threads that lets the programmer explicitly program in the spots where thread-switching happens.  Hopefully this example usage will explain the idea better:

import deterministic

def main():
    deterministic.run(consumer0, consumer1, consumer2)

def consumer0():
    print('consumer 0 yields to consumer 2')
    yield 2
    print('consumer 0 exits')

def consumer1():
    print('consumer 1 yields to next consumer')
    yield
    print('consumer 1 exits')

def consumer2():
    print('consumer 2 yields to consumer 1')
    yield 1
    print('consumer 2 yields to next consumer')
    yield
    print('consumer 2 exits')

if __name__ == '__main__':
    main()

Which outputs:

consumer 0 yields to consumer 2
consumer 2 yields to consumer 1
consumer 1 yields to next consumer
consumer 2 yields to next consumer
consumer 0 exits
consumer 1 exits
consumer 2 exits

Again, the idea is to experiment with how real multi-threaded code behaves, but in a highly controller environment.

The actual code follows below.  Some specific feedback I'm hoping for:

Is there a synchronization primitive that better models what I'm trying to do than simple locking?
Even if not, is there a better way to structure the code to make it easier to reason about?
Finally, general coding and style advice is more than welcome

import threading, time, types

def run(*consumers):
    sync = Syncrhonizer(len(consumers))
    _run_threads(
        threading.Thread(target=DeterministicRunner(sync, i, c).run)
        for i, c in enumerate(consumers)
    )

class Syncrhonizer:
    def __init__(self, num_instances):
        self._instances = list(range(num_instances))

        self._lock = threading.Lock()
        self._current = 0
        self._want_abort = False

    def lock(self, idx):
        while True:
            self._lock.acquire()

            if self._want_abort:
                self._lock.release()
                raise SyncrhonizerAbort()

            if self._current == idx:
                return

            self._lock.release()
            time.sleep(0.001)

    def die(self):
        self._want_abort = True
        if self._lock.locked():
            self._lock.release()

    def yield_to(self, idx=None):
        if idx is None:
            idx = self._get_next_instance()

        if idx not in self._instances:
            self.die()
            raise Exception('Can not yield to non-existent instance "%s"' % idx)

        self._current = idx
        self._lock.release()

    def _get_next_instance(self):
        try:
            return next(n for n in self._instances if n > self._current)
        except StopIteration:
            return self._instances[0]

    def remove(self, idx):
        self._instances.remove(idx)
        if self._lock.locked() and self._instances:
            self.yield_to()

class SyncrhonizerAbort(Exception):
    """Abort execution because of an issue in another thread"""

class DeterministicRunner:
    def __init__(self, syncer, idx, method):
        self._syncer = syncer
        self._idx = idx

        self._g = method()
        if not isinstance(self._g, types.GeneratorType):
            raise Exception('Not a generator')

    def run(self):
        try:
            while True:
                self._syncer.lock(self._idx)

                n = next(self._g)

                self._syncer.yield_to(n)
        except StopIteration:
            pass
        finally:
            self._syncer.remove(self._idx)

def _run_threads(threads):
    threads = list(threads)

    for t in threads:
        t.start()

    for t in threads:
        t.join()