There are three ways I know of to deal with large container classes:

large constructors
post-constructor modifiers
sub-categories

None of them are 'nice'.

Large Constructor

Your code is an example of the large constructor.

Post Construction

The post-constructor modifier system will have a bunch of 'set' methods, and you call them like:

 myFile.setSize(...);
 myFile.setMD5(...);

Sub-Categories

The sub-cateogory option is not awful, it is done by grouping related parameters together. For example, the two times could be one class:

class FileTimes():
    def __init__(self, created, modified):
        self.created = created
        self.modified = modified

then the file locations could be grouped as well

class FileLocation():
    def __init__(self, path, public_url=None):
        self.public_url = public_url
        self.path = path

FileGroup would be, perhaps, the various 'types', like type, media_type, mime_type.

Once you have sub-categorized your parameters, the constructor becomes simpler, like:

def __init__(self, name, locations, times, types, md5, size, public_key=None, preview=None):

But, though you have simplified this class's constructor, you now have to build up a hierarchy of data to initialize it.... which is not simple.

Recommendation

As for me, given the nature of your JSON data, it appears that the large constructor is the lesser of the evils. It is 'tailored' to match the JSON data format, and it works well.

Your question:

  My colleague says that the constructor is very large, and this code is horrible. Is he right?

The answer is: yes, it is large, and the code is ugly.... and he's right. But, not everything can be small, and pretty. This is the lesser of the evils.

I would not change it. Your class has a lot of related data, it has to get in there somehow.

Other Issues

Your constructor has the input public_key but does not store that as a property.

You should consider using a generator in your get_list_of_all_files: you should yield each File, instead of returning the completed list.


Spreadsheet generated through Google Drive file iteration

Tracking Previously Indexed Files

From my tests it appears that DriveApp.getFiles() returns the files in the order that they were last modified. This is not guaranteed in the Google Scripts specifications; however, this information could be used to drastically speed up your script. Just a few things need to be considered.

Storing the last time the script was run

You could store the time you last ran the script as a ScriptProperty, which you could get right before you delete them all at the start. Then you could iterate through the files until you find one with a file_last_updated date prior to when you last ran the script.

while (files.hasNext() && Seconds < 240) {
  var file = files.next();

  var file_last_updated = file.getLastUpdated();

  if (file_last_updated > Last_Time_Script_Was_Run) {
    // find file and update it
    // if not found then add new one
  }
}

Permanently deleted files

Another thing to note is that if you only check the most recently modified files your script will never notice when a file has been permanently deleted. The only way files are permanently deleted is when they are deleted from the trash (or by an authorized script). You could keep track of these by occassionally rechecking every single file in your drive, or by only permanently deleting files with a separate script that updates your sheet of drive files. Look into this SO question: Permenantly Deleting Files for more info.

Updating files on the sheet

You'll need to add the file id to your spreadsheet so that the script will be able to find the file data it needs to update. Array lookup may be too slow since you have so many files; you could use an object to map the file id to its index. But try both to be sure.

function Start_Up() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getActiveSheet();
  var fileData = sheet.getDataRange().getValues();

  fileData.shift(); // remove header row
  // say ID is the 4th index

  var indexMap = {};
  for (var i = 0; i < fileData.length; i++) {
    indexMap[fileData[i][4]] = i; // map the id to the index
  }

  Iterate_Files(fileData, indexMap);
}

function Iterate_Files(fileData, indexMap) {
  // ...

  // when updating a file
  var id = file.getId();

  if (indexMap[id] === undefined) { // add new file
    fileData.push([...]);
  }
  else { // update existing file
    fileData[indexMap[id]] = [...];
  }

  // ...
}

Minor optimizations

You can eke out a little extra performance by changing how you check the time. I got a 10 second speed up checking ~1200 files by doing the following.

var file,
    file_name,
    folder_name,
    file_url,
    file_last_updated;

while (files.hasNext() && Date.now() - Start_Time < 240000) {
  file = files.next();

  file_name = file.getName();
  if (file.getParents().hasNext()) {
    folder_name = file.getParents().next().getName();
  } else {
    folder_name = 'Root';
  }
  file_url = file.getUrl();
  file_last_updated = file.getLastUpdated();
  output.push([file_name, folder_name , file_url, file_last_updated]);
}


Simple ActiveRecord attributes encryption in Rails 5+

Some notes:

The recommended way to overwrite accessors is to use super.

As @Flambino says, it's better not to hardcode secrets directly in the code. It can be a file not committed to the repository.

I'd write the crypt method this way:
  def crypt
    @crypt ||= begin
      key = ActiveSupport::KeyGenerator.new('password').generate_key('salt')
      ActiveSupport::MessageEncryptor.new(key)
    end
  end


Java implementation of the longest monotone increasing subsequence

Coding details

