Processing player's move in an ASCII rogue-like game

point playerPos = player.get_position();
point moveTilePos;

moveTilePos.setX(playerPos.getX());
moveTilePos.setY(playerPos.getY()-1);
processPlayerMove(player, moveTilePos);

Well, of course you shouldn't do that. Declaring an "uninitialized" variable to be initialized later via mutation is one of the cardinal sins of modern C++ programming. One reasonable way to write this code would be

point playerPos = player.get_position();
processPlayerMove(
    Point(playerPos.getX(), playerPos.getY() - 1)
);

But if you find yourself writing Point(p.getX(), p.getY()-1) often enough, then you should factor it out into a function:

point playerPos = player.get_position();
processPlayerMove(playerPos.upward(1));

And then you can eliminate that pesky helper variable:

processPlayerMove(player.get_position().upward(1));

There, that looks clean enough!

Next, look at your switch statement and refactor it to be clearer.

switch (input) {
    case MOVE_UP:
        processPlayerMove(player.get_position().upward(1));
        break;
    case MOVE_DOWN:
        processPlayerMove(player.get_position().downward(1));
        break;
    case MOVE_LEFT:
        processPlayerMove(player.get_position().leftward(1));
        break;
    case MOVE_RIGHT:
        processPlayerMove(player.get_position().rightward(1));
        break;
}

Can you think of a similar way to simplify this code? What would it look like?


Mocking pathlib.Path I/O methods in a maintainable way which tests functionality not implementation

Mocking system calls, especially those with side effects (mkdir()), is difficult and error prone.

I would rather use a temporary directory for test purposes. This approach has the added advantage of really testing your FS manipluation code.

import datetime
import os
import pathlib

from contextlib import contextmanager
from tempfile import TemporaryDirectory

@contextmanager
def temporary_test_dir():
    oldpwd = os.getcwd()
    with TemporaryDirectory("test-path") as td:
        try:
            os.chdir(td)
            yield
        finally:
            os.chdir(oldpwd)

def get(base, timestamp, channel):
    base = pathlib.Path(base)
    path = base / "tofu" / timestamp.strftime("%Y%m%d") / f"{channel:>02d}" / "quinoa.txt"
    if path.exists():
        print(path, "exists")
    else:
        path.parent.mkdir(exist_ok=True, parents=True)
    return path

@temporary_test_dir()
def test_get():
    # All relative FS operations will be made in a temporary directory
    result = get("quorn", datetime.datetime.now(), 42)
    assert result.parent.exists()

I'm not sure what is the point of the tested function, but it doesn't matter for this example's sake.

If you really need to mock the filesystem part, I would suggest using an existing library such as pyfakefs, although I have never had such a need.


try-with-resources

Since Java 7, you can use try-with-resources for safe and efficient handling of the underlying I/O resource.

return boolean

if (condition) {
    return true;
} else {
    return false;
}

This kind of code can be simplified as return condition.

Method names

Your naming can be better refined to reflect what they are doing. For example, getStatus can be renamed as hasUniqueNumerals, following the standard is/has prefix for methods returning a boolean. winningLotteryTicket can be renamed as countWinningPairs.

for-each loop

Your loop on c.toCharArray() can also be written as:

for (char current : c.toCharArray()) {
    charSet.add(current);
}

What's nice

You checked if the concatenation of the two inputs will give you 10 or more digits, returning false first if not.
You declared charSet as a Set rather than a HashSet and relied on generic type inference.


Why aren't using mongoose .populate() method instead?

Refer to the Mongoose documentation for Population here


Converting domain-specific regular-expressions to a list of all matching instances

1. Review

This is clear, well-documented code.
The doctests all call binf_motifs_to_sequences but your function is named shorthand_to_instances so all the doctests fail.
There's no need to have this kind of infrastructure for running doctests:

if __name__ == "__main__":
    import doctest
    doctest.testmod()

since you can easily run doctests from the command line using Python's -m option:

python -m doctest mymodule.py

