texts:
I'm outputting the results of a query to file.txt in JSON. The file is updated every time I click on 'submit'(form) and depending on the variables it updates the query.

Right now the table only has about 20 records and will probably increase by 2/3 new records everyday.

Is there a better way to updating the file test.txt getting the results from a query?

index.cfm:

  <cfsavecontent variable="mytest">
    [
    <cfoutput query="getimeline">
    <cfif (getimeline.CurrentRow EQ getimeline.RecordCount)>
    {"title":"#name_time#","date":"#dateformat(date_time,"mmmm d, yyyy")#"}
    <cfelse>
    {"title":"#name_time#","date":"#dateformat(date_time,"mmmm d, yyyy")#"},
    </cfif>

    </cfoutput>
    ]
    </cfsavecontent>

    <cffile action="write" file="C:test.txt"  output="#mytest#">

test.txt:

[

{"title":"Advance pay Rollovers","date":"October 23, 2015"},

{"title":"New Card Ordering Process 1","date":"December 28, 2015"},

{"title":"about about","date":"February 5, 2016"}

]


texts: Drop-down menu button highlighting and hiding

texts:
I'm learning JS/jQuery at the moment and have built the following standalone script but I feel that it can probably be improved in some ways?

For example - is there a better way of switching the selected text on the .dropdown-menu li a click event rather than needing to replace the entire HTML?

Constructive advice welcome.

EDIT: Added HTML to help with context:

    <button type="button" class="button defaultbutton">Default Value </button>

Katie

Richard

Matthew

Sophie

Default Value

    <button type="button" class="button primarybutton">Click Me </button>

Katie

Richard

Matthew

Sophie

So currently the script checks if the user is clicking in a dropdown menu that needs an inverted caret.

$(function() {
// Handles initial dropdown click event, if any dropdown menu is visible close it
$('.dropdowncontain').click(function(e){
    if (!$('.dropdown-menu', this).is(':visible')) {
        $('.dropdown-menu').hide();
    }
    $('.dropdown-menu', this).toggle();
    // Stop the bubbling of the event to the document level
    e.stopPropagation();
});

// Handles hiding the dropdown menu's when the user clicks elsewhere in the document
$(document).click(function() {
    $('.dropdown-menu').hide();
});

// Handles updating the text in the button and highlighting the selected option
$('.dropdown-menu li a').click(function(e){
    var parentBtn = $(this).parents('.dropdowncontain').find('.defaultbutton');
    var that = $(this).parents('.dropdowncontain').find('.dropdown-menu li a');
    var selectedText = $(this).text();

        if (that.hasClass('highlightdropdown')){
            that.removeClass('highlightdropdown');
        }

    $(this).addClass('highlightdropdown');

    // If the containing parent div has a class with 'defaultbutton' add the invert class to the caret
    if (parentBtn.hasClass('defaultbutton')) {
        $(this).parents('.dropdowncontain').find('.button').html(selectedText+' ');
    }
    else {
        $(this).parents('.dropdowncontain').find('.button').html(selectedText+' ');
    }
    // Prevent the page jumping to the top when a link with no source is selected
    e.preventDefault();
});
});


texts: LINQ to SQL query filter, with the name match ignoring multiple punctuation characters

texts:
I have the following LINQ to SQL query which works fine but looks ugly:

var filter = "filter";

query = query.Where(x =>
    x.Name.Replace("'", "").Replace("\"", "").Replace("#", "").Replace("/", "").Replace("-", "").Contains(filter) ||
    x.FullName.Replace("'", "").Replace("\"", "").Replace("#", "").Replace("/", "").Replace("-", "").Contains(filter));

It'd be nice to be able to do something similar to this (which isn't possible because LINQ to Entities won't recognize the method):

var filter = "filter";
var removals = new string[] { "'", "\"", "#", "/", "-" };

query = query.Where(x =>
  Replaces(x.Name, removals).Contains(filter) ||
  Replaces(x.Full, removals).Contains(filter));

... but I can't figure out how that could be written. I've written predicates that dealt with entire expressions, but not with just a single property.

This is a LINQ to SQL expression, so I can't just pull it out into its own method or I'll get an error like:

  Additional information: LINQ to Entities does not recognize the method
  'System.String RemoveAll


texts:
I have written this method which calculates the range (max - min) of an ArrayList. I have two for loops each for a different ArrayList. The for loops do exactly the same thing except they each use a different list, so I was wondering if there was a way to just use one for loop (or any other way) that does the work but iterates through both ArrayLists so that I don't have nearly identical for loops.

public static void calcRange(ArrayList <Integer> list1, ArrayList<Integer> list2){
    int max = list1.get(0);
    int min = list1.get(0);
    int max2 = list2.get(0);
    int min2 = list2.get(0);

    for (int i : list1){
        if ( i > max){
            max = i;
        } else if (i < min){
            min = i;
        }
    }
    for (int i : list2){
        if ( i > max2){
            max2 = i;
        } else if (i < min2){
            min2 = i;
        }
    }
    System.out.println("List 1 Range: "+(max - min)+"\tList 2 Range: "+(max2 - min2));
}


texts:
I am a beginner in Python and I am yet to move on from the basics to things like OOP.I wrote all of this code (Python 3) in an hour or so for a simple countdown timer.Although some parts of it are seemingly excessive,is the core of the code pythonic enough or are there better ways of structuring it?I would also like to know a better way for writing comments and variables effectively.More specifically I think the IOTimer() function could be cleaner.

#modules
import datetime
import time
#TIMER
#Enter Preferences

supported_formats = ["hrs","min","sec"]

print("\n")

def get_input():
    global unit_input
    unit_input = input("Enter the format in which you want to time yourself:{}:".format(supported_formats))
    unit_input.lower()

#Check if the format entered is valid.
get_input()

if unit_input in supported_formats:
    pass
else:
    print("Invalid Input.Please re-enter you desired format.\nThe input is case insenseitive")
    get_input()

def countdown_timer(x):
    while x >= 0 :
        x -= 1
        print("{} remaining".format(str(datetime.timedelta(seconds=x))))
        print("\n")
        time.sleep(1)

#Check for input and assign variable to determine the total amount of seconds
def IOTimer():
    while True:
        try:
            if unit_input == "hrs":
                hours  = int(input("Enter the number of hours: "))
                print("\n")
                minutes = int(input("Enter the number of minutes: "))
                print("\n")
                seconds = int(input("Enter the number of seconds: "))
                print("\n")
                break
            elif unit_input == "min":
                hours = 0
                minutes = int(input("Enter the number of minutes: "))
                print("\n")
                seconds = int(input("Enter the number of seconds: "))
                print("\n")
                break
            elif unit_input == "sec":
                hours = 0
                minutes = 0
                seconds = int(input("Enter the number of seconds: "))
                print("\n")
                break
        except:
            print("Invalid Input.Re-enter the values")
            print("\n")
            IOTimer()
    hours_in_sec = hours*3600
    minutes_in_sec = minutes*60
    total_seconds = hours_in_sec + minutes_in_sec + seconds
    print("Starting countdown for {}".format(str(datetime.timedelta(seconds=total_seconds))))
    print("\n")
    time.sleep(2)
    countdown_timer(total_seconds)

IOTimer()


texts:
I wrote a script that will web scrape data for a list of stocks. The scraper has to get the data from 2 separate pages so each stock symbol must scrape 2 different pages. If I run the process on a list that is 1000 items long it will take around 30 minutes to complete. It's not horrible, I can set it and forget it, but I'm wondering if there is a way to speed up the process. Maybe store the data and wait to write it all at the end instead of on each loop? Any other ideas appreciated.

import requests
from BeautifulSoup import BeautifulSoup
from progressbar import ProgressBar
import csv

symbols = {'AMBTQ','AABA','AAOI','AAPL','AAWC','ABEC','ABQQ','ACFN','ACIA','ACIW','ACLS'}
pbar = ProgressBar()

with open('industrials.csv', "ab") as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    writer.writerow(['Symbol','5 Yr EPS','EPS TTM'])
    for s in pbar(symbols):
        try:
            url1 = 'https://research.tdameritrade.com/grid/public/research/stocks/fundamentals?symbol='
            full1 = url1 + s
            response1 = requests.get(full1)
            html1 = response1.content
            soup1 = BeautifulSoup(html1)

            for hist_div in soup1.find("div", {"data-module-name": "HistoricGrowthAndShareDetailModule"}):
                EPS5yr = hist_div.find('label').text

        except Exception as e:
            EPS5yr = 'Bad Data'
            pass

        try:
            url2 = 'https://research.tdameritrade.com/grid/public/research/stocks/summary?symbol='
            full2 = url2 + s
            response2 = requests.get(full2)
            html2 = response2.content
            soup2 = BeautifulSoup(html2)

            for div in soup2.find("div", {"data-module-name": "StockSummaryModule"}):
                EPSttm = div.findAll("dd")[11].text

        except Exception as e:
            EPSttm = "Bad data"
            pass

        writer.writerow([s,EPS5yr,EPSttm])


texts: Hash Tables: Ice Cream Parlor solution in javascript

texts:
I tried solving the Hash Tables: Ice Cream Parlor question in javascript:

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

function readLine() {
    return inputString[currentLine++];
}

// Complete the whatFlavors function below.
function whatFlavors(cost, money) {

// Solution starts here
  var dict1={};

  var len=cost.length;

  for(var i=0; i<len; i++) {

    if (cost[i]<money) {
      if(dict1[cost[i]] !== undefined)
      {
       if(Array.isArray(dict1[cost[i]]))
       {
         dict1[cost[i]].push(i);
       }
       else
       {
         dict1[cost[i]] = [dict1[cost[i]]];
         dict1[cost[i]].push(i);
       }
     }
     else
       dict1[cost[i]] = i;
    }
  }

  cost.sort(function(a,b) {return a-b});

  for(var j=0; j<len; j++){
    var left=0;
    var right=len-1;
    if(cost[j]<money){
      var ser=money-cost[j];
      while(left<right){
        var mid=Math.floor((left+right)/2);

        if(ser===cost[mid]){
          var val1=cost[j];
          var val2=cost[mid];
          break;
        }
        if(ser<cost[mid]){
          right = mid-1;
        }
        else{
          left = mid+1;
        }
      }
      if(val1 !== undefined && val2 !== undefined ){
        break;
      }
    }
  }

  var index1;
  var index2;
  if (val1===val2) {
     index1 = dict1[val1][0];
     index2 = dict1[val2][1];
  }
  else{
     index1 = dict1[val1];
     index2 = dict1[val2];
  }

  if (index2 > index1) {
    console.log(index1+1, index2+1);
  }
  else{
    console.log(index2+1, index1+1);
  }
  // Solution ends here
}

function main() {
    const t = parseInt(readLine(), 10);

    for (let tItr = 0; tItr < t; tItr++) {
        const money = parseInt(readLine(), 10);

        const n = parseInt(readLine(), 10);

        const cost = readLine().split(' ').map(costTemp => parseInt(costTemp, 10));

        whatFlavors(cost, money);
    }
}

It works for all inputs except when it is very large, for example when the input is very large for eg:
30733 39289
12352 19413
448 3955
74 75
12316 34744
2916 4669
1941 6571
2871 17443
34132 42603
1753 9623
7217 8111
3411 17665
3190 16653
1923 14237
6307 22944
10874 22052
967 21913
7562 7948
11038 36319
586 8260
338 1426
17083 37691
11944 15889
10347 13601
643 1653
18754 19595
9561 22822
22521 26308
114 1965
338 412
8423 9497
6371 33551
1292 3705
5634 9563
14043 14669
12566 39425
1149 2638
12664 12939
10217 29104
it simply throws Wrong Answer, is there a better way to write the same script?


texts: Recurrent action on concurrent collection