You can initialize list like this : int[] list = {1,2,9,4,7,3,11,8,14,6};
for (int j = 1, n = i-1; j <= n; ++j) { // do not loop on limit calculation
length++; // for length = length + 1;


I can't speak for that particular Railscast episode, but rails provides an idiomatic way to deal with validation errors. Taking your code as an example, I'd change it to look like this (using Rails 4.2):

app/controllers/profiles_controller.rb:

class ProfilesController < ActionController::Base
  def show
    @profile = Profile.find(...)
  end

  def new
    @profile = Profile.new(profile_params)
  end

  def create
    @profile = Profile.new(profile_params)

    if @profile.save
      redirect_to profile_path(@profile)

    else
      render :new
    end
  end

  def edit
    @profile = Profile.find(...)
  end

  def update
    @profile = Profile.find(...)

    if @profile.update_attributes(profile_params)
      redirect_to profile_path(@profile)

    else
      render :edit
    end
  end

  private

  def profile_params
    # call params.require(:profile).permit(...) to whitelist attributes as needed
    params.require(:profile)
  end
end

app/views/profiles/new.html.haml:

%h2 New Profile
= render partial: 'form'

app/views/profiles/edit.html.haml:

%h2 Edit Profile
= render partial: 'form'

app/views/profiles/_form.html.haml:

= form_for(@profile) do |f|
  - # Display any form errors, if any
  - if @profile.errors.any?
    .errors
      %h2 Errors
      %ul
        - @profile.errors.full_messages do |message|
          %li= message

  - # Assuming profiles have first_name and last_name as attributes
  %section
    = f.label :first_name
    = f.text_field :first_name

  %section
    = f.label :last_name
    = f.text_field :first_name

  %section
    = f.submit

This is a very common pattern in rails apps that you can also see being used in the rails guides. The form_for helper is smart enough to generate the correct path to submit the form to depending on weather or not the @profile instance variable contains a record that has or has not been persisted. Persisted records (new ones or those with errors) will be posted to create. Records being updated will be set to whatever the update action/path for that controller is.

Whenever updating or saving a record fails, the controller will render the appropriate view (new or edit) and use the record that failed validation when rendering the form. From here, your view can inspect the record and display any errors if they exist (@profile.errors).

This won't fix an issue of a user navigating backwards and forwards through your form, but it should reduce the need to do so and it'll let you avoid weirdness you may have encountered while persisting form data within the session variable (which gets serialized and de-serialized into whatever your session store is during each request).

PS: I find that thinking of multi-step forms with more than one or two steps as state machines helps greatly in trying to conceptualize the different states and transitions you need to handle when you need to determine at what point in a form a particular session should be in. To that effect, I would highly recommend checking out the wicked gem which does a lot of this grunt work for you.


Generating an array of unique values of a specific property in an object array

I know this is an old post but purely for those looking for ways to do this heres a way that I found works nicely with a single line

var table = [
  {
    a:1,
    b:2
  },
  {
    a:2,
    b:3
  },
  {
    a:1,
    b:4
  }
];

let result = [...new Set(table.map(item => item.a))];
document.write(JSON.stringify(result));


The script is vulnerable to an injection attack. If anyone can write files under any of the directories to be backed up then the script can be made to execute code of their choosing. (I realize that this is your home directory and "this could never happen" but bear with me for a moment). The problem is that a non-validated string is passed to os.system():

backup_cmd = "tar -C ~ -zcvf %s %s" % ( target , ' '.join(newer_files) )
status = os.system(backup_cmd)

Attacker just needs to:

cd some/where/writable
touch '; rm -rf ~'

But it doesn't even need to be a malicious attack. If any of the files have characters in their names that are interesting to the shell then the script may fail. A tamer example: if any filename contains a hash character (#) then all subsequent filenames in the newer_files list will be ignored and will not be backed up by tar(1).

Instead please consider using os.exec*() or better still the subprocess module. These take a vector of arguments rather than a string and so do not suffer from the same problem.


C++ conversion from std::string to arithmetic type using std::locale::classic()

I see two things I'd change here.

The first is that right now it supports only conversion from string to the specified (arithmetic) type. Sometimes you want (for example) to convert to a string, not just from one. To support that, we can add a second template parameter for the type of the input argument.

My second big point is that you're starting from a problem where the locale to use was hard-wired into boost::lexical_cast. But instead of fixing (what seems to me like) the real problem, you've just hard-wired a different locale.

Instead of that, I'd prefer to specify a locale to use by default, but also allow the user to specify a locale to use for the conversion, if they choose to do so.

Putting those together, we get a function something like this:

template<typename T, typename U>
inline auto lexical_cast(U const& in, std::string const &name = "C")
{
    std::stringstream istr;
    istr.imbue(std::locale(name));
    istr << in;

    std::string str = istr.str(); // save string in case of exception

    T val;
    istr >> val;

    if (istr.fail())
        throw std::invalid_argument(str);

    return val;
}

Now we can do things like:

// Treat as German input
auto x = lexical_cast<double>("1.234,567", "de");

or:

// convert to string in user's locale
auto s = lexical_cast<std::string>(123456.78, "");

Finally, I'd note one basic difference between this and boost::lexical_cast. This throws an exception if and only if it is unable to convert the input to a result of the output type (at all). Boost lexical_cast not only requires that you be able to convert the input to the output type, but also that when the conversion completes that it consume the entire input.

Consider, for example, something like:

int x = lexical_cast<int>("1 x");

With your lexical_cast, this will succeed because it successfully converted the 1 to an int. With Boost lexical_cast, this will throw an exception because even though it converted 1 to an int, that didn't use the x.


For such a simple calculation, the logic used for the bdtip and bdtotal variables wasnt straight forward. Instead of creating it with the value of one of the operands, then multiplying/adding it by the other operand, why not do something like the following:

txt_check = txtcheck.getText().toString();
tpercent = txttippct.getText().toString();

BigDecimal hundred = new BigDecimal("100");
BigDecimal pct = new BigDecimal(tpercent);

BigDecimal bdpercent = pct.divide(hundred, 2, BigDecimal.ROUND_UNNECESSARY);
BigDecimal bdcheck = new BigDecimal(txt_check);

BigDecimal bdtip = bdcheck.mulitply(bdpercent);
BigDecimal bdtotal = bdcheck.add(bdtip);


Generic wrapper for System.Runtime.Caching.MemoryCache

When implementing the Dispose interface it is advisable to use a two stage clean up. So that when you use this not inside a using clause the garage collection can also work correctly.

Technically you can get away with it here; but I find it is useful to always use this pattern. Maintenance/Bug fixing then becomes easier as you do not need to start messing with other stuff just update the Dispose method. Another reason is that MS recommends this.

    public ~MemoryCacheWrapper()
    {
        // Garbage collection has kicked in tidy up your object.
        Dispose(false);
    }

    // Implement IDisposable.
    public void Dispose()
    {
        // Dispose has been called clean up your object and members that
        // are disposable.
        Dispose(true);

        // Now Make sure that you don't call the cleanup again via the Finalizer
        // Effectively you are taking over garbage collection so make sure you
        // don't do it again
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        // Only do this once.
        if(!this._isDisposed)
        {
            // If called via IDispose interface then clean up sub-objects.
            // That implement the IDispose interface.
            if(disposing)
            {
                // Dispose managed resources.
                _memoryCache.Dispose();
            }

            // Now clean-up and objects that don't implement dispose.
            // i.e close any file handles

            // Currently nothing to do.
        }
        _isDisposed = true;
    }


Invoking function stored in a struct using Rust

There are two distinct applications of mutability in Rust:

Bindings (variables) can be mutable or immutable.
Borrows (references) can be mutable or immutable.

Here, you're not using any borrows, so we're only concerned with bindings.

Note that values are not intrinsically mutable or immutable. Therefore, when you move a value from one binding to another, you can change the mutability. The methods invoke and get_invocation take ownership of the Cmd, therefore they can decide to declare self as mutable, even if the original value is not declared as mutable. For example, this is valid:

impl<T: FnMut()> Cmd<T> {
    pub fn invoke(mut self) {
        (self.invocation)();
    }
}

fn help() {
    println!("not implemented yet :)");
}

fn main() {
    let cmd = Cmd::new("help", help);
    cmd.invoke();
}

If you were to take self by mutable reference, rather than by value, then the original variable would indeed need to be declared as mutable. You could not invoke the function with only an immutable reference, because FnMut closures can't be invoked from an immutable borrow. If that's a problem, switch to Fn instead.

impl<T: FnMut()> Cmd<T> {
    pub fn new(name: &str, invocation: T) -> Cmd<T> {
        Cmd {
            name: String::from(name),
            invocation,
        }
    }

    pub fn invoke(&mut self) {
        (self.invocation)();
    }

    fn get_invocation(&mut self) -> &mut T {
        &mut self.invocation
    }
}

fn help() {
    println!("not implemented yet :)");
}

fn main() {
    let mut cmd = Cmd::new("help", help);
    cmd.invoke();
}


Time calculation
timeInSecs = firstPlaceTime.second + firstPlaceTime.minute * 60 + firstPlaceTime.hour * 3600

The first thing to do is attempt to get this as a timespan and avoid your own time math. In other words,
from datetime import datetime, time, timedelta

MIDNIGHT = time()

# ...

first_place_time = datetime.strptime(row[3], "%H:%M:%S.%f")
time_span = first_place_time - datetime.combine(first_place_time, MIDNIGHT)
time_difference = time_span.total_seconds() * 1.15

Unpacking
You can unpack your row and avoid row[0], etc. fixed indexing, like:
category, position, name, race_time = row[:4]

Call reuse
This is written twice:
datetime.strptime(row[3], "%H:%M:%S.%f")

so store it to a temporary variable.
PEP8
MaleCategoryList should be male_category_list, and MaxTime should be max_time.
Convert
Given the above code, you can get rid of most of convert. You should not put the time through another round-trip using a string.


Why define PORT as a constant independently in TextReceiver and TextSender? Isn't it the whole point that it's one and the same value? Let's stick to Single Source of Truth then. And if not, why make them public?
I'm not sure if this is necessary:

if (in != null) {
    close(in, clientSocket, serverSocket);
} else if (clientSocket != null) {
    close(clientSocket, serverSocket);
} else if (serverSocket != null) {
    close(serverSocket);
}

I'd rather have close skip over null values when iterating through closeables.
It could be a better choice to use a finally clause for closing resources (in TextReceiver). It executes regardless of whether there was an exception or not.
If we're logging all other exceptions, I can't see the reason not to log the IOException in close.


A simple cipher that uses the sums of previous characters

As with CRC, this doesn't offer cryptographic strength.

The o in the public API needs an informative name, perhaps "offset".

In a duck-typed language, feel free to omit checks such as:

if not isinstance(inpt, str):
    raise TypeError("Input nust be a string")

since the first call to ord() will have much the same effect. Do go to the trouble of writing a docstring which describes the arguments.

Rather than an if, you might break this into two functions.

Try to show parallel structure. You chose to build up a list of strings in the 1st case, yet appended to a string in the 2nd case.

One of your modulo operations, (o % 96), seems to be redundant.

Consider naming your magic numbers, 32 and 96. Or do away with them entirely: produce binary output which you then base64 encode.

The nested loops offer quadratic performance. You have an opportunity to store sums in a temp variable if you want linear performance.


Country, city, and address tables for a customer

besides removal of duplication, there are other issues, more important IMO, that need addressing:

Using Exceptions as control flow is considered an anti pattern. There are several reasons for this, they are outlined here. in your case, an added reason is that the insert is only needed for the first time for every key. the proper way to do it is to try to select and when you get no data, do an insert. this way, the decision to insert is done in an if statement, and after the 2nd time, there will be no redundant access to the DB.
naming convention: in Java (as well as several other languages) there is a naming convention for method that dictates that prefix getXxx() means the method retrieves information and does not modify it. your methods break the principle of least surprise. if the caller of these methods is not aware of the implementation, it will not expect changes to DB after calling them.


Suppress API call in Redux Saga based on a timer

Disclaimer: I´m not an expert in redux / redux-saga. This post is not directly answering your questions. Rather, it is focused on code design / architecture and what is the most useful approach for the underlying problem.

For me, the main question is: Who is in charge of determining when the data is invalid?

Imho, there are at least three answers to this:

The API / backend / server
The frontend application
One particular UI component

If it is 1., then I would use HTTP cache headers like Cache-Control: max-age=150. This way, the backend can change the value without requiring to adapt the frontend. Also, it removes the need for any conditional code. The saga can always call the API and the browser does the caching.

If it is 2., then the saga should contain the conditional code to determine whether to fetch new data or to used cached values. Where to put the actual cache and how to do this is a question on its own with regards to frontend application architecture.

If it is 3., then the particular UI component should contain the conditional code and it should also contain / be in charge of the cached values.


Hash table for Coursera's algorithms course

Well, if you're looking to move away from functional programming, making yourself some classes might be a good start.

In your .h file, you declare your class and all that jazz, so it becomes

#include <iostream>
#include <vector>
#include <fstream>
#include <set>
#include <map>
#include <cmath>
#include <sys/time.h>

using namespace std;

class HashTable
{
    typedef set<long int> inner;
    typedef map<int, inner> hashTable_T;
};

Only it doesn't. As has been pretty well established, using namespace std is bad practice. So this is what our header looks like now.

#include <iostream>
#include <vector>
#include <fstream>
#include <set>
#include <map>
#include <cmath>
#include <sys/time.h>

class HashTable
{
    typedef std::set<long int> inner;
    typedef std::map<int, inner> hashTable_T;

    hashTable_T hash;
};

Right, let's start having a look at that .cpp file. Now I see 3 functions that all do an operation on a single hash table. That smells functional to me, so I reckon we're actually going back to editing our .h. And since we're adding in some functions, may as well chuck in a little constructor.

As well as that, we need to think about visibility, as in setting what's public, protected and private, so we'll do that here too. Typically, the members of the class are either private or protected, so we'll make that happen, and whatever functions need to be accessed outside of the class are public, so we'll do that too.

We should give the variable int t, which is being passed to readFile(int) a meaningful name too, but I'm not sure what to call it, so I'll leave that up to you.

#include <iostream>
#include <vector>
#include <fstream>
#include <set>
#include <map>
#include <cmath>
#include <sys/time.h>

class HashTable
{
    typedef std::set<long int> inner;
    typedef std::map<int, inner> hashTable_T;

    private:
        hashTable_T hash;

    public:
        HashTable();
        void readFile(int t, const char* fileName);
        int findinTable(const long int &value, const int &binL,const int &binH, set<int> &setofTs);
        void print();
};

Okay, back to that .cpp.
We're killing that using namespace std again. I know all of the c++ tutorials use it, but trust me, you shouldn't.

Given that we've made it a class function, and we might want to read from other files (sorry to those shouting YAGNI, but this is just a little change), why not pass in a string which is the file name? As well as this, I've put in a few formatting changes which I think makes it a bit more readable. This means the readFile function becomes

void HashTable::readfile(int t, const char* fileName){

    ifstream ipstream(fileName);

    long int output;

    while (ipstream >> output){
        int  index = output/(2*t);
        hash[index].insert(output);
    }
}

After making it a class function, and doing a little bit of formatting, your findinTable is now:

int HashTable::findinTable(const long int &value, const int &binL, const int &binH, set<int> &setofTs){
    hashTable_T::iterator it, itL, itH;
    inner::iterator itIn;
    long int sum;

    itL = hash.upper_bound(binL);
    if (itL != hash.begin()){
        itL--;
    }

    itH = hash.upper_bound(binH);

    bool done = false;
    while(itL != hash.end()){
        for (itIn = (itL->second).begin(); itIn != (itL->second).end(); itIn++){
            sum = *itIn + value;
            if (sum <= t && sum >= -t && *itIn != value){
                setofTs.insert(sum);
            }
        }
        itL++;
        if (done){
            break;
        }
        if (itL == itH){
            done = true;
        }
    }
}

Getting onto your print function:

void HashTable::print(){
    hashTable_T::iterator it;
    inner::iterator vecIt;

    for (it=hash.begin(); it!=hash.end(); it++){
        std::cout << it->first << " :";
        for (vecIt = (it->second).begin(); vecIt != (it->second).end(); vecIt++){
            std::cout << *vecIt << " ";
        }
        std::cout << std::endl;
    }
}

Okay, looking pretty good so far. Probably not perfect, but a decent start. We wrote that constructor, so I think we should use it. I think it could probably use a bit of modification before it's worth writing though. So the declaration for it was HashTable();, but I think if it's made to be HashTable(const char* sourceFile, int tVal);, it'd be much better.

Then we'd have (as our constructor):

HashTable::HashTable(const char* sourceFile, int tVal){
    readFile(tVal, sourceFile);
}

Finally! Onto main. Now, I'm not entirely convinced about my solution to this but in particular, and I'm pretty sure that there's a more elegant way of doing it that I'm missing, but I'm going to say extract the bit which is doing the work, and put it into a class function. The only alternative (that I can see) is breaking the encapsulation, which is pretty non-OO. So I think that we add a function like this (but with a much better name):

std::set<int> HashTable::makeSet(int t){
    std::set<int> setofTs;
    hashTable_T::iterator it = hash.begin();
    inner::iterator it2;
    int binL, binH;
    for (it; it != hash.end(); it++){
        for (it2 = (it->second).begin(); it2 != (it->second).end(); it2++){
            binL = (-t-(*it2))/(2*t);
            binH = (t- (*it2))/(2*t);
            findinTable(*it2, binL, binH, setofTs);
        }
    }
    return setofTs;
}

So therefore main becomes:

int main(){
    int t = 10000;
    HashTable hTable("algo1-programming_prob-2sum.txt", t);

    std::set<int> setoFTs = hTable.makeSet(t);
    cout << setofTs.size() << endl;
    return 0;
}

And as a round-up, I'll show what states our 2 files are in at this point. I've done a bit of extra cleaning up that I'll explain as I go along in comments

ht2.h

#pragma once //Include guard, always good to have
#include <fstream> //Grouped the includes
#include <iostream>

#include <map>
#include <vector>
#include <set>

#include <cmath>
//Got rid of sys/time, as I couldn't see what it was being used for. If I'm wrong, ignore this.

class HashTable
{
    typedef std::set<long int> inner;
    typedef std::map<int, inner> hashTable_T;

    //Grouped all of the functions by type.
    private:
        hashTable_T hash;

    public:
        HashTable(){};
        HashTable(const char* sourceFile, int tVal);

        int findinTable(const long int &value, const int &binL,const int &binH, set<int> &setofTs);

        void print();
        void readFile(int t, const char* fileName);
};

ht2.cpp

#include "ht2.h"

HashTable::HashTable(const char* sourceFile, int tVal){
        readFile(tVal, sourceFile);
    }

void HashTable::readfile(int t, const char* fileName){

    ifstream ipstream(fileName);

    long int output;

    while (ipstream >> output){
        int index = output/(2*t);
        hash[index].insert(output);
    }
}

int HashTable::findinTable(const long int &value, const int &binL, const int &binH, set<int> &setofTs){
    hashTable_T::iterator it, itL, itH;
    inner::iterator itIn;
    long int sum;

    itL = hash.upper_bound(binL);
    if (itL != hash.begin()){
        itL--;
    }

    itH = hash.upper_bound(binH);

    bool done = false;
    while(itL != hash.end()){
        for (itIn = (itL->second).begin(); itIn != (itL->second).end(); itIn++){
            sum = *itIn + value;
            if (sum <= t && sum >= -t && *itIn != value){
                setofTs.insert(sum);
            }
        }
        itL++;
        if (done){
            break;
        }
        if (itL == itH){
            done = true;
        }
    }
}

std::set<int> HashTable::makeSet(int t){
    std::set<int> setofTs;
    hashTable_T::iterator it = hash.begin();
    inner::iterator it2;
    int binL, binH;
    for (it; it != hash.end(); it++){
        for (it2 = (it->second).begin(); it2 != (it->second).end(); it2++){
            binL = (-t-(*it2))/(2*t);
            binH = (t- (*it2))/(2*t);
            findinTable(*it2, binL, binH, setofTs);
        }
    }
    return setofTs;
}

void HashTable::print(){
    hashTable_T::iterator it;
    inner::iterator vecIt;

    for (it=hash.begin(); it!=hash.end(); it++){
        std::cout << it->first << " :";
        for (vecIt = (it->second).begin(); vecIt != (it->second).end(); vecIt++){
            std::cout << *vecIt << " ";
        }
        std::cout << std::endl;
    }
}

//This *could* be in a file all on it's own, but let's not make it look lonely.
int main(){
    int t = 10000;
    HashTable hTable("algo1-programming_prob-2sum.txt", t);

    std::set<int> setoFTs = hTable.makeSet(t);
    cout << setofTs.size() << endl;
    return 0;
}


Thanks for sharing your code.

Naming

Finding good names is the hardest part in programming, so always take your time to think about the names of your identifiers.

Naming Conventions

Please read and follow the Java Naming Conventions

eg.:

Let class names always start with an uppercase letter
let boolean variables and methods returning a boolean value start with is, has, can or alike. (isGameRunning vs. gameOn)

Choose you names from the problem domain, not from the technical solution.

eg.: your class keyListener might better be named PadelControl

don't use comments to "save" code

Modern IDEs keep a history of the last saved versions of your code files. They have capability to compare with this old versions and get them back (or parts of). Also using a source code management system like git or svn is quite easy for the same purpose.

So there is no need to keep "inactive code" as comments in your code files. just remove them.

use adapter classes if possible

Almost all Swing interfaces have empty implementation classes called *Adapter in your case it is the KeyAdapter. You can extend that class and only implement the method you need, keeping your code clean from the empty implementation of the unneeded methods.

do not add code with unknown/unverified behavior

You method go() ends with an empty loop.
I suspect you added this because you thought you program would exit otherwise. Maybe you have been told to do so or red somewhere.
But you most likely never tested that behavior.

This empty loop results in 100% activity of one of your CPUs cores. Some years ago, when there was only one core your computer would have been unusable after the start of your program. Thanks to technology advance this loop does not stall your PC.

So never add code just because it sounds like a good idea, always test that certain code really has the expected effect. If it doesn't delete it immediately.

  There is a programing technique called Test Driven Development supporting that.


Every Optional.isPresent() can be replaced with the fluent Optional.ifPresent() which takes a Consumer function arg (that can be lambda expr) which accepts the value of the Optional.get()

properties.entrySet().stream().filter(property -> existProp.containsKey(property.getKey()))
.findFirst().ifPresent(foundPropertyValue -> {
  // Same key already exists
  LOG.warn("Property with key {} already exists in requires {}", foundPropertyValue.getKey(), requires.get(reqidx).getName());
  // in case the existing property has the same value (check only for value of type String)
  if (foundPropertyValue.getValue() instanceof String
      && existProp.get(foundPropertyValue.getKey()) instanceof String
      && (foundPropertyValue.getValue()).equals(existProp.get(foundPropertyValue.getKey()))) {
        throw new Exception("Property " + foundPropertyValue.getKey() + "  exists already with value " + foundPropertyValue.getValue() + " in requires " + requiresName);
  }
});


Quick Sort Implementation with iterators

You have done a great job.  Here’s my suggestions:

Sort the include directives in alphabetical order.
Instead of using the generic name Iter, it may be a good idea to express the random access requirement: something like RandomIt.
Iterators should be passed by value, not const reference.  Don’t be afraid to copy iterators — they are intended to be lightweight objects that are frequently copied, and passing them by const reference will incur overhead over passing them by value because of the additional indirection.
It is more logical to use auto piv = std::prev(end);, because int y = x - 1; is more logical then int y = x; --y;, right?  (Of course you can use end - 1, but that may be less efficient if the subtraction operator of the iterator isn’t inlined.)
You can use std::iter_swap instead of manually ADL’ing swap.
Instead of enforcing <=, consider taking a custom comparator as the standard algorithms do.  (Also note that the standard library facilities always use < as the comparator by default.  <= is not required unless you provide a custom comparator.)

Also, always choosing last element as the pivot can make the code vulnerable to reversely sorted sequences.  You can consider taking a random number generator to randomize the choice if this becomes a problem.


Counting multiples of 3 or 5 using threads

Bug

Both sums are much too large to fit into a 32-bit int.  So this code returns an incorrect answer.

Gaussian solution

If you first calculate how many multiples of whatever there are, you can use the Gaussian formula to get the sum directly.

public class MultipleOf implements Runnable {

    private final int interval;
    private final long ceiling;
    private long sum;

    public MultipleOf(int interval, long ceiling) {
        this.interval = interval;
        this.ceiling = ceiling;
    }

    @Override
    public void run() {
        // n is the number of multiples of interval that are less than ceiling
        long n = (ceiling - 1) / interval;
        sum = interval * (n * (n+1) / 2);
    }

    public long getSum() {
        return sum;
    }

}

This also requires only one multiples class and removes the magic numbers from the class.

You can run the code like

    private static long parallelSolution(long ceiling) throws InterruptedException {
        long totalSum = 0;

        MultipleOf multipleOf3 = new MultipleOf(3, ceiling);
        Thread thread3 = new Thread(multipleOf3);

        MultipleOf multipleOf5 = new MultipleOf(5, ceiling);
        Thread thread5 = new Thread(multipleOf5);

        MultipleOf multipleOf15 = new MultipleOf(15, ceiling);
        Thread thread15 = new Thread(multipleOf15);

        thread3.start();
        thread5.start();
        thread15.start();

        thread3.join();
        thread5.join();
        thread15.join();

        totalSum += multipleOf3.getSum();
        totalSum -= multipleOf15.getSum();
        totalSum += multipleOf5.getSum();

         return totalSum;
    }

When I ran this with almost your original main, I got an answer in 2 milliseconds.  Your original code ran in 6000 milliseconds in my test.  Of course, running without threads takes 0 milliseconds.

I also changed the thread names to be more descriptive.

Overhead

I'd try running your solution without threads and see if it is faster or slower.


Structurally, it looks ok to me. I'd be worried about the hard-coded numbers, though. If your page changes, you'll have to update all those.

I'm betting the numbers match the offsets of some elements, so it'd be more flexible to determine the numbers at runtime, using jQuery's .offset() function.

I would perhaps do something like this (assuming the offsets you want are for the elements you're currently selecting):

// set up your "scroll triggers" (using "klass" since "class" is a reserved word)
var scrollTriggers = [
  { selector: ".media-about", klass: "tada" },
  { selector: ".media-info", klass: "tada" },
  { selector: ".media-history", klass: "tada" },
  { selector: ".media-dimension", klass: "flipInY" }
];

// on load, get the elements and their offsets
$(function () {
  scrollTriggers.forEach(function (trigger) {
    trigger.element = $(trigger.selector);
    trigger.offset = trigger.element.offset().top;
  });

  // sort according to offset
  scrollTriggers.sort(function (a, b) { return a.offset - b.offset });
});

// on scroll, loop through the triggers
$(document).on("scroll", function () {
  var scrollTop = $(this).scrollTop(),
      trigger, i, l;
  for(i = 0 , l = scrollTriggers.length ; i++) {
    trigger = scrollTriggers[i];
    if(trigger.offset <= scrollTop) {
      trigger.element.closest(".animated").addClass(trigger.klass);
    } else {
      break; // no need to check the others; their offsets are all higher
    }
  };
});

It's still doing a some unnecessary work (finding closest(".animated") for elements you've already scrolled past and handled), but it shouldn't be a huge drain on things.

Point is that this way, it's easier to keep the JS in sync with the actual markup (no hard-coded numbers), and we've reduced duplication.

An even more automated way to do this would be to give all the relevant elements a special class, e.g. scroll-trigger, and give them a data-* attribute, e.g. data-triggered-class="tada" to hold the class name that should be added when triggered.

With that, the code becomes

var scrollTriggers = [];

// on load, get the elements and their offsets
$(function () {
  scrollTriggers = $(".scroll-trigger")
    .map(function () {
      var element = $(this);
      return {
        element: element,
        offset: element.offset().top,
        klass: element.data("triggered-class")
      };
    })
    .get()
    .sort(function (a, b) { return a.offset - b.offset });
});

// (same on-scroll handling as above)

Now, there's no need to add elements to the JS at all; just declare triggers in the HTML.


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

It is not entirely clear to me what the goal of that mask exactly is, but I guess you want to bring focus to your content div while editing it (correct me if I'm wrong, perhaps a simple demo would be nice to see what you want to achieve exactly)

If my assumption is correct, I would keep thing a lot simpler, and let css take care of things. This is by far the most performant solution I believe, since browser are obviously quite well optimized for applying css.

You could just apply a ridiculously large box shadow to your focus div, which will obscure the rest of the content, while keeping it's background in tact. No need to alter your DOM and check for resizes or anything. The css would look something like this:

div[contenteditable] {
  box-shadow: 0 0 0 9999px rgba(0,0,0,.8);
}

I've set up a very simple demo to demonstrate (hit the edit button to see the effect, and edit the content to see how it reacts on resize)

$('button').click(function() {
 $('div').first().attr('contenteditable', true);
});
body {
  background: red;
}

div[contenteditable] {
  box-shadow: 0 0 0 9999px rgba(0,0,0,.8);
}

Test CMS

  Lorem ipsum

  Lorem ipsum

<button>edit</button>


I think you can DRY this up pretty well by refactoring.

This feels like a “ifs are evil” code smell to me. There are three “if” statements within that whereHas. They are packed in fairly tightly, and it makes that part of the code more difficult to read. Trying to refactor that as much as possible can resolve the duplication along the way, and ultimately make things much more readable and manageable.

Try to give every “if” it’s own method, if for no other reason than the opportunity to give it a very concise name explaining what it does. This greatly improves code readability.
The “if"s being repeated is a good indicator that you can flip the control around. Try to find a way to visit each “if” once and do all the things you need to do based on the results in one place. In this case, that means breaking the construction of the query into a couple of pieces.
“if"s are decision points. They are apt to be the focus in future debugging efforts. Push these decision points to as early in the process as you can, and obsess over making that code as simple and as readable as possible.
Auth::guard( 'supplier' )->user() gets resolved a number of times. Instead, resolve it once as early as possible and catch the results in a class attribute or parameter.
The “if/elseif” is overreaching; much of the content is the same. Narrow the scope to just resolving the required supplier id, encapsulate it in a method, and call that within the required context.  Furthermore, this looks to be a second important variable which gets used multiple times, so resolve this as early as possible as well and get it into an attribute or parameter.
Inline role ids is a bad idea. It’s possible that the database will change, or a problem will occur on data recover or seeding on deploy to a new environment, leaving different role to id mapping. Even a short exposure to this problem will mean non-admins could be logged in as admins. Further, using the full name inline instead of ids helps improve code readability as it tells more of a story. “This happens for admins” instead of “this happens for some user role, I could look in the database to know which...” Using the name adds a bit of overhead, but it can be eager loaded with the user and makes the code a lot more readable.
No need to load the accountant user record as we only need the id, which we have account_id anyway. Referencing that directly will save a query here, or more as this block is repeated.
Database field names can be used to help improve readability, too. $user->role_id would help identify that it’s a foreign key rather than a string. Likewise, putting ‘is_’ or ‘has_’ on the front of booleans helps make them quickly obvious, such as $user->is_superuser. Along with that, setting $casts = [‘us_superuser’ => ‘boolean’,] ; in the models lets you compare it against true/false instead of 1 or 0, which is a lot more readable.
whereNotNull(‘order_state_id’) is slightly more readable than where(‘order_state_id’, ‘!=’, null). This can be applied to a number of the where() clauses
Refactor this query builder into a “plain old php” class.  Call it a repository if you think it fits, but don’t get too hung up on the name. It could be as easy as a new app/Queries/OrderList.php folder and class.  That new class can be injected into the controller. Make it fluent, and abstract decisions out of it. The class should do the lifting, but be dumb. The calling entity should encapsulate the decision making and directing, and only that.
Replace eloquent with whereHas with query builder, joins, and where clauses. The eloquent and whereHas approach can certainly still work and be much cleaner than it currently is, but I find query builder to be much more readable and consistent across different models and needs when the queries start to get complicated. Perhaps this one is down to a personal preference.

With all of that in mind, here’s where I would land given my understanding of the posted code.

app/Queries/OrderList:

<?php

namespace App\Queries;

use App\Models\OrderList;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class OrderLists
{
    protected $query;

    public function buildQuery(int $idLimitation): self
    {
        $this->query = DB::table('order_lists')
            ->select([
                'order_lists.id as id',
                //etc
            ])
            ->whereNotNull('order_state_id')
            ->whereNotNull('address_id')
            ->whereNotNull('user_id')
            ->where('id', '>', $idLimitation);

        return $this;
    }

    protected function applyNonSuperUserClauses(int $requiredSupplierId):self
    {
        $this->query->leftJoin('order_details', 'order_lists.id', '=', 'order_details.order_list_id');
        $this->query->where('order_details.supplier_id', '=', $requiredSupplierId);

        //Other  join and where clauses as appropriate

        return $this;
    }

    protected function fetchResults():Collection{

        return $this->query->get();
    }

controller:

 public function index(OrderList $orderListQuery)
    {
        $user = Auth::guard('supplier')->user();

        $idLimitation = $this->fetchIdLimitation();

        if ($this->isSuperUser($user)) {
            return view('your.view', [
                'orderList' => $orderListQuery
                    ->buildQuery($idLimitation)
                    ->fetchResults(),
            ]);
        }

       //More secured version is the default behavior.
        return view('your.view', [
            'orderList' => $orderListQuery
                ->buildQuery($idLimitation)
                ->applyNonSuperUserClauses($this->getRequiredSupplierIdByRole($user))
                ->fetchResults(),
        ]);

    }

 protected function isSuperUser($user): bool
    {
        return $user->is_super_user;
    }

 protected function getRequiredSupplierIdByRole($user): ?int
    {
        if ($this->hasAdminRole()) {
            return $user->id;
        }

        if ($this->hasLimitedUserRole()) {
            return $user->accountant_id;
        }
        return null;
    }

 //'Admin' and 'LimitedUser' based on assumptions about role ids 1,2,3,4.
    // Change these to be as concise as possible.
    protected function hasAdminRole($user): bool
    {
        return (in_array($user->role->name, $this->getAdminRoles()));
    }

    protected function getAdminRoles(): array
    {
        return [
            'Admin',
        ];
    }

    protected function hasLimitedUserRole($user): bool
    {
        return (in_array($user->role->name, $this->getLimitedRoles()));
    }

    protected function getLimitedRoles(): array
    {
        return [
            'Middle Manager',
            'Secretary',
            'Janitor',
        ];
    }

This turned into a long reply. Hopefully something here helps!


compare different pandas dataframes to find matching rows

Here is what we start with.

In [16]: df1
Out[16]:
  name  year
0  ram  1873
1  rob  1900

In [17]: df2
Out[17]:
  name                     text
0  ram               A good kid
1  ram      He was born on 1873
2  rob               He is tall
3  rob         He is 12 yrs old
4  rob  His father died at 1900

What you probably want to do is merge your two DataFrames.  If you're familiar with SQL, this is just like a table join.  The pd.merge step essentially "adds" the columns from df1 to df2 by checking where the two DataFrames match on the column "name".  Then, once you have the columns you want ("year" and "text") matching according to the "name" column, we apply the function lambda x: str(x.year) in x.text (which checks if the year is present in the text) across the rows (axis=1).

In [18]: cond = pd.merge(
    ...:     left=df2,
    ...:     right=df1,
    ...:     how="left",
    ...:     left_on="name",
    ...:     right_on="name",
    ...: ).apply(lambda x: str(x.year) in x.text, axis=1)

This gives us a Series which has the same index as your second DataFrame, and contains boolean values telling you if your desired condition is met or not.

In [19]: cond
Out[19]:
0    False
1     True
2    False
3    False
4     True
dtype: bool

Then, we filter your Series to where the condition is true, and give the index, optionally converting it to a list.

In [20]: cond[cond].index
Out[20]: Int64Index([1, 4], dtype='int64')
In [21]: cond[cond].index.tolist()
Out[21]: [1, 4]

If all you need later on is to iterate over the indices you've gotten, In [18] and In [20] will suffice.


Mean of the squares of differences for a large matrix

The overall Matlab algorithm can be simplified.  The key is to realize that:

Inter-column differences never change
You can use cumulative sums on the means of each column

First let us remove the variable step factor.  So tstep = 1.  I will reincorporate the variable step factor later.

Let B be a \$m \times n\$ matrix.  B(:,1:i) yields a \$m \times i\$ submatrix of B.
Let D = diff(B(:,1:i),1,2).  This yields the column differences of B(:,1:i).

The first column of D, aka D(:,1), is equal to the second column of B minus the first column of B, aka B(:,2) - B(:,1)
The second column of D, aka D(:,2) is equal to the third column of B minus the second column of B, aka B(:,3) - B(:,2)
...
The last column of D, aka D(:,i-1) is equal to the \$i^{th}\$ column of B minus the \$(i-1)^{th}\$ column of B, aka B(:,i) - B(:,i-1)

You'll notice that if i increases by 1, these column differences remain the same.  The only thing that changes is that we obtain one additional column difference in D.  Hence you do not need to perform the diff() function multiple times.  Simply perform it once on the entire \$m \times n\$ matrix to yield a \$m \times (n-1)\$ matrix of column differences and take submatrices of this difference matrix.

So the original code you posted:

B=(20*randn(10000,1000));
RV_B=ones(size(B,2),1);
t_step = 1;

i=2;
j=1;

while i <= size(B,2)+1-t_step
    RV_B(j)=    sum(mean(diff((B(:,1:i)),1,2).^2,1));
    i=i+t_step;
    j=j+1;
end

RV_B(j)=    sum(mean(diff((B(:,1:end)),1,2).^2,1));
M_1=RV_B';

Can be simplified to:

RV_B=ones(size(B,2),1);
t_step = 1;
D = diff(B,1,2);

i=2;
j=1;

while i <= size(B,2)+1-t_step
    RV_B(j)=    sum(mean(D(:,1:i-1).^2,1));
    i=i+t_step;
    j=j+1;
end

RV_B(j)=    sum(mean(D(:,1:end).^2,1));
M_1=RV_B';

The next step is to realize that if D is our \$m \times (n-1)\$ difference matrix, mean(D) yields a \$1 \times (n-1)\$ matrix of column means.  If we truncate columns of this matrix as we do when we take submatrix D(:,1:i-1) it does not affect the means of the columns that are still there.  So instead of performing mean() over and over on submatrices, we can again pull it out the loop, perform mean() once on the entire matrix D, and take submatrices of this mean matrix.

So now the code could look like this:

RV_B=ones(size(B,2),1);

t_step = 1;
D = diff(B,1,2);
MD = mean(D.^2);

i=2;
j=1;

while i <= size(B,2)+1-t_step
    RV_B(j)=    sum(MD(:, 1:i-1));
    i=i+t_step;
    j=j+1;
end

RV_B(j)=    sum(MD(:, 1:end));
M_1 = RV_B';

Similarly, instead of performing a sum on the rows of the submatrices, we can perform a cumulative sum along the rows (or rather row): $$\begin{align}CSMD[i][j] &= \sum_{k=1}^{j} MD[i][k] \\
&= CSMD[i][j-1] + MD[i][j]\end{align}\\$$

Incorporating Matlab's built-in cumsum() along with changing some intermediary variable names to better illustrate their purpose yields the following code:

diffB = diff(B,1,2);
meanSquaredDiff = mean(diffB.^2);
M_1 = cumsum(meanSquaredDiff, 2);

Now we no longer have any explicit loops (in the matlab code at least).  This algorithm is much faster and simpler.  Consequently, it is much easier to port to C.

You will find that for tstep=1, M_1 for your algorithm has dimension size(B,2) and for the simplified code I provided it has dimension size(B,2)-1.  However, in your original algorithm, M_1(end) and M_1(end-1) are always the same if tstep=1, hence you were performing one calculation too many.

Now let us reincorporate the variable step factor.  Realize that if we increase tstep it is equivalent to taking every \$\textrm{tstep}^{th}\$ output after the cumulative sum.  So if you want tstep=5 you perform the same three-line code above but at the end sample it via M_1 = M_1(1:5:end) or in general M_1 = M_1(1:step:end).  You can use isequal to compare the outputs of your original approach to this approach.  Remember that you one-padded your output so if you use \$\textrm{tstep} \gt 1\$, you need to remove the extra padding when comparing the matrices.

Finally the last index of the non-padded output will differ as well (if \$\textrm{tstep} \gt 1\$) since your computation computes the last index differently than the rest of the indices.  You can fix this by performing tmp =  M_1(end); M_1 = M_1(1:step:end); M_1(end) = tmp; instead of simply M_1 = M_1(1:step:end) however the latter approach is more consistent in my opinion.


You can swap JEZ and JNZ and then remove the noop jump to check, and because the instruction before start is the same as before the JMP to it at the end you can remove the two instructions:

MOV UP, ACC
START:
 MOV 0, DOWN
 JNZ CONTINUE
 MOV UP, ACC
 JEZ START
 MOV 1, DOWN
CONTINUE:

If you don't mind using more nodes you can simplify Node 2,3 by letting it ADD UP ADD RIGHT and MOV ACC, DOWN (and MOV 0, ACC)

Then Node 3,2 MOVs UP, RIGHT and node 3,3 is a copy of node 2,2. This removes 2,3 as a bottleneck that needs to gather 3 values and instead will let the other nodes help gather them.


I'll focus more on the

  How can I improve my code

part of your question.

Imports at the top

Move your import time to the top of the file, which is standard in Python.

Code in functions

Your logo dimension calculation should be in a function instead of global scope. The code at the bottom should be in a top-level main function.

Integer division

w = int(logo_img.shape[1] * scl / 100)

can be

w = logo_img.shape[1] * scl // 100

Use pathlib

...so that this:

'./test/' + current_object.object_name

can be

Path('test') / current_object.object_name


Don't do this:
*c = realloc(*c, sizeof(**c) * (*capacity));

Once you have error handling that's more sophisticated than exit(1), this will become a liability.  You need a temporary:
char *tmp = realloc(*c, new_capacity);
if (!tmp) {
    /* error handling - c is still valid */
    /* ... */
}
*c = tmp;
*capacity = new_capacity;

If you always initialize the data pointer to start as a null pointer, you don't need to use malloc() instead of realloc().  String_allocate_space would be easier to write if it accepts a pointer to a struct String; that makes it closer to the object-oriented version:
void String_init(struct String* string)
{
    string->data = NULL;
    string->size = string->capacity = 0;
}

void String_allocate_space(struct String* string)
{
    size_t new_capacity = string->capacity ? 2 * string->capacity : 16;
    char *tmp = realloc(string->data, new_capacity);
    if (!tmp) {
        /* error handling - c is still valid */
        exit(1);                /* TODO: improve error reporting */
    }
    string->data = tmp;
    string->capacity = new_capacity;
}

I've also incorporated a change above to start with a larger initial size (16) instead of 1.  That lets us skip the first 4 reallocations for free.

The read() method has a flaw that will become apparent when you try to read another value into a string - unlike std::string, reading with >> will append to it, instead of replacing it.  We need to reset size at the beginning:
void String_read(struct String* string)
{
    string->size = 0;
    int ch;
    while (ch = getc(stdin)) {

        if (!isalpha(ch))
            break;

        add_character(string, ch);
    }
    add_character(string, '\0');
}

Also, the logic is slightly wrong - we want to finish when we see a space, rather than any non-alpha (which could be digits or punctuation characters).  (Well done for remembering that getch() returns int rather than char - that's one common error avoided).
void String_read(struct String* string)
{
    string->size = 0;
    int ch;
    while ((ch = getc(stdin)) != EOF && !isspace(ch)) {
        add_character(string, (char)ch);
    }
    add_character(string, '\0');
}

When we free the string, we don't need a loop.  Instead, we have a single free().  It's a good idea to reset the size and capacity so that the string object is consistent - it can be used again and/or freed again without harm:
void String_free(struct String* string)
{
    free(string->data);
    string->data = NULL;
    string->size = string->capacity = 0;
}

This is an important concept in object-oriented programming - objects have invariants that they guarantee are true at the start and end of every (public) operation.  In this case, the invariants are that

data points to valid storage of at least capacity if capacity > 0 and is a null pointer otherwise.
size is not greater than capacity.

We can improve the printing so that it outputs any embedded NUL characters, just like C++ strings do:
void String_print(struct String* string)
{
    if (fwrite(string->data, 1, string->size, stdout) != string->size) {
        exit(1);                /* TODO: improve error reporting */
    }
}

Note that this will now print the trailing NUL we added.  We no longer need that to mark the end of string, so we can remove that line.

Modified code
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

struct String {
    char* data;
    size_t size;
    size_t capacity;
};

void String_init(struct String* string)
{
    string->data = NULL;
    string->size = string->capacity = 0;
}

void String_allocate_space(struct String* string)
{
    size_t new_capacity = string->capacity ? 2 * string->capacity : 1;
    char *tmp = realloc(string->data, new_capacity);
    if (!tmp) {
        /* error handling - c is still valid */
        exit(1);                /* TODO: improve error reporting */
    }
    string->data = tmp;
    string->capacity = new_capacity;
}

void add_character(struct String* string, char ch)
{
    if (string->size == string->capacity) {     // if current letter exceeds capacity
        String_allocate_space(string);
    }
    string->data[string->size++] = ch;    // append it
}

void String_read(struct String* string)
{
    string->size = 0;
    int ch;
    while ((ch = getc(stdin)) != EOF && !isspace(ch)) {
        add_character(string, (char)ch);
    }
}

void String_print(struct String *restrict string, FILE *restrict stream)
{
    if (fwrite(string->data, 1, string->size, stream) != string->size) {
        exit(1);                /* TODO: improve error reporting */
    }
}

void String_free(struct String* string)
{
    free(string->data);
    string->data = NULL;
    string->size = string->capacity = 0;
}

int main()
{
    struct String string;

    String_init(&string);
    String_read(&string);
    String_print(&string, stdout);
    String_free(&string);
}


Function name

The function name getColor isn't representative of what it does its better of being named createRgbaString (or something along those lines)

Return early

Your script returns in two different places, this should be changed so you exit the function early, it saves an else statement and a level of identing

Variable nameing style

Your variable naming style is not compatible with PSR2 but that isn't the end of the world.

Line length

Your line length exceeds 80 character line length, this is again not the end of the world but will make it hard to read for some people

Repeated calculation

Your repeatedly do the same calculation if the $index != 2 I would move this into a function so if it needs to be updated you only have todo it in one location

How I might write it

I have used terrible variable names, because I don't have the time do work out the complete logic of your script, so this should be unit tested if your going to use it

function getColor($value, $values_range, $opacity = '0.7')
{
    $deltaS = ($values_range['max'] - $values_range['min']) / 2;
    $ds = ($value - $values_range['min']) / $deltaS;
    $nearest_color_index = floor($ds);
    $alpha = $ds - $nearest_color_index;

    $r = $g = $b = -1;

    $colors = [
        ['r'=>255,'g' => 60,'b' => 40],
        ['r' => 255,'g' => 247,'b' =>40],
        ['r' => 12,'g' => 197,'b' => 17]
    ];

    $rNormal = getColorIndexPlusModifier($nearest_color_index, "r", 0, $colors);
    $gNormal = getColorIndexPlusModifier($nearest_color_index, "g", 0, $colors);
    $bNormal = getColorIndexPlusModifier($nearest_color_index, "b", 0, $colors);

    if ($nearest_color_index == 2) {
        return "rgba($rNormal,$gNormal,$bNormal,$opacity)";
    }

    $rPlusOne = getColorIndexPlusModifier($nearest_color_index, "r", 1, $colors);
    $gPlusOne = getColorIndexPlusModifier($nearest_color_index, "g", 1, $colors);
    $bPlusOne = getColorIndexPlusModifier($nearest_color_index, "b", 1, $colors);

    $r = doCalculation($rNormal, $alpha, $rPlusOne);
    $g = doCalculation($gNormal, $alpha, $gPlusOne);
    $b = doCalculation($bNormal, $alpha, $bPlusOne);

    return "rgba($r,$g,$b,$opacity)";
}

function getColorIndexPlusModifier($colorIndex, $colorString, $toModifyBy, $colors)
{
    return round($colors[$colorIndex + $toModifyBy][$colorString]);
}
//TODO Rename to something meaningful
function doCalculation($normalValue, $alpha, $plusOneValue)
{
    return round($normalValue + $alpha * ($plusOneValue - $normalValue));
}


Can this list comprehension be made more pythonic?

For integer division, use the // operator.  In Python 3, / will do floating-point division.

The task could be more succinctly accomplished using re.findall().

Also, the goal of the function is not obvious.  Pythonic code would include a docstring explaining its purpose.

import re

def split_string(s):
    """
    Splits a string into a list, with each element consisting of
    three characters.  Any incomplete group at the end is discarded,
    and then the last complete group is also discarded.
    """
    return re.findall(r'.{3}', s)[:-1]


Note: Your code is not useful. Rational numbers are available in the Go math/big standard library. For example,

package main

import (
    "fmt"
    "math/big"
)

func main() {
    fmt.Println("Enter a number:")
    var r = new(big.Rat)
    fmt.Scanln(r)
    fmt.Println(r)
}

I read your code, the code you imported from github.com/retep-mathwizard, and the code from rolfl's answer. I see problems.

Let's start with something simple, the calculation of the greatest common divisor or factor.

You embedded this code in a slab of code. It should be a function. For example,

func gcf(numer, denom int) int {
    var gcf int
    for i := numer/2 + 1; i >= 0; i-- {
        if (numer%i == 0) && (denom%i == 0) {
            gcf = i
            break
        }
    }
    return gcf
}

It's very inefficient. For well over two thousand years we have known of a much better way to do this.

Rolfl used a much better algorithm.

// Euclidian algorithm
func gcf(a, b int64) int64 {

    if a < b {
        return gcf(b, a)
    }

    if b == 0 {
        return a
    }

    a = a % b
    return gcf(b, a)
}

If you put blank lines between each sentence you can't see very much on a single screen. It's essential that code be readable. Think of blank lines as more like paragraph separators.

The algorithm is implemented using recursion. Any recursive algorithm can be written as an iterative algorithm. Go doesn't have tail recursion. Limit the use of recursion to the few cases where recursion is much easier to understand than iteration.

Here's an idiomatic Go GCD function. It's simple, direct, and fast.

func gcd(x, y int64) int64 {
    for y != 0 {
        x, y = y, x%y
    }
    return x
}

Here are some Go benchmarks which show how slow your GCF algorithm is.

BenchmarkGCFXXX        30000         54564 ns/op
BenchmarkGCFPeter   10000000           156 ns/op

Go types play an essential role in writing idiomatic Go. Rational is an obvious type:

// A rational number r is expressed as the fraction p/q of two integers:
// r = p/q = (d*i+n)/d.
type Rational struct {
    i int64 // integer
    n int64 // fraction numerator
    d int64 // fraction denominator
}

Like many types, Rational should have a formatted string function. Your formatted output is ugly

7182818284590 and  141592653
    -------
       1000000000

I think this looks much better

7182818284590 + 141592653/1000000000

Here's a Go String method for the Rational type. Note the attention to pretty-printing details.

func (r Rational) String() string {
    var s string
    if r.i != 0 {
        s += strconv.FormatInt(r.i, 10)
    }
    if r.n != 0 {
        if r.i != 0 {
            s += " + "
        }
        if r.d < 0 {
            r.n *= -1
            r.d *= -1
        }
        s += strconv.FormatInt(r.n, 10) + "/" + strconv.FormatInt(r.d, 10)
    }
    if len(s) == 0 {
        s += "0"
    }
    return s
}

An obvious indication of problems is the difficulty in testing. Your program only handles one input value. Rolfl hardcoded a single fixed value: num := "12345.6785".

For a problem like this, which is driven by user input, the Go main function should be an input loop. For example,

func main() {
    snr := bufio.NewScanner(os.Stdin)
    enter := "Enter a decimal number:"
    for fmt.Println(enter); snr.Scan(); fmt.Println(enter) {
        d := snr.Text()
        if len(d) == 0 {
            break
        }
        r, err := ParseDecimal(d)
        if err != nil {
            fmt.Fprintln(os.Stderr, "Input error:", err)
            continue
        }
        fmt.Println(r)
    }
    if err := snr.Err(); err != nil {
        if err != io.EOF {
            fmt.Fprintln(os.Stderr, err)
        }
    }
}

Now we have an easy way to test. Let's make sure that we can handle all reasonable values. Here are some values that you don't handle.

0; 0.; -0; 1; -1; -1.1; 1.; and so on.

You should always expect the worst from user input and handle errors gracefully. For example,'

func ParseDecimal(s string) (r Rational, err error) {
    sign := int64(1)
    if strings.HasPrefix(s, "-") {
        sign = -1
    }
    p := strings.IndexByte(s, '.')
    if p < 0 {
        p = len(s)
    }
    if i := s[:p]; len(i) > 0 {
        if i != "+" && i != "-" {
            r.i, err = strconv.ParseInt(i, 10, 64)
            if err != nil {
                return Rational{}, err
            }
        }
    }
    if p >= len(s) {
        p = len(s) - 1
    }
    if f := s[p+1:]; len(f) > 0 {
        n, err := strconv.ParseUint(f, 10, 64)
        if err != nil {
            return Rational{}, err
        }
        d := math.Pow10(len(f))
        if math.Log2(d) > 63 {
            err = fmt.Errorf(
                "ParseDecimal: parsing %q: value out of range", f,
            )
            return Rational{}, err
        }
        r.n = int64(n)
        r.d = int64(d)
        if g := gcd(r.n, r.d); g != 0 {
            r.n /= g
            r.d /= g
        }
        r.n *= sign
    }
    return r, nil
}

Even if you write impeccable code, you will still be judged on the quality of the external packages that you use. The packages from github.com/retep-mathwizard/ are of very low quality.

Here's my complete program. It's a first draft.

package main

import (
    "bufio"
    "fmt"
    "io"
    "math"
    "os"
    "strconv"
    "strings"
)

// A rational number r is expressed as the fraction p/q of two integers:
// r = p/q = (d*i+n)/d.
type Rational struct {
    i int64 // integer
    n int64 // fraction numerator
    d int64 // fraction denominator
}

func (r Rational) String() string {
    var s string
    if r.i != 0 {
        s += strconv.FormatInt(r.i, 10)
    }
    if r.n != 0 {
        if r.i != 0 {
            s += " + "
        }
        if r.d < 0 {
            r.n *= -1
            r.d *= -1
        }
        s += strconv.FormatInt(r.n, 10) + "/" + strconv.FormatInt(r.d, 10)
    }
    if len(s) == 0 {
        s += "0"
    }
    return s
}

func gcd(x, y int64) int64 {
    for y != 0 {
        x, y = y, x%y
    }
    return x
}

func ParseDecimal(s string) (r Rational, err error) {
    sign := int64(1)
    if strings.HasPrefix(s, "-") {
        sign = -1
    }
    p := strings.IndexByte(s, '.')
    if p < 0 {
        p = len(s)
    }
    if i := s[:p]; len(i) > 0 {
        if i != "+" && i != "-" {
            r.i, err = strconv.ParseInt(i, 10, 64)
            if err != nil {
                return Rational{}, err
            }
        }
    }
    if p >= len(s) {
        p = len(s) - 1
    }
    if f := s[p+1:]; len(f) > 0 {
        n, err := strconv.ParseUint(f, 10, 64)
        if err != nil {
            return Rational{}, err
        }
        d := math.Pow10(len(f))
        if math.Log2(d) > 63 {
            err = fmt.Errorf(
                "ParseDecimal: parsing %q: value out of range", f,
            )
            return Rational{}, err
        }
        r.n = int64(n)
        r.d = int64(d)
        if g := gcd(r.n, r.d); g != 0 {
            r.n /= g
            r.d /= g
        }
        r.n *= sign
    }
    return r, nil
}

func main() {
    snr := bufio.NewScanner(os.Stdin)
    enter := "Enter a decimal number:"
    for fmt.Println(enter); snr.Scan(); fmt.Println(enter) {
        d := snr.Text()
        if len(d) == 0 {
            break
        }
        r, err := ParseDecimal(d)
        if err != nil {
            fmt.Fprintln(os.Stderr, "Input error:", err)
            continue
        }
        fmt.Println(r)
    }
    if err := snr.Err(); err != nil {
        if err != io.EOF {
            fmt.Fprintln(os.Stderr, err)
        }
    }
}


Exception handling continuing the excecution

How about something like this?

Define a one-method interface like so:

public interface TryAndLogFailure { void execute(); }

Then define a method which takes an object which implements the interface and does your exception handling for you:

public void tryAndLogFailure(TryAndLogFailure talf) {
  try {
    talf.execute();
  } catch (Exception e) {
    logger.log(...);
  }
}

Now your calls to the methods can be sequential:

tryAndLogFailure(new TryAndLogFailure{ public void execute() { methodAAAACanThrowException(); } });
tryAndLogFailure(new TryAndLogFailure{ public void execute() { methodBBBBCanThrowException(); } });
// etc...
tryAndLogFailure(new TryAndLogFailure{ public void execute() { methodZZZZCanThrowException(); } });

Admittedly, this could probably be worked a little more to make it prettier, but this is my first crack off the top of my head. If only Java had support for closures.

(Also - I should note that I agree with Winston. The reason why this code feels ugly is because the concept itself is ugly. Catching Exception is almost never a good idea and requires strong justification. Given more context, we may be able to help you redesign the code to avoid this sort of code smell.)


well done providing doc strings
sticking to the Style Guide for Python Code makes Python code easier to grasp, especially for someone who didn't write it
to make the naming more convincing, you should factor out sequential_deterministic_stand_in_for_seeing_the_required_result() and sequential_deterministic_stand_in_for_checking_the_result()
As a bonus, this removed implementation detail from the docstrings of "the oracle functions".
the nested loops in oraclesort() seem to iterate all permutations of elements from input_seq - as indicated in the docstring.
Using itertools.permutations() is easier to read and should test sequences of like length, only.
(Strictly faster than the related bogobogosort for not repeatedly checking the same sequence.)
instead of determining the index of the minimum value and using slices to construct input_lst_without_min, you could use just determine the minimum value, compare it to the start of the candidate sequence and remove it from the sequence to sort recursively:
input_lst_without_min = input_seq[:]
input_lst_without_min.remove(min(input_seq))


Check your inputs in enter()

You don't check that the user entered a valid vector index. For example, if I enter a 3 as the row and/or column number the program crashes. You should reject an input if the user enters an invalid row and/or column number (like you do if the user selects a space that is already taken).

All control paths of check() should return a value

You only ever return true in check(). If none of the check conditions are true then you should explicitly return false at the end of the function.

Use the correct type for indexing

You have for loops like for (int i = 0; i < vec.size(); i++), which compare the signed integer i to the unsigned integer vec.size(). Use std::vector< std::vector<char> >::size_type.

Use a type alias / type definition for the std::vector< std::vector<char> > container

Use a type alias like using container = std::vector< std::vector<char> >; if your compiler supports it, otherwise use a type definition like typedef std::vector< std::vector<char> > container;. You can put it after the #include statements so you can use it for all your functions. This is useful for a couple of reasons:

It's a shorter name for the container. This comes in handy when referring to the container and/or its size_type, for example: container::size_type is shorter and easier to read than std::vector< std::vector<char> >::size_type.
It's easier to change the container. You may decide later to use a std::array instead, in which case you only need to modify the using statement rather than all instances of std::vector< std::vector<char> >.


Model structure for Player Team and Match in football application

It is difficult to say how good your models are, since it depends on your application requirements and demands, current and future/planned use cases.

But, few points from the top of my head:

there are some important fields missing - for example, team names
I don't particularly like the TeamMatch model. Instead, I'd expect the Match to have links to the home and away teams:

class Match(models.Model):
    home_team = models.ForeignKey(Team, related_name='home_matches')
    away_team = models.ForeignKey(Team, related_name='away_matches')

    date = models.DateField(default=now)

    def __str__(self):
        return "Match between '%s' and '%s' on %s" % (self.home_team.name, self.away_team.name, self.date)

you will also need some way of keeping the score of a match. A separate MatchResult model?
how about a use case when a player moves from one team to another? If this is something you want to keep track of, you would probably need something like a PlayerContract model to relate players and teams for a certain period of time

Also, please see these similar model design discussions:

How should I design my django models for team, player and match objects?
Models for a team


It took me a while until I understood your range notation. Consider switching to CIDR syntax. Networks are routed using CIDR so you usually can express ownership of an IP address by CIDR notation.

Another thing to note is that your code does not support IPv6. IPv6 will become more and more important over the next years. I recommend supporting it right now to be safe!

Now to your code:

Your function does several things at once. It loops through the provided ranges and checks each range. This should be separated into two functions: One reusable function that checks whether the IP address matches the whitelist entry and another one that calls the first function for each whitelist entry:

function checkIpWhitelist($ranges, $ip) {
    foreach ($ranges as $range) {
        if (isIpInRange($range, $ip)) return true;
    }

    return false;
}

Your algorithm indeed is overly complex and also has an unnecessary overhead because of that range call. range will create an array using that range, this takes time and memory!

I suggest normalizing the provided whitelist entry first: Convert any non-range to a range containing only that number and convert it to a data structure that is easier to handle than a string (array containing integers). Note that I am using array_map for that. In my opinion this functional programming style is easier to read and understand. You can easily write it as a normal foreach loop, though!

function isIpInRange($rangeString, $ip) {
    $range = array_map(function ($item) {
        $parts = explode('/', $item);
        if (count($parts) == 1) $parts[1] = $parts[0];

        return array_map('intval', $parts);
    }, explode('.', $rangeString));

Provided the user put in a syntactically correct range $range will be an array containing 4 arrays with two integers (start and each of the range) each. We can now check each part. I put a not around the whole expression in the if, as I find it more natural to read (“unless $ip[$i] is in the range the result is false”)

    $ip = explode('.', $ip);
    for ($i = 0; $i < 4; $i++) {
        if (!($range[$i][0] <= $ip[$i] && $ip[$i] <= $range[$i][1])) return false;
    }
    return true;
}

Spice it up using sanity checking! Currently the algorithm accepts dumb inputs, such as -9.94143.255/123.1/2/3/3.5. We maybe should check that first. This is a security feature, isn't it? Validating IP addresses is easy using PHP:

if (!filter_var($ip, FILTER_VALIDATE_IP)) {
    throw new InvalidArgumentException('Provide a valid ip address, please. "'.$ip.'" is not valid');
}

Validating your range is a little bit harder, but still possible. I suggest a regular expression for checking the basic structure and afterwards validating the ranges of the numbers. I am using Exceptions for error reporting here, but you can use anything you want.

// before normalizing
if (!preg_match('!^\d+(/\d+)?\.\d+(/\d+)?\.\d+(/\d+)?\.\d+(/\d+)?$!', $rangeString)) {
    throw new InvalidArgumentException('Provide a valid range, please. "'.$rangeString.'" is not valid');
}

// after normalizing
for ($i = 0; $i < 4; $i++) {
    // negative and non-numbers caught by the regular expression
    if ($range[$i][0] > $range[$i][1] || $range[$i][0] > 255 || $range[$i][1] > 255) {
        throw new InvalidArgumentException('Provide a valid range, please. "'.$rangeString.'" is not valid');
    }
}

Compiling that together we get these shiny two functions:

function checkIpWhitelist($ranges, $ip) {
    foreach ($ranges as $range) {
        if (isIpInRange($range, $ip)) return true;
    }

    return false;
}

function isIpInRange($rangeString, $ip) {
    if (!filter_var($ip, FILTER_VALIDATE_IP)) {
        throw new InvalidArgumentException('Provide a valid ip address, please. "'.$ip.'" is not valid');
    }

    if (!preg_match('!^\d+(/\d+)?\.\d+(/\d+)?\.\d+(/\d+)?\.\d+(/\d+)?$!', $rangeString)) {
        throw new InvalidArgumentException('Provide a valid range, please. "'.$rangeString.'" is not valid');
    }

    $range = array_map(function ($item) {
        $parts = explode('/', $item);
        if (count($parts) == 1) $parts[1] = $parts[0];

        return array_map('intval', $parts);
    }, explode('.', $rangeString));

    for ($i = 0; $i < 4; $i++) {
        // negative and non-numbers caught by the regular expression
        if ($range[$i][0] > $range[$i][1] || $range[$i][0] > 255 || $range[$i][1] > 255) {
            throw new InvalidArgumentException('Provide a valid range, please. "'.$rangeString.'" is not valid');
        }
    }

    $ip = explode('.', $ip);
    for ($i = 0; $i < 4; $i++) {
        if (!($range[$i][0] <= $ip[$i] && $ip[$i] <= $range[$i][1])) return false;
    }
    return true;
}


Here are few things I observed:

You repeated session_start() twice in your member.php - you can only do that once in order to start the session
You are not sanitizing your input for bad values - its best practice to do so to avoid SQL injection - however as a beginner its a good idea that you started with PDO and not legacy mysql_query
After a redirect you should exit(); because your script will continue to process until end of the file. Why let a script continue when you're done.
I know you are trying to section your code but if PHP code continues don't close it un-necessarily. (referring to index.php and to the if error part).
You should use require or require_once. include causes an error if include is invoked (by mistake) more than one time.
Last observation would be in your member.php it should be a blacklist if and not if/else. You should basically tell the user that you shouldn't be here if you are not logged in..if not just proceed to the rest of the script (ask question if you didn't understand this part)


Find all sub matrices of type N*M in it which are palindromic

Checking if a matrix is a palindrom can be simplified using the fact that you store your matrices as a list of rows.

If the matrix is a palindrom, then:

each line is a palindrom by itself;
each line is equal to its symetic (first with last, second with the one before last, etc).

Which can be written like:

def check_palindrome(mat):
    for i, row in enumerate(mat, 1):
        if row != row[::-1]:
            # The current row is not a palindrome
            return False
        if row != mat[-i]:
            # One of the columns is not a palindrome
            return False
    return True

Here I use the second argument of enumerate to get the correct index when accessing the matrix backwards.

This writing can be simplified using the all builtin:

def check_palindrome(mat):
    return all(
            row == mat[-i] and row == row[::-1]
            for i, row in enumerate(mat, 1)
    )

You can also shave half the tests by using enumerate(mat[:(len(mat)+1)//2], 1) but it won't change the overall complexity.


A simple multithreaded FileLogger in C++

Just up front, your code doesn't have any blatant bugs which would prevent its use. There are a few things that you could do to improve it though:

One thing that I'd try to avoid is singletons. These are effectively globals and bring with them almost all their problems. In particular, it prevents isolating code for unit tests. The alternative is that you pass a logger to the constructor of every object that needs it. This is called dependency injection, as a keyword for future research.
Instead of fout.open(path), you could pass the filename to the constructor of fout using the initializer list.
Your logger isn't copyable or assignable due to its members. I'd make that explicit though.
When writing, std::endl already flushes the stream, so the explicit std::flush is redundant.
The biggest issue is the way your writing thread operates. In effect, it wakes up every 10ns (that's 100.000.000 times per second) and looks for work (a.k.a. polling). Firstly, I can't imagine that this fast response time is actually relevant to a logger. If you have 0.1s delay between writing to the logger and seeing the data in the file, that should be enough by far. However, that's not a solution. What you actually want there is a condition variable, which allows you to only wake up the writer thread when actual works needs to be done.
There is a comment lock/unlock this each time messages is pushed or popped, which is already in the right direction. What has helped me in the past is to document which mutex protects which data. It may even be a good idea to put just those parts into a separate struct in some cases, just to make it clearer. Also, for all other members, document who is allowed to access them. For example, fout doesn't require synchronization, because it is exclusively accessed by the writer thread.
A minor fault, but still a fault is also that you access the queue without locking to check if it is non-empty. Since this typically only involves a simple pointer comparison (though that's implementation-defined), it will probably not cause issue. Using a condition variable as sketched below fixes this part as well.
You could implement this using lock-free algorithms. This is a complete rewrite though and not "smoothing out the rough edges" of your current approach. Just keep that in mind as future research project perhaps.
A minor flaw is that there is no way to shut down the logger. This is probably harmless, but it will probably trigger memory debuggers (leak detectors). If you decide not to implement shutdown, you don't need writerThread though, just call t.detach() after starting.
If your target is C++ 17 or later, you could also use the filesystem library which has a dedicated path type. I'd generally prefer that over raw char* string. Even without C++ 17, I'd use std::string, unless I have good reasons not to.
Concerning pushing on the queue, consider using emplace_back() instead, to avoid one more copying operation.
Concerning removal from the queue, there is a trick: Create a second, local queue (initially empty) and swap that with the member (holding a lock for the time of that operation, of course). Then you have all the content in a local object that you can process at leasure, without having to worry about locking. This becomes important when retrieving multiple messages at once, so that you don't repeatedly lock/unlock without need. This can lead to "thread convoys": Imagine one thread perpetually writing messages using lock/push/unlock triples, so it becomes a stream of lock/push/unlock/lock/push/unlock... Now, if this thread ever gets scheduled out while it holds the lock and the writer thread is scheduled in, it will then itself run a lock/pop/unlock/lock/pop/unlock.. stream. On the first lock, it will block until the logging thread continues. This thread will be able to write one message, before it is blocked by the writer thread. In other words, ownership of the mutex will pingpong between the two threads, wrecking performance. Also, this is hard to catch, because it both comes and goes spontaneously.

For reference, here is a sketch of the push and pop operations using a CV:

mutex mtx;
condition_variable cv;
deque<string> queue;

void push(string s) {
    unique_lock<mutex> lck(mtx);
    queue.push_back(s);
    lck.unlock();
    cv.notify_one();
}

string pop() {
     unique_lock<mutex> lck(mtx);
     cv.wait(lck, []{ return !queue.empty();})
     string res = queue.front();
     queue.pop_front();
     return res;
}

This is not much more than the examples given by cppreference.


You can use SendAsync:

sender.PingCompleted += new PingCompletedEventHandler (PingCompletedCallback);
sender.SendAsync(dest, timeout, buffer, options, textLabel);

And the callback:

private static void PingCompletedCallback (object label, PingCompletedEventArgs e)
{
   if (e.Reply.Status == IPStatus.Success)
   {
      label.Text = "ok";
   }
   else
   {
      label.Text = "not ok!";
   }
}

Disclaimer: I haven't run this code. I believe the delegate will be able to access the label, but I've had issues with it in the past.


Convenience function for writing files in CSV, JSON, etc

You’ve got your code split into various sections; why not make the sections their own methods?

if filepath.lower().endswith('.csv'):
   return _write_csv(filepath, data, kwargs)
elif filepath.lower().endswith('.json'):
   return _write_json(filepath, data, kwargs)
elif filepath.lower().endswith('.jsonl'):
   return _write_jsonl(filepath, data, kwargs)
elif filepath.lower().endswith('.pickle'):
   return _write_pickle(filepath, data, kwargs)
elif filepath.lower().endswith('.yml') or
     filepath.lower().endswith('.yaml'):
   return _write_yml(filepath, data, kwargs)
elif filepath.lower().endswith('.h5') or
     filepath.lower().endswith('.hdf5'):
   return _write_hdf5(filepath, data, kwargs)
else:
   raise NotImplementedError('File \'{}\' is not known.'.format(filepath))

With the appropriate dict, you could even:

path = filepath.lower()
for ending, writer in writers.items():
    if path.endswith(ending):
        return writer(filepath, data, kwargs)
raise NotImplementedError(f"File {filepath} is not known")

Or,

ext = os.path.splitext(filepath)[1].lower()
if ext in writers:
    writers[ext](filepath, data, kwargs)
raise NotImplementedError(f"File {filepath} is not known")


That book is a little dated in some of its recommendation (although still a great book).  That particular IF-ELSE recommendation leads to the ArrowCode anti-pattern, a better way (at least it reduces congnitive load) would be to use Guarded Clauses (see here too)

public TVMData(decimal discountRate, decimal periodLength, decimal cashFlowFromAsset, decimal cashOutFlow, PaymentPerPeriod paymentFrequency = PaymentPerPeriod.Annual)
        {
            if (discountRate < 0m)
                throw new ArgumentOutOfRangeException("Discount Rate must be greater than Zero", "discountRate");
            if (periodLength < 1m)
                throw new ArgumentOutOfRangeException("Period Length must be equal or greater than One", "periodLength");
            if (cashFlowFromAsset < 0m)
                throw new ArgumentOutOfRangeException("Cash Flow From Asset must be greater than Zero", "cashFlowFromAsset");
            if (cashOutFlow > 0m)
                throw new ArgumentOutOfRangeException("Cash Out Flow must be less than or equal to Zero", "cashOutFlow");

            this.DiscountRate = discountRate;
            this.PaymentFrequency = Convert.ToDecimal(paymentFrequency);
            this.PeriodLength = periodLength;
            this.CashFlowFromAsset = cashFlowFromAsset;
            this.CashOutFlow = cashOutFlow;
        }

Your Code here converts double to decimal, you may have issues with calling functions not taking into account the smaller range decimal has when compared to double

public TVMData(double discountRate, double periodLength, double cashFlowFromAsset, double cashOutFlow, PaymentPerPeriod paymentFrequency= PaymentPerPeriod.Annual)
      : this(Convert.ToDecimal(discountRate), Convert.ToDecimal(periodLength), Convert.ToDecimal(cashFlowFromAsset), Convert.ToDecimal(cashOutFlow), paymentFrequency){}

I would also move these to private if I could.  Reducing the scope and visibility of data leads to more reliable/maintainable code by reducing coupling (see here for better argument or here).

public decimal DiscountRate;
public decimal PeriodLength;
public decimal CashFlowFromAsset;
public decimal CashOutFlow;
public decimal PaymentFrequency;


Finding previous/next item in an OrderedDict

One way of simplifying the problem is to provide a thin wrapper around the OrderedDict. Something along the lines of:

class DictCycler:
    def __init__(self, data):
        self.data = data
        ...

    def next(self):
        ...

    def previous(self):
        ...

An other way is to make use of itertools capability. Especially cycle and islice. The idea being that, using cycle, cycling through the elements in the proper order is straightforward, and cycling in reverse can be done by going forward N - 2 times (where N is the length of the dictionary) with the help of islice. This yield:

import itertools

class DictCycler:
    def __init__(self, data):
        self.data = data
        self.iterator = itertools.cycle(data)
        self.jump_to_previous = len(data) - 2

    def next(self):
        return self.data[next(self.iterator)]

    def previous(self):
        prev = itertools.islice(self.iterator, self.jump_to_previous, None)
        return self.data[next(prev)]

You then just have to populate your dictionary and freeze it into this wrapper.

If you need to be able to modify the dictionary contained in data after passing it to this class, you will need to adapt the recipe a bit.


Function to lock a file using memcache, Version 1

The code only acquires a lock for the source of the move, and not for the destination. This means that there's a race between two users trying to move two different files to the same destination.
There's a race between:

memcache.delete(filename)

and:

user = memcache.get(filename)

It's not clear how the lock is released. It doesn't happen in process.
The test else: if fileExists: seems backwards.


Format conversion of localization files | 3txt to xliff

Improving speed

For each line, running 3 sed commands to extract the n-th line from 3 files,
and then running further 2-4 sed commands is of course slow.

My first recommendation would be to implement this in another scripting language, say, Python.

If you really want to do this in Bash, you could:

Combine the 3 files into one, with their lines interleaved. That is, take the 1st line from each file, then the 2nd from each file, and so on. And then in each iteration of your loop, read 3 lines.
Instead of transforming the < and > by running sed for each line, run sed just once for the entire input

If we can assume that all 3 files have the same number of lines,
then you can create the input with lines interleaved like this:

paste -d '\n' "$FILE_ID" "$FILE_SOURCE" "$FILE_TARGET"

When replacing < and > using sed, you can do it with a single sed command using multiple -e flags, like this:

sed -e 's/</\&lt;/g' -e 's/>/\&gt;/g'

Putting it together:

paste -d '\n' "$FILE_ID" "$FILE_SOURCE" "$FILE_TARGET" | sed -e 's/</\&lt;/g' -e 's/>/\&gt;/g' | \
for ((COUNTER = 1; COUNTER <= TOT_STRING; ++COUNTER)); do
    read ROW_ID
    read ROW_SOURCE
    read ROW_TARGET
    # ...
done

Simplify

This is unnecessarily complicated:

ROW_ID=$(sed -n $(( $COUNTER ))p $FILE_ID)
ROW_SOURCE=$(sed -n $(( COUNTER ))p $FILE_SOURCE)
ROW_TARGET=$(sed -n $(( COUNTER ))p $FILE_TARGET)

You can write much simpler:

ROW_ID=$(sed -n ${COUNTER}p $FILE_ID)
ROW_SOURCE=$(sed -n ${COUNTER}p $FILE_SOURCE)
ROW_TARGET=$(sed -n ${COUNTER}p $FILE_TARGET)

Counting loops in Bash

Instead of this:

COUNTER=1
while [ "$COUNTER" -le "$TOT_STRING" ]; do
    # do something
    COUNTER=$(( $COUNTER + 1 ))
done

This is equivalent, but cleaner and simpler:

for ((COUNTER = 1; COUNTER <= TOT_STRING; ++COUNTER)); do
    # do something
done

Naming

TOT_STRING is a strange name for a variable with an integer value.

Printing large text

Instead of this:

echo "<?xml version='1.0' encoding='utf-8'?>"
echo "<xliff xmlns=\"urn:oasis:names:tc:xliff:document:1.1\" version=\"1.1\">"
echo " <file source-language=\"en-US\" datatype=\"plaintext\">"
echo "    <body>"
echo "      <trans-unit xml:space=\"preserve\" id=\"1\" approved=\"no\" restype=\"x-gettext-domain-header\">"
echo "        <source>Project-Id-Version: 1.0"
echo " Report-Msgid-Bugs-To: email@example.com"
echo "POT-Creation-Date: $time+0200"
echo "PO-Revision-Date: $time+0200"
echo "Last-Translator: JohnnyKing"
echo "Language-Team: JohnnyKing"
echo "MIME-Version: 1.0"
echo "Content-Type: text/plain; charset=UTF-8"
echo "Content-Transfer-Encoding: 8bit"
echo "X-Generator: csv2xliff.sh"
echo "</source>"
echo "        <target state=\"translated\">Project-Id-Version: 1.0"
echo " Report-Msgid-Bugs-To: email@example.com"
echo "POT-Creation-Date: $time+0200"
echo "PO-Revision-Date: $time+0200"
echo "Last-Translator: JohnnyKing"
echo "Language-Team: JohnnyKing"
echo "MIME-Version: 1.0"
echo "Content-Type: text/plain; charset=UTF-8"
echo "Content-Transfer-Encoding: 8bit"
echo "X-Generator: csv2xliff.sh"
echo "</target>"
echo "      </trans-unit>"

A simpler way to write:

cat << EOF
<?xml version='1.0' encoding='utf-8'?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.1" version="1.1">
 <file source-language="en-US" datatype="plaintext">
    <body>
      <trans-unit xml:space="preserve" id="1" approved="no" restype="x-gettext-domain-header">
        <source>Project-Id-Version: 1.0
 Report-Msgid-Bugs-To: email@example.com
POT-Creation-Date: +0200
PO-Revision-Date: +0200
Last-Translator: JohnnyKing
Language-Team: JohnnyKing
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Generator: csv2xliff.sh
</source>
        <target state="translated">Project-Id-Version: 1.0
 Report-Msgid-Bugs-To: email@example.com
POT-Creation-Date: +0200
PO-Revision-Date: +0200
Last-Translator: JohnnyKing
Language-Team: JohnnyKing
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
X-Generator: csv2xliff.sh
</target>
      </trans-unit>
EOF

Indentation

The indentation here is odd:

echo "X-Generator: csv2xliff.sh"
echo "</target>"
echo "      </trans-unit>"

    COUNTER=1

        while [  "$COUNTER" -le "$TOT_STRING" ]; do

        ROW_ID=$(sed -n $(( $COUNTER ))p $FILE_ID)
        ROW_SOURCE=$(sed -n $(( COUNTER ))p $FILE_SOURCE)
        ROW_TARGET=$(sed -n $(( COUNTER ))p $FILE_TARGET)

        if [ "$ROW_SOURCE" = "$ROW_TARGET" ]; then
            echo "      <trans-unit xml:space=\"preserve\" id=\"$ROW_ID\">"
            echo "        <source>$(echo $ROW_SOURCE | sed 's/</\&lt;/g' | sed 's/>/\&gt;/g')</source>"
            echo "        <target></target>"
            echo "      </trans-unit>"
        else
            echo "      <trans-unit xml:space=\"preserve\" id=\"$ROW_ID\" approved=\"yes\">"
            echo "        <source>$(echo $ROW_SOURCE | sed 's/</\&lt;/g' | sed 's/>/\&gt;/g')</source>"
            echo "        <target state=\"translated\">$(echo $ROW_TARGET | sed 's/</\&lt;/g' | sed 's/>/\&gt;/g')</target>"
            echo "      </trans-unit>"
        fi

        COUNTER=$(( $COUNTER + 1 ))
        done

echo "       </trans-unit>"
echo "    </body>"
echo "  </file>"
echo "</xliff>"

It would be more natural this way:

echo "X-Generator: csv2xliff.sh"
echo "</target>"
echo "      </trans-unit>"

COUNTER=1

while [  "$COUNTER" -le "$TOT_STRING" ]; do
    ROW_ID=$(sed -n $(( $COUNTER ))p $FILE_ID)
    ROW_SOURCE=$(sed -n $(( COUNTER ))p $FILE_SOURCE)
    ROW_TARGET=$(sed -n $(( COUNTER ))p $FILE_TARGET)

    if [ "$ROW_SOURCE" = "$ROW_TARGET" ]; then
        echo "      <trans-unit xml:space=\"preserve\" id=\"$ROW_ID\">"
        echo "        <source>$(echo $ROW_SOURCE | sed 's/</\&lt;/g' | sed 's/>/\&gt;/g')</source>"
        echo "        <target></target>"
        echo "      </trans-unit>"
    else
        echo "      <trans-unit xml:space=\"preserve\" id=\"$ROW_ID\" approved=\"yes\">"
        echo "        <source>$(echo $ROW_SOURCE | sed 's/</\&lt;/g' | sed 's/>/\&gt;/g')</source>"
        echo "        <target state=\"translated\">$(echo $ROW_TARGET | sed 's/</\&lt;/g' | sed 's/>/\&gt;/g')</target>"
        echo "      </trans-unit>"
    fi

    COUNTER=$(( $COUNTER + 1 ))
done

echo "       </trans-unit>"
echo "    </body>"
echo "  </file>"
echo "</xliff>"