Assertions should be used for programming errors (conditions that you believe can't happen), but this assertion:

assert char in alphabet+'['+']'+'{'+'}'+'x'

is really a runtime error (it might happen if bad data was passed to the function), so it would be better to raise an exception.
A given shorthand can have exponentially many matching sequences. For example, xxxx already has 256 matching sequences over a four-character alphabet. For this reason, I would avoid returning a list of matching sequences, as this requires building a list and storing all the sequences in memory. It would be better to generate the sequences one at a time.

2. Simplifying

The way to make this kind of code simpler is to use functional decomposition to divide it into pieces that are simpler to understand, implement, and test.

A sensible division into two pieces would be to first, parse the shorthand notation, producing some kind of data structure; and second, take the data structure and generate the matching sequences. Since the alphabet is likely to be small, the natural data structure to use is just a sequence of strings giving the characters that match at each position. So given the shorthand xT[AG]{AT} over the alphabet ACGT, the intermediate data would be the sequence ['ACGT', 'T', 'AG', 'CG'].

(If alphabets were expected to be much larger, then this might be somewhat wasteful in space, and so there might be a need to have a more sophisticated data structure here.)

I've called the first step "parsing" but really it's so simple that it's just lexical analysis and in Python this can be done simply by writing a regular expression that matches a token, and calling re.finditer to loop over the tokens:

import re

class ParseError(Exception): pass

def shorthand_parse(shorthand, alphabet):
    """Parse bioinformatics shorthand notation and generate strings giving
    the characters in alphabet that are allowed to match at each
    position in the sequence.

    Square brackets means "it could be any of these letters" in this
    location. Curly braces means "it's *not* one of these letters" in
    this location (it can be any letter in the given alphabet except
    these). Lowercase "x" means it could be any of the letters in the
    given alphabet.

    >>> list(shorthand_parse('xT[AG]{AT}', 'ACGT'))
    ['ACGT', 'T', 'AG', 'CG']

    """
    # Use set() to remove duplicates, and sorted() to ensure that the
    # output is in a canonical order (for predictability and testing).
    alphabet = set(alphabet)
    alphabet_str = ''.join(sorted(alphabet))
    shorthand_re = r'''(x)             # Any character in alphabet
                      |([{0}])         # Single character
                      |\[([{0}]*)\]    # One of these characters
                      |{{([{0}]*)}}    # Not one of these characters
                      |(.)             # Anything else is an error
                    '''.format(alphabet_str)
    for m in re.finditer(shorthand_re, shorthand, re.VERBOSE):
        x, single, oneof, noneof, error = m.groups()
        if x:
            yield alphabet_str
        elif single:
            yield single
        elif oneof:
            yield ''.join(sorted(set(oneof)))
        elif noneof:
            yield ''.join(sorted(alphabet - set(noneof)))
        else:
            raise ParseError("unexpected character '{}'".format(error))

Now that we have the strings of characters that are valid at each position, we want the Cartesian product of those strings. This can be computed by itertools.product, and in fact the output of shorthand_parse is already in the right format for input to that function:

import itertools

def shorthand_sequences(shorthand, alphabet):
    """Generate all sequences matching the given bioinformatics shorthand
    notation over the given alphabet.

    >>> list(shorthand_sequences('T[AG]', 'AGCT'))
    ['TA', 'TG']
    >>> list(shorthand_sequences('T{A}T', 'AGCT'))
    ['TCT', 'TGT', 'TTT']
    >>> list(shorthand_sequences('G{AGC}AGTC', 'AGCT'))
    ['GTAGTC']
    >>> list(shorthand_sequences('xGTC', 'AGCT'))
    ['AGTC', 'CGTC', 'GGTC', 'TGTC']
    >>> list(shorthand_sequences('[AG]{AT}[CG]', 'AGCT'))
    ['ACC', 'ACG', 'AGC', 'AGG', 'GCC', 'GCG', 'GGC', 'GGG']

    """
    for seq in itertools.product(*shorthand_parse(shorthand, alphabet)):
        yield ''.join(seq)


Use the built in Counter in the collections module:

>>> from collections import Counter
>>> Counter('qwertyqweryyyy')
Counter({'y': 5, 'e': 2, 'q': 2, 'r': 2, 'w': 2, 't': 1})


I think I would make a state object and a user object to represent this delema.

We will make a user class to encapsulate working with the user api

var User = function(sessionStorage, authService){
    var self = this,
       userInfo = buildUserInfo(sessionStorage["userInfo"]);

    self.isAuthentic = function(cb){
       if(!hasActiveLogin) return;

          //THIS is where the "doesn't work" part of your code is
          //this service looks to be an async service. and you are using it in a synced way
       authService.isAuthentic(userInfo._id).then(function(d){
           userInfo.isAuthenticated = d.data == "true";
           cb(d);
       });
    }

    self.hasActiveLogin = function(){
        var valid = userInfo != null;
            valid = valid && userInfo._id;
        return valid;
    }

    self.isAuthenticated = function(){
       return self.hasActiveLogin() && userInfo.isAuthenticated;
    }

    self.getUserInfo = function(){
       userInfo;
    }

    self.clearUserInfo = function(){
        sessionStorage["userInfo"] = null;
    }

    function buildUserInfo(userInfoData){
       return userInfoData ? JSON.parse(userInfoData) : null;
    }

};

now the root scope can simply handle that user

This implementation is not perfect... but it does show how to use javascript to encapsulate these kinds of issues into manageable objects.

$rootScope.$on('$stateChangeStart', function(event, toState){

     if(!_.has(toState.data, 'requireLogin')) return;

     var user = new User($window.sessionStorage,

    if(!user.hasActiveLogin()){
       event.preventDefault();
       $state.go('login');
    }

    //im not exactly sure how the service works so this peice of encapsulation
    // may be over kill
    if(user.isAuthenticThen(function(d)){
       if(!user.isAuthenticated()){
          user.clearUserInfo();
          event.preventDefault();
          $state.go('login');
       }

       $rootScope.userInfo = user.getUserInfo();
       $rootScope.userAuth = user.getUserInfo().isAuthenticated || false;
    }
});


How to dynamically Generate Sort strings for Data Layer from Controller

The data layer that appears to be causing your problem is the root cause.

You're abstracting over an abstraction, and in the process having to marshall sort orders around as a result. Prefer injecting your context in a request scope and remove the abstraction.

You can always create an abstraction over the specific query, and inject the query, which has a dependency on the context, if you really need to.


Is it ok to pull out specific arguments from a Java dynamic proxy invocation?

Casting is never 'pretty'.... But, in a proxy situation like this (assuming you really need the proxy), it is possibly unavoidable.

I can recommend though that you do it defensively... you should really do:

if (args.length > 0) {
    if (args[0] instanceof Token) {
        System.out.println("Token with id: "+((Token)args[0]).getId()+ " was passed");
    } else {
        System.out.println("Proxy for a method which does not have an initial token: " + args[0]);
    }
} else {
    System.out.println("Proxy for a method that is being passed no arguments.");
}

If your situation requires that these values are populated, then you should throw exceptions instead of the other println methods.

Also, you should consider checking that the number of arguments in the args matches the number of arguments expected in method.getParameterTypes(), but with var-args, that can be hard.

Additionally, this line:

throw new RuntimeException("unexpected invocation exception: " + e.getMessage());

Should incorporate the actual cause.... when you get an exception through this catch block, it will be one of those times when the cause is critical, and you are throwing the cause away! That exception should look like:

throw new RuntimeException("unexpected invocation exception: " + e.getMessage(), e);


c# Factory Pattern Generic Exception Handler using dot net core

Well, AddLogForException isn't doing anything with it's parameters, perhaps make it virtual or do something with them?

You could also add a rule engine stating if a exception is registered with a specific action then do that, else do default.

Your registration could be a dictionary or thread safe dictionary or dictionary

say your class would have a backing field like this:

Dictionary<exception, Action<Exception,IHttpContextAccessor,string>> dict = new Dictionary<exception, Action<Exception,IHttpContextAccessor,string>>();

and you can register items like this

public void Register(Exception ex, Action<Exception,IHttpContextAccessor,string> del)
{
   lock(this)
   {
      dict.Add(ex, del);
   }
}

public override AddLogForException<T>(
        T exception,
        IHttpContextAccessor httpContext,
        string description)
        where T : Exception
    {

       if(dict.TryGetValue(exception, out var delegate)
       {
           delegate.DynamicInvoke(new object[]{exception,httpContext,description});
       }
       else
           base.AddLogForException(exception,httpContext,description)
    }

This registration is similat to a swich statement only this is a way to manage the options in the consuming project and leaves room for updates as you go on a and adapt it on a case by case as long as your exceptions are granular enough that you can add a "rule" on them.

I have no access to VS now but I guess it will compile just fine. if you have an issue just send me comment and I will have a look for you.


function FormatToolTip() {
    "use strict";

    amplify.request.define("listTooltips", "ajax", {
        url: "resources/prototype/tooltips.json",
        dataType: "json",
        type: "GET"
    });

    amplify.request({
        resourceId: "listTooltips",
        success: function (data) {
            amplify.store('tooltips', data.toolTips);
        }
    });

    // Get the tooltip from storage, given it's id
    this.buildToolTip = function (id) {
        var tips = amplify.store('tooltips');
        for (var i = 0, len = tips.length; i < len; i++) {
            var val = tips[i];
            if (id == val.id) {
                return val.text;
            }
        }

        // This doesn't appear to be used?
        //return amplify.store(this.ToolTipId);
    };

    // Don't think this is used either
    /*
    this.setToolTipId = function (toolTipId) {
        if (toolTipId != undefined || toolTipId != null) {
            amplify.store(this.ToolTipId, toolTipId);
        }
    };
    */
}

Just use a data attribute in your markup:

And initialize like so:

* Untested


Replacing if validations with a better error handling

It looks as if you have two things going on: detecting the error, and reporting the error.  You have a lot of different error handling; is there a way to abstract this down into a message?  Maybe a pair of functions, one of which abstract all of these errors down to a single, page-side error code, and the other of which presents a textual version of that.  Or something that returns a tuple.

In the meantime, I've broken it down into "something went wrong" and "what kind of wrongness happened" blocks.

The one thing that stands out at me is you have two different return types: whatever is returned from the function classes(), and the undefined at the end of the function on success.  By putting the error handler's return on its own line, I've made sure that js-hint and js-lint won't complain about inconsistent return types.

(function (err, res) {
    if ((err) || (res.status == 401) || (!res.ok) || (res.body && res.body.error)) {
        classes(targetElement).remove('selected');
        if (err || (res.body && res.body.error) || (!res.ok)) {
            log("Fetch error: ", (err || res.error || (res.body && res.body.error)));
        }
        if (res.status == 401) {
            errorContainer.innerHTML = t(res.body.error);
        }
        return;
    }
    log('successfull upvote %s', self.comment.id);
});


This is one of the cleanest code I have come across in a while. Congrats to your lovely, well-written code!

Just some points:

I don't like seeing this:

public class Ticker {
    private long lastTick;
    // ...
    }
}

It is more readable (IMO) when you put spaces after the beginning and before the end:

public class Ticker {

    private long lastTick;
    // ...
    }

}

I don't see a reason why not to do so, as the rest of your code is very well spaced.
This method:

public boolean update() {
    long currentTime = System.currentTimeMillis();

    if (currentTime >= nextTick) {
        long targetTimeDelta = 1000L / tickRate;

        if (lastTick == 0 || nextTick == 0) {
            lastTick = currentTime - targetTimeDelta;
            nextTick = currentTime;
        }

        float deltaTime = (float) (currentTime - lastTick) / targetTimeDelta;

        for (TickListener listener : tickListeners) {
            listener.onTick(deltaTime);
        }

        lastTick = currentTime;
        nextTick = currentTime + targetTimeDelta;

        return true;
    }

    return false;
}

Just my opinion, but I feel uncomfortable with that many spaces in code. The only place I would use spaces would be:

Between Node declarations in JavaFX, or JWhatever declarations in Swing.
Where there is an obvious change in what the code will do.

So it would be more like:

public boolean update() {
    long currentTime = System.currentTimeMillis();
    if (currentTime >= nextTick) {
        long targetTimeDelta = 1000L / tickRate;
        if (lastTick == 0 || nextTick == 0) {
            lastTick = currentTime - targetTimeDelta;
            nextTick = currentTime;
        }

        float deltaTime = (float) (currentTime - lastTick) / targetTimeDelta;
        for (TickListener listener : tickListeners) {
            listener.onTick(deltaTime);
        }

        lastTick = currentTime;
        nextTick = currentTime + targetTimeDelta;
        return true;
    }
    return false;
}


Comments:

about all of your comments add close to no value to your code.

//get random number from 0 to new range of unshuffled deck
int randomDraw = r.Next(0, initial.Count);

Your comment just writes out, what your code does in the next line. This is unneccesary noise and you should not do it. The probably only acceptable comment is this one:

for (int i = 2; i <= 14; i++) //2-ace(14)

This exactly explains why you start on 2 and end with 14, the rest can be removed.

But as @Marc-Andre pointed out correctly, this comment also becomes pure noise, as soon as you extract these magic numbers to named constants:

const int LOWEST_CARD = 2;
const int HIGHEST_CARD = 14;
for (int i = LOWEST_CARD; i <= HIGHEST_CARD; i++)

Extracting methods:

Why not extract your whole shuffle algorithm to a method? This makes the code in your startDeck less cluttered. Example:

public static List<int> startDeck(int numDecks)
{
    List<int> initial = new List<int>();

    prepareDeck();

    return shuffled(initial);
}

You now exactly know, what your startDeck does.

Naming:

Your class Cards. this is definitely not nice, but that name is not OK. What does your class do? Name it after that. Try to keep your classes in SRP, they only should do one thing and nothing more.

Deck might have been better depending on what it does apart from what you posted.
Alternatively use Shuffler, Helper or similar.

Algorithm:

The english wikipedia article on the Fischer-Yates algorithm gives pretty nice pseudocode and tells us, that the algorithm is an in-place algorithm.
This means you will not need a second list to put your shuffled cards in.

//To shuffle an array a of n elements (indices 0..n-1):
for i from n − 1 downto 1 do
      j ← random integer with 0 ≤ j ≤ i
      exchange a[j] and a[i]

this means, if you were strictly following the algorithm your code should look (something) like this:

int temp, randomNumber;
int count = initial.Count;
for (int index = count -1; index > 0; index--){
   randomNumber = r.Next(0, index+1);
   temp = initial [index];
   initial[index] = initial[randomNumber];
   initial[randomNumber] = temp;
}
return initial;


Entering address details into Google Maps geocoder

The main change I would make is to reduce the responsibility of codeAddress() to do just the geocoding.  If it successfully looks up the address, then it can pass the location to a callback.

I don't have enough context to tell whether geocoder, map, and marker are global variables, or whether all of this code lies inside some other scope.  Out of habit, I've converted them into local variables.  You decide whether that's right for you.  The point variables in your drag handlers should definitely be made local, though!

function initialize() {
    var geocoder = new google.maps.Geocoder();
    var map = new google.maps.Map(document.getElementById('map-canvas'));

    var marker = new google.maps.Marker({
        map: map,
        position: map.getCenter(),
        draggable: true
    });

    google.maps.event.addListener(marker, 'dragend', function() {
        var point = marker.getPosition();
        map.panTo(point);
        showCoords(point);
    });

    google.maps.event.addListener(map, 'dragend', function() {
        var point = marker.getPosition();
        marker.setPosition(map.getCenter());
        showCoords(point);
    });

    var address = document.getElementById('address').value;

    codeAddress(geocoder, address, function(location) {
        map.setCenter(results[0].geometry.location);
        map.setZoom(15);
        marker.setPosition(map.getCenter());
        showCoords();
    });
}

function codeAddress(geocoder, address, callback) {
    geocoder.geocode({'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            callback(results[0].geometry.location);
        } else {
            alert('Geocode was not successful for the following reason: ' + status)
        }
    });
}


Your code is safe as far as I can tell. You may consider adding some additional levels of spam checking though to stop invalid requests sooner.

Use a token generated by your server when the form renders, pass that to php-file.php to check when processing the submission, if it isn't in your token list, it didn't come from your server. These tokens should only be used once before they are discarded. It will help you stop Cross Site Request Forgery attempts. It would mean having a storage medium to keep track of the tokens though, so it adds a little bit of overhead to the process.
Honeypot field(s). These are just input fields that you hide with CSS so that a normal user would not fill them in. If they have a value when you process your script you should stop execution.


Find articulation points/ cut vertices in graph

PEP-8
class vertex:
class graph:

PEP-8 asks that you name these Vertex and Graph, with initial capital.
naming nodes
    self.key = key

Yes, you will be using this as a dict key.
But name would have been the more natural identifier for a node name.
unused attribute
Please delete this line:
    self.nbnodes = 0

That quantity may be trivially obtained with len(self.root),
and in any event you never reference it.
edge weight
At first blush this appears to be a default edge ID of zero:
def add(self, key1, key2, edge=0):

Later it looks more like an edge weight, an attribute of the edge.
It would be helpful for a docstring to clarify this.
Or just name it edge_weight.
API
Consider having cutver() print nothing,
and instead return a result which the caller may print.
Also, _cutver() feels a lot like a Fortran subroutine,
as it has side effects on the result parameter,
rather than returning a result.
sentinel
You use this:
      parent[vertex] = -1

without every verifying that a node name is not -1,
or constraining each node name to be a str.
The usual convention would be to use None to represent this.
docstring
    self.curr = 0

This is absolutely not self-descriptive enough.
Use a """docstring""" or # comment to tell us what quantity it is measuring.
reference
In general _cutver() is obscure,
which increases the difficulty of answering your two questions.
It cites no references and does not attempt to justify
any of its algorithmic steps.
Perhaps it correctly finds cut vertices,
but the text does not give us any reason to see why that is obviously true.
If the code tries to adhere to Hopcroft73 (with Tarjan, algorithm 447),
then choosing to omit identifiers like lowpoint
is not helping the reader to see how the current implementation
corresponds to what Hopcroft describes.


No, it is not. The reason is that list comprehensions are in general as fast as or faster than the explicit loop, because they might be performed in C, while the explicit loop will always execute in Python. Also, the set constructor already takes care of the i not in setList part and you need to traverse the whole list anyways.

Here is a shorter one-liner:

numbers = list(set(map(int, input().split())))

I used map instead of a list comprehension, but you could also use a generator expression:

numbers = list(set(int(i) for i in input().split()))

Note that str.split by default splits on whitespace, so there is no need to specify split(' '), unless you want a different result for strings like 100\n200(newline) or 100  200 (double space).

As a timing comparisons, here are the four proposals as functions taking an input string and returning the desired list:

def op1(s):
    nums = s.split(' ')
    return list(set([int(i) for i in nums]))

def op2(s):
    nums = s.split(' ')
    setList = set()
    myList = []
    for i in nums:
        if int(i) not in setList:
            myList.append(int(i))
            setList.add(int(i))
    return myList

def graipher1(s):
    return list(set(map(int, s.split())))

def graipher2(s):
    return list(set(int(i) for i in s.split()))

And this is how I generated a bunch of random inputs of increasing size:

import random
inputs = [" ".join(map(str, [random.randrange(1000) for _ in range(i)])) for i in range(1, 2000, 50)]

With this, I ran the four functions to get this timing graph as a function of the number of numbers in the input:

Note that your first function performs almost as good as a straight set comprehension. Your alternative proposal is always the worst of all possibilities. The version with map is the fastest of the approaches I tried.

(Note that my timings were done using Python 2.7, so your mileage may vary, but I am confident that your second proposal will still loose.)


Get all possible subsets from a set of distinct integers using OOP

I. This chunk of code:

a = []
n = int(input("Enter number of elements of list: "))
for i in range(0,n):
    b = int(input("Enter element: "))
    a.append(b)

is mostly C-like (or Pascal-like etc). You can replace it with more Pythonic:

a = input('Enter elements splitted by ":" ').split(' ')

II. Here:

print (sub().f1(a))

You are creating a sub instance within the print function. It is a bad idea because it will disappear after print. You should create it before you print something (and, yes, classes names in Python are in CamelCase):

waka = Sub()
print(waka.f1(a))

III. I prefer to create __init__() function each time I create a class. It is not really necessary but in most cases, it is the first one is creating in the new class:

class Sub(object):
    def __init__(self):
        pass

IV. If it is your homework you should do with recursion, the code is pretty OK. In another case, I recommend you to use Python itertools module (you should avoid recursion as much as possible):

    def f2(self, current, s1):
        return [
            e
            for e in itertools.chain.from_iterable([
                [sorted(l) for l in itertools.combinations(s1, length)]
                for length in range(1, len(s1))
            ])
        ]

So here is the result code for recursion version:

class Sub(object):
    def __init__(self):
        pass

    def f1(self, s1):
        return self.f2([], sorted(s1))

    def f2(self, current, s1):
        if s1:
            return self.f2(current, s1[1:]) + self.f2(current + [s1[0]], s1[1:])
        return [current]

a = input('Enter elements splitted by " ": ').split(' ')
waka = Sub()
print(waka.f1(a))


Lock-free multi-producer multi-consumer queue

Missing barrier
When I looked at your code, I could immediately tell there was something wrong because you use a release barrier without an acquire barrier that pairs with it.
You have this barrier in try_enqueue() between writing to m_data and writing to m_tail_2:

std::atomic_thread_fence( std::memory_order_release );

But you don't have any corresponding acquire barrier in try_dequeue() between reading from m_tail_2 and reading from m_data.  You should put in a barrier like this:
bool try_dequeue( T& out )
{
    // ...

    // Add this barrier which pairs with the other release barrier
    std::atomic_thread_fence( std::memory_order_acquire );

    out = m_data[head % m_size];

    // ...
}

Without this barrier, the cpu could read m_data[head] speculatively before the read of m_tail_2, and you could end up getting an older value instead of the value just written.
Sequence of events that lead to error

Initially, m_data[0] = 0
Cpu 1: try_enqueue(): m_data[0] = 5
Cpu 1: try_enqueue(): fence(release)
Cpu 1: try_enqueue(): m_tail_2 = 1
Cpu 2: try_dequeue(): reads m_tail_2 as 1
Cpu 2: try_dequeue(): exchange(head, head+1) (no effect)
Cpu 2: try_dequeue(): reads m_data[0] as 0

Due to weak memory ordering, on step 7 above, m_data[0] can be read as 0 instead of 5 because there was no acquire barrier between steps 5 and 7.  The strong exchange on step 6 did not perform a barrier because it was called with std::memory_order_relaxed, std::memory_order_relaxed as the memory ordering.
Note that there are 2 possible ways that memory accesses can be "reordered".  The first is that the compiler might shift lines of code around, and therefore, your accesses are actually performed out of order with respect to a program execution timeline.  This is not what is happening in my example above.  The second way is that the memory system may reorder accesses.  In other words, even if two reads occur one after the other in the program execution timeline, the second read may read an earlier value than the first read.  This second case is what causes step 7 above to fail.
Possible missing barrier
Similarly, you might need an acquire barrier in try_enqueue() before your write to m_data, which pairs with the release barrier in try_dequeue().  I say "might" because this one is harder to explain.  The barrier is only needed if the cpu would do a speculative write to m_data before reading m_head_2.  But because m_head_2 is used to determine whether or not to actually write to m_data, there is a data dependency there which would seem to guarantee that m_head_2 is read before writing to m_data.  However, there are processors such as the DEC Alpha which have strange behavior with respect to data dependencies.  So I'm not 100% sure about whether this barrier is needed, and if it is needed, it may only be needed for DEC Alpha and similar processors.


Calculator with multiple inputs to add up

Your x function has a few notable things:

x is a very poor name. It doesn't give any hints as to what the function is supposed to do. The name of your function should let the reader of your code know what its purpose is. Something like get_user_input would be much better.

You're associating data with the function object itself; essentially creating static variables. This is not a good idea though. This means that this function can only be called once before you overwrite the previous entered data. In your case here, that may not be a big deal, but it is not a good habit to get into. This will significantly complicate code later when you have functions that you're calling in multiple places in your code. Return the results instead.

You're having the user enter a confirmation, but then you're checking that they match outside of the function. Just check inside the function and loop until they match.

After fixing up those points, I have:
def get_user_input():
    while True:
        n_numbers = int(input("Type how many numbers you would like to add up: "))
        confirmation = int(input("Please confirm by typing the same number: "))

        if n_numbers == confirmation:
            return n_numbers
        else:
            print("The numbers were not the same.")

They you can get rid of the else case at the bottom of your code. You'd then use this function like:
n_numbers = get_user_input()

And use n_numbers instead of x.x.

You don't do any error handling anywhere. I find it odd that in your code, you require confirmation to ensure the user didn't typo the number they entered, but you aren't protecting against them typing in nonsensical input (like hello). If the user types a non-number, you'll get a ValueError that will crash your program. You may want to consider wrapping calls to int and float in a try/except to ensure that your program won't crash.

This loop:
nums = []
while i != n_numbers:
    INTnum = float(input("Write the numbers to be added up: "))
    nums.append(INTnum)
    i+=1

Can be cleaned up by using a range:
nums = []
for _ in range(n_numbers):
    INTnum = float(input("Write the numbers to be added up: "))
    nums.append(INTnum)

Now you don't need to manually handle i. This can be further cleaned up by using a list comprehension:
nums = [float(input("Write the numbers to be added up: "))
        for _ in range(n_numbers)]

Whenever you find yourself manually handling loop indices like you were with i, there's likely a better way that handles the looping for you.
The same can be said for this loop:
while index != len(nums):
    num = nums[index]
    ans = ans + num
    index+=1

Note how you never need index except to access nums. Just loop over nums directly:
for num in nums:
    ans += num  # The same as "ans = ans + num"

If you need to loop over a list, just loop over the list directly.
Really though, that's just sum:
ans = sum(nums)

Your comments aren't a good use of commenting. A lot of them are simply restating what the code itself says:
#the ans veriable is eqal to itself + the number that was recorded from the idex
ans = ans + num

. . .

#creating new veriables for the next loop
index = 0

If something is already self-explanatory, don't simply restate that in a comment. Your code reads like you're under the impression that every line of code requires a comment, but this isn't true. Ideally, your code itself should be all the explanation the reader needs, but if more explanation is required, note why the code is unreadable or why it's behaving as it is. When half your code is comments that just restate the code, it detracts from the important part: the code.


Dijkstra finding shortest path satisfying given constraints

This is an interesting problem. You hacked Dijsktra's algorithm to make it solve the problem, but this hack has a cost. In Dijkstra's classical algorithm:

you stop once all nodes have been visited;
you start an iteration with the best (shortest) candidate path.

In your version:

you stop once you reach your destination and you have a full basket of fishes;
same start for iterations.

Basically, you walk until your basket is full and then you rush to the end store. The BFS selection ensure you that you get the effective shortest path (good point: your algorithm is correct).

Of course, without the Dijkstra's stop condition, your algorithm is not O(n lg n) anymore.

Consider the following graph for instance:

A -- B --...-- C

The cost_matrix is:

cost_matrix =  [[0, 1, 0],
                [1, 0, 999],
                [0, 999, 0]]

If you look for a path from 1 to 3, your function will play ping-pong between 1 and 2 until the distance reaches 999 and then consider 3.

A bit of theory now. Take the following instance of your problem: every store (node) has only one type of fish, and two stores do not have the same type of fish. You want a basket filled with all existing types of fish. That means: you have to visit each store at least once. This is a variation of the Travelling Salesman problem because you are allowed to visit every store mutliple times, but the complexity is the same (see https://math.stackexchange.com/questions/1269983/traveling-salesman-problem-why-visit-each-city-only-once and https://en.wikipedia.org/wiki/Travelling_salesman_problem#Computational_complexity).

Hence, I think you won't find any easy answer. It seems to me that your best choice, if you want to improve efficiency, is to "branch and bound".


Computing the difference of the cross-totals of the diagonals of a matrix

How well/bad is this code written?

A good first timer implementation.

  Is the code abstract enough?

Mostly. It does make unnecessary assumptions about range.  It assumes int math does not overflow.

To make more abstract, code could use typedef int TVS_int; to ease future type changes.

  How can you solve such challenges more quickly?

Take advantage that the matrix is square.

With computing along the diagonal of a square matrix, only the matrix and its one size parameter are needed.

Use const to hint the the compiler about certain potential optimizations and convey code's intent better.

size_t is the best size of array indexing, not too wide nor too narrow.

I like the idea of using a wider intermediate type to mitigate overflow problems.

typedef int TVS_int;
typedef long long TVS_int2;  // a type with wider range.

TVS_int diagonalDifference_alt(const TVS_int** arr, size_t n) {
  TVS_int2 sum_up = 0;
  TVS_int2 sum_dn = 0;

  for (size_t i = 0; i<n; i++) {
    // Notice both `arr` use the same `arr[i]` --> potentially easier to optimize
    sum_up += arr[i][n-i-1];
    sum_dn += arr[i][i];
  }
  TVS_int2 diff = sum_up - sum_dn;
  return (TVS_int) ((diff < 0) ? -diff : diff);  // OF possible here in range reduction
}

if(left_to_right - right_to_left > 0) unnecessarily incurs the potential for int overflow.  Simply compare instead.  if (left_to_right > right_to_left)


Sorting an ArrayList of Vehicles using quick sort

In method 1 the sorted list you create here:

ArrayList<Vehicle> sorted = new ArrayList<Vehicle>();

is never used and overwritten here:

sorted = lesser;

Just drop the variable sorted and return lesser.

There is no reason to limit the method to ArrayLists or even Vehicles. Just have Vehicle implement the standard Comparableinterface and let your method have the signature:

protected <T extends Comparable<T>> List<T> quickSort(List<T> list) {
  // ...
}


Comparing information to a directory of active enployees

This is the sample dataset I created.  The OP's code suggests that the Active Directory tab has an extra row.

Always Use Worksheets CodeNames Whenever Possible

Referencing worksheets by their code names will avoid naming conflicts while working with multiple workbooks and changing the worksheet name will not break any code.

Sheets("Active Directory") -> wsActiveDirectory
Sheets("Dump")-> wsDump
Sheets("Output") -> wsOutput

Use Constants for Magic Numbers

Using constants for values that should only be set once will make your code easier to read and maintain.  Constants will also throw an error if you try to change their values.

Before

startRow = 5
outputRow = 5

After

Const startRow As Long = 5, outputRow As Long = 5

Matching Lists

Dictionaries are optimised for fast lookups.  Using a Scripting.Dictionary will match the values will easily make the code run 100 times faster.

The trick is to create a composite key for all fields. Note: make sure to use a delimiter.

  1;Towney;Research and Development

Private Function getKey(ByVal rowIndex As Long, ByRef Target As Range) As String
    getKey = Target.Cells(rowIndex, 1) & ";" & Target.Cells(rowIndex, 2) & ";" & Target.Cells(rowIndex, 3)
End Function

SQL Solution

As Ryan Wildry stated "Using SQL is great for these type of set based comparisons." but this can be a little tricky.  The way I did it is I pasted my datasets into an Access Database as tables and use the Query Designer to help me write the code.

SELECT Dump.ID, Dump.Name, Dump.Department, "Item found in ""Dump"" but not in ""Active Directory""" AS [Found]
FROM Dump
WHERE (((Exists (SELECT NULL
  FROM [Active Directory]
  WHERE ([Active Directory].ID = Dump.ID) AND ([Active Directory].Name = Dump.Name) AND ([Active Directory].Department = Dump.Department)
))=False));
UNION ALL SELECT [Active Directory].ID, [Active Directory].Name, [Active Directory].Department, "Item found in ""Active Directory"" but not in ""[Active Directory]""" AS [Found]
FROM [Active Directory]
WHERE (((Exists (SELECT NULL
  FROM [Dump]
  WHERE ([Active Directory].ID = Dump.ID) AND ([Active Directory].Name = Dump.Name) AND ([Active Directory].Department = Dump.Department)
))=False));

I then aliased the tables to make it easier to replace the table names with the Excel Table Definition.

 SELECT t1.Name, t1.ID,  t1.Department, 'Item found in "Dump" but not in "Active Directory"' AS [Found]
 FROM [Dump$B4:E23] As t1
 WHERE (((Exists (SELECT NULL
   FROM [Active Directory] As t2
   WHERE (t2.ID = t1.ID) And (t2.Name = t1.Name) And (t2.Department = t1.Department)
 ))=False))
 UNION ALL
 SELECT t1.Name, t1.ID,  t1.Department, 'Item found in "Active Directory" but not in "Dump"' AS [Found]
 FROM [Active Directory$B4:E20] As t1
 WHERE (((Exists (SELECT NULL
   FROM [Dump] As t2
   WHERE (t2.ID = t1.ID) And (t2.Name = t1.Name) And (t2.Department = t1.Department)
 ))=False))

Now that I had the SQL working, I replaced the messages and created a single Select statement that I could modify to handle both selecting record in Dump and not in Active Directory or selecting records in Active Directory that are not in Dump.

SELECT t1.ID, t1.Name, t1.Department, "Message" AS [Found]
FROM [Dump] As t1
WHERE (((Exists (SELECT NULL
  FROM [Active Directory] As t2
  WHERE (t2.ID = t1.ID) AND (t2.Name = t1.Name) AND (t2.Department = t1.Department)
))=False));

Sub FindUnmatchedRowsCopyFromRecordset()

Create a recordset and use Range.CopyFromRecordset to transfer the records.

Sample SQl:

SELECT t1.Name, t1.ID,  t1.Department, 'Item found in "Dump" but not in "Active Directory"' AS [Found]
FROM [Dump$B4:E23] As t1
WHERE (((Exists (SELECT NULL
  FROM [Active Directory$B4:E20] As t2
  WHERE (t2.ID = t1.ID) And (t2.Name = t1.Name) And (t2.Department = t1.Department)
))=False))
UNION ALL
SELECT t1.Name, t1.ID,  t1.Department, 'Item found in "Active Directory" but not in "Dump"' AS [Found]
FROM [Active Directory$B4:E20] As t1
WHERE (((Exists (SELECT NULL
  FROM [Dump$B4:E23] As t2
  WHERE (t2.ID = t1.ID) And (t2.Name = t1.Name) And (t2.Department = t1.Department)
))=False))

Sub FindUnmatchedRowsAppend()

This is a slightly more complicated technique that appends the records directly to the Output tab.

Sample SQl:

INSERT INTO [Output$B4:E4] SELECT t3.* FROM (SELECT t1.Name, t1.ID,  t1.Department, 'Item found in "Dump" but not in "Active Directory"' AS [Found]
FROM [Dump$B4:E23] As t1
WHERE (((Exists (SELECT NULL
  FROM [Active Directory$B4:E20] As t2
  WHERE (t2.ID = t1.ID) And (t2.Name = t1.Name) And (t2.Department = t1.Department)
))=False))
UNION ALL
SELECT t1.Name, t1.ID,  t1.Department, 'Item found in "Active Directory" but not in "Dump"' AS [Found]
FROM [Active Directory$B4:E20] As t1
WHERE (((Exists (SELECT NULL
  FROM [Dump$B4:E23] As t2
  WHERE (t2.ID = t1.ID) And (t2.Name = t1.Name) And (t2.Department = t1.Department)
))=False))) as t3

Code

Option Explicit

Sub FindUnmatchedRowsAppend()
    Dim conn As Object
    Set conn = getThisWorkbookConnection
    conn.Open

    DeleteOutputResults
    Dim OutputDef As String
    OutputDef = getTableDefinition(wsOutput)

    Dim SQL As String
    SQL = "INSERT INTO " & OutputDef & " SELECT t3.* FROM (" & getOutputResultQuery & ") as t3"

    conn.Execute SQL
    conn.Close
End Sub

Public Sub FindUnmatchedRowsCopyFromRecordset()
    Dim conn As Object
    Set conn = getThisWorkbookConnection
    conn.Open
    Dim SQL As String
    SQL = getOutputResultQuery

    Dim rs As Object
    Set rs = conn.Execute(SQL)

    DeleteOutputResults
    wsOutput.Range("B5").CopyFromRecordset rs

    conn.Close

End Sub

Private Function getOutputResultQuery() As String
    Dim ActiveDirectoryDef As String
    ActiveDirectoryDef = getTableDefinition(wsActiveDirectory)

    Dim DumpDef As String
    DumpDef = getTableDefinition(wsDump)

    Const BaseSQl As String = "SELECT t1.Name, t1.ID,  t1.Department, '@Message' AS [Found]" & vbNewLine & _
        "FROM [xlTable1] As t1" & vbNewLine & _
        "WHERE (((Exists (SELECT NULL" & vbNewLine & _
        "  FROM [xlTable2] As t2" & vbNewLine & _
        "  WHERE (t2.ID = t1.ID) And (t2.Name = t1.Name) And (t2.Department = t1.Department)" & vbNewLine & _
        "))=False))"

    Dim SelectDump As String
    SelectDump = Replace(BaseSQl, "[xlTable1]", DumpDef)
    SelectDump = Replace(SelectDump, "[xlTable2]", ActiveDirectoryDef)
    SelectDump = Replace(SelectDump, "@Message", "Item found in ""Dump"" but not in ""Active Directory""")

    Dim SelectAD As String
    SelectAD = Replace(BaseSQl, "[xlTable1]", ActiveDirectoryDef)
    SelectAD = Replace(SelectAD, "[xlTable2]", DumpDef)
    SelectAD = Replace(SelectAD, "@Message", "Item found in ""Active Directory"" but not in ""Dump""")

    Dim SQL As String
    SQL = SelectDump & vbNewLine & "UNION ALL" & vbNewLine & SelectAD

    getOutputResultQuery = SQL
End Function

Private Sub DeleteOutputResults()
    Dim Target As Range
    With wsOutput
        Set Target = .Range("B4:E4", .Cells(.Rows.Count, "B").End(xlUp))
        Target.Offset(1).ClearContents
    End With
End Sub

Private Function getTableDefinition(ws As Worksheet) As String
    Dim Target As Range
    Select Case ws.Name
        Case wsActiveDirectory.Name, wsDump.Name
            With ws
                Set Target = .Range("B4:E4", .Cells(.Rows.Count, "B").End(xlUp))
            End With
            If ws Is wsActiveDirectory Then
                Rem Remove Summary Row
                Set Target = Target.Resize(Target.Rows.Count - 1)
            End If
        Case wsOutput.Name
            With ws
                Set Target = .Range("B4:E4", .Cells(.Rows.Count, "B").End(xlUp))
            End With
    End Select

    getTableDefinition = getTableDefinitionFromRange(Target)
End Function

Private Function getThisWorkbookConnection() As Object
    Dim conn As Object
    Set conn = CreateObject("ADODB.Connection")
    With conn
       .Provider = "Microsoft.ACE.OLEDB.12.0"
       .ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
       "Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
    End With

    Set getThisWorkbookConnection = conn
End Function

Private Function getTableDefinitionFromRange(Target As Range) As String
    Dim SheetName As String
    SheetName = Target.Parent.Name
    Dim Address As String
    Address = Target.Address(RowAbsolute:=False, ColumnAbsolute:=False)
    getTableDefinitionFromRange = "[" & SheetName & "$" & Address & "]"
End Function

Download Link

ADDump.xlsm


Length-Based Frame Stream En-/Decoding in Go

You may consider to use binary.Read. I find this more readable and self documented. See this example.

var len uint16
err := binary.Read(buf, binary.LittleEndian, &len)

The writing part:

len := uint16(len(p))
err := binary.Write(buf, binary.LittleEndian, len)

Also don't forget to check that len(p) doesn't overflow uint16 (less than 65535).

Apart from that your code is fine.


Find a Sum of Particles in A Set of Boxes Given a Number of Rows and Columns

Inside the inner loop, \$1/k\$ is a constant term. So you could extract that multiplication from the inner loop, and apply it on the computed subtotal. This won't change the order of complexity though.

I was wondering if there is a closed form for computing the sum of reciprocal powers (to replace the summing and thereby speed things up), but I couldn't find.

I was also wondering if you inverted the direction of computations to sum by columns instead of summing by rows, would there be a closed form to replace the summing, but I couldn't find that either.

Other than some clever math optimizations, the computation by rows or columns could run in parallel, but the input parameters would have to be large enough to be worth the overhead.


Graceful shutdown of applications/servers

So to be helpful to others who might be interested in the final outcome after many R&D days and suggestions from other forum users so on., this is what I ended up with. I hope it helps and comments are welcome.

cmd/myself/main.go

package main

import (
    "context"
    "net/http"
    "log"
    "os"
    "os/signal"
    "syscall"

    "myself/internal/app"
)

func main() {
    srv := &http.Server{
        Addr:    ":8080",
        Handler: router.New(),
    }

    ctx, cancel := context.WithCancel(context.Background())

    signalChan := make(chan os.Signal, 1)

    go handleSignal(signalChan, cancel)

    if err := app.New(srv).Start(ctx); err != nil {
        log.Fatal(err)
    }

    log.Info("shutdown complete")
}

func handleSignal(signalChan chan os.Signal, cancel context.CancelFunc) {
    // os.Interrupt: Ctrl-C
    // syscall.SIGTERM: kill PID, docker stop, docker down
    signal.Notify(signalChan, os.Interrupt, syscall.SIGTERM)

    sig := <-signalChan

    log.Infof("shutdown started with %v signal", sig)

    cancel()
}

internal/app/mysql.go

package app

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "time"
)

type App struct {
    server  *http.Server
}

func New(srv *http.Server) App {
    return App{
        server:  srv,
    }
}

func (a App) Start(ctx context.Context) error {
    shutdownChan := make(chan struct{})

    go handleShutdown(ctx, shutdownChan, a)

    if err := a.server.ListenAndServe(); err != http.ErrServerClosed {
        return fmt.Errorf("failed to start [%v]", err)
    }

    <-shutdownChan

    return nil
}

func handleShutdown(ctx context.Context, shutdownChan chan<- struct{}, a App) {
    <-ctx.Done()

    ctx, cancel := context.WithTimeout(context.Background(), 10 * time.Second)
    defer cancel()

    if err := a.server.Shutdown(ctx); err != nil {
        log.Infof("interrupted active connections [%v]", err)
    } else {
        log.Infof("served all active connections")
    }

    close(shutdownChan)
}

```


Your inner if-else is incorrect, and that's why it's not working under Marshmallow.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        System.out.println("Check : has permission");
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
        handleFlash();
    }
} else {
    handleFlash();
}


Filtering a DataFrame based on two logical conditions, first one numpy array values, second one current day based

One way to refactor the loop is to locate the desired rows with idxmax() and then index them in one shot:
df = df[df.index < current_day]
th_array = th_array[th_array < df.cumulated.max()]

indexes = pd.DataFrame(df.cumulated.values[:, None] > th_array).idxmax()
df.iloc[indexes]

#             cumulated
# 2021-03-25        185
# 2021-03-30       1110
# 2021-04-04       2035
# 2021-04-10       3145

Explanation
First, keep only the rows before current_day:
df = df[df.index < current_day]

#             cumulated
# 2021-03-24          0
# 2021-03-25        185
# ...
# 2021-04-10       3145
# 2021-04-11       3330

And keep only the th_array values less than cumulated.max():
th_array = th_array[th_array < df.cumulated.max()]

# array([   0, 1000, 2000, 3000])

Then use array broadcasting to build a boolean matrix of cumulated > th_array where rows correspond to cumulated and columns to th_array:
valid = pd.DataFrame(df.cumulated.values[:, None] > th_array)

#         0      1      2      3
# 0   False  False  False  False
# 1    True  False  False  False
# 2    True  False  False  False
# 3    True  False  False  False
# 4    True  False  False  False
# 5    True  False  False  False
# 6    True   True  False  False
# 7    True   True  False  False
# 8    True   True  False  False
# 9    True   True  False  False
# 10   True   True  False  False
# 11   True   True   True  False
# 12   True   True   True  False
# 13   True   True   True  False
# 14   True   True   True  False
# 15   True   True   True  False
# 16   True   True   True  False
# 17   True   True   True   True
# 18   True   True   True   True

So for each column (th_array), we want the first True row (cumulated). These can be found with idxmax(). Since False is 0 and True is 1, all the True indexes are tied for the max, and the first one wins the tiebreaker:
indexes = valid.idxmax()

# 0     1
# 1     6
# 2    11
# 3    17
# dtype: int64

Then just iloc these indexes for the final filtered df:
df.iloc[indexes]

#             cumulated
# 2021-03-25        185
# 2021-03-30       1110
# 2021-04-04       2035
# 2021-04-10       3145

Timing
For the sample data, the indexing method runs ~11 times faster than looping+appending:
>>> %timeit iloc(df, th_array)
989 µs ± 15.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

>>> %timeit loop(df, th_array)
10.9 ms ± 202 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Testing functions for reference:
def iloc(df, th_array):
    df = df[df.index < current_day]
    th_array = th_array[th_array < df.cumulated.max()]
    indexes = pd.DataFrame(df.cumulated.values[:, None] > th_array).idxmax()
    return df.iloc[indexes]

def loop(df, th_array):
    df_filtered = pd.DataFrame()
    for y in th_array:
        x = df[(df['cumulated'] > y) & (df.index < current_day)]
        if x.empty is False:
            df_filtered = df_filtered.append(x.iloc[0])
    return df_filtered


Read a text file and print pre-defined html when specific keywords are found

I'll give you a hint. Try using a foreach loop:
http://www.php.net/manual/en/control-structures.foreach.php

You can store all your files and associated information in an associative array, such as:

$files = array(
  0 => array(
    'filename' => "export_file_system_status_output";
    'status_update' => "online";
  ),
  1 => array(
    'filename' => "another_file";
    'status_update' => "offline";
  )
);

You should really try this on your own :) If you don't get it, I'll give you a more complete answer :)

On a side note, your HTML is not valid. Use classes instead of ids when possible, and use quotes:

#performancedegradation

Performance is slower than normal.

Hope this helps :)

EDIT:

Here's what your final code will look like, with the array I posted above:

foreach($files as $file)
{
  $handle = fopen($file['filename'], "r");
  $file = fread($handle,filesize($file['filename']));
  if (preg_match('#' . $file['status_update'] . '#', $file, $match))
  {
    echo '

#performancedegradation

Performance is slower than normal.

';
  }
}


Run multiple prerequisite methods in parallel before continuing

Another option is Parallel.Invoke:

Dictionary<string, string> processOptions = null;
Dictionary<string, string> businessAreas = null;
Dictionary<string, string> requirementLevels = null;
List<TemplateSection> sections = null;
List<TemplateVersion> versions = null;

Parallel.Invoke(() => sections = GetSectionsInTreeForm(latestVersionGuid),
                () => versions = GetTemplateVersions(templateId),
                () => processOptions = GetOptionSetProcessPhaseTypes(),
                () => businessAreas = GetOptionSetBusinessAreaTypes(),
                () => requirementLevels = GetOptionSetRequirementLevelTypes());

It should be pointed out that these tasks run in threads from the thread pool (in both cases: Task and Parallel.Invoke). That's OK for few tasks with a run time from 2-5 seconds, but for long running tasks it is better to use a Task object with TaskCreationOptions.LongRunning to run the task in it's own thread. Otherwise the threadpool threads will be blocked for other short running tasks.

Tasks provide a more granular control but that is not required in your case so I would prefer the simpler Parallel.Invoke variant.


Max Contiguous Subarray: Divide and Conquer

Nested max
max(max(L, R), X)

can be
max((L, R, X))

Actual tests
Assert what you're expecting:
assert 0 == max_subarray_sum([])
assert 6 == max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4])
assert 1479 == max_subarray_sum([904, 40, 523, 12, -335, -385, -124, 481, -31])


Hackerrank All Women's Codesprint 2019: Name the Product

Imports
import math, os, random, re, sys
from collections import defaultdict as dd, Counter as count

Seriously, don't do this. It may be useful to read PEP8 regarding imports again.

Imports should be on separate lines.

Why do Counter as count?  It impairs readability.
Especially in larger scripts, every Python dev knows Counter, but count could be a random variable and is easy to be overshadowed.

You don't use all of the imported modules; just remove them if you don't need them.

   alphabet = "abcdefghijklmnopqrstuvwxyz"

Here you missed something that is in the standard lib: from string import ascii_lowercase

Misc

This dd(lambda: 0, ... adds no value
Counter is already a dictionary with default value 0 just remove that part

Magic numbers
5 is a Magic number, you should define it as a CONSTANT:
  NAME_LENGTH = 5

The rest looks good!


Filtering a list of customers in Java based on three criteria

As far as which is easier to read, there isn't a clearly correct answer. The second is more shorter, but more cramped. I personally prefer code with a little more whitespace, such as the first example. Others prefer code that's more succinct. Which is more readable is probably a question to ask your coworkers.

Marking variables as final will clue the reader in that they don't change once assigned.

In camelCase, the method name should be filterStepByStep.

Both methods use lambdas, so the name filterWithLambda is misleading.

In recent versions of Java, you don't need to specify the type on the right hand side of a generic assignment. You can just use <>.

You can get rid of 'valid' by returning false early.

The equals check for locations can be cleaned up using customer.locationId::equals, or, better, by just using contains.

The check on tags can be cleaned up using Set operations.

I would consider renaming the variables to matchCustomerName, matchLocation, and matchTags to make the checks read more cleanly.

If you were to make all these changes, your code might look more like:

public static List<Customer> filterStepByStep(
        final List<Customer> customers,
        final String searchString,
        final List<Tag> selectedTags,
        final List<LocationId> selectedLocations) {

    final List<Customer> filteredCustomers = new ArrayList<>(customers);
    final boolean matchCustomerName = searchString != null && !searchString.trim().isEmpty();
    final boolean matchLocation = selectedLocations != null && selectedLocations.size() > 0;
    final boolean matchTags = selectedTags != null && selectedTags.size() > 0;

    filteredCustomers.removeIf(customer -> {
        if (matchCustomerName && !customer.name.contains(searchString)) {
            return true;
        }

        if (matchLocation && !selectedLocations.contains(customer.locationId)) {
            return true;
        }

        if (matchTags) {
            final Set<Tag> matchedTags = new HashSet<>(selectedTags);
            matchedTags.retainAll(customer.getTags());
            return matchedTags.isEmpty();
        }

        return false;
    });

    return filteredCustomers;
}

public List<Customer> filterWithLambda(
        final List<Customer> customers,
        final String searchString,
        final List<Tag> selectedTags,
        final List<LocationId> selectedLocations) {

    final List<Customer> filteredCustomers = new ArrayList<>(customers);
    final boolean matchCustomerName = searchString != null && !searchString.trim().isEmpty();
    final boolean matchLocations = selectedLocations != null && selectedLocations.size() > 0;
    final boolean matchTags = selectedTags != null && selectedTags.size() > 0;

    filteredCustomers.removeIf(customer -> {
        return (matchCustomerName && !customer.name.contains(searchString))
                || (matchLocations && !selectedLocations.contains(customer.locationId))
                || (matchTags && !selectedTags.stream().anyMatch(customer.getTags()::contains));
    });

    return filteredCustomers;
}


Is this Graham Scan Algorithm? Is it O(n log n)?

Yes, it is.

  Is this elegant, readable Haskell code?

No. It's buggy and far from elegant. Let's start with the bugs in convex_hull_find:

          convex_hull_find []           = []
          convex_hull_find (x:[])       = x:[]
Bug 1:    convex_hull_find (x:x1:[])    = x:x1:[]
Bug 2:    convex_hull_find (x:x1:x2:[]) = x:x1:x2:[]
          convex_hull_find a            = (find_half_hull (tail sorted_x) [head sorted_x]) ++ (find_half_hull (tail (reverse sorted_x)) [head (reverse sorted_x)])
Bug 3:      where sorted_x                    = sortBy predicate a
                  predicate (x, y) (x1, y1)   = compare x x1
                  find_half_hull ([]) hull    = ...

The first bug is simple and obvious: for non-unique inputs like [(0,0),(0,0)], the convex hull should be [(0,0)], but the input is returned verbatim. Non-unique inputs of arbitrary length are also handled improperly. The second bug arises from reordering inputs of length three. Obviously, [p1, p2, p3] (counterclockwise triangle), [p3, p2, p1] (clockwise) and [p2, p3, p1] (different starting point) should all result in the exact same convex hull, namely the counterclockwise triangle [p1, p2, p3] that starts with the lowest-sorting point.

To fix the first bug, just ensure the input is sorted and unique before you do any processing, even in case of short-circuit evaluation. The second bug can be fixed by removing the special case for inputs of length three, there is no need for it anyway. Also, replace head and tail by last and init so the lowest-sorting point stays in the first position for arbitrary-length inputs.

The third bug is a bit more tricky: if two points have the same x-coordinate, sorting by x is insufficient to find the starting point. You need to brake ties by y. Luckily, that's how Haskell orders tuples by default, so just replace sortBy predicate a by sort a. The input [(1,1),(1,0),(2,0),(1,2),(0,0)] triggers the faulty behavior.

Below is a corrected version of the function, complete with type annotations and a docstring. I renamed find_half_hull to grahamScan and made it a first-order citizen to improve readability. Note that function names in Haskell are camelCase by convention, not snake_case.

convexHull :: (Num a, Ord a) => [(a,a)] -> [(a,a)]
-- ^ Convex hull in two dimensions.
convexHull points
  | length sorted <= 2 = sorted
  | otherwise = init (grahamScan sorted) ++ init (grahamScan $ reverse sorted)
  where sorted = map head $ group $ sort points

In addition to renaming find_half_hull to grahamScan, I split it in two separate, simple functions and slapped a docstring to each. They are defined as follows:

grahamScan :: (Num a, Ord a) => [(a,a)] -> [(a,a)]
-- ^ Performs a Graham scan on an ordered list of unique points.
grahamScan = foldr push []
  where push point stack = grahamEliminate (point:stack)

The first of those, grahamScan, simply pushes points onto a stack one by one (starting with the last) and calls grahamEliminate on each iteration. The latter tests if the top three point form a counterclockwise triangle and removes points as appropriate.

grahamEliminate :: (Num a, Ord a) => [(a,a)] -> [(a,a)]
-- ^ Pops second-to-top element from a stack if top three elements do
--   not form a counterclockwise triangle. Repeats if necessary.
grahamEliminate (p1:p2:p3:stack)
  | doubleArea p1 p2 p3 <= 0 = grahamEliminate (p1:p3:stack)
grahamEliminate stack = stack

Finally, the following code can be replaced by a one-liner. Just leave it to the caller to test the sign, it's easier than to test for your custom type.

data Direction = LeftTurn | RightTurn | Straight deriving (Show, Eq)

findDirBetter (x, y) (x1, y1) (x2, y2)
    | cros_product == 0 = Straight
    | cros_product > 0  = LeftTurn
    | cros_product < 0  = RightTurn
    where cros_product = (x1 - x) * (y2 - y1) - (y1 - y) * (x2 - x1)

The complete code is then:

import Data.List

convexHull :: (Num a, Ord a) => [(a,a)] -> [(a,a)]
-- ^ Convex hull in two dimensions.
convexHull points
  | length sorted <= 2 = sorted
  | otherwise = init (grahamScan sorted) ++ init (grahamScan $ reverse sorted)
  where sorted = map head $ group $ sort points

grahamScan :: (Num a, Ord a) => [(a,a)] -> [(a,a)]
-- ^ Performs a Graham scan on an ordered list of unique points.
grahamScan = foldr push []
  where push point stack = grahamEliminate (point:stack)

grahamEliminate :: (Num a, Ord a) => [(a,a)] -> [(a,a)]
-- ^ Pops second-to-top element from a stack if top three elements do
--   not form a counterclockwise triangle. Repeats if necessary.
grahamEliminate (p1:p2:p3:stack)
  | doubleArea p1 p2 p3 <= 0 = grahamEliminate (p1:p3:stack)
grahamEliminate stack = stack

doubleArea :: Num a => (a,a) -> (a,a) -> (a,a) -> a
-- ^ Twice the area of a counterclockwise triangle. Negative if clockwise.
doubleArea (x1,y1) (x2,y2) (x3,y3) = (x2-x1) * (y3-y1) - (y2-y1) * (x3-x1)


I think the mapper looks ok, but in the cost centers management method, you violate encapsulation by directly manipulating the travel's cost centers list.

I'd rather leave the list management to the travel class:

class Travel {
    ...
    void addCostCenter(CostCenter c) {
       ...
    }

    void removeCostCenter(CostCenter c) {
       ...
    }

    boolean containsCostCenter(CostCenter c) {
        ...
    }

    CostCenter findByDetails(Long detailsId) {
        ....
    }
}

... and use it like this:

protected void assignCostCenter(CostCenterDTO costCenterDTO, Travel travel, Long detailsId) throws BusinessException {
    // note: moved outside declaration of CostCenter to smaller scope
    if (costCenterDTO.getCostCenters() != null) {
        Center center = commonDao.find(costCenterDTO.getCostCenters().getId());
        CostCenter costCenter = costCenterDTOMapper.mapToDTO(costCenterDTO.getCostCenters(), travel, detailsId, center);
        // can costCenterDTOMapper.mapToDTO actually return null? If not, declare it like that and
        // remove the ugly null-check
        if (costCenter != null && !travel.containsCostCenter(costCenter)) {
            // depending on the business logic, you might also consider
            //    travel.addCostCenterIfNotExists(costCenter)
            // and skip the if
            travel.addCostCenter(costCenter);
        }
    } else {
        travel.removeCostCenter(travel.findByDetails(detailsId));
    }
}


Move one element before another in an associated array

I wouldn't bother with a foreach loop because it will do more iterating than necessary.  I recommend halving the array at the desired position and squeezing the element-to-be-moved into the gap created.  Consider this much more concise method:

Code: (Demo Link)

function moveKeyBefore($arr, $find, $move) {
    if (!isset($arr[$find], $arr[$move])) {
        return $arr;
    }

    $elem = [$move=>$arr[$move]];  // cache the element to be moved
    $start = array_splice($arr, 0, array_search($find, array_keys($arr)));
    unset($start[$move]);  // only important if $move is in $start
    return $start + $elem + $arr;
}
$arr = ['foo1'=>'bar', 'foo2'=>'buzz', 'foo3'=>'bazz'];
var_export(moveKeyBefore($arr, 'foo3', 'foo1'));

Output:

array (
  'foo2' => 'buzz',
  'foo1' => 'bar',
  'foo3' => 'bazz',
)

Explanation:

First check that both of the nominated keys exist in the array, if not return the input array untouched.  isset() is very fast, certainly faster than in_array().  Furthermore, the !isset() check will require both keys to exist otherwise the early return will be triggered.  This is as fast as this part gets.

Next, if both $find and $move exist in the array, my function will generate three array fragments:

$elem contains the associative array element declared by $move.
$start contains the elements that precede $find.  array_search() returns the offset (numeric key) of the $find value in $arr.
$arr is modified by array_splice() and contains all elements from find to the end.

After the splice, when $move is in the $arr half, the union action bumps the duplicate element out.  When $move is in the $start half, the convenient "bump" is lost, this means that the $move element needs to be removed from its original location.  unset() can be used unconditionally because it doesn't error when the target element is not found.


Checking if variable is defined before accessing its properties

Are you looking for this?

var data = object && object.attribute && object.attribute.data || {};

Alternatively, you could create a simple function to safely index objects that may not be defined, such as:

function resolve(value) {
    return function(key) {
        return key ? resolve((value || {})[key]) : value;
    };
}

You'd use it like this:

var data = resolve(object)('attribute')('data')() || {};

If anything in the chain does not exist, it will return undefined. This might be useful if you have deeply nested and unpredictable objects, such as an object resulting from parsing JSON data from a remote resource.

http://jsfiddle.net/VHcdq/1/


Code reduction possible with modulo operator?

If your triplets were zero-based (i.e., {0, 1, 2}, {3, 4, 5}, …) then the answer might have been more obvious.  As it is, you have to apply an offset of -1, then divide by three to figure out which triplet an element belongs to.

if ((mvt[i] - 1) / 3 == (mvt[i + 1] - 1) / 3) {
    // This shouldn't happen: mvt[i] and mvt[i + 1] are in the same triplet
}


You are correct that the first step is to sort the array. The second step - an actual search for solution - is also happen to be of n*log(n) complexity. What is important, they are very different n*log(n): sorting is implemented in native code, so it is virtually instantaneous comparing to the Python loops. The key to solution is to realize that the second step can be done in linear time:

Given a sorted array data you may build another sorted array target_minus_data in linear time. It is also sorted, descending. Reverse it (linear time). Now there are two sorted arrays sharing the same value. It can be found also in linear time by a merge-like algorithm.

Of course, you don't have to physically reverse target_minus_data - just iterate it backwards. If you look closely, you do not even have to build it; everything can be done in the fly. Merge data with itself, from both ends, a backward iterator returning target - data[bkwd].


Iterator to generate all the words (of a given words) that are one change away

am I doing it the 'right' way?

Please excuse the rude answer but: No.

general critic

Java is a class based object oriented language. So you should solve the problem in an object oriented way. This does not nessesarrily mean that your approach needs more classes and objects, but it does mean that you should apply the single responsibility pattern and find better separation of concerns.

Eg.: The responsibility of an Iterator is to give access to individual elements of a collection or stream like data structure. But the creation of this elements is not.

detailed critic

formal issues

naming

The way you choose the names in you approach has some problems.

First of all you should stick to the Java Naming Conventions In particular class names should always start with an upper case letter and the first part in a method name should be a verb.

Your variables should have readable names taken from the problem domain. You have one letter abreviations. It is quite certain that you don't remember the meaning of that one letter variables yourself when you read this in 2 month...

magic numbers

In your approach you use magic numbers, even if they are chars actually. You should rather use constants with proper names like LETTER_WITH_LOWEST_ASCII_VALUE instead of 'a'.

returning literal null explicitly

You should never return a literal null reference explicitly unless it is a valid part of the result space.

Especially you should not indicate an error by returning null. Use exceptions instead. In your case the next() method should throw  NoSuchElementException instead of returning null.

single line blocks

If you omit the curly braces for single line blocks then at least proper indent this line.

explicit use of literal true/false

In your hasNext() method you explicitly return the literal  true/false values. This introduces the possibility to change the methods logic by accident. Why didn't you simply return the result of the compare instead of wrapping it into an if statement?

use of continue

continue and break are the poor mans goto. In 20+ years of coding in Java I never ever used a continue or a break (other than inside a switch  where break is inevitable).
So instead of placing a continue think of how you could write your code without it, which is very simple in your case.

raw types

The Iterator interface supports a generics parameter but your implementation does not use it. Therefore  your next() method is declared to return a Object and the caller of your code must explicitly cast the value to a String relying on you that you don't return something else.

broken OO principles

separation of concerns / single responsibility

As already mentioned the creation of the result collection is out of scope of an Iterators responsibility.

Therefore you should have a separate class or a method in your "main app" that creates some Collection or a Java8-Stream containing the result elements. Then there would be no need to write your own Iterator implementation at all.

other missed best practices

single abstraction layer

single abstraction layer means that a method either calls other methods or does some "low level" operations, but not both. (only loops, and conditionals are allowed in both method types).

You method next() does both: it calls hasNext() and the does some operations to create the next element. The code inside the if block which does the "low level operations" should be moved to a separate method so that hasNext() only calls other methods.


I see some things that may help you improve your code.

Use all required #includes

The Media.cpp file uses a std::exception but is missing this line:

#include <exception>

Use std::runtime_error

The code in Media.cpp includes this line:

throw(std::exception("Cannot load player texture"));

However, that shouldn't compile because there is no constructor for std::exception that takes a const char * argument.  Instead, that should probably be this:

throw(std::runtime_error("Cannot load player texture"));

Don't forget SDL_Init

Any SDL2 program must call SDL_Init but yours doesn't.  To fix that, I'd recommend adding an SDL object as illustrated on the SDL Wiki.  It simply makes an object whose constructor calls SDL_Init and whose destructor calls SDL_Quit while translating SDL error into C++ exceptions.

Remember object scoping rules

Right now, your objects are all declared within the try block.  This also means that they only exist within that block because of C++ scoping rules.  In a real version of the program, you'd either need to have something happen inside that try block.


Removing untagged docker images using Python

I would split the line of the output once and re-use that. Also, if you don't pass a separator to str.split, it will split on whitespace, so "A    B C".split() == ['A', 'B', 'C'].

import subprocess

output = subprocess.Popen(["docker", "images"], stdout=subprocess.PIPE)
result = output.communicate()[0].split("\n")

image_list = []
for line in result[1:]:
    line = line.split()
    if line[0] == "<none>":
        image_list.append(line[2])

for image in image_list:
     #Piping both stdout and stderr to stdout.
     output = subprocess.Popen(["docker", "rmi", "-f", image], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
     print(output.communicate()[0])

I would probably change if line[0] == "<none>" to if line[1] == "<none>" to adhere more closely to what you want to do. I'm not sure if it can happen that the repository is not none, but the tag is.

I would also change the grouping slightly, so that things which logically belong together are grouped. This is the first step towards putting them into their own functions, which could be slightly overkill here, but would make it a lot easier to re-use parts of this:

import subprocess

def get_docker_images():
    output = subprocess.Popen(["docker", "images"], stdout=subprocess.PIPE)
    return map(str.split, output.communicate()[0].split("\n")[1:-1])

def no_tag(images):
    for image in images:
        if image[1] == "<none>":
            yield image

def delete_images(images):
    for image in images:
        output = subprocess.Popen(["docker", "rmi", "-f", image[2]],
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.STDOUT)
        print(output.communicate()[0])

if __name__ == '__main__':
    delete_images(no_tag(get_docker_images()))


The faster way to know if a number is already in a data structure is to use an object, not an array.  So, if you don't have to have the numbers in an array, then this would be a lot faster, particular when the number of items gets big because the object look up is massively faster than the linear search of .indexOf():

var numbers = {};
function recurse(newNumber) {
    if(newNumber in numbers) {
        return newNumber;
    }
    //do stuff to number
    numbers[newNumber] = true;
    return recurse(modified_number);
}

You can then iterate through the items in numbers like this:

for (var num in numbers) {
    if (numbers.hasOwnProperty(num) {
        // process num here
    }
}

FYI, if speed is really your goal here, recursion is not the fastest way to do this (because functions calls are kind of slow in javascript), particularly if you don't have much or any local state in the function so you could just use a while loop of sorts.


Loop over whole array starting from any index

There is no reason to initialize i as {c + std::distance(begin, start)}. Upon such initialization you are guaranteed that i == start. A much simpler i{start} suffices.
Testing for i == size, or i == end inside the loop, as well as tracking two iterators, feels wasteful. Consider splitting the loop into two, e.g:

    for (i = start; i != end; ++i) {
        fn(i);
    }

    for (i = begin; i != start; ++i) {
        fn(i);
    }

I am not sure that for_start is a good name. I am also not sure what name would be good. iterate_rotated perhaps?


Basically, this structure makes very little sense by itself, without knowing the real purpose of all these classes and the similarities worth extending.

But some suggestions could be made anyway.

whatever class that is intended to display some data, by definition cannot have a property like first name. First names are generally belong to persons. A class must represent a solid entity, not a Frankenstein constructed from different parts. So in your place I would avoid creating such entities as cyborgs, that bear both human-like and machine-like features. Whatever belongs to a person, goes to one class, and whatever belongs to a table renderer belongs to another class.
There is a PHP coding standard, and you are supposed to follow its guidelines.

So, for as little information as provided in your question, here is a class structure I propose for you:

There is a class Person that holds the person's personal information,

class Person
{
    // Parameters
    protected $firstName;
    protected $middleName;
    protected $lastName;

    public function __construct($firstName, $middleName, $lastName)
    {
        $this->firstName = $firstName;
        $this->middleName = $middleName;
        $this->lastName = $lastName;
    }

    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;
        return $this;
    }

    public function setMiddleName($middleName)
    {
        $this->middleName = $middleName;
        return $this;
    }

    public function setLastName($lastName)
    {
        $this->lastName = $lastName;
        return $this;
    }

    public function getFirstName()
    {
        return $this->firstName;
    }

    public function getMiddleName()
    {
        return $this->middleName;
    }

    public function getLastName()
    {
        return $this->lastName;
    }
}

and a class Output that renders tables.

class Output
{
    protected $person;

    public function __construct(Person $person)
    {
        echo 'this Master construct
';
        $this->person = $person;
    }

    protected function generateCpc()
    {
        echo 'this cpc generated
';
        echo $this->person->getFirstName()." ".$this->person->getMiddleName()." ".$this->person->getLlast_name;
        echo '
';
    }

    protected function generateBasetable()
    {
        echo 'this basetable generated
';
        echo $this->person->getFirstName()." ".$this->person->getMiddleName()." ".$this->person->getLlast_name;
        echo '
';
    }

    protected function generateLayer()
    {
        echo 'this layer generated
';
        echo $this->person->getFirstName()." ".$this->person->getMiddleName()." ".$this->person->getLlast_name;
        echo '
';
    }

    public function generate()
    {
        $this->generateCpc();
        $this->generateBasetable();
        $this->generateLayer();

        echo 'this master generated
';
        echo $this->person->getFirstName()." ".$this->person->getMiddleName()." ".$this->person->getLlast_name;
        echo '
';
    }
}

so it can be used like this

$output = new Output(new Person('ken dan', 'sunico', 'tinio'));
$output->generate();


Can I improve this code for readability and/or performance?

I think that your code to “remove the values that are identical” is quite confusing.

First, it doesn't remove anything, it just sets the values to zero. And unless you filter that out later, it will cause problems in your final calculation.

Second, modifying the indexing variable of a for is usually not a good idea. It's unexpected and creates code that is hard to understand.

Third, I think you don't actually need this. It would be much easier to remove zero values after you compute the differences.

Now, in your code to get the differences, I find the logic hard to follow. (One reason is probably non-descriptive variable names.) And I don't understand why do you have all those conditions there, computing a difference (even with the possibility of a reset) should be simpler. Also, you seem to ignore the fact that if you compute the difference between n values, you will get only n - 1 results.

I would rewrite this code using Zip() and Skip() like this:

var result = Enumerable.Zip(
    data, data.Skip(1),
    (first, second) =>
    second.Value < first.Value
        ? second
        : new BarChart { second.Time, Value = second.Value - first.Value });

Also, naming a single value in a chart BarChart is confusing, a better name would be something like BarChartValue.

You also asked for performance optimizations. Is your code actually causing performance problems? Have you profiled your application and has this code been identified as bottleneck? If not, don't worry (much) about performance, it won't make a difference anyway.


Checking if a string contains all unique characters

A way to optimize it would be to return as soon as you have found a duplicate, unless the question specifically asks you to list all duplicates.
You could refactor it to something like that:
public static boolean checkUnique(String s) {
    int len = s.length();
    for (int i = 0; i < len; i++) {
        int c = s.codePointAt(i);
        int next = s.indexOf(c, i + 1);
        if (next > i) {
             return false;
        }
    }
    return true;
}

It isn't more efficient as your solution, but I doubt there is an algorithm that can do it better.