texts:
I have a bunch of concurrent threads carrying out operations which return alerts. The alerts have to be persisted to a DB, but this cannot be done concurrently as it may cause duplicate alerts being created.
To avoid duplicate alerts I have written a class containing a ConcurrentBag<T> with a Timer that triggers Action<T> (in this case, sending my pending alerts to the DB) at a set interval.

I'm wondering if what I wrote it is written in a way that will not cause problems in the execution in the future. If alerts get lost due to an unexpected exception that would be problematic. I'd appreciate comments/criticisms/suggestions for improvement.

Here's the code:

class PeriodicConcurrentBag<T>
{
    public int Count
    {
        get { return this.items.Count(); }
    }

    public bool HasItems
    {
        get { return this.items.Any(); }
    }

    public bool IsStopped { get; private set; }

    private int timerPeriod;
    private Timer timer;
    private ConcurrentBag<T> items;
    private Action<IEnumerable<T>> actionOnItems;

    public PeriodicConcurrentBag(Action<IEnumerable<T>> actionOnItems, int periodInSeconds)
    {
        this.timerPeriod = periodInSeconds * 1000;
        this.actionOnItems = actionOnItems;

        this.items = new ConcurrentBag<T>();
    }

    public void Start()
    {
        this.IsStopped = false;
        this.timer = new Timer(this.InternalPeriodicAction, null, this.timerPeriod, Timeout.Infinite);
    }

    public void Stop()
    {
        this.IsStopped = true;
    }

    public void AddItem(T item)
    {
        this.items.Add(item);
    }

    public void AddItems(IEnumerable<T> items)
    {
        this.items.AddRange(items);
    }

    private void InternalPeriodicAction(object state)
    {
        if (!this.IsStopped)
        {
            var currentItems = Interlocked.Exchange(ref this.items, new ConcurrentBag<T>());
            this.actionOnItems(currentItems);

            if (!this.IsStopped)
                this.Start();
        }
    }
}

EDIT: The AddRange() method is an extension method I created for ConcurrentBag.


texts: Find all occurrences of all permutations of a shorter string within a longer string

texts:
Input is two strings, the first string being the long string and the second smaller string being the permuted string.

The output should return the starting indices of all occurrences as well as the permutation of the substring in the longer string.

Case 1)

permutationsInString('abcdcbadefbac', 'abc')
sample output: { '0': 'abc', '4': 'cba', '10': 'bac' }

Case 2)

 permutationsInString('abcabacba', 'abc')
sample output: { '0': 'abc',
'1': 'bca',
'2': 'cab',
'4': 'bac',
'5': 'acb',
'6': 'cba' }

Case 3)

permutationsInString('a', 'abc')
sample output: {}

My solution is Naive and Brute Force, was wondering if there are any other possible ways to reduce the time and space complexity.

function permutationsInString(longString, shortString) {
  let hash = {}; // let hash store the resulting found permutation strings and their respective index in the long string
  let permutations_shortStrings = permutationArr(shortString) ; // permute the short string and store the values in an array called permutations_shortStrings
  for(let i = 0 ; i < permutations_shortStrings.length ; i++) { // iterate through the array of permutations to check if the long string contains any of the values
    if(longString.indexOf(permutations_shortStrings[i]) !== -1)  // need to check for -1 as it indicates the substring cannot be found
      hash[longString.indexOf(permutations_shortStrings[i])] = permutations_shortStrings[i];
    }

    return hash ;

}

function permutationArr(str)
{
  var arr = str.split(''),
  permutations = [];

  function swap(a, b)
  {
    var tmp = arr[a];
    arr[a] = arr[b];
    arr[b] = tmp;
  }

// Heap's algorithm implementation
  function generate(n) {
    if (n == 1) {
      permutations.push(arr.join().replace(/,/g, ''));
    } else {
      for (var i = 0; i < n; ++i) {
        generate(n - 1);
        swap(n % 2 ? 0 : i, n - 1);
      }
    }
  }

  generate(arr.length);
  return permutations;
}


texts: Reduce the calls to database for validations in rails

texts:
I was building a rails web, and used form object to separate the validation logics per form.

I had to find_referral_code twice in order to store the user_id of referrer. I wonder how I can improve it.

after_sign_up_form.rb

def get_referred_by_id
    User.where(referral_code: referer_referral_code).first.id
end

def validates_presence_of_referer_referral_code
    u = User.find_by_referral_code(referer_referral_code)
    if u.nil?
        errors.add :referer_referral_code, "Not a valid Referral Code"
    else
        if @user.referral_code == referer_referral_code
            errors.add :referer_referral_code, "Can't use your own referral code"
        end
    end
end

def validates_unique_primary_email
    # errors.add :primary_email, "Email is taken"
end

def email_is_self
    (@user.identities.pluck(:email) << @user.email).flatten.include? primary_email
end


texts: Class for multithreaded insert into database

texts:
Here I have class that supposed to take dictionaries of product objects and their articles (kind of unique identifier) from queue and insert or update them in database table.

Received dictionary looks like this:

products_and_articles= {'products':[],'articles':[]}

Please suggest any improvements I can make to this class.

class TableUpdater(threading.Thread):

def __init__(self, import_queue, model_for_update):

    self.import_queue = import_queue
    self.model_for_update = model_for_update
    threading.Thread.__init__(self)

def run(self):
    while True:
        try:
            products_and_articles = self.import_queue.get(block=True, timeout=20)

            products_for_update = self.model_for_update.objects.filter(article__in=products_and_articles['articles'])
            articles_for_update = [product.article for product in products_for_update]

            articles_for_create = list(set(products_and_articles['articles']) - set(articles_for_update))
            absent_products = [p for p in products_and_articles['products'] if p.article in articles_for_create]
            products_for_create = []

            for new_product in products_and_articles['products']:
                for old_product in products_for_update:
                    if new_product.article == old_product.article:
                        for old_field in old_product._meta.get_all_field_names():
                            for new_field in new_product._meta.get_all_field_names():
                                if old_field == new_field and old_field != 'id' and old_field != 'slug':
                                    setattr(old_product, old_field, getattr(new_product, old_field))

            bulk_update(products_for_update)

            if len(products_for_update) != len(products_and_articles['products']):
                for new_product in absent_products:
                    old_product = self.model_for_update()
                    for old_field in old_product._meta.get_all_field_names():
                        for new_field in new_product._meta.get_all_field_names():
                            if old_field == new_field and old_field != 'id':
                                setattr(old_product, old_field, getattr(new_product, old_field))
                    products_for_create.append(old_product)

                product_bulk_create(products_for_create, 0, articles_for_create)

        except Queue.Empty:
            print 'Queue is empty'
            break


texts: Pandas merge a "%Y%M%D" date column with a "%H:%M:%S" time column

texts:
I have a dataframe with a column composed by date object and a column composed by time object.
I have to merge the two columns.
Personally, I think it is so ugly the following solution.
Why I have to cast to str?
I crafted my solution based on this answer
#importing all the necessary libraries
import pandas as pd
import datetime

#I have only to create a Minimal Reproducible Example
time1 = datetime.time(3,45,12)
time2 = datetime.time(3,49,12)
date1 = datetime.datetime(2020, 5, 17)
date2 = datetime.datetime(2021, 5, 17)
date_dict= {"time1":[time1,time2],"date1":[date1,date2]}

df=pd.DataFrame(date_dict)

df["TimeMerge"] = pd.to_datetime(df.date1.astype(str)+' '+df.time1.astype(str))


texts:
The C in CRUD Silverlight:

Create new Silverlight business application "CRUD"
Add ADO.NET Entity Data Model to CRUD.web
Select the db, the tables, build the project
Add Domain Service Class to CRUD.web
Select the tables and also select the allow editing option for the table "tname"
Build the project
Keep two textboxes "ID" and "NAME" on MainPage.xaml
Keep a button "SAVE NEW RECORD" on MainPage.xaml
Build
Add the following code

Partial Public Class MainPage
    Inherits UserControl

    Dim dserv As New DomainService1

//default methods generated
Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
        'declare a table object
        Dim table As New tname
        'assign values to fields
        table.ID = TextBox1.Text
        table.NAME = TextBox2.Text
        'add table object entity
        dserv.tnames.Add(table)
        'submit the changes, to make it permenant in the db
        dserv.SubmitChanges()
    End Sub

Record inserted

Is this the easiest way for having no side effects to add a new record? Is this the optimal way to add a new record?


texts:
I'm new to python and programming in general and I found Project Euler problems a good way to practice python. But my code is pretty slow. It seems to work, didn't wait long enough for the code to print the answer though. Any tips on how to make it faster ? I assume that you don't have to check every single number but that's just a guess any help appreciated.

tri_nums = [1]
divisors = []
temp_divisors =[]

while len(divisors) <= 500:
    for x in range(1, tri_nums[-1] + 1):
        if tri_nums[-1] % x == 0:
            temp_divisors.append(x)
    if len(temp_divisors) > len(divisors):
        divisors = temp_divisors[:]
    temp_divisors.clear()

    print("Number: " + str(tri_nums[-1]))
    print("Number of divisors: " + str(len(divisors)))
    print("List of divisors: " + str(divisors))
    tri_nums.append(len(tri_nums) + 1 + tri_nums[-1])


texts: Single producer single consumer command queue

texts:
I needed to create commands simply with lambda and execute it in another thread. The following code works fine. Any suggestions about performance are appreciated.

I want to use SSE aligned variables as lambda captures, for instance:

__m128 xmm0;
queue.Enqueue([xmm0](){
    //...
});

template<unsigned MaxCommand = 1000> class TCommandQueueSPSC
{
    static const unsigned MaxLambdaSize = sizeof(void*) * 7;

    struct alignas(16) ICMD
    {
        virtual ~ICMD() {}
    };
    struct alignas(16) CMDBase : ICMD
    {
        char mBuffer[MaxLambdaSize];
    };
    static_assert(sizeof(CMDBase) % 16 == 0, "should be 16 aligned");
    static const unsigned CMDSize = sizeof(CMDBase);

    alignas(64) volatile unsigned       mHead = 0;
    volatile bool                       mRuning = false;
    Event                               mWaitEvent;
    alignas(64) volatile unsigned       mTail = 0;
    ThreadID                            mConsumerThreadID = 0;
    alignas(64) CMDBase                 mElements[MaxCommand];

    bool IsEmpty() const { return mHead == mTail; }
    bool IsFull() const { return ((mTail + 1) % MaxCommand) == mHead; }

    void* BeginEnqueue()
    {
        UASSERT(!IsFull()); //assert if full
        return mElements + mTail;
    }
    void EndEnqueue()
    {
        mTail = (mTail + 1) % MaxCommand;
    }

    ICMD* BeginDequeue()
    {
        if (mHead == mTail) return nullptr;
        return (ICMD*)(mElements + mHead);
    }
    void EndDequeue()
    {
        mHead = (mHead + 1) % MaxCommand;
    }

public:
    TCommandQueueSPSC(const TCommandQueueSPSC&) = delete;
    TCommandQueueSPSC& operator = (const TCommandQueueSPSC&) = delete;

    TCommandQueueSPSC() : mWaitEvent(false, false) {}

    template<typename Lambda> void Enqueue(const Lambda& proc)
    {
        if (Thread::ID() == mConsumerThreadID)
        {
            proc();
            return;
        }

        struct NewCMD : public ICMD
        {
            Lambda mProc;
            NewCMD(const Lambda& p) : mProc(p) {}
            ~NewCMD()
            {
                mProc();
            }
        };
        static_assert(sizeof(NewCMD) <= CMDSize, "");
        static_assert(alignof(NewCMD) <= alignof(ICMD), "");
        void* cmd = BeginEnqueue();
        new (cmd) NewCMD(proc);
        EndEnqueue();
    }
    template<typename Lambda> void EnqueueAndWait(const Lambda& proc)
    {
        if (Thread::ID() == mConsumerThreadID)
        {
            proc();
            return;
        }

        struct NewCMD : public ICMD
        {
            Lambda mProc;
            TCommandQueueSPSC*  mOwner;
            NewCMD(const Lambda& p, TCommandQueueSPSC* owner) : mProc(p), mOwner(owner) {}
            ~NewCMD()
            {
                mProc();
                mOwner->mWaitEvent.SetSignaled();
            }
        };
        static_assert(sizeof(NewCMD) <= CMDSize, "");
        static_assert(alignof(NewCMD) <= alignof(ICMD), "");
        void* cmd = BeginEnqueue();
        new (cmd) NewCMD(proc, this);
        EndEnqueue();

        mWaitEvent.Wait();
    }
    void RunTillQuit()
    {
        mRuning = true;
        mConsumerThreadID = Thread::ID();

        while (mRuning)
        {

            if (ICMD* cmd = BeginDequeue())
            {
                cmd->~ICMD();
                EndDequeue();
            }
            else
            {
                 _mm_pause();
            }
        }
    }
    void Quit() { mRuning = false; }
    volatile bool IsRuning() const { return mRuning; }
 };


texts: Formatting fractions found in a given string to html fraction

texts:
I'm working on a site running woocommerce and wp where the user will add/has added a dimension attribute.

The dimension string will take the following format originally:

Ht: 30 1⁄2" W: 22 1⁄2" D: 18"

and should return the string with html to format the fraction e.g:

Ht: 30 1&frasl;2" W: 22 1&frasl;2" D: 18"

will the following to consider:

The amount of fractions in the string will be unknown (0 - X)
The string can be any valid fraction
The user may/may not add a space in between the fraction and the quotation e.g Ht: 30 1/2 " W...

Here's my solution:

add_filter( 'woocommerce_attribute', __NAMESPACE__ . '\\format_dimension_attr', 10, 2 );

/**
 * Format fractions in the Dimension attr string to include proper html
 *
 * e.g The 1/2 in 'Height: 5 1/2"' should be
 *
 * 1&frasl;2
 */
function format_dimension_attr( $value, $att ) {

    if ( 'Dimensions' === $att['name'] ) {
        // Use the raw value instead of $value (which includes html)
        $raw = $att->get_options()[0];

        if ( strpos( $raw, '/' ) !== false ) {

            $raw = explode( ' ', $raw );

            // Check for accidental space before quotation and remove it
            // e.g 'height: 5 1/2 "' will produce [5, 1/2, "]
            $raw = array_filter( $raw, function( $val ) {
                return '"' !== $val;
            } );

            // Run through the array
            $raw = array_map( function( $val ) {

                // Format the current item if it contains a slash
                if ( strpos( $val, '/' ) !== false ) {
                    // Remove any " before splitting
                    $val = explode( '/', trim( $val, '"' ) );
                    $val = '' . $val[0] . '&frasl;' . $val[1] . '"';
                }

                return $val;

            }, $raw );

            // Replace the p tag we removed by using the raw value
            $value = wpautop( join( ' ', $raw ) );
        }
    }

    return $value;
}


texts: Generic methods to find the maximal element in part of a list

texts:
This is the question from Oracle docs:

  Write a generic method to find the maximal element in the range
  [begin, end) of a list.

I had my implementation like this:

    public static <T extends Comparable> T maximalElement (List<T> list, int from, int to) {
        T max = list.get(from);
        for (int i = from + 1; i < to; i++) {
            T elem1 = list.get(i);
            if (elem1.compareTo(max) > 0) {
                max = elem1;
            }
        }
        return max;
    }

When I viewed the answer, it was something like this:

     public static <T extends Object & Comparable<? super T>> T max (List<? extends T> list,
                                                                    int begin, int end) {

        T maxElem = list.get(begin);

        for (++begin; begin < end; ++begin) {
            if (maxElem.compareTo(list.get(begin)) < 0) maxElem = list.get(begin);
        }
        return maxElem;
    }

So, I got the results running like this:

        List<Integer> c = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        System.out.println(Test.maximalElement(c, 3, 8));
        System.out.println(Test.max(c, 3, 8));

Results are same, so I am quite excited that my version of generics is more simpler than one implemented in the answer. So, I want to check if my implemented version is really simpler and okay or am I not seeing something? Because oracle developers are not dumb enough to complex things out for nothing.

So, can you experts please help me understanding the difference or scenarios where my implemented version fails?


texts:
I'm making a simple httpcode monitor as an example for teaching myself PHP OOP. I have written the code below and would be interested in having it improved.

In particular, I'm not sure about this line:

$httpcode = $website->get_httpcode($url);

This seems very inefficient to me as I have to to pass the URL back to the website class right after I have already done just that two lines above. Shouldn't it already remember its URL? That might be a dumb question, but in my mind, I've already made an object called website and given it a URL. Then if I want the httpcode of the URL, then I feel there should be some way for it to remember its URL which I passed two lines above.

class website {
var $url;

function __construct($url) {
    $this->url = $url;
}

public function get_url() {
    return $this->url;
}

public function get_httpcode($url) {
    //get the http status code
    $agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
    $ch=curl_init();
    curl_setopt ($ch, CURLOPT_URL,$url );
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_VERBOSE,false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSLVERSION, 3);
    $page=curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $httpcode;
}
}

// create an instance of the website class and pass the url
$website = new website("http://www.google.com");
$url = $website->get_url();
$httpcode = $website->get_httpcode($url);


texts: Correctness of calculations with struct timespec

texts:
I've noticed some discrepancies in timings in our system, and I'm trying to narrow down what could be causing them.

I'm reviewing out time abstraction, and as far as I can determine it's fine.

Am I missing anything, and is it portable (besides being constrained to POSIX)?

typedef struct timespec Time;
static inline Time getTime() {
    static struct timespec time;
    clock_gettime(CLOCK_MONOTONIC, &time);
    return time;
}
static inline __constant Time timeAdd(Time oldTime, Time time) {
    if (time.tv_nsec + oldTime.tv_nsec >= 1E9)
        return (Time){
            tv_sec: time.tv_sec + oldTime.tv_sec + 1,
            tv_nsec: time.tv_nsec + oldTime.tv_nsec - 1E9
        };
    else
        return (Time){
            tv_sec: time.tv_sec + oldTime.tv_sec,
            tv_nsec: time.tv_nsec + oldTime.tv_nsec
        };
}
static inline __constant Time timeDiff(Time oldTime, Time time) {
    if (time.tv_nsec < oldTime.tv_nsec)
        return (Time){
            tv_sec: time.tv_sec - 1 - oldTime.tv_sec,
            tv_nsec: 1E9 + time.tv_nsec - oldTime.tv_nsec
        };
    else
        return (Time){
            tv_sec: time.tv_sec - oldTime.tv_sec,
            tv_nsec: time.tv_nsec - oldTime.tv_nsec
        };
}
static __always_inline __constant double timeSeconds(Time time) {
    return time.tv_sec + time.tv_nsec/1E9;
}
static inline double timeSince(Time oldTime) {
    struct timespec time;
    clock_gettime(CLOCK_MONOTONIC, &time);
    return timeSeconds(timeDiff(oldTime, time));
}


texts: Finding the right property value from array of objects

texts:
I have a below snippet, here I am using array.find to find the first success case and end it. So here is the code snippet
const USERS_LIST = [
  {
    key: "john",
    location: "dublin",
  },
  {
    key: "joe",
    subKeys: [
      {
        key: "jane",
        locaction: "washington",
      },
      {
        key: "mary",
        location: "newyork",
      },
    ],
  },
  {
    key: "chris",
    location: "amsterdam",
  },
];

so what I am trying here is I go through each object in USERS_LIST and check for a subKeys property. If a subKeys property is present, loop through that and check whether that key is eligible. If it's eligible then I need to stop it or it will pass to the next subkey. If I don't find any subKeys eligible then iterate to the next USERS_LIST object then it takes the key and checks for eligible, whichever I find the first I do a callback and stop executing.
I am able to solve this with this snippet
USERS_LIST.find((user) => {
      if (user?.subKeys) {
        user.subKeys.find((subUser) => {
          let subUserStatus = checkEligible({
            action: subUser.key,
          });
          if (subUserStatus) {
            callback(subUser.location);
            return true;
          }
          return false;
        });
      } else {
        let userAccess = checkEligible({ action: user.key });
        if (userAccess) {
          callback(user.location);
          return true;
        }
      }
      return false;
    });

Is there a better way using with array.some or any other functions where I can achieve the same output.


texts: Get height for tallest possible stack of boxes

texts:
This code is meant to compute the height for the tallest stack of boxes out of a given collection of boxes. A box has width, height, and depth dimensions. The height of a stack of boxes is the sum of all of the heights of the boxes in the stack. The boxes cannot be rotated. A box can only be stacked on top of another box if its width, height, and depth are strictly smaller.

I'm doing this to improve my style and to improve my knowledge of fundamental algorithms/data structures for an upcoming coding interview.

from operator import attrgetter

class Box:
    def __init__(self, width, height, depth):
        self.width = width
        self.height = height
        self.depth = depth

    def smaller_than(self, other_box):
        return (self.width < other_box.width and
                self.height < other_box.height and
                self.depth < other_box.depth)

def tallest(boxes):
    boxes = sorted(boxes, reverse=True, key=attrgetter('height'))
    largest_height = 0
    for i in range(len(boxes)):
        bottom_box = boxes[i]
        total_height = bottom_box.height
        cur_top_box = bottom_box
        for j in range(i+1,len(boxes)):
            if boxes[j].smaller_than(cur_top_box):
                total_height += boxes[j].height
                cur_top_box = boxes[j]
        if total_height > largest_height:
            largest_height = total_height
    return largest_height

The question wasn't clear about how the boxes were represented or inputted. I just made them into a Box class and assumed that they were passed as a list to tallest(). If there are any better ways of representing the boxes or inputting them (especially in an interview environment) I would be happy to hear it.

I think this code has time complexity O(n^2) and space complexity O(n). Please correct me if I'm wrong. Any suggestions about how I can improve these complexities are welcome.


texts:
I am attempting to complete an assignment, which is basically Connect 3, instead of the classic Connect 4 game.  The AI I am using is the exact same as the opponent, but the opponent wins more because it goes first.  I've researched for days and cannot grasp MINIMAX, or think of ways to make this AI better.

public int getBestColumn(Player[][] state, Player player) {
    for (int c = 0; c < GRID_WIDTH; c++)

    int r = top(state, c);

    if (r >= 0) {
        Player[][] hypothetical = state;
        hypothetical[r][c] = player;
        if (getWinner(hypothetical, r, c) == player)
            return c;

        Player opponent = (player == Player.PLAYERX ? Player.PLAYERO : Player.PLAYERX);
        hypothetical[r][c] = opponent;
        if (getWinner(hypothetical, r, c) == opponent)
            return c;
        if(player==opponent)
            return c;

        hypothetical[r][c] = Player.NONE;

    }
}

    return (new Random()).getBestColumn(state, player);
}
}
}


texts: Running over a log file to extract log times

texts:
I need to run over a log file with plenty of entries (25+GB) in Python to extract some log times.

The snippet below works.  On my test file, I'm ending up with roughly 9:30min (Python) and 4:30min (PyPy) on 28 million records (small log).

import datetime
import time
import json
import re

format_path= re.compile(
    r"^\S+\s-\s"
    r"(?P<user>\S*)\s"
    r"\[(?P<time>.*?)\]"
)

threshold = time.strptime('00:01:00,000'.split(',')[0],'%H:%M:%S')
tick = datetime.timedelta(hours=threshold.tm_hour,minutes=threshold.tm_min,seconds=threshold.tm_sec).total_seconds()
zero_time = datetime.timedelta(hours=0,minutes=0,seconds=0)
zero_tick = zero_time.total_seconds()
format_date = '%d/%b/%Y:%H:%M:%S'

obj = {}
test = open('very/big/log','r')

for line in test:
  try:
      chunk = line.split('+', 1)[0].split('-', 1)[1].split(' ')
      user = chunk[1]
      if (user[0] == "C"):
        this_time = datetime.datetime.strptime(chunk[2].split('[')[1], format_date)
        try:
            machine = obj[user]
        except KeyError, e:
            machine = obj.setdefault(user,{"init":this_time,"last":this_time,"downtime":0})
        last = machine["last"]
        diff = (this_time-last).total_seconds()
        if (diff > tick):
          machine["downtime"] += diff-tick
        machine["last"] = this_time

  except Exception:
    pass

While I'm ok with the time the script runs, I'm wondering if there are any obvious pitfalls regarding performance, which I'm stepping in (still in my first weeks of Python).

Can I do anything to make this run faster?

EDIT:

Sample log entry:

['2001:470:1f14:169:15f3:824f:8a61:7b59 - SOFTINST [14/Nov/2012:09:32:31 +0100] "POST /setComputerPartition HTTP/1.1" 200 4 "-" "-" 102356']

EDIT 2:

One thing I just did, was to check if log entries have the same log time and if so, I'm using the this_time from the previous iteration vs calling this:

this_time = datetime.datetime.strptime(chunk[2].split('[')[1], format_date)

I checked some of logs, there are plenty of entries with the exact same time, so on the last run on pypy I'm down to 2.43min.


texts:
I occasionally find myself bumping into code like this (either in other projects or banging out initial prototypes myself):

 if @product.save
   if current_member.role == "admin"
     redirect_to krowd_path(@product)
   else
     redirect_to new_product_offer_path(@product)
   end
 else
   render :new
 end

What is a good way to avoid this type of situation all together?


texts: Communicating events between entity components with minimal code overhead

texts:
I'm working on a game which utilises a variant of the entity component system pattern. In my current code, I have been communicating between components using code of the form:

_entity.GetComponent<MovementComponent>().TargetPosition = targetPosition;

I wanted to remove this very strong coupling which my components have (as a result of specifying exactly which component should receive the message), and transition towards an event / message system.

As a result, I've written an implementation which seems ideal, however it uses run-time dynamic typing which has me concerned that there may be a better way to achieve my goals.

My code is as follows, currently:

Inside Entity:

public void SendMessage<T>(T message) {
    _components.ForEach(x => (x as dynamic).Message(message));
}

Inside Abstract Component class:

public virtual void Message(IComponentMessage componentMessage) { }

Inside an example component (MovementComponent) that receives a move message:

public void Message(MoveMessage message) {
    Console.Write("Received message");
}

Dispatching a command to move:

private void IssueMovement(TileCoordinate targetPosition) {
    Console.Write("Dispatching move message");
    _entity.SendMessage(new MoveMessage(targetPosition));
}

Example Message class - MoveMessage:

public class MoveMessage : IComponentMessage {
    public readonly TileCoordinate MoveTo;

    public MoveMessage(TileCoordinate coordinates) {
        MoveTo = coordinates;
    }
}

NB: IComponentInterface is just an empty interface at the current moment in time.

The way I see it, my current approach has some big advantages:

Adding a new message type does not require any modification elsewhere to be supported.
Subscribing to an event is as easy as creating a method with the correct event class.
There is practically no overhead for listening to a specific event - no need to instantiate a class, inherit some event-specific interface, register interest at run-time with a subscribe method, etc.
As messages are represented by classes (like a MoveMessage), they can contain all the relevant data without needing to be cast or coerced.

However, as mentioned at the beginning of my question, I am concerned about using run-time dynamic typing in this fashion (See my dispatch code in Entity - the second snippet in this post). This system will probably be handling a lot of messages, and I have some concerns about the overhead incurred (it also feels like a code smell in general)

I would really appreciate feedback on this approach; particularly whether it seems like an abuse of dynamic to more experienced C# developers than I, but would also appreciate alternative suggestions.

Alternative approaches I've considered, and why I did not go with them initially:

Exhaustive set of event properties which components can subscribe to manually - adds extra code overhead to each message type, which I'd like to avoid
Dictionary from event Type to handler in each component - have to subscribe at run-time, which feels undesirable.
Switching dynamically inside a non-overloaded handler - more viable than it sounds since most components will not listen to more than a few message types, but still has unpleasant code overhead

I am quite sure this code is okay, outside of the overhead induced by the run-time typing - my apologies if this makes it a bad fit. I am just hoping for a once-over review by someone more experienced to reassure me that this is a good design.


texts: Show list of numbers 1-10 multiplied by user entered number

texts:
Objective of this program is to have the user enter 2 or 9 and output
the respective numbers multiple by 2 10 times.
Example if a user enters 2, browser will output the following:

2 times 2 is:4
3 times 2 is:6
⋮
11 times 2 is:22

I want like to know how can I simplify the underneath code? I have
placed the computation of the user entered value multiple by 2, on 2
separate" if else-if" statements. In case the user enters a wrong
number and subsequently when he enters the correct value, the values
wil be multipled by 2. See Loop A and Loop B comments to understand
what I mean.

let value = prompt("Enter Value between 2 or 9");

document.write(value);
document.write(`<br>`);

if (value == 2 || value == 9) {
//Loop A, when user enters 2 or 9, a list of its multiple by 2 is output to the user 10
//times since I have already written the logic here how do I ensure it do not
//write it again

  for (let i = 0; i < 10; i++) {
    value2 = value * 2;
    document.write(`${value} times 2 is:${value2}`);
    document.write(`<br>`);
    //by adding "value++" the user entered value will increment
    value++;
  }
} else if (value < 2 || value > 9) {
  for (i = 0;(value < 2 || value > 9); i++) {
    value = prompt("Enter Value between 2 or 9");

    if (value == 2 || value == 9) {
    //Loop B, I want the computation to go to loop A instead of me having to write
    //the computation of user value x 2
  //How can i accompolise this
      for (let i = 0; i < 10; i++) {
        value2 = value * 2;
        document.write(`${value} times 2 is:${value2}`);
        document.write(`<br>`);
        //by adding "value++" the user entered value will increment
        value++;
      }
      break;
    }
  }
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
 <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
</head>
<body>
 <script type="text/javascript" src="myscript_multi_validation.js"></script>
</body>
</html>


texts: Inserting using multiple contexts into LocalDB

texts:
I've written this ActionResult to model an Order that goes through. I couldn't think of another way to write this without using context Db<Sets>. It runs kinda slow, taking around 4 seconds to complete. Is there way to optimize the code or is this kinda has to happen since I'm doing so many inserts?

public ActionResult New(CustomerOrderModel model)
{
    ViewBag.LimitNotExceeded = checkLimit();
    if (ModelState.IsValid)
    {
        int prepaid;
        int userIdLoggedIn = WebSecurity.CurrentUserId;
        try
        {
            //
            //Add Customer
            using (var ctx = new CustomerContext())
            {
                ctx.CustomerInfos.Add(model.CustomerModel);
                ctx.SaveChanges();
            }

            //
            //Add Order
            model.OrderInfo.UserProfileUserID = userIdLoggedIn;
            model.OrderInfo.Customer_id = model.CustomerModel.id;
            model.OrderInfo.DateCreated = DateTime.Now.ToLocalTime();
            using (var ctx = new OrdersContext())
            {
                ctx.OrderInfos.Add(model.OrderInfo);
                ctx.SaveChanges();
            }

            //
            //Add Code
            key = "s121sd";
            KeyCode TheKey = new KeyCode();
            TheKey.code = key;
            TheKey.Customer_id = model.CustomerModel.id;
            TheKey.nif = model.CustomerModel.nif;
            TheKey.UserProfileUserId = userIdLoggedIn;
            TheKey.DateCreated = DateTime.Now.ToLocalTime();
            using (var ctx = new CodesContext())
            {
                ctx.CodesInfos.Add(TheKey);
                ctx.SaveChanges();
            }

            //
            //Assign and Create debts
            using (var ctx = new UsersContext())
            using (var dbx = new DebtsContext())
            {
                prepaid = ctx.UserProfiles.Find(userIdLoggedIn).Prepaid;
                if (prepaid > 0)
                {
                    --prepaid;
                    string query = "UPDATE dbo.UserProfile SET Prepaid='" + prepaid + "' WHERE UserId='" + userIdLoggedIn + "';";
                    ctx.Database.ExecuteSqlCommand(query);
                }
                else
                {
                    Debts NewDebt = new Debts();
                    NewDebt.paid = false;
                    NewDebt.DateCreated = DateTime.Now.ToLocalTime();
                    NewDebt.UserProfileUserId = userIdLoggedIn;
                    NewDebt.Order_id = model.OrderInfo.id;
                    dbx.DebtInfos.Add(NewDebt);
                    int debts = dbx.DebtInfos.Count(q => q.UserProfileUserId == userIdLoggedIn);
                    if (debts <= ctx.UserProfiles.Find(userIdLoggedIn).MaxDebt)
                    {
                        //
                        //Warn them when they reach their last
                    }
                    dbx.SaveChanges();
                    string query = "UPDATE dbo.UserProfile SET Prepaid='" + prepaid + "' WHERE UserId='" + userIdLoggedIn + "';";
                    ctx.Database.ExecuteSqlCommand(query);
                }
            }
            //DateTime a = DateTime.FromBinary(model.OrderInfo.Timestamp);
            return RedirectToAction("Index", "Home");
        }

        catch (DataException ex)
        {
            ViewBag.ChangeResult = ex;
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
        }
    }
    return View(model);
}


texts:
My program will fork, launching $n children. When a child finishes, the parent will launch a new one, if we have more to launch.

#!/usr/bin/perl

use strict;
use warnings;
use POSIX ":sys_wait_h";

#function, that every child will run
sub func
# {{{
{
      my $i = shift;
      my $delay = shift;

      print "$i started\n";
      sleep($delay);
      print "$i finished\n";
}
# }}}

#max number of concurrent children
my $max_n = 2;

#number of seconds each child will sleep
my @delays = (8, 5, 5);
my $n_elements = scalar(@delays);

#number of currently running children
my $n;
if ($n_elements > $max_n) {
      $n = $max_n;
}
else {
      $n = $n_elements;
}

#initial children creation
my $i;
for ($i = 0; $i < $n; $i++) {
      my $pid = fork();
      if ($pid == 0) {
            #child runs the function
            func($i, $delays[$i]);
            exit(0);
      }
}

#any children still running?
while ($n > 0) {
      #wait until one of them dies
      my $dead_child_pid = wait();
      print "$dead_child_pid done\n";

      #do we need to create new children?
      if ($i < $n_elements) {
            #create a child
            my $pid = fork();
            if ($pid == 0) {
                  func($i, $delays[$i]);
                  exit(0);
            }
            else {
                  #move pointer to the next element of @delays
                  ++$i;
            }
      }
      else {
            #decrease number of running children
            $n--;
      }
}

print "parent finished\n";

When I run it, it prints:

1 started
0 started

Here I check the processes:

bash-4.2$ ps -A | grep perl
 3433 pts/2    00:00:00 perl
 3434 pts/2    00:00:00 perl
 3435 pts/2    00:00:00 perl

So, it created 3 processes: 3433 - parent, 3434 and 3435 - children. Then:

1 finished
3435 done
2 started

Now again:

bash-4.2$ ps -A | grep perl
 3433 pts/2    00:00:00 perl
 3434 pts/2    00:00:00 perl
 3438 pts/2    00:00:00 perl

It launched the 3-rd child with pid 3438 after the death of the 2-nd.

0 finished
3434 done
2 finished
3438 done
parent finished

So, everything seems to be correct with the exception of the reversed launching order of children in the 1-st loop.

Maybe, it's possible to unite children creation from the both loops into a function. As their code has similar parts:

  my $pid = fork();
  if ($pid == 0) {
        #child runs the function
        func($i, $delays[$i]);
        exit(0);
  }

Do you see any more drawbacks in my code?


texts:
I am using this static method in my class IconManager to read an image from jar file. imagepath is a relative path to the image.

This code works perfect. But I was told it is error-prone, because does not handle Exceptions correctly.

private static BufferedImage readBufferedImage (String imagePath) {
    try {
        InputStream is = IconManager.class.getClassLoader().getResourceAsStream(imagePath);
        BufferedImage bimage = ImageIO.read(is);
        is.close();
        return bimage;
    } catch (Exception e) {
        return null;
    }
}

How would you refactor the code?


texts:
I use the following code which works OK, the code is filtering requests and in case there are too many requests it sends some logs/errors
since I'm very new to Java my question if there is a better way to write it especially the while statement ...

 public final class filterBu implements Filter {

        private static AtomicInteger reqcnt;
        private static final String MAX_CUNCCURENT = "maxConcurrent";
        private static final Logger logger = LoggerFactory.getLogger(ContentValidationFilter.class);
        private static final String EXCEED_MAX_REQUESTS_MSG = "maximum reaced";
        private static int maxCunnccurent;
        private static final int TOO_MANY_REQUESTS = 429;

        @Override
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
            while (true) {
                int value = reqcnt.get();
                if (value >= maxCunnccurent) {
                    ((HttpServletResponse) resp).sendError(TOO_MANY_REQUESTS, EXCEED_MAX_REQUESTS_MSG);
                    return;
                }
                if (reqcnt.compareAndSet(value, value + 1)) {
                    break;
                }
            }
            try {
                chain.doFilter(req, resp);
            } finally {
                reqcnt.decrementAndGet();
            }

        }

        @Override
        public void init(FilterConfig config) throws ServletException, NumberFormatException {
            maxCunnccurent = Integer.parseInt(config.getInitParameter(MAX_CUNCCURENT));
            if (maxCunnccurent < 1) {
                logger.error("excced limit");
            }
            reqcnt = new AtomicInteger(0);
        }

    }


texts: Determine all ways a string can be split into valid words, given a dictionary of all words

texts:
This function word_break(s, dictionary) receives a string s and a set of all valid words dictionary, and must return all possible ways the string s can be split into valid words, if any.

For example, a string catsanddog with dictionary {'cat', 'cats', 'sand', 'and', 'dog'} can be broken in two ways: cats and dog and cat sand dog.

My solution to this recursively breaks the input string at various index (offset), and uses memoization as I realized we may be breaking at the same offset multiple times.

Here is the full code along with a test case, in Python 2.x:

def memoize(fn):
    memo = {}
    def wrapped_fn(*args):
        if args not in memo:
            memo[args] = fn(*args)
        return memo[args]
    return wrapped_fn

def word_break(s, dictionary):
    @memoize
    def _word_break(offset):
        if offset == len(s):
            return []

        breaks_from_offset = []
        if s[offset:] in dictionary:
            breaks_from_offset.append([s[offset:]])

        for i in range(offset+1, len(s)):
            if s[offset:i] in dictionary:
                for break_from_i in _word_break(i):
                    breaks_from_offset.append([s[offset:i]] + break_from_i)

        return breaks_from_offset

    return [' '.join(words) for words in _word_break(0)]

# print word_break('catsanddog', {'cat', 'cats', 'sand', 'and', 'dog'})
# -> [cat sand dog', 'cats and dog']

Based on LeetCode question Word Break II: https://leetcode.com/problems/word-break-ii/description/

As this is an "interview" algorithm question, I would love feedback that keeps that setting in mind. That said, I also appreciate any feedback to help me write more production-ready Python code :)


texts: Processing form values for each day of week

texts:
I am using PHP, and I am getting the value back from the form. Since I am working with time, I have an array by (1 x 4) x 7, and I feel like I could do a better job at it. I just don't know exactly how should I approach the problem

$schedule = array(
    round(abs(strtotime($_POST['mon'][1]) - strtotime($_POST['mon'][0])) / 3600, 2),
    round(abs(strtotime($_POST['mon'][3]) - strtotime($_POST['mon'][2])) / 3600, 2),

    round(abs(strtotime($_POST['tue'][1]) - strtotime($_POST['tue'][0])) / 3600, 2),
    round(abs(strtotime($_POST['tue'][3]) - strtotime($_POST['tue'][2])) / 3600, 2),

    round(abs(strtotime($_POST['wed'][1]) - strtotime($_POST['wed'][0])) / 3600, 2),
    round(abs(strtotime($_POST['wed'][3]) - strtotime($_POST['wed'][2])) / 3600, 2),

    round(abs(strtotime($_POST['thu'][1]) - strtotime($_POST['thu'][0])) / 3600, 2),
    round(abs(strtotime($_POST['thu'][3]) - strtotime($_POST['thu'][2])) / 3600, 2),

    round(abs(strtotime($_POST['fri'][1]) - strtotime($_POST['fri'][0])) / 3600, 2),
    round(abs(strtotime($_POST['fri'][3]) - strtotime($_POST['fri'][2])) / 3600, 2),

    round(abs(strtotime($_POST['sat'][1]) - strtotime($_POST['sat'][0])) / 3600, 2),
    round(abs(strtotime($_POST['sat'][3]) - strtotime($_POST['sat'][2])) / 3600, 2),

    round(abs(strtotime($_POST['sun'][1]) - strtotime($_POST['sun'][0])) / 3600, 2),
    round(abs(strtotime($_POST['sun'][3]) - strtotime($_POST['sun'][2])) / 3600, 2),
);


texts:
I wanted to keep my controller tests DRY, readable, and make writing new tests very simple so that it encourages good practices like one assertion per test (if you have to redo a lot of work over and over, chances are you're just gonna shove more assertions into the same test to avoid the extra work).

Here's the strategy I'm using:

RSpec.describe FireController do
    let(:do_request) { post :create, request_body }
    let(:request_body) { {} }

    describe '#create' do
       context 'when we have firewood' do
           let(:request_body) { { firewood: true } }
           it 'creates fire' do
               do_request
               expect(response.body).to eql('fire!!!')
           end
       end
    end
end

I would like some opinions on potential downsides to a strategy like this.


texts: Handling multiple try-catches in a for loop

texts:
Good day! I would like to know if this is possible to be refactored into a cleaner code.
The reason I'm doing it like this is to catch the column that the error appeared on and then potentially output the column name and value for the client to view later on.
// Make the name act as the key and the value equates to ID
// $towers['tower1'] = 1;
$towers = Tower::pluck('id', 'name')->toArray();
$departments = Department::pluck('id', 'name')->toArray();

foreach($data as $key => $row) {
    try {
        // $row['tower'] = 'Hello World Tower'
        // Try to see if $row['tower'] is present in the $towers data source
        $data[$key]['tower'] = $towers[$row['tower']];
    } catch (\Exception $e) {
        // Exception occurs because index is not available
        $error_holder[$key]['tower_error'] = $e->getMessage();
    }

    // Same logic as above
    try {
        $data[$key]['department'] = $departments[$row['department']];
    } catch (\Exception $e) {
        $error_holder[$key]['department_error'] = $e->getMessage();
    }
}


texts:
I'm learning Scala and could use another set of eyes on the code below. I'm creating a test runner for the 99 scala problems set. I figure between actually solving the problems and working through the pains of setting up a new IDE (trying IntelliJ from Eclipse), using new build tools (trying SBT from Maven), new testing tools etc, I'll have the language down pat. The code below is a runner that grabs all the solution files in a given directory and executes them. While the code works, I can't help but feel as though I'm doing this in the 'Java' way and not the 'Scala' way (ie - I'm not being very 'functional' in my implementation). Does anyone who knows Scala pretty well have any comment on what I've written thus far?

runner:

import java.io.File
import org.apache.commons.io.FilenameUtils

/**
 * boodstraps program
 */
object bootStrap {

    def main(args: Array[String]): Unit = {

      // go through solution files and execute
      for (fName <- getSolutionFiles(new File("./src/main/scala"))) {
        val fNameNoExtS = FilenameUtils.removeExtension(fName.getName)
        solutionRunner(fNameNoExtS)
      }

    }

    def solutionRunner(name: String): Unit = {
      println(name)
      val classLoader = this.getClass.getClassLoader
      val clazz = classLoader.loadClass(name)
      val solutionMethod = clazz.getDeclaredMethod("solution")
      solutionMethod.invoke(clazz.newInstance)
    }

  /**
   * trolls through working directory and all sub directories in search of files
   * with names starting with "sp_" ('sp' for 'scala problem'). thanks to
   * stack overflow for base code: http://stackoverflow.com/questions/2637643/
   * how-do-i-list-all-files-in-a-subdirectory-in-scala
   *
   * @param f - java File object
   * @return targetFileList - Array[java.io.File] - list of file objects
   *         that have names starting with "sp_"
   */
    def getSolutionFiles(f: File): Array[File] = {
      // create lists of files, directories, and target files
      val fullFileList = f.listFiles
      val targetFileList = fullFileList.filter(_.getName.matches("^sp_.*"))
      val dirList = fullFileList.filter(_.isDirectory)

      // recursively append target files located in sub directories to list.
      // return populated list to caller.
      targetFileList ++ dirList.flatMap(getSolutionFiles)
    }

}

simple 'sp' file:

class sp_01 {

  def solution(): Unit = {
    println("in sp_01, baby!")
  }

}


texts:
I need code review for using ASP.NET Identity in a new app.

Goals:

Use int instead of GUID for IDs.
Separate identity from view layer

I need code review if I did everything right. Yes it is working but maybe I did something that I shouldn't or maybe there is some place for improvement.

ApplicationUser

public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole,
    CustomUserClaim>
    {
        public ICollection<ProductCategory> ProductCategories { get; set; }
        public ICollection<Store> Stores { get; set; }
        public ICollection<Product> Products { get; set; }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(
    UserManager<ApplicationUser, int> manager)
        {
            var userIdentity = await manager.CreateIdentityAsync(
                this, DefaultAuthenticationTypes.ApplicationCookie);
            return userIdentity;
        }
    }

    public class CustomUserRole : IdentityUserRole<int> { }
    public class CustomUserClaim : IdentityUserClaim<int> { }
    public class CustomUserLogin : IdentityUserLogin<int> { }

    public class CustomRole : IdentityRole<int, CustomUserRole>
    {
        public CustomRole() { }
        public CustomRole(string name) { Name = name; }
    }

    public class CustomUserStore : UserStore<ApplicationUser, CustomRole, int,
        CustomUserLogin, CustomUserRole, CustomUserClaim>
    {
        public CustomUserStore(ApplicationDbContext context)
            : base(context)
        {
        }
    }

    public class CustomRoleStore : RoleStore<CustomRole, int, CustomUserRole>
    {
        public CustomRoleStore(ApplicationDbContext context)
            : base(context)
        {
        }
    }

DbContext

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole,
    int, CustomUserLogin, CustomUserRole, CustomUserClaim>
    {
        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        public ApplicationDbContext()
            : base("DefaultConnection")
        {...

View models are still in view layer. All above is in data layer (class library).
In the view assembly in AccountController I changed all ApplicationUser to reference ApplicationUser in data layer assembly.

I also added extension to get UserID as int:

public static int GetUserIdInt(this IIdentity identity)
        {
            if (identity == null)
                throw new ArgumentNullException("identity");

            string stringUserId = identity.GetUserId();

            int userId;
            if (string.IsNullOrWhiteSpace(stringUserId) || !int.TryParse(stringUserId, out userId))
            {
                return default(int);
            }

            return userId;
        }


texts:
Write a function (in Haskell) which makes a list of strings
  representing all of the ways you can balance N pairs of parentheses:

  Example:

balancedParens 0
[""]
balancedParens 1
["()"]
balancedParens 2
["()()","(())"]
balancedParens 3
["()()()","(())()","()(())","(()())","((()))"]

My code produces the right answer but is very slow.

I would appreciate any help on how to speed it up (I have little Haskell experience, so the main struggle for me was implementing the proper algorithm).

module Balanced.Parens where

import Data.List
import Data.List.Split

mutateBP :: String -> [String]
mutateBP "()" = ["(())", "()()"]
mutateBP  xs  = [xs ++ "()", "()" ++ xs, "(" ++ xs ++ ")"]

continuousSubSeqs :: String -> [String]
continuousSubSeqs = filter (not . null) . concatMap inits . tails

indicesOfSubStr :: String -> String -> [Int]
indicesOfSubStr []  _   = []
indicesOfSubStr sub str = filter (\i -> sub `isPrefixOf` drop i str) $ head sub `elemIndices` str

splitBP :: String -> String -> [[String]]
splitBP s xs = chunksOf 2 (concat (map (\i -> [take (i + 1) xs, drop (i + 1) xs]) (indicesOfSubStr s xs)))

get1st :: (a,b,c) -> a
get1st (a,_,_) = a

get2st :: (a,b,c) -> b
get2st (_,b,_) = b

get3st :: (a,b,c) -> c
get3st (_,_,c) = c

zipWithNums' :: String -> [(Char, Int, Int)]
zipWithNums' xs = zip3 xs (parensNum xs) [0..]

findMatch "" = (0, "", "", 0)
findMatch xs = (length xs, group, tail', matchIdx)
  where zipWithNums = zip3 xs (parensNum xs) [0..]
        matchNum = 1 + (get2st $ head zipWithNums)
        matchPar = if '(' == (get1st . head) zipWithNums then ')' else '('
        matchAndTail = dropWhile (\x -> (get1st x /= matchPar) || (get2st x /= matchNum) ) (tail zipWithNums)
        matchIdx = if 0 == length matchAndTail then 0 else (get3st $ head matchAndTail) + 1
        group = take matchIdx xs
        tail' = drop matchIdx xs

groups xs = nub $ filter (\x -> (length $ get2st x) /= 0) [(take (xs_l - l) xs, g, t) | (l, g, t, idx) <- map findMatch (tails xs)]
  where xs_l = length xs

parensNum :: String -> [Int]
parensNum xs = scanl (\acc x -> if '(' == x then acc + 1 else acc - 1) 1 xs

isValidBP :: String -> Bool
isValidBP "" = True
isValidBP xs = (length valid_parens_num) - 1 == length xs
  where parens_num = parensNum xs
        valid_parens_num = takeWhile (>0) parens_num

balancedParens :: Int -> [String]
balancedParens 0 = [""]
balancedParens 1 = ["()"]
balancedParens n = nub $ concat $ map (\x -> [p ++ z ++ s| p <- [get1st x], z <- mutateBP $ get2st x, s <- [get3st x]]) gr
  where gr = concat $ map groups (balancedParens (n - 1))


texts: Performance of a method to mask all but one rectangular element on the page

texts:
The point of this code is to mask a page where the user is editing the page's 'body' content. This is in a CMS. The rest of the page is the website template (i.e. header, index bar etc...). I've covered resizing the window, and the DIV itself growing larger.

I'd love to know if there is a more efficient way to do this. I've used a DIV position: fixed as a mask under the editable DIV but some of our templates have irregular background colours (or images) and I really want to have a transparent editing area so that the experience is as close as possible to the end result.

If it's not apparent, this code creates a DIV whose borders cover the space that the editable DIV does not take up on the document. As the page resizes or the editable DIV changes size, these borders need to change size.

NOTE: The outer container may have overflow: hidden applied (thus the need to append the mask to the body element). The intention of the mask is to prevent clicking on any other area of the page other than the area that is being edited.

var content_builder_element = $("#content_builder");

var mask = $('

');

buildMask(content_builder_element, mask, false);

$('body').append(mask);

$(window).resize(function() {
    buildMask(content_builder_element, mask, true);
});

window.setInterval(function() {
    buildMask(content_builder_element, mask, true);
}, 100);

function buildMask(reference, mask, resize) {
    var offset = reference.offset();
    var height = reference.outerHeight(true);
    var width = reference.outerWidth(true);

    // We don't want the width of the masks to mess with the document width
    if (resize) {
        mask.css('borderRightWidth', 0);
        mask.css('borderBottomWidth', 0);
    }

    var document_width = $(document).width();
    var document_height = $(document).height();

    mask.width(width);
    mask.height(height);

    mask.css('borderTopWidth', offset.top);
    mask.css('borderRightWidth', document_width - offset.left - width);
    mask.css('borderBottomWidth', document_height - offset.top - height);
    mask.css('borderLeftWidth', offset.left);
};
body {
  background-color: orange;
}

.content_builder_mask {
  border: 0px solid rgba(0, 0, 0, 0.6);
  position: absolute;
  top: 0;
  left: 0;
}

#somecontainer {
  margin: 50px;
  overflow: hidden;
  }

#content_builder {
  min-height: 200px;
  position: relative;
  z-index: 500;
}
<!DOCTYPE html>


texts: Project Euler #8: max product of 13 consecutive digits in a sequence


texts:
I have a class library in which I'm using generics as below. I'm not sure if it's an improper use or not. So aside from the fact that it works and everything "depends", id like some specific critique on how this usage might fall apart. In particular In wondering about the shadowing of non generic properties with generic counterparts. Is this an accepted practice?

 public interface IPickOrder
    {
        IPickOrderHeader Header { get; }

        ERPListBase<IPickOrderLine> Lines { get; }
    }

 public interface IPickOrder<TPickOrderHeader, TPickOrderLine> : IPickOrder
        where TPickOrderHeader : class, IPickOrderHeader
        where TPickOrderLine : class, IPickOrderLine
    {
        new TPickOrderHeader Header { get; }

       new ERPListBase<TPickOrderLine> Lines { get; }
    }

 public class PickOrder : IPickOrder
    {
        public IPickOrderHeader Header { get; protected set; }

        public ERPListBase<IPickOrderLine> Lines { get; protected set; }

        public PickOrder() { }
    }

   public class PickOrder<TPickOrderHeader, TPickOrderLine> : PickOrder, IPickOrder<TPickOrderHeader, TPickOrderLine>
        where TPickOrderHeader : class, IPickOrderHeader, new()
        where TPickOrderLine : class, IPickOrderLine, new()
    {
        public new TPickOrderHeader Header
        {
            get { return base.Header as TPickOrderHeader; }
            protected set { base.Header = value; }
        }

        public new ERPListBase<TPickOrderLine> Lines { get; protected set; }

        /// <summary>
        ///
        /// </summary>
        public PickOrder() : base() { }
    }


texts: Plugin that grabs the coordinates of all the cities in our database

texts:
I have a plugin that grabs the coordinates of all the cities in our database working in WordPress here.

function findCoordinates($address) {
$latitude  = null;
$longitude = null;
if (!is_string($address)) {
    throw new InvalidArgumentException("Address must be a string");
}

$url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . str_replace(' ', '+', $address);

$response = json_decode(@file_get_contents($url));
if (isset($response)) {
    $result    = $response->results[0];
    $latitude  = $result->geometry->location->lat;
    $longitude = $result->geometry->location->lng;
}

return array($latitude, $longitude);

}
function Coordinates_admin() {

$SQL = "SELECT a.*, b.name as state,b.code as state_code, c.name as country, c.iso_code as country_code From city a
JOIN state b on a.IDState = b.IDState
Join country c on b.IDCountry = c.IDCountry";

$retval = mysql_query($SQL);
if (!$retval) {
    die('Could not get data: ' . mysql_error());
}
while ($row = mysql_fetch_array($retval)) {

    $address = $row["name"] . "," . $row["state"] . "," . $row["state_code"] . "," . $row["country"] . "," . $row["country_code"];
    list($latitude, $longitude) = findCoordinates($address);
?>

Now I'm working on another plugin that adds new cities to the database, and I want it to get the lat and long automatically. I successfully did this but I was told I'm just retyping code instead of using reusable code. I went through examples and tutorials and still don understand what I am doing wrong (but it works). I am very confused on this and looking for some help on how I can make this code shorter using reusable code from my previous plugin functions.

//add city
if(isset($_POST['Add_City'])){
//adds IDState, name and unactive for new city.
$idstate = $_POST ['idstate'];
$name = $_POST ['name'];

$SQL="INSERT INTO city (IDState, name, is_active) VALUES ('". $idstate ."','". $name ."', ' 0 ' )";
$result=mysql_query($SQL) or die(mysql_error());

//grabs new city id.
$cityid = mysql_insert_id();

//puts together address for that specific city.
$SQL2 = "SELECT a.*, b.name as state,b.code as state_code, c.name as country, c.iso_code as country_code From city a
JOIN state b on a.IDState = b.IDState
Join country c on b.IDCountry = c.IDCountry WHERE IDCity= $cityid";
$retval = mysql_query($SQL2);

if (!$retval) {
    die('Could not get data: ' . mysql_error());
}
while ($row = mysql_fetch_array($retval)) {
    $address = $row["name"] . "," . $row["state"] . "," . $row["state_code"] . "," . $row["country"] . "," . $row["country_code"];
    list($latitude, $longitude) = findCoordinates($address);
    $SQL3="UPDATE city SET latitude=$latitude, longitude=$longitude WHERE IDCITY= $cityid";
    $result1=mysql_query($SQL3) or die(mysql_error());
}
}


texts:
This playbook aims to verify if a specific file exists in a specific directory and, if not, to create it.
Neither the file nor the directory may exist before the verification.
After the process is finished, I would like to have a statement that ell me that the file exists.
See what I came up with and please give me feedback for clearer and smooth code.
I defined the host and the roles in the tree, so I am referring only to the tasks.

- name: Checking if processed_sms directory exists if it doesn't create it.
  file
    path: "/home/pi/sms_service/processed_sms"
    state: directory

- name: Checking if place_holder.txt exists if it doesn't create it.
  file:
    path: "/home/pi/processed_sms/place_holder.txt"
    state: touch
  register: is_place_holder_exists

- name: printing message if place_holder.txt file exists
  debug:
    msg: "place_holder.txt file exists"
  when: is_place_holder_exists.dest == "/home/pi/sms_service/processed_sms/place_holder.txt"

```


texts:
Here is qsort implementation using iterators as it is in std::sort

// iterator check
template <typename It, typename T>
constexpr bool is = std::is_same<std::iterator_traits<It>::iterator_category, T>::value;

// quick sort
template <typename BidIt, typename Pred>
void qsort(BidIt first, BidIt last, Pred compare) noexcept
{
    static_assert(is<BidIt, std::bidirectional_iterator_tag> || is<BidIt, std::random_access_iterator_tag>,
        "bidirectional iterator required");

    auto size = std::distance(first, last);

    if (size > 1) {
        using content_type = std::iterator_traits<BidIt>::value_type;

        content_type pivot = *first;
        std::vector<content_type> left(size), right(size);
        auto left_end = left.begin();
        auto right_end = right.begin();

        for (BidIt i = std::next(first); i != last; ++i) {
            compare(*i, pivot) ? *left_end++ = *i : *right_end++ = *i;
        }

        qsort(left.begin(), left_end, compare);
        qsort(right.begin(), right_end, compare);

        std::copy(left.begin(), left_end, first);
        *std::next(first, std::distance(left.begin(), left_end)) = pivot;
        std::copy(right.begin(), right_end, std::next(first, std::distance(left.begin(), left_end) + 1));
    }
}

Your thoughts?


texts: Random tone generator using Web Audio API

texts:
This is a random frequency audio generator made with the Web Audio API by Mozilla. The end-goal is an audio frequency trainer: the website plays an audio frequency and the user tries to guess which frequency it is. The frequencies will be limited to those found on 31 band graphical equalisers, and I'll include multiple difficulties.

This is my first step: the generator for the 'easy' difficulty (4 frequencies).

// create web audio api context
var audioCtx = new AudioContext();

// create oscillator (tone) and gain (volume) node
var tone = audioCtx.createOscillator();
var volume = audioCtx.createGain();

// create array of frequency values
var frequencies = ["100", "400", "1600", "6300"];
// pick a random frequency
var frequency = frequencies[Math.floor(Math.random() * frequencies.length)];

// set oscillator type (sine, square, sawtooth or triangle)
tone.type = 'sine';
// set oscillator frequency in Hz
tone.frequency.value = frequency;
// set gain volume (above 1 will clip)
volume.gain.value = 0.5;

// set tone destination to go through volume
tone.connect(volume);
// set volume destination to output
volume.connect(audioCtx.destination);

// start oscillator x seconds after timestamp
tone.start(1);
// stop oscillator x seconds after timestamp
tone.stop(4);

Don't mind the excessive commentation, I've only just started using JavaScript and don't trust myself to remember what every line of code does after a few days.


texts:
I'm practicing writing code less by brute force. I'd like feedback for writing a prime sieve more Pythonic, simpler, or more creatively perhaps.

def prime_sieve(limit):
    numbers = dict()
    limit = int(limit)
    for n in range(2, limit + 1):
        numbers[n] = ()
    primes = numbers.copy()
    for n in numbers:
        m = n
        while m <= limit:
            m = m + n
            primes.pop(m, 0)
    return primes


texts: Fast Thread- and multiprocess-safe file operations in python under Linux

texts:
I'm trying to implement an alternative to python built-in open(), but safe for use in multi-threaded and multiprocessing environment. I'm using advisory locking, because all file operations in my application are performed using my locked_open() function and no other process is accessing that data.

It is only required to run on modern linux distributions, no compatibility with Windows or OS X is required. Also it have to be fast, because I'm going to use it for caching operations.

The code and the tests:

from contextlib import contextmanager
import os, fcntl
import unittest
from testfixtures import TempDirectory

M_READ, M_WRITE, M_READWRITE = range(3)
MODES = (
    # open for reading
    (os.O_RDONLY, fcntl.LOCK_SH, 'rb'),
    # create for writing
    (os.O_WRONLY | os.O_CREAT | os.O_TRUNC, fcntl.LOCK_EX, 'wb'),
    # open for reading and writing
    (os.O_RDWR | os.O_CREAT, fcntl.LOCK_EX, 'r+b')
)
BLOCKING_FLAGS = (fcntl.LOCK_NB, 0)

@contextmanager
def locked_open(filename, mode=M_READ, blocking=True):
    open_mode, flock_flags, mode_str = MODES[mode]
    flock_flags = flock_flags | BLOCKING_FLAGS[blocking]

    fd = os.open(filename, open_mode)
    fcntl.flock(fd, flock_flags)
    fileobj = os.fdopen(fd, mode_str)

    yield fileobj

    fileobj.flush()
    os.fdatasync(fd)
    fcntl.flock(fd, fcntl.LOCK_UN)
    fileobj.close()

class LockedOpenTestCase(unittest.TestCase):
    filename = 'testfile.txt'
    test_data = b'random text'

    def setUp(self):
        self.tempdir = TempDirectory()
        self.filepath = os.path.join(self.tempdir.path, self.filename)

    def tearDown(self):
        self.tempdir.cleanup()

    def test_write(self):
        with locked_open(self.filepath, M_WRITE) as f:
            f.write(self.test_data)
        self.assertEqual(self.test_data, self.tempdir.read(self.filename))

    def test_read(self):
        self.tempdir.write(self.filename, self.test_data)
        with locked_open(self.filepath, M_READWRITE) as f:
            self.assertEqual(self.test_data, f.read())

    def test_read_and_write(self):
        self.tempdir.write(self.filename, self.test_data)
        with locked_open(self.filepath, M_READWRITE) as f:
            data = f.read().swapcase()
            f.seek(0)
            f.write(data)

        self.assertEqual(
            self.test_data.swapcase(),
            self.tempdir.read(self.filename))

    def test_concurrent_read(self):
        self.tempdir.write(self.filename, self.test_data)
        with locked_open(self.filepath, M_READ) as f1:
            with locked_open(self.filepath, M_READ) as f2:
                self.assertEqual(self.test_data, f1.read())
                self.assertEqual(self.test_data, f2.read())

    def test_non_blocking_read_during_write_raises(self):
        with locked_open(self.filepath, M_WRITE):
            with self.assertRaises(IOError):
                with locked_open(self.filepath, M_READ, blocking=False):
                    pass

    def test_non_blocking_write_during_read_raises(self):
        self.tempdir.write(self.filename, self.test_data)
        with locked_open(self.filepath, M_READ):
            with self.assertRaises(IOError):
                with locked_open(self.filepath, M_WRITE, blocking=False):
                    pass

The code seems to be correct, and all tests are passing, but I get the feeling that I'm reinventing the wheel here.

Now the questions:

Are there any issues with the code that I should be aware of? (besides from what I already said)
Are my tests sufficient?
Any suggestions regarding performance?
Are there any easier ways to achieve same result?


texts:
Would you please run through this code and provide your comments?

void quote_container::allocate(string *i_string, string *i_value){
    string temp_name = *i_string;
    double temp_value;

    // Convert the input string to upper case.
    stringToUpper(temp_name);

    if (temp_name =="OPEN"){
        temp_value = atof( (*i_value).c_str() );
        open = (float)temp_value;
    }
    else if (temp_name =="DAYHIGH") {
        temp_value = atof( (*i_value).c_str() );
        high  = (float)temp_value;
    }
    else if (temp_name =="DAYLOW") {
        temp_value = atof( (*i_value).c_str() );
        low  = (float)temp_value;
    }
    else if (temp_name =="LOW52") {
        temp_value = atof( (*i_value).c_str() );
        year_low  = (float)temp_value;
    }
    else if (temp_name =="HIGH52") {
        temp_value = atof( (*i_value).c_str() );
        year_high  = (float)temp_value;
    }
    else if (temp_name =="PRICEBANDLOWER") {
        temp_value = atof( (*i_value).c_str() );
        lower_price_band  = (float)temp_value;
    }
    else if (temp_name =="PRICEBANDUPPER") {
        temp_value = atof( (*i_value).c_str() );
        upper_price_band  = (float)temp_value;
    }
    else if (temp_name =="TOTALBUYQUANTITY"){
        temp_value = atof( (*i_value).c_str() );
        tbq  = temp_value;
    }
    else if (temp_name =="TOTALSELLQUANTITY") {
        temp_value = atof( (*i_value).c_str() );
        tsq  = temp_value;
    }
    else if (temp_name == "BUYQUANTITY5" || temp_name == "BUYQUANTITY4" || temp_name == "BUYQUANTITY3"||
        temp_name == "BUYQUANTITY2"|| temp_name == "BUYQUANTITY1") {
        temp_value = atof( (*i_value).c_str() );
        tbq2  = tbq2 + temp_value;
    }
    else if (temp_name == "SELLQUANTITY5" || temp_name == "SELLQUANTITY4" || temp_name == "SELLQUANTITY3"||
        temp_name == "SELLQUANTITY2" || temp_name == "SELLQUANTITY1")  {
            temp_value = atof( (*i_value).c_str() );
        tsq2  = (float)tsq2 + temp_value;
    }
    else if (temp_name == "BUYPRICE1" || temp_name == "BUYPRICE2" || temp_name == "BUYPRICE3"||
        temp_name == "BUYPRICE4" || temp_name == "BUYPRICE5") {
            temp_value = atof( (*i_value).c_str() );
        avg_buy_price  = avg_buy_price + (float)temp_value ;
    }
    else if (temp_name == "SELLPRICE5" || temp_name == "SELLPRICE4" || temp_name == "SELLPRICE3"||
        temp_name == "SELLPRICE2" || temp_name == "SELLPRICE1") {
            temp_value = atof( (*i_value).c_str() );
        avg_sell_price  =  tsq2 + (float)temp_value;
    }
    else if (temp_name == "FACEVALUE") {
        temp_value = atof( (*i_value).c_str() );
        face_value = (float)temp_value;
    }
    else if (temp_name == "PREVIOUSCLOSE") {
        temp_value = atof( (*i_value).c_str() );
        prev_close = (float)temp_value;
    }
    else if (temp_name == "LASTPRICE") {
        temp_value = atof( (*i_value).c_str() );
        last_price = (float)temp_value;
    }
    else if (temp_name == "TOTALTRADEDVOLUME") {
        temp_value = atof( (*i_value).c_str() );
        ttv = (float)temp_value;
    }
    else
        cout <<"\n\t Ignoring --"<<temp_name<<"---"<<*i_value;

}

Also

void quote_container::stringToUpper(string &s)
{
   for(unsigned int l = 0; l < s.length(); l++)
    s[l] = toupper(s[l]);
}

Could the above code be improved in any way?


texts:
I have done this code. But I am not sure that I have got the exact answer. I have never solved this kind of problem earlier.
General form of a $2n+1$ degree Hermite polynomial:
$$p_{2n+1} = \sum_{k=0}^{n} \left(f(x_k)h_k(x) + f'(x_k)\hat{h}_k(x)\right) \tag{1}$$
$$h_k(x) = (1-2(x-x_k)l^\prime_k(x_k))l^2_k(x_k) \tag{2}$$
and,
$$\hat{h}_k(x) = (x-x_k)l^2_k(x_k) \tag{3}$$
where the Lagrange basis function being,
$$l_k(x) = \prod_{j=0, j\neq k}^{n} \frac{x-x_j}{x_k-x_j} \tag{4}$$

import numpy as np
import matplotlib.pyplot as plt
from itertools import combinations
from numpy.polynomial import Polynomial

def l(k, x):
    n = len(x)
    assert (k < len(x))
    x_k = x[k]
    x_copy = np.delete(x, k)
    denominator = np.prod(x_copy - x_k)
    coeff = []
    for i in range(n):
        coeff.append(sum([np.prod(x) for x in combinations(x_copy, i)]) * (-1) ** (i) / denominator)
    coeff.reverse()
    return Polynomial(coeff)

def h(k, x):
    # initialize with none
    l_k=None
    l_k_sqr=None
    l_k_prime = None
    coeff = None
    p = None
    coeff=x[k]
    l_k = l(k,x)
    l_k_sqr = Polynomial.__pow__(l_k,2)#l_k**2
    l_k_prime=Polynomial.deriv(l_k,1)
    p=(1-(2*x*l_k_prime)+(2*coeff*l_k_prime))*coeff
    return p * l_k_sqr

def h_hat(k, x):
    l_k = l(k,x)
    l_k_sqr = Polynomial.__pow__(l_k,2)
    coeff = None
    p = None
    coeff=x[k]
    # place your code here!!!!!!!!!!!!!!!!!!!!!!!
    p=(x-coeff)*coeff
    return p * l_k_sqr

def hermit(x, y, y_prime):
    assert (len(x) == len(y))
    assert (len(y) == len(y_prime))

    f = Polynomial([0.0])
    for i in range(len(x)):
        f += (y[i]*h(i,x))+(y_prime[i]*h_hat(i,x))
          # pass statement does nothing
        # place your code here!!!!!!!!!!!!!!!!!!!!!!!
    return f
pi = np.pi
x       = np.array([0.0, pi/2.0,  pi, 3.0*pi/2.0])
y       = np.array([0.0,    1.0, 0.0,       -1.0])
y_prime = np.array([1.0,    0.0, 1.0,        0.0])
n = 1
f3     = hermit(x[:(n+1)], y[:(n+1)], y_prime[:(n+1)])
data   = f3.linspace(n=50, domain=[-3, 3])
test_x = np.linspace(-3, 3, 50, endpoint=True)
test_y = np.sin(test_x)

plt.plot(data[0], data[1])
plt.plot(test_x, test_y)
plt.show()


texts: Conditional Concatenation of a Pandas DataFrame

texts:
I am concatenating columns of a Python Pandas Dataframe and want to improve the speed of my code.

My data has the following structure:

    Apple    Pear    Cherry
    1        2       3
    4        5       NaN
    7        8       9

I only want to concatenate the contents of the Cherry column if there is actually value in the respective row. If my code works correctly, the result of the example above should be:

    Result
    1 :: 2 :: 3
    4 :: 5
    7 :: 8 :: 9

My code so far is this:

a_dataframe[result] = a_dataframe.apply(lambda r:
          str(r.loc['apple']) + ' :: ' + str(r.loc['pear'])+' :: '+str(r.loc['cherry'])
          if pd.notnull(r.loc['cherry']) & (r.loc['cherry'] != "")
          # if cherry value is empty, do not add cherry into result
          else str(r.loc['apple']) + ' :: ' + str(r.loc['pear']),
          axis=1)

Any thoughts on how I can improve the speed of my code? Can I run this without an apply statement using only Pandas column operations?

Thanks up front for the help.


texts: String permutation iterative improvements?

texts:
I have written some code (below) which iterates over each character of a string and adds that character to every index of previous permutations.

For example, in case of abc: b is added to every index of perm(a) resulting in ab, ba.

Now c is added to every index of perm(c) resulting in cab, abc, acb, cba, bac, bca.

I use a Set, to avoid duplicates.

Please review code and how it could be improved while keeping it iterative. I am particularly looking for improvements to my existing code, rather than alternative solutions(if possible), so that I can better understand the optimization process.

There may be a faster recursive solution, but I'm currently looking to improve my iterative approach.

  //method called from main
Set<String> perm(String input)
{
    Set<String> perm = new HashSet<String>();
    if(input == null || input.length() == 0 || input.length() == 1)
    {
        perm.add(input);
        return perm;
    }
 //convert to char array for iteration
    char[] arr = input.toCharArray();
 //add first char as first perm
    perm.add(String.valueOf(arr[0]));

    //iterate arr and find perm for each char
    for(int i=1; i<arr.length; i++)
    {
        perm = findPerm(String.valueOf(arr[i]), perm);
    }
    System.out.println(perm.size());
    return perm;
}

private Set<String> findPerm(String next, Set<String> perm)
{
    Set<String> perms = new HashSet<String>(perm);
 //iterate each perm to add next char            at all indexes
    for(String each : perm)
    {
        perms.addAll(addAtEachIndex(each, next));
   //remove the older perms
   //for example in case of ABC,  ab and ba should be deleted after making cab abc acb cba bca and bac
        perms.remove(each);
    }
    return perms;
}

private Set<String> addAtEachIndex(String each, String next)
{
    //ab c
    //^a^b^
    //0,0+c+0,1  0,1+c+1,1  0,1+c
//add the next char to each index of current perm
    Set<String> finalPerms = new HashSet<String>();
    finalPerms.add(each+next);
    finalPerms.add(next+each);
    for(int i=0; i<each.length(); i++)
    {
        finalPerms.add(each.substring(0,i+1) + next +each.substring(i+1, each.length()));
    }
    return finalPerms;
}


texts:
I have made a procedure to display the highest and the lowest popular Items for a particular time of a given date. The procedure works with no errors or exceptions and everything is functional. As you can see, the queries are repeated twice for the purpose of showing the first record on Items, but the only differences are in Order (ASC and DESC).

Is there any way I can reduce the amount of the code? How can I show the highest and lowest Items in one query rather than two? I only want to make the code neat and easy to read.

      create or replace procedure hight_lowest (param in date)
    as
    V_PNO_LOW   number(5);
    V_PNO_HIGH  number(5);
    BEGIN
    SELECT Item_no INTO V_PNO_LOW
    FROM
    (SELECT Items.Item_no SUM(Items.Quantity) AS total,
   TO_CHAR(Prodcution_d,
   'dd-mm-yyyy') AS pro_date
   FROM Items
   JOIN Parts
   ON Parts.Serial_no = Items.Serial_no
   GROUP BY Item_no, TO_CHAR(Prodcution_d, 'dd-mm-yyyy')
   ORDER BY SUM(Items.Quantity) ASC)
   WHERE ROWNUM = 1
   AND pro_date = TO_CHAR(Param_DATE,'mm-yyyy') ;

   DBMS_OUTPUT.PUT_LINE('LOWEST ITEM: ' || V_PNO_LOW);

  SELECT Item_no INTO V_PNO_LOW
  FROM
  (SELECT Items.Item_no SUM(Items.Quantity) AS total, TO_CHAR(Prodcution_d,
  'dd-mm-yyyy') AS pro_date
  FROM Items
  JOIN Parts
  ON Parts.Serial_no = Items.Serial_no
  GROUP BY Item_no, TO_CHAR(Prodcution_d, 'dd-mm-yyyy')
  ORDER BY SUM(Items.Quantity) DESC)
  WHERE ROWNUM = 1
  AND pro_date = TO_CHAR(Param_DATE,'mm-yyyy') ;

 DBMS_OUTPUT.PUT_LINE('HIGHEST POPULAR ITEM: ' || V_PNO_HIGH);

 END;
  /


texts: Processing an image to extract green-screen mask

texts:
I am using OpenCV to process an image, and in my code, I have to check / edit each pixel separately:

import cv2, numpy

# we just use an empty image for the purpose of this MCVE
img = cv2.imread("source.jpg")
width = len(img[0])
height = len(img)

empty_img = numpy.zeros((height, width, 3), numpy.uint8)

i = 0
r = 0
c = 0

for line in img:
    c = 0

    for pixel in line:
        blue = pixel[0]
        green = pixel[1]
        red = pixel[2]

        if green != max(red, green, blue) or green < 35:
            # this has a greenishy hue
            empty_img.itemset((r, c, 0), 255)

        c += 1
    r += 1

This code works, but is quite slow (it takes about 23 seconds to process the image). How could/should I speed this up?

source.jpg:

result should be:


texts:
I was wondering if any of you know any best practices or design patterns so that I can have good logging in my programs without them looking messy or bloated.

I am currently using C# and NLog, however I guess any advice here would be language and tool agnostic.

The problem we have is that we want to have good logging, however we can't seem to find a way around having many lines which just log operations, which can turn a simple method like this:

void Foo()
{
    Bar bar = dbContext().Bars.First();
    bool someCondition = bar.DoSomething();
    if (someContition)
    {
        dbContext().FooBars.Add(new FooBar());
    }
}

Into something which looks like this:

void Foo()
{
    _logger.Info("Getting first bar from database...");

    Bar bar = dbContext().Bars.First();

    _logger.Info("First bar returned from database, id = {0}", bar.Id);

    _logger.Info("Doing something on bar with id = {0}", bar.Id);
    bool someCondition = bar.DoSomething();

    _logger.Info("Something done on bar with id = {0}, response = {1}", bar.Id, someCondition);

    if (someContition)
    {
        _logger.Warn("Adding new FooBar to database");
        dbContext().FooBars.Add(new FooBar());
        _logger.Warn("Added new FooBar to database successfully");
    }
}

Here we now have more logging lines than code lines.

However I am being told by operations that this level of logging is required, and at the moment is still too coarse.

Is there any way around this ugly manual logging, or am I stuck with it?


texts: Project Euler no. 17: Counting letters to write the numbers from 1 to 1000

texts:
I'm very new to programming and am admittedly embarrassed sharing my code for critique. This code works and produces the correct answer to the Project Euler Problem 17, which asks how many letters there are when the numbers from one to one thousand are written out in words (excluding spaces and punctuation).

I was hoping I could get some critique on how to make it less ugly and more streamlined, or even approach the problem from a totally new angle so I can better learn from this solution.

# the final list that holds the string lengths
addList = []

# dictionary holding integer:corresponding word pairs
numbersDict = {
0:"zero",
1:"one",
2:"two",
3:"three",
4:"four",
5:"five",
6:"six",
7:"seven",
8:"eight",
9:"nine",
10:"ten",
11:"eleven",
12:"twelve",
13:"thirteen",
14:"fourteen",
15:"fifteen",
16:"sixteen",
17:"seventeen",
18:"eighteen",
19:"nineteen",
20:"twenty",
30:"thirty",
40:"forty",
50:"fifty",
60:"sixty",
70:"seventy",
80:"eighty",
90:"ninety"
}

### There has to be an easier way to do all this below ###

def numberLetters(num):

    letters = ""

    if 0 < num <= 20:
        letters += numbersDict[num]

    if 21 <= num <= 99:
        a,b = divmod(num, 10)
        if b == 0:
            letters += numbersDict[a*10]
        else:
            letters += numbersDict[a*10] + numbersDict[b]

    if 100 <= num <= 999:
        if num % 100 == 0:
            letters += numbersDict[int(num / 100)] + "hundred"
        else:
            digit = int(num / 100)
            num = num - digit * 100
            if 0 < num <= 20:
                letters += numbersDict[digit] + "hundredand" + numbersDict[num]
            if 21 <= num <= 99:
                a,b = divmod(num, 10)
                if b == 0:
                    letters += numbersDict[digit] + "hundredand" + numbersDict[a*10]
                else:
                    letters += numbersDict[digit] + "hundredand" + numbersDict[a*10] + numbersDict[b]
    if num == 1000:
        letters += "onethousand"

    return letters

for i in range(1,1001):
    addList.append(len(numberLetters(i)))
print(sum(addList))


texts:
The class I'm using is called Review and looks like this:

public class Review
{
    public virtual Guid Id { get; set; }

    public virtual int Rating { get; set; }

    public virtual Guid RestaurantId { get; set; }

    public virtual Guid UserId { get; set; }
}

I'm using a LINQ statement to first check a few things and afterwards group by a user's reviews. I'll explain what I mean with this:

var reviewsByUsers =
    reviews
    .GroupBy(x => x.RestaurantId)
    .Where(x => x.Count() >= 3)
    .SelectMany(x => x.ToList())
    .Distinct()
    .GroupBy(x => x.UserId)
    .Where(x => x.Count() >= 2)
    .Select(x => x.ToList())
    .ToList();

And now step by step:

1. reviews is a list of all reviews given on a bunch of restaurants. This is not the database, it's a list I receive as a parameter of the method.

2. .GroupBy(x => x.RestaurantId) Group these reviews per each restaurant. This is for counting them later.

3. .Where(x => x.Count() >= 3) Exclude any restaurants which don't have 3 or more reviews on them.

4. .SelectMany(x => x.ToList()) Flatten the list so we can group again.

5. .Distinct() To be sure that I'm not getting doubles.

6. .GroupBy(x => x.UserId) Group the reviews per user. This is for counting them later.

7. .Where(x => x.Count() >= 2) Exclude any user which has less than 2 reviews.

8. .Select(x => x.ToList()) I don't need anything else per user, a list of reviews per user is enough.

All of this will result in a List<List<Review>> which is a list that contains a list of all reviews grouped by the UserId.

I'm certain there has to be a better way to perform these checks and create a list of lists grouped by user id. I'm just very new to C#, so I don't know how to increase this LINQ statement.