The link in the post to your fft file is broken, so I can't see the function
prototype.  This is a pity, because it is otherwise difficult to know what to
make of your arrays:

double (*vocalData)[2] =  malloc(2 * 512 * sizeof(double));

This says vocalData is a pointer to an array of two doubles.  You have
allocated 1024 doubles at this address.  So on a 64bit system you have:

                  8 bytes
vocalData[0] ->  |--------|
                 |--------|
vocalData[1] ->  |--------|
                 |--------|
vocalData[2] ->  |--------|
                 |--------|
    etc

You fill the array with

for (x = 0; x < 512; x++){
    *vocalData[x] = (double)vocalBuffer.buffer[i+x];
}

This fills alternate doubles in your allocated space and leaves the others
uninitialized.

                  8 bytes
vocalData[0] ->  |xxxxxxxx|
                 |--------|
vocalData[1] ->  |xxxxxxxx|
                 |--------|
vocalData[2] ->  |xxxxxxxx|
                 |--------|
    etc

I don't know for sure that this is not what you want, but...

Also all that converting from float to double and then back to float is very
inefficient.  As onsetsds_process takes floats, I can see the need, but
maybe you should use an FFT function that also deals in floats.

Finally it would be better to #define FFT_SIZE 512 at the top and use
FFT_SIZE throughout instead of the explicit 512.  This is better practice,
for example making it much easier to change the FFT length if it is necessary.

Oh and don't forget to free any memory you have allocated once you have
finished with it.  In this case, that means all of your allocations should be
freed on exit (although if your return 0 is the end of the program that is
academic).


Import huge XML data set into MongoDB while parsing data

Since inserting into the DB takes a non-negligible amount of time, you should try to use insert_many, instead of insert_one. If you used a single thread this would be easy, just chunk your file and insert a whole chunk. Since you are using multiprocessing, this is a bit more complicated, but it should still be doable

(untested code)

from itertools import islice
import pymongo
import multiprocessing as mp
from tqdm import tqdm
import et

def chunks(iterable, n):
    it = iter(iterable)
    while (chunk := tuple(islice(it, n))):  # Python 3.8+
        yield chunk

def work(chunk):
    try:
        posts.insert_many([attrib_to_dict(elem.attrib) for _, elem in chunk],
                          ordered=False)
    except pymongo.errors.BulkWriteError:
        # skip element
        pass

if __name__ == "__main__":
    pool = mp.Pool(4)
    # progress bar
    pbar = tqdm(total=POSTS_SIZE)
    n = 100
    try:
        for chunk in chunks(et.iterparse("Posts.xml", tag="row"), n):
            pool.apply_async(work, args=(chunk,),
                             callback=lambda: pbar.update(len(chunk)))
        pool.close()
    except KeyboardInterrupt:
        pool.terminate()
    finally:
        pbar.close()
        pool.join()

Here I used this to ignore duplicate keys.


Readability vs. maintainability: nested functions

Option 1
The nested function is not bad (depending on the situation). Of course, they bring more complexity and reduces extensibility. But in some cases, you wish to bundle some function that works with the main function output (well, it's not very different from the class).
Of course you should return object instead of the list for the usage convenience:
const myFunction = ({foo, bar}) => {
  return {
    function1() {
        return foo + bar
    },
    function2() {
        return foo * bar;
    }
  }
}
myFunction().function1()

To sum up, this design can simplify usage in some cases. However, the worst thing about this pattern is that these functions are not extendible and you can't use partial functionality (like using only function1). In most cases, I recommend avoiding this unless you are writing a library/helper function and which to simplify usage by attaching other chain function to the main output (fetch is a good example).

Option 2
Regarding the second option, it works fine as long as your function is not too complex and you don't have too many parameters. You can partially solve the issue with a lot of parameters using TypeScript (because you can statically describe them).
However, if possible I recommend changing logic a bit. Instead of requiring all parameters why don't you require the output of functions? Then you can have multiple functions which return different output + you can also write your own implementation for one part. This option opens a way for unlimited possibilities.
Example:
const myFunction = ({foo, bar}) => {
    return [
        foo,
        bar
    ]
}

myFunction({
    foo: function1(),
    bar: function1(),
})

// You can "extend" this function:
myFunction({
    foo: function1(),
    bar: myCustomFunction(),
})


Google Sheet with a column of names merged with Google Doc

I realized I didn't need all those loops so I simplified things to 1 loop:

for (rowNum = 2; rowNum <= lastRow; rowNum ++){
//Splitting names
  var cell = range.getCell(rowNum,colNum).getValues()[0];
  var sCell = cell[0].split(", ");
  sheet.getRange(rowNum,colNum +1,1,sCell.length).setValues([sCell]);
  var fName = sCell[1]; // first name
  var lName = sCell[0]; // last name

// make copy of doc and save as student name.
  var docTemplate = DriveApp.getFileById(myDoc);
  var newFile = docTemplate.makeCopy(fName + lName);
  var newDoc = DocumentApp.openById(newFile.getId());
  DriveApp.getFolderById(myNewFolder).addFile(newFile);
  DriveApp.getFolderById(mySourceFolder).removeFile(newFile);

// replace text
  var body = newDoc.getBody();
  body.replaceText('{first name}', fName);
  body.replaceText('{last name}', lName);
  body.replaceText('{date}' , date);
  }


Async function with slow web reference(web service) slowing down webpage

There's not enough information here to tell you what's wrong, but I'll tell you what I would do differently regardless.

Manually spawning threads is something you should avoid doing, especially if there's a chance that thread is just going to wait on a lock.  As the remote service gets slower and your app gets busier, you'll have more and more idle threads taking up resources.  You can make a single mail thread that has new params passed to it (in a thread-safe way).


HTML5: Section in Article is Untitled Section in the Outliner

Question 1 (title and author in heading)

  Is it benefit to the outliner to mix Title and Author in the same element? Considering that the outliner reads both as one.

Does the author name needs to be in the article heading?

If so, instead of
Title of the Article 1
Name of the Author
 (the br element is wrong here) you should divide the parts like
TITLE by AUTHOR
 or
TITLE (AUTHOR)
. Use span if you want to style these parts differently.

The title/author combination in your second example is wrong, because it creates a wrong outline. You should use hgroup here:

  <hgroup>

Title of the Article 2

Name of the Author

  </hgroup>

But I'd advise against putting the author name in a heading (depends on the real site context, though). I'd only put the author name in a heading (next to the title or in a hgroup together with the title), if there is no more than one article per author or if the titles are ambiguous.

Question 2 (section vs. div in article)

  The problem I find is that when using section it generates an untitled section in the outliner. So the only solution is to use a div instead of a section. Is that semantic?

Within article you would use section elements for chapters etc. (and other article elements for comments). So yeah, if you don't have/need those chapters (each would have its own heading, whether explicit or implicit = untitled), use div. Or better (if you don't need any special styling hook), don't use any element. Everything within article (which is not within header/footer/nav/'aside') is the "prose" content.

Question 3 (whole markup)

  I want to know if my whole code is properly semantic, respecting both html5 specification and the outliner.

I'd go with:

Title of the Article 1

    Name of the Author

Paragraph content

header is not needed here, because it would only contain the h1
used h1 instead of h2 (the first heading counts, no matter which level; simply use what you like more)
used footer instead of header for the author name and author picture; see HTML5 spec: "A footer typically contains information about its section such as who wrote it …"
placed the "read more" link in nav because it is the main navigation within this sectioning content

you are free to give an explicit heading for nav (and maybe visually hide it, so that it is still read by screen-readers), but it's not a must, of course

whether the social links belong in nav or not depends on context; in general, these are not considered major navigation, so I put them in footer (instead, an aside element could be used)

Regarding @danchet remark about header/footer: It's totally fine (and often needed!) to have several header and footer elements on the same page page. The footer element applies to "its nearest ancestor sectioning content or sectioning root element", so each section/article/nav/aside/etc. can have its very own footer (and yes, even several).


Since there is no answer yet - what I would try:

I would search words rather than characters. make a dictionary of words (bag of words) and count the frequency. your test bag of words should be a subset of the source bag of words mostly. by comparing to other sources you could analyze relevance of words and other measures.

The big advantage of words vs. characters is that the comparison resyncs with every whitespace. an insertion/deletion of a character will result in a single changed word. you are now talking in edit distance of words, rather than characters. so translate your strings to arrays of words (whatever representation you use for a word (sequential number, hash, reference, ...).

Now slide your test words over the source words and count the number of word matches. for your parameters this will be around 1,000 word over 1,000,000 words, which sounds reasonable. you get an array of match counts with length 1,000,999. it will have the following properties

some noise floor of matches. the most frequent words of your language match by accident
some (at least one) entries greater or equal to the longest matching subsequence
some 'distribution' (near gaussian?) caused by inserted/deleted words indicating where to find your test file

this would be less heuristic than your approach, although you probably will again apply some more algorithms/heuristics to find the 'exact' match start/end.

EDIT: I simply had to try the bag of words approach

I simply slide a window of the probe words length ofer the text words in single word steps. for this text window i calculate the bag of words and compare it to the probe and sum the absolute difference values for every entry.

e. g.: 'so the the moon' vs. 'the moon moon is' resulting (so:1 the:2 moon:1) vs. (the:1 moon:2 is:1) wich results in a diff (so:1 the:1 moon:-1 is:-1) in absolute values (so:1 the:1 moon:1 is:1) summing up to the value 4.

This measure for my test set

text size 100,000 chars (~ 16,000 words)
probe size 6,000 chars (~ 1,000 words)
probe edits (change, insert, delete) 300 chars (letters, digits, punctuation, whitespace)
bag size for a 1000 words window from text ~ 500 words with frequencies from 20+ down to 1
bag size of the (edited) probe ~ 600 words

gives the following result

This looks pretty robust to me. We see

for the best match a word-edit-distance of 460 (inserting a whitespace may results in a distance of 3)
for a non-matching region a word-edit-distance of 1200
a near linear transition double as wide as the probe size

See the transition scaled up


Functional programming

Since you've tagged this post with functional-programming I guess that the goal of this exercise may have been to practice functional programming or to present you skills in functional programming. This way or another, I'll stick to the assumption that it was supposed to be written in the functional programming paradigm.

When working with functional code, a function returning a Unit is a huge warning sign. In functional programming we compose programs of functions which are (quoting John De Goes):

  Total: They return an output for every input.
  Deterministic: They return the same output for the same input.
  Pure: Their only effect is computing the output.

In FP, if a function returns a Unit, it basically means that the function does nothing, as the only thing a function can do is to return a result.

rotatedMatrix

In FP preallocating the rotatedMatrix doesn't make sens, because in order to stay Pure rotateByOne is disallowed to mutate the rotatedMatrix. And the solution is simple, the rotateByOne should allocate and return a rotated matrix.

rotateByOne

While moving the allocation of rotatedMatrix into the rotateByOne would make rotateByOne a pure function, the implementation of the function would still be clattered with state mutations, and generally much more complex than it needs to be.

So let's have a look at how it can be improved.

Edge-case/error handling aside, I would expect the problem to be solved with a def rotateByOne(in: Array[Array[Int]]): Array[Array[Int]]. That function would have to create a new matrix of the same dimensions, finding a new value of each cell in the matrix. It's implementation could look like

  def rotateByOne(in: Array[Array[Int]]): Array[Array[Int]] = {
    val size = in.length
    (0 until size).map { i =>
      (0 until size).map { j =>
        newValueAt(in, i, j)
      }.toArray
    }.toArray
  }

Now all that's left is to implement the def newValueAt(in: Array[Array[Int]], i: Int, j: Int): Int which is again - a pure function - doing nothing but returning an Int. There are 5 cases to be considered, in newValueAt. Using the value of the cell:
below, above, on the right, on the left, and the same cell.

For 3 x 3 matrix it's:

b l l
b s a
r r a

For 4 x 4 matrix it's:

b l l l
b b l a
b r a a
r r r a

After a few minutes of trial and error, I've ended up with the following implementation:

  def newValueAt(in: Array[Array[Int]], i: Int, j: Int): Int = {
    val s = in.size - 1
    if      (i >= j && s - i >  j) in(i + 1)(j) // 'b'
    else if (i <  j && s - i >= j) in(i)(j - 1) // 'l'
    else if (i <= j && s - i <  j) in(i - 1)(j) // 'a'
    else if (i >  j && s - i <= j) in(i)(j + 1) // 'r'
    else                           in(i)(j)     // 's'
  }


Using JavaScript's Array.splice with assigning the replacements item as an array

This looks straightforward and solid under ES5. I have no comments or criticism for that.

However, under ES6, there's the spread operator (which is relatively well supported in most modern browsers, and in Babel), with which you can effectively oneline the whole thing like so:

targetArray.splice(start, end, ...replacements);


Looking cleaner code of Python Combining Image with PIL

You can simplify the checks that find the smallest image. If you assume that if the image is smaller in one dimension, it will be smaller in both (which you seem to be already), you can find the smallest image using min's key parameter:
small_image = min(image1, image2, key=lambda image: image.size[0])
large_image = image1 if image2 == small_image else image2

canvas = large_image.load()
insert = small_image.load()

The key function is applied to each image before they're compared. In this case, I'm comparing each of the image's size[0] values. To get the larger image, you could get creative with sets if images are hashable, but I think a conditional expression is probably easiest.
This also reduces your check at the bottom to just
large_image.show()

This part:
r, g, b = insert[col, row]

if r < 250 and g< 250 and b< 250:
        canvas[col, row + 130] = r, g, b

Can be simplified a bit if you use all with a generator expression:
color = insert[col, row]

if all(c < 250 for c in color):
    canvas[col, row + 130] = color

This frees you up from needing to create, compare, then recombine three separate variables.

Final code:
from PIL import Image

image1 = Image.open("lady_tiny.jpg")
image2 = Image.open("eiffel.jpg")

small_image = min(image1, image2, key=lambda image: image.size[0])
large_image = image1 if image2 == small_image else image2

canvas = large_image.load()
insert = small_image.load()

for col in range(width):
    for row in range(length):
        color = insert[col, row]

        if all(c < 250 for c in color):
            canvas[col, row + 130] = color

large_image.show()


It looks like you are XORing a mildly modified key with the plaintext, then mildly modifying the key every 10 blocks.  As @SimonForsberg has noted, such simplistic schemes just are amateur-grade ciphers, and certainly not cryptographically secure.  (Cryptanalysis would be beyond the scope of Code Review, though.)

Only a few experts are capable of producing cryptographically secure algorithms — and even then, they submit their schemes to merciless peer review.  There's always someone out there who is smarter than you are.  Attacks only get better, never worse.  If you want a cryptographically secure scheme, don't roll your own crypto.


It would seem to me that one way to solve this is to change all the directed arcs in the dag to undirected edges. The rest is to recognize the disjoint subgraphs using breadth-first search:

def convert_directed_graph_to_undirected_graph(graph):
    """Converts each directed arc into an undirected edge."""
    undirected_graph = {}
    for node, child_node_list in graph.items():
        if node not in undirected_graph.keys():
            undirected_graph[node] = []
        undirected_graph[node].extend(child_node_list)
        for child_node in child_node_list:
            if child_node not in undirected_graph.keys():
                undirected_graph[child_node] = []
            undirected_graph[child_node].append(node)
    return undirected_graph

def crawl_subgraph(source_node, undirected_graph, visited):
    """Implements breadth-first search in order to find the entire subgraph including the source noe."""
    if source_node in visited:
        return None
    visited.add(source_node)
    queue = deque([source_node])
    subgraph = [source_node]
    while queue:
        current_node = queue.popleft()
        for neighbor_node in undirected_graph[current_node]:
            if neighbor_node not in visited:
                visited.add(neighbor_node)
                subgraph.append(neighbor_node)
                queue.append(neighbor_node)
    return subgraph

def find_disjoint_dags(graph):
    """Finds all disjoint subdags in the input dag."""
    undirected_graph = convert_directed_graph_to_undirected_graph(graph)
    visited = set()
    disjoint_subgraphs = []
    vertices = set(undirected_graph)
    for vertex in vertices:
        subgraph = crawl_subgraph(vertex, undirected_graph, visited)
        if subgraph:
            disjoint_subgraphs.append(subgraph)
    return disjoint_subgraphs

Hope that helps.


It all seems really nice, I would change few things:

Firstly, your format_event_time takes a node object as a param, which is counter-intuitive as I would expect it to accept Time object. I would rename it to 'parse_xml_date` or similar and give it text instead:

def parse_xml_time(time_string)
  Time.parse(time_string).iso8601
end

The main purpose of this change is to make your build_event method the only method specifying the exact xml locations of the required properties, so it is easy to find if those changed.

Secondly,your build_event method can be slightly simplified to (including first change):

def build_event(node)
  {
    title: node.at_xpath('title').content
    url: node.at_xpath('link').content
    start: parse_xml_time(node.at_xpath('pubDate').content)
    allDay: false
  }
end

And finally I would add a small private method get_param:

def get_xml_param(attribute, node)
  node.at_xpath(attribute).content
end

Which would simplify build_event to:

def build_event(node)
  {
    title: get_xml_param('title', node)
    url: get_xml_param('url', node)
    start: parse_xml_time(get_xml_param('pubTime', node))
    allDay: false
  }
end

UPDATE:

Actually there might be few more changes.

Your parse_events method can be written like this:

def parse_events
  xml.xpath('//item').map {|node| build_event(node) }
end

And I would consider caching an xml method:

def xml
  @xml ||= Nokogiri::XML::Document.parse(open(@url))
end


I don't know anything about phyton, but I will throw my 5 ct in anyway.

Adding horizontal spaces between assignments to variables/properties and vertical spacing between related parts will make your code more readable like so

for row in fichier:
        name1 = row[0] #name of the first port
        name2 = row[1]

        portid1 = str(tree.xpath("//name[text()='%s']/parent::*/id/text()" %name1)) #searches for the port id in the .xml
        portid2 = str(tree.xpath("//name[text()='%s']/parent::*/id/text()" %name2))

        portid1 = portid1[2:-2] #output was surrounded by [""] so i cut the first two and last two
        portid2 = portid2[2:-2]

        result.append(("<link>\n<portid1>{}</portid1>\n<portid2>{}</portid2>\n</link>\n").format(portid1, portid2)) #store data

If you need a comment about a variable, then this variable is poorly named. So better name the variable in a meaningful name and remove the comment.

name1=row[0] #name of the first port
name2=row[1]

vs.

first_port_name = row[0]
second_port_name = row[1]

The same approach I would use for

portid1=str(tree.xpath("//name[text()='%s']/parent::*/id/text()" %name1)) #searches for the port id in the .xml
portid2=str(tree.xpath("//name[text()='%s']/parent::*/id/text()" %name2))

like so

first_port_id = str(tree.xpath("//name[text()='%s']/parent::*/id/text()" %name1)) #searches for the port id in the .xml
second_port_id = str(tree.xpath("//name[text()='%s']/parent::*/id/text()" %name2))

So the mentioned points together would look like so

for row in fichier:
        first_port_name = row[0]
        second_port_name = row[1]

        first_port_id = str(tree.xpath("//name[text()='%s']/parent::*/id/text()" %name1)) #searches for the port id in the .xml
        second_port_id = str(tree.xpath("//name[text()='%s']/parent::*/id/text()" %name2))

        first_port_id = first_port_id[2:-2] #output was surrounded by [""] so i cut the first two and last two
        second_port_id = second_port_id[2:-2]

        result.append(("<link>\n<portid1>{}</portid1>\n<portid2>{}</portid2>\n</link>\n").format(first_port_id , second_port_id )) #store data


Don't repeat yourself

The try-random-catch block appears two times in your code. The easiest way to fix this would be to delete the first occurrence. You don't need it, as the while check will be true on the first loop, thus executing that block.

Handling Exceptions

There are a lot of ways to handle an exception, but just silently ignoring it is not one of them. It will make it very hard to find bugs.

Alternatives are:

just let the exception bubble up all the way
log the exception to a file (for detailed information use getStackTrace)
print the exception to console (best use printStackTrace, not getMessage)
handle the exception

It is also important to not catch a blanket Exception, but the specific exceptions that may be thrown. With your code, a reader doesn't really know what might be thrown (and thus has no idea at all what might have gone wrong).

Random file selection

Your selection process isn't really random.

Let's say you have structure like this:

/
/dir
/song.mp3
/dir/nonMp3File
/dir/anotherSong.mp3

Now, we enter goDeeper, and randomly select dir. On the next iteration, we randomly select nonMp3File. Now, null is returned and we restart at /. That means if you have a lot of non-mp3 files in you music folder (cover art, etc), the deeper nested the file, the less likely it will be that it will be selected, because the goDeeper returned null first.

Even if you fix 1., your program will still favor songs that are less deeply nested inside subdirectories.

This might not be a bad thing (it depends on the structure of your music directory, and how you want to select) though.

the hardcoded 123456 lets me suspect that you are not really randomly selecting among the children. Something like rand = new Random().nextInt(children.length + 1); might be better.

Infinite loop

If you don't have any MP3 files, the program will loop forever. If the ratio of MP3 to non-MP3 is bad, the program might loop for a long time before playing a song.

Naming

random might be randomFileName (both in main and goDeeper).
f might be baseDirectory (for the variable as well as the parameter).
goDeeper might be getRandomFileName.

Misc

Use curly braces, even for one-line statements to avoid bugs and to increase readability.
Remove unused variables: you are never using myProcess, so just remove it (not the call to exec, just the variable declaration).


As mentioned in my comment, it's not entirely clear what the purpose of this code is, beyond adding points to a vector. Given that, I see several things that I think could make this more clear.
Use Types
C++ is a strongly typed language and that not only gives you type safety, it also improves comprehension. The ultimate goal of this code appears to be to add several QPointfs to an array. But it's written with 3 different types to accomplish that job - whatever type x_pos and y_pos are (presumably float or double?), chars in the directions vector, and QPointf in the fieldPos vector. This is inefficient as the compiler will end up inserting a bunch of code to convert between types, but more importantly, it obscures what's happening.
I would declare directions like this:
std::vector<QPointf> directions {
    QPointf( 1.0, -1.0),
    QPointf( 1.0,  1.0),
    QPointf(-1.0,  1.0),
    QPointf(-1.0, -1.0)
};

I would change x_pos and y_pos into a single QPointf. It implements operator+=() so you can work in a similar manner as you are currently.
In general, when you find yourself using std::pair, it's a good sign that you need to use a better type like some sort of point, (mathematical) vector, or size struct. Code that uses std::pair is very difficult to read because the members, first and second are meaningless names for whatever task your code is performing.
Put the Right Things Into the Array
It might be more clear to just make a longer array with the directions you actually want instead of all the various loops. For example, instead of cramming everything into 4 QPointfs and looping over them and flipping back and forth between x and y positions, just make the array have what you want in it:
std::vector<QPointf> directions {
    QPointf( 1.0,  0.0),
    QPointf( 0.0, -1.0),
    QPointf( 1.0,  0.0),
    QPointf( 0.0, -1.0),
    // etc.
};

This will eliminate the need for multiple loops and the need to check even or odd iterations, which allows you to do the following.
Use Range-based Looping
Rather than writing a loop based on the size of the directions array and then having magic numbers like 5 in your inner loops, you can use the new C++11 and later syntax for range-based looping:
for (auto nextPoint : directions)
{
    pos += nextPoint * offset;
    fieldPos.push_back(pos);
}

But of course, you're not multiplying them all by offset. So your vector may need to contain objects of a new type in it that's something like:
typedef struct Direction {
    QPointf direction;
    float offset;
} Direction;

I'd use better names than Direction and direction, but since I don't know what they represent, I can't. If it's for a player, then PlayerDirection, or whatever's appropriate. So the loop would be more like:
for (auto nextDir : directions)
{
    pos += nextPoint.direction * nextPoint.offset;
    fieldPos.push_back(pos);
}

It means you'll end up having a long declaration for the array, but it will make the code a lot simpler. You could even put the values into a data file and read them at runtime if you think they'll change in the future.


AngularJS expression redundancy in templates

I think the way you've chosen to do it here is probably the best option.  The other reasonable options, as far as I can see, are:

moving the h3 content string and button class out of the template, and setting them in code based on isUserConnected.  So the HTML for the header would be e.g.:

{{loginPromptHeader}}

This has the disadvantage of having presentation concerns moved out of the template and into the code somewhere.
wrapping the entire HTML in an if-else statement, with each branch repeating all of the HTML structure that doesn't change.  The disadvantage of this is that it involves much more of a maintenance overhead from repeated code.  It wouldn't surprise me if this option was also more processor-intensive, because it involves more DOM elements being created/removed each time.


Consider warmwaffle's code at GitHub (re: https://github.com/warmwaffles/Noise).  The one difference I see between the two solutions is how the 'metaVector2f's are created.  Your code is using non-repeatable random numbers; whereas, the other uses a mathematical calculation which includes prime numbers and bit shifting operations.  The latter would produce a repeatable solution with the same seed versus yours.  This may be worth something if you're testing or troubleshooting elsewhere.


I think easiest way is using tags.
You can connect more then one button to one IBAction func. Just Make sure sender is UIButton.

After that change buttons tag property.

After changing tags. We just need to use switch-case

@IBAction func ButtonAction(_ sender: UIButton) {
      switch sender.tag {
            case 0:
                print("Button 1 Clicked")
            case 1:
                print("Button 2 Clicked")
            default: break
      }
}


Is there a better way to search directories for a file or files?

static void Main(string[] args)
    {
        String mask = "*.txt";
        String source = @"c:\source\";
        String destination = @"c:\destination\";

        String[] files = Directory.GetFiles(source, mask, SearchOption.AllDirectories);
        foreach (String file in files)
        {
            File.Move(file, destination + new FileInfo(file).Name);
        }
    }

Add in your own directory exists verification logic... but this should be all you need at the core.  I haven't verified this code, but these built in functions should do what you want.


Multithread to print odd and even numbers

Multiple threads are usually used to compute things in parallel.
In this example nothing is computed in parallel:
while one thread is running,
the other is waiting.
With no practical value,
it's not a great demonstration of multithreading.
I suggest to look for more practical targets in the future.

Since evenready and oddready always have opposite values,
one of them would be enough, and less error-prone.

Instead of for (; x < 10;) { it's more natural to use while (x < 10) {.

using namespace std; is considered bad practice.


This is the reason why some people want ternary operators removed from the language. It's not quite the worst abuse I've seen, but it's pretty close. This took quite a while to disentangle. I'm going to go through it in steps:

First step: make it slightly more readable. Break up everything:

return (factor<0.0f)
?
from
:
((factor>1.0f)
?
to
:
(((((from >> 24) > (to >> 24))
?
((from>>24)-(D3DCOLOR)(factor*(float)((from>>24)-(to>>24))))
:
((from>>24)+(D3DCOLOR)(factor*(float)((to>>24)-(from>>24)))))<<24)
|
(((((from<<8)>>24)>((to<<8)>>24))
?
(((from<<8)>>24)-(D3DCOLOR)(factor*(float)(((from<<8)>>24)-((to<<8)>>24))))
:
(((from<<8)>>24)+(D3DCOLOR)(factor*(float)(((to<<8)>>24)-((from<<8)>>24)))))<<16)
|
(((((from<<16)>>24)>((to<<16)>>24))
?
(((from<<16)>>24)-(D3DCOLOR)(factor*(float)(((from<<16)>>24)-((to<<16)>>24))))
:
(((from<<16)>>24)+(D3DCOLOR)(factor*(float)(((to<<16)>>24)-((from<<16)>>24)))))<<8)
|
(((((from<<24)>>24)>((to<<24)>>24))
?
(((from<<24)>>24)-(D3DCOLOR)(factor*(float)(((from<<24)>>24)-((to<<24)>>24))))
:
(((from<<24)>>24)+(D3DCOLOR)(factor*(float)(((to<<24)>>24)-((from<<24)>>24))))))));

Not a hell of a lot of improvement, but we can at least start to see some of the shifting operations here and (sort) of what they're being applied to.

Second step: make some utility functions -

typedef unsigned long D3DCOLOR;

D3DCOLOR Alpha(D3DCOLOR color)
{
    return (color >> 24);
}

D3DCOLOR Red(D3DCOLOR color)
{
    return (color << 8) >> 24;
}

D3DCOLOR Green(D3DCOLOR color)
{
    return (color << 16) >> 24;
};

D3DCOLOR Blue(D3DCOLOR color)
{
    return (color << 24) >> 24;
}

Effectively, what's being done here is masking out each part (A, R, G, B) one at a time. I'm assuming it's in this format: it doesn't really matter if it isn't, because it's doing the same thing to each byte in the long. The only thing that will change is the order, but we'll stick with these function names for now. Let's add this into the mix:

return (factor<0.0f)
?
from
:
((factor>1.0f)
?
to
:
(Alpha(from) > Alpha(to))
?
(Alpha(from) - (D3DCOLOR)(factor * (float)(Alpha(from) - Alpha(to)))
:
((Alpha(from) + (D3DCOLOR)(factor * (float)((Alpha(to)- Alpha(from))))))) << 24
|
(Red(from) > Red(to))
?
((Red(from) - (D3DCOLOR)(factor * (float)(Red(from) - Red(to))))
:
(Red(from) + (D3DCOLOR)(factor * (float)((Red(to) - Red(from)))))) << 16
|
(Green(from) > Green(to))
?
((Green(from) - (D3DCOLOR)(factor*(float)(Green(from) - Green(to)))
:
(Green(from) + (D3DCOLOR)(factor * (float)((Green(to) - Green(from)))))) << 8
|
(Blue(from) > Blue(to))
?
((Blue(from) - (D3DCOLOR)(factor * (float)(Blue(from) - Blue(to)))
:
(Blue(from) + (D3DCOLOR)(factor * (float)((Blue(to) - (Blue(from)))))) >> 24;

Ok, getting there. It's almost readable now. Note the parens here are something of a pain, and we must be careful to get them correct.

We can now do the (laborious) task of replacing ternary operators with if/else:

D3DCOLOR GetFadedColor(D3DCOLOR from, D3DCOLOR to, float factor)
{
    D3DCOLOR col = 0;

    if (factor < 0.0f) {
        col = from;
    }
    else if (factor > 1.0f) {
        col = to;
    }
    else {
        if(Alpha(from) > Alpha(to)) {
            col = (Alpha(from) - (D3DCOLOR)(factor * (float)((Alpha(from) - Alpha(to))))) << 24;
        }
        else {
            col = (Alpha(from) + (D3DCOLOR)(factor * (float)((Alpha(to)- Alpha(from))))) << 24;
        }

        if(Red(from) > Red(to)) {
            col |= (Red(from) - (D3DCOLOR)(factor * (float)((Red(from) - Red(to))))) << 16;
        }
        else {
            col |= (Red(from) + (D3DCOLOR)(factor * (float)((Red(to) - Red(from))))) << 16;
        }

        if(Green(from) > Green(to)) {
            col |= (Green(from) - (D3DCOLOR)(factor * (float)((Green(from) - Green(to))))) << 8;
        }
        else {
            col |= (Green(from) + (D3DCOLOR)(factor * (float)((Green(to) - Green(from))))) << 8;
        }

        if(Blue(from) > Blue(to)) {
            col |= (Blue(from) - (D3DCOLOR)(factor * (float)((Blue(from) - Blue(to)))));
        }
        else {
            col |= (Blue(from) + (D3DCOLOR)(factor * (float)((Blue(to) - (Blue(from))))));
        }
    }

    return col;
}

Ok, so now it's readable. This can likely be simplified further - there's quite a bit of duplication here. All that really changes are some shift values. Hopefully this is enough that you can do that simplification yourself, however.


Four-function calculator with roots and powers

I am not sure it is very clear to you what your different functions are returning as you seem to be trying to print their return value even though they do not return anything special.

You do not need to change your variable names in each function without special reason. a and b are decent names in your case, you don't need to use c and d later and then e and f as there is no way to get confused anyway.

The way you use your x variable is pretty cryptic to me. I guess this is just some testing/debugging but it would help if you could submit a clean version of your code for reviewing.

Most of what happens in your function is (pretty much) the same from one to another. A good thing to do is to try to avoid repetition whenever you can and to abstract common behaviors. The quick and dirty way I've used to avoid such a repetition was to notice that you ask the user for 2 numbers anyway so it doesn't really matter which operator we will use them for. My minimalist solution stores things in a dictionary (you could improve the content of the dictionary if you wanted to have more things changing from one operator to another such as user prompts).

#!/usr/bin/python
import operator

operations={
        'a':('Addition',      operator.add),
        's':('Substraction',  operator.sub),
        'm':('Multiplication',operator.mul),
        'd':('Division',      operator.truediv),
        'p':('Power',         operator.pow),
        'r':('Root',          lambda x, y:x**(1/y)),
}

while True:
        # TODO : Next line could be generated from the list if it keeps growing
        x = input('(Add, Subtract, Divide, Multiply, Powers, Roots or Quit)').lower()
        if x in operations:
                operation_name,operator=operations[x]
                print(operation_name)
                a = float(input('First Number:'))
                b = float(input('Second Number:'))
                print("Your answer is ",operator(a,b))
        elif x.startswith('q'):
                break
        else:
                print("Please type the first letter of what you want to do.")


Is it "legit" to use a Linq query in a razor view?

This is not an ideal way to do things. The model passed to your view should only have what you need for the view.

There are a few different things going on here. One is searching for the information and two is displaying it in your view. The solution will depend on the context in which it is happening.

One option is that you can change your service to be searchable on GroupId. This way only the information you need is passed back.

If you get an entire object back from your service and just want to filter the contacts on that more complex model, you could create a repository that does that filtering or use a ViewModel.

The main thing here is that you never want to do this type of filtering in your view. Only send your view the data that it needs.


Time table where workers overstay past midnight

It can be tough to come up with a definitive solution without having your data, but here's a few ideas that I would consider if I was having to solve this problem.

Since you have the full date and time in your data table, you could store that in your time table, and just display the time part of the date/time.  Then your elapsed time calculations would be simplified because you can use the difference between arriving and leaving that you're already calculating in the sheet.

Alternatively, if you could change your time table to allow multiple entries in one day for each person, you could have the person "leave" at midnight (23:59:59 or 24:00:00) the day the arrive, and "arrive" at 00:00:00 the next day.  This would still require some complexity in the time calculations.

If those ideas won't work for you, you can make a small improvement in your "hours" calculation.  The last part of it (MAX(D11-D10-(1/24),0)) is overly complicated.  You've just checked that (D11-D10)<(4/24), you know that D11-D10 will be >= 4/24, so the MAX calculation could just be D11-D10-(1/24).


Find length of largest substring with unique characters

I am more concerned this code does not look "javascript" enough

There's no such thing as "javascript enough". If that meant anything, for me it would be keeping it simple. The best code is one that's written in a way that you never have to run to debug. Errors will show themselves voluntarily.

  returns the length of the largest substring

But your function isn't named that way. It's named LongestSubstringNoRepeats which sounds like it returns the substring, not the length. Always name appropriately. Do not give ambiguous or confusing names. It may be popular among devs that naming is one of the two hardest problems in computer science, but that only happens because it's a detail easily missed.

substring.split("").map((char) => {
  newChars[char] = true;
});

Never use functions outside their intended purpose. array.map is intended to create another array based on the values of an existing array, a 1:1 transform. In this case, you used it as a loop. If you intend to do that, use array.forEach instead.

Also, avoid unnecessary creation of objects. In this case string.split creates an array, array.map also creates another. This operation is probably possible using only string manipulation.

let currSubstring = {
    length: 1,
    substring: s[0],
}

currSubstring.chars = {};
currSubstring.chars[s[0]] = true;

// to

let currentSubString = {
  length: 1,
  substring: s[0],
  chars: { [s[0]]: true }
}

Can be shortened by using computed property names.

One way to check for repeats is to use Set. It's like an array, but will only hold unique values. Once you add in something that already exists, Set never changes size - something you can check if a character already repeated.

Always name your variables fully and explicitly. Abbreviations should be avoided as it will only cause headaches down the road. JS can be compressed with tools so code size is never an issue. Write for a human, not for the machine.

Always provide test cases. In this case, just looking at the code doesn't give me the impression that it works. It may not work at all or has edge cases you never thought of. TDD is always a good start, especially for API-ish code/code that doesn't involve anything else other than a function that returns a value.


One simple improvement: the return type of make_array_of_2d_func_values() can be auto, to save writing std::array<std::invoke_result_t<Func, std::size_t, std::size_t>, rows * cols> twice.

I think you may be able to specialize std::tuple_size and std::get for the index table so that it doesn't require any storage even when invoked with non-constexpr arguments; I'm still experimenting but expect an update to this answer!


compare two logic commented one to my logic java

Not sure if your fixed logic actually works. But I see couple of issues with the code.

both if and else block is setting a boolean. But I don't find any use of it in your code. boolean prodPresent = false

How do you get access to items ? is it instance variable ?
The if and else block has lot of common code which can be written outside of the condition.

Here I am not concerned with your logic but tried to organize the second version of the code which you posted. My intention is to avoid repetitive code in both the if-else block

public void setOrderedProduct(String prodName, int eoq) {
PurchaseOrderDTO itemData = new PurchaseOrderDTO();
String productCd = getProdCd(prodName);

itemData.setProdname(prodName);
itemData.setQty(eoq);
itemData.setProdcd(productCd);

double costPrice = ProductView.getProductCost(vendorno, productCd);
itemData.setPrice(costPrice);

double extPrice = ProductView.getProductMSRP(vendorno, productCd);
itemData.setExt(extPrice);

if (orderedProdNameList.contains((Object) prodName)) {
  int indexOfProdName = orderedProdNameList.indexOf((Object) prodName);

  ProductView.addPurchaseDetails(itemData, vendorno);
  if (eoq > 0) {
    items.set(indexOfProdName, itemData);
    ProductView.updatePurchaseDetails(itemData, vendorno);
  } else if (eoq == 0) {
    for (int i = 0; i < items.size(); i++) {
      if (items.get(i).getProdname().equalsIgnoreCase(prodName)) {
        items.remove(i);
        ProductView.removePurchaseDetails(itemData, vendorno);
      }
    }
  }

} else {
  orderedProdNameList.add(prodName);
  items.add(items.size(), itemData);
  ProductView.addPurchaseDetails(itemData, vendorno);
}
 if (items.size() > 0) { calculateTotal(); }
}


I have not tested this that well. If anyone finds a bug, please let me know.

// Throws away the unused bits
public byte ReadFirstNBits(int n)
{
    Contract.Requires(n >= 0 && n <= 8, "Code contract may be too slow for your needs");
    byte val = base.ReadByte();
    return val >> (8 - n);
}

// Throws away the unused bits
public byte ReadLastNBits(int n)
{
    Contract.Requires(n >= 0 && n <= 8, "Code contract may be too slow for your needs");
    byte val = base.ReadByte();
    byte mask = (byte)((1 << n) - 1);
    return val & mask;
}

You can try this for yourself if you have a Python prompt:

>>> a = 0b11001001
>>> a
201
>>> a >> 4
12
>>> a >> 5
6
>>> a >> 3
25
>>> a >> 6
3
>>> a >> 2
>>> for i in range(8): print bin(a >> i)

0b11001001
0b1100100
0b110010
0b11001
0b1100
0b110
0b11
0b1
>>>


PHP code to scale images and generate thumbnails

Please don't count this as an answer. I've never done anything with any of the image libraries before, so I can't help you with the specifics. I would have put this into a comment, but its obviously too big. However, here are a few things to ponder.

First, in regards to the comments Keiran Lovett made, a class may make this a little simpler to work with, but it may also add an unnecessary level of overhead or abstraction. This seems like a relatively simple application, thus the overhead and abstraction that a class would introduce may not be worth it. It depends on a number of things, but the main ones I would contemplate are if I were going to be doing a lot of different things with these images, or how much simpler or faster/slower it would make it. Either way, I definitely would start using functions, and then if you decide to use a class it will make the transition easier.

Your maximum width and height should be made into constants, or at the very least variables. This avoids the "magic numbers" and makes it easier to use and update these values should you ever decide to change them.

define( 'MAX_Y', 524 );
define( 'MAX_X', 700 );

How do you treat images that have been rotated? An image flipped to a different aspect ratio would result in a smaller image on one axis and a skewed thumbnail. Or at least, so it would seem to me. I'm not sure how to do this, but it is something you may want to look in to.

And finally, in regards to how memory intensive this is going to be, I don't know. The best way to find out would be to run some tests and profile it. Create 100 (or more) oversize images and run the necessary code in a loop to convert each one. This is where having functions would be handy.

$start = microtime( TRUE );
for( $i = 0; $i < 100; $i++ ) {
    //functions to scale and convert
}
$total = microtime( TRUE ) - $start;


Amanda's Relationship Tips app, with scroll performance issues

What is this?

//////////////////////////CONFIGURE THE CELL//////////////////////////

////USER NAME//////////////////////////////////////

//User's Profile Picture//

////DATE LABEL (WHEN CREATED)/////////////////////////

////DESCRIPTION TEXT OF POST/////////////////////////////////

////COMMENT BUTTON/////////////////////////////////////////////////////

////////////////////////////

It's good to break your code into small, digestable chunks, but when you're using comments like this to segment them out, you're doing it wrong.

If you'd just create some small, reusable, testable methods, you wouldn't need comments like this.  The method names themselves will document every thing that's happening here.

 UILabel *cUser = (UILabel*) [cell viewWithTag:105];

 profilePictureAttributes *thumbnailImageView = (profilePictureAttributes*)[cell viewWithTag:106];

 UILabel *dateLabel = (UILabel*) [cell viewWithTag:102];

 UITextView *postLabel = (UITextView*) [cell viewWithTag:103];

 CommentButton *commentButton = (CommentButton*) [cell viewWithTag:222];

This sort of code is extraordinarily prone to error.  We've taken the time to create our WallCell class, so why add the proper methods for setting our cell up correctly?

Seems like your WallCell class should have exposed the following methods:

- (void)setPostAuthor:(NSString *)author;
- (void)setProfilePicture:(UIImage *)profilePicture;
- (void)setPostDate:(NSDate *)date;
- (void)setPostMessage:(NSString *)message;
- (void)addTarget:(id)target forAction:(SEL)action withIndex:(NSInteger)index;

Although... I might argue that it should be even simpler.  You should replace the first four methods with:

- (void)setPost:(WallPost *)post;

Where the WallPost class looks something like this:

@property User *postAuthor;
@property NSDate *postDate;
@property NSString *message;

And the User class looks something like this:

@property NSString *name;
@property UIImage *profilePicture;

(although, arguably, that last one is maybe just the URL to the picture)


You make the assumption of random accesses iterators.
It would be nice to be able to do this with any iterator (including input iterator)

template <class InIt, class OutIt>
OutIt adjacent_sum(InIt begin, InIt end, OutIt result)
{
    if (begin == end)
    {     return result;    // From @Corbin
    }

    auto  last = (*begin);  // Get the value now before incrementing the iterator.
    ++begin;
    while (begin != end)
    {
        auto next = (*begin);
        *result   = next + last;
        last      = next;

        ++result;
        ++begin;
    }
    return result;
}

Now the following works:

adjacent_sum(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),
             std::ostream_iterator<int>(std::cout, "\t"));


Store variables function-wide and access them in an anonymous function

lastSelectedIndex is already visible from eventListener. It is in fact visible from everywhere inside the immediately invoked anonymous function.

Try putting console.log("lastSelectedIndex is", lastSelectedIndex); in there and you'll see.

This is due to the concept of closures which in technical-ish terms means that when a variable is not found inside a function's context, it looks in the parent context (the context the function was in when created) and so on all the way up to the window object. In plain-english terms this means that you should forget all your Java/C#/Php training and the variables visible inside a function are exactly those that you intuitively think should be.

That being said, there is going to be only one instance of lastSelectIndex for this block of code, so if the eventlistener is ever attached to more than a single element all instances of the listener will be referencing the same lastSelectIndex.

There are plenty of ways to skin this cat and you really did not give enough details on what your trying to achieve to give advice on best practices but let me try to give some advice anyways

DO the simplest thing that can possibly work first
DON'T name your functions after how they're used (eventlistner)
DO name your functions after what they do
DON'T use data- attributes directly. Use a library like jquery, at the very least use element.dataset to retrieve them, though keep in mind the data api is not available in all browsers (which libraries handle for you)
CONSIDER having everything set up in response to a user action that triggers it so in pseudocode, the following would be all inline (and with js can be written gracefully and very compact).

when the user changes the option
 memoize the previous value
 query the server
   on success continue
   on error restore the previous value
Finally, if you do this more than a few times, CONSIDER coming up with an abstraction (possibly a custom control) for this pattern so you don't have to do it every time


Simple Caesar cipher cryptanalysis in Ruby

Nice work.  You can get some easy improvements by:

Taking advantage of ruby's functional methods to eliminate temp variables and generally make the code more declarative
Use constants where appropriate
Make your code reflect your style by using static method on a module rather than a class -- you're not actually using the class for anything in the original code.  Alternatively, you can pass in a save the ciphertext in the class constructor, and then do something like crypt_instance.analyze.
Avoid "magic numbers" like 25 or 26.

Rewrite:

module Cryptanalysis
  ALPHABET = ('A'..'Z').to_a

  ENGLISH_FREQUENCY = { :A => 0.080, :B => 0.015, :C => 0.030,
                        :D => 0.040, :E => 0.130, :F => 0.020,
                        :G => 0.015, :H => 0.060, :I => 0.065,
                        :J => 0.005, :K => 0.005, :L => 0.035,
                        :M => 0.030, :N => 0.070, :O => 0.080,
                        :P => 0.020, :Q => 0.002, :R => 0.065,
                        :S => 0.060, :T => 0.090, :U => 0.030,
                        :V => 0.010, :W => 0.015, :X => 0.005,
                        :Y => 0.020, :Z => 0.002 }

  def self.decrypt_caesar(ciphertext, shift)
    decrypt = ALPHABET
    encrypt = ALPHABET.rotate(shift)
    ciphertext.tr(encrypt, decrypt)
  end

  def self.analyze(ciphertext)
    freqs = frequencies(clean(ciphertext))

    (0..ALPHABET.size)
    .map{|i| [i, score(freqs, i)]}
    .sort_by { |x| -x[1] }
    .take(5)
    .to_h
  end

  def self.clean(text)
    text.upcase.gsub(/[^A-Z]/i, '')
  end

  def self.score(freqs, shift)
    ENGLISH_FREQUENCY
    .values
    .rotate(shift)
    .zip(freqs.values)
    .map{|x| x.first * x.last}
    .reduce(:+)
  end

  def self.frequencies(text)
    ENGLISH_FREQUENCY
    .keys
    .map {|k| [k.to_sym, text.count(k.to_s) / text.size.to_f]}
    .to_h
  end
end

text = "the quick brown fox jumps over the lazy dog"
puts 'Top 5 possible shifts: '
puts Cryptanalysis.analyze(text)


These nested loops

    for i in range(len(nums)):
        for j in range(i,len(nums)):

undoubtedly make the time complexity quadratic. This is the reason for TLE. There is no point to optimize this code; you need to rethink the approach. I don't want to spell out the linear algorithm, and deprive you the fun of finding it. Hint: think of the sliding window.

A condition j == i inside the inner loop happens exactly once, and we perfectly know when. Lift it out:

    for i in range(len(nums)):
        T[i] = nums[i]
        if T[i] == k:
            count +=1
        for j in range(i + 1, len(nums)):
            currSum = T[j-1] + nums[j]
            T[j] = currSum
            if currSum == k:
                count +=1


Robustly dealing with malformed Unicode files

The answer to your question depends on the version of python being used, and exactly what behavior you want. In Python 3.1 and up, the surrogateescape error handler can adeptly handle corrupted files that are otherwise encoded with UTF-8, and even write them back out again. Just use codecs.open(FILE, MODE, "utf-8", "surrogateescape"). If you want to know when invalid bytes were encountered, you can either scan for the relevant surrogate characters (those in the range U+DC80..U+DCFF), or compare to values you get from the replace error handler.

Through Python 2.7, it appears that the surrogateescape error handler is unavailable. You could contrast the results between the ignore and replace error handlers, but there is no convenient way to process the file in Unicode and write it out byte for byte.

In either version, you can theoretically write your own error handler that performs similarly to surrogateescape, ignore or replace, and counts the number of problems it sees. I'm uncertain whether this count can be scoped to a single file, however, as it appears an error handler only receives knowledge of the substring in question when an error is encountered.

On to a code review. Your code feels almost clunky to me. There's a stray import codecs, a lot of repetition (I can't fathom why re-reads the line with an error) and it doesn't try to leverage iterators. Perhaps you're on a particularly old version of Python (no, you use as in the except line), or perhaps you just haven't worked with iterators much. Probably most of this was from trying to extract the core issue, but I can only review it as is. I apologize for any errors in my code that follows; I haven't tested it, but I am willing to update it.

I would be strongly tempted to replace most of your code with something like this, and that's before trying to leverage anything I talked about above:

unicodeerror = 0
for i, line in enumerate(open("test.xml", "r")):
    try:
        line.decode("utf-8")
    except UnicodeDecodeError:
        print "WARNING: Encoding error in line", i+1
        unicodeerror += 1

if unicodeerror > 5:
    raise StandardError("ERROR: Too many Unicode errors")

If you need to do more, such as actually process the line, then it's reasonable to save the results of the decode, and to try again with an error handler in the except clause:

    try:
        text = line.decode("utf-8")
    except UnicodeDecodeError:
        # error tracking omitted
        text = line.decode("utf-8", "ignore")
    process(text)

If you wanted to integrate a comparison between two error handlers, it would replace the exception, so you could do something like this:

import codecs
unicodeerror = 0
for i, (ignored, replaced) in enumerate(zip(
    codecs.open("test.xml", "r", "utf-8", "ignore"),
    codecs.open("test.xml", "r", "utf-8", "replace"))):
    if ignored != replaced:
        print "WARNING: Encoding error in line", i+1
        unicodeerror += 1
if unicodeeror > 5:
    raise StandardError("ERROR: Too many Unicode errors")

And I'll leave a custom error handler totally up to you. If it works, it would probably be a lot more efficient than this approach, but there's something to be said for the simplicity of the visible code.

As a side comment, while I found this question interesting enough to delve into, the more I did so, the more it felt like a question about the right way to do this than a request to review your code. Keep in mind that it's much more on topic here to review code and make suggestions on how to improve it. So this particular approach isn't necessarily a great fit for codereview.SE.


Bug

elif ' ' or '/t' or '/n' in letter:
    new_message += letter

Provided that execution reaches that point (i.e. letter.isalpha() is false), this condition always evaluates to True, because the space character is a non-empty string.  The rest of the expression doesn't matter due to short-circuit evaluation of or.  For the record, the string consisting of the two characters / and t is always True, and the two-character string '/n' can never appear within a one-character string.

Of course, that means that the elif letter.isnumeric() and the else branches are unreachable.

Did you mean to write this instead?

elif letter in ' \t\n':
    new_message += letter

Naming

letter might not be a letter of the alphabet.  A better name would be character, char, or just c.

Design

shift would be a better as a pure function: it should accept the message as one of its parameters (instead of prompting for it) and return the enciphered result (instead of printing it).  Then, you would call

print(shift(input("Input message you would like encrypted:\n"), -1))

Why do you want to disallow certain characters?  If digits and spaces are to be passed through unmodified, why shouldn't the same be true of punctuation?

Efficiency

Strings in Python are immutable.  Every time you call += on a string, it allocates a new string and fills it with the old content and the new ending.  Therefore, += is a relatively expensive operation and should be avoided.

A better alternative would be to build a list (by appending or using a list comprehension).  Then, you construct the result by calling ''.join(…).

Pythonic cleverness

Your alphabet could just be string.ascii_lowercase instead of that list.

The classic way to implement a Caesar Cipher in Python is using str.translate().

from string import ascii_lowercase as ALPHABET

def shift(message, offset):
    trans = str.maketrans(ALPHABET, ALPHABET[offset:] + ALPHABET[:offset])
    return message.lower().translate(trans)

print(shift(input("Input message you would like encrypted:\n"), -1))


Yes, it is a variant that does the inner loop from the opposite side than the canonical version.

This has the effect that you do a lot more comparisons than you would otherwise because you cannot early out as soon as you find where the element should be inserted to.

Now for the nitpicks:

There is no need to #include<iostream> for this.

Indentation isn't consistent.


Extending native JavaScript Promise with cancellation support

You can override the executor and can pass an onCancel function to it like following:
class ResponsePromise extends Promise {
  constructor(executor) {
    const onCancel =  (cb) => {
      //using nextTick because we cant use "this" before super()
      setTimeout(()=> {
        this.cancelCb = cb;
      })
    }

    const oExecutor = (resolve, reject) => {
      executor(resolve, reject, onCancel);
    }

    super(oExecutor);
  }
  cancel() {
    if (this.cancelCb) {
      this.cancelCb();
    } else {
      console.warn('onCancel not provided');
    }
  }

I have explained this in http://w3.cafe/promise-with-progress-javascript/


Safe navigating function for nested object properties

It is a good exercise on recursion, but I'd suggest using built-in functions. Think that what you want to abstract is this syntax:

obj[a][b][c]

But doing some checking in between:

obj[a] && obj[a][b] && obj[a][b][c]

It seems to be a good job for a reducer, where obj is the accumulator, that gets passed along, and the properties are given as an array that you can reduce over, so p below will be each of the properties above:

function getDeepProp(obj, props) {
  return props.split('.').reduce(function(acc, p) {
    // if the accumulator is something
    // then lookup the next nested property
    // otherwise return undefined
    if (acc == null) return
    return acc[p]
  },obj) // the initial accumulator is the object
}

For example:

var obj = {
  a: {
    b: {
      c: 1000
    }
  }
}

console.log(getDeepProp(obj, 'a.b.c')) //=> 1000
console.log(getDeepProp(obj, 'a.b.foo')) //=> undefined

Note that acc can be an object, or an array, since arrays are objects, and the bracket syntax is the same:

console.log(getDeepProp([[[2,[3]]]], '0.0.1.0')) //=> 3

Also, I would worry about the function doing too much. If properties have not been passed, then the function shouldn't be used in the first place. That's why I'd suggest, among other reasons, to take the object (the receiver of the operation), always last:

function getDeepProp(props, obj)


How to efficently generate n different subsets of length k from List?

As noted in a comment, I did a series on my blog about interesting ways to solve this problem.  But let's think about simple ways we can modify your program to solve your problem.  We wish to produce all the subsets of source of size k, so let's add k to your method signature:

public static IEnumerable<IEnumerable<T>> SubSetsOf<T>(IEnumerable<T> source, int k)
{

All right, what is our base case?  Your original base case was "if the source is the empty set, then its only subset is the empty set".  We must modify that, because our new contract is that we only return subsets of size k.

Let's be efficient. If k is zero then we can just take the early out; we know ahead of time that there is a subset of size zero regardless of the contents of source:

    if (k == 0)
        return Enumerable.Repeat(Enumerable.Empty<T>(), 1);

Now we know that k is not zero. If the source is empty, or k is negative, then there must be no solution:

    if (k < 0 || !source.Any())
        return Enumerable.Empty<IEnumerable<T>>();

All right. That's our base case.

Now we must modify your recursive case.  We now know that k is positive, and source is not empty.

There are two possibilities: either the first element is in the subset, or it is not. What are the subsets of size k that lack the first element?

    var haveNots = SubSetsOf(source.Skip(1), k);

Super. What are the subsets of size k that contain the first element? They are the subsets of size k-1 appended with that element.

    var element = source.Take(1);
    var smallerHaveNots = SubSetsOf(source.Skip(1), k-1);
    var haves = smallerHaveNots.Select(set => element.Concat(set));

And now we're done:

    return haves.Concat(haveNots);
}

A very small modification to your algorithm greatly speeds it up.  But we could make it more efficient still.  What if, instead of an IEnumerable<T> for source we had an ImmutableStack<T> for source?  The only operations that we ever perform on source are:

Is it empty?
Extract the head
Recurse on the tail

which is exactly the operations of an immutable stack. We could do this entire operation but allocation far fewer helper objects; each time you call Skip(1), that generates a new object, but there's no need to do that; you could just use the tail of the stack.

Similarly: the outputs are a sequence of possibly-empty tails that sometimes have a head pushed onto them; you can get efficiency wins by making the outputs also immutable stacks.

See if you can go from there and make a really efficient implementation of this algorithm.


Instead of this:

for f in os.listdir(cache):
        # ...
        use_by = time.time() - 30 * 60
        if os.path.getatime(f) < use_by:
                # ...

Consider this:

use_by = time.time() - 30 * 60
for f in os.listdir(cache):
        # ...
        if os.path.getatime(f) < use_by:
                # ...

In this version, use_by is set only once, before the loop begins,
which is slightly more efficient.
Unless, you really want the timing to be re-evaluated in every iteration.

It can be error-prone and lead to nasty bugs to re-assign the loop variable (as well as method arguments), like here:

for f in os.listdir(cache):
        f = os.path.join(cache, f)

And in any case, I would recommend using more meaningful variable names, for example:

for filename in os.listdir(basedir):
    path = os.path.join(basedir, filename)

The code you posted sounds like a good idea.
It could be turned into a reusable, general function with parameters:

basedir: base directory to clean
limit: time limit to use, in minutes

Something like this:

def wipe_unused(basedir, limit):
    """
    Remove files in *basedir* not accessed within *limit* minutes

    :param basedir: directory to clean
    :param limit: minutes
    """
    atime_limit = time.time() - limit
    count = 0
    for filename in os.listdir(basedir):
        path = os.path.join(basedir, filename)
        if os.path.getatime(path) < atime_limit:
            os.remove(path)
            count += 1
    print("Removed {} files.".format(count))

if __name__ == '__main__':
    wipe_unused(os.path.join(os.getcwd(), 'cache'), 30 * 60)


Python - username and password authentication

# importing pickle

Obviously. Don't clutter your code with comments unless they add something we don't already know.

# defining variables
create_username = 0
create_password = 0
password = 0
username = 0

This is generally a bad idea, and you aren't in mid-1990s C. Don't predeclare your variables. Initialize them where they're actually used.

print(users)

If users is a plain-old dictionary, I recommend the use of pprint instead of print.

"enter username(type signup to create an account): "

This is called in-band control, and is a bad idea. What if someone's username is called "signup"? You want out-of-band control. Ask explicitly whether the user wants to sign up or log in.

if username == "signup" or username == "Signup":

Don't do two comparisons. Convert username to lowercase and compare with 'signup'.


Bot-like Spring Java service for checking advertisements

It appears that you are using Random across multiple threads. I guess you plan to replace it in the future, but still, according to the documentation:

  Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.

You should probably rewrite this to use java.util.concurrent.ThreadLocalRandom. As the docs say:

  When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention.


First off, this is just a part of the Apriori algorithm. Here, you're just finding frequent itemsets. Apriori continues to find association rules in those itemsets.

Also, using combinations() like this is not optimal. For example, if we know that the combination AB does not enjoy reasonable support, we do not need to consider any combination that contains AB anymore (ABC, ABD, etc. will all be infrequent as well). Your algorithm does not take this into consideration.

This means that your algorithm will check all the possible combinations (2n, where n is the number of possible items), while in fact we can prune the search tree as above and reduce this complexity drastically (depending on the density of the dataset).


How can I optimize this database to array structure code?

Non-optimizing suggestions

Your SQL is not very clear. What kind of object is acceptable for the type column, and how do you manage to put items into that column? How specific or general should the terms be in that column? What is the value column? label, and even optgroup? To me, these are extremely confusing. Is optgroup a group of options, or a group of outputs? This isn't official, but it's a good read and it might help you.

If each value of value (naming confusion right there!) starts with "ix", then why is it there? I can't even tell what that column means because the Earth comes between two cars! Anyways, if each entry starts with that prefix, consider adding it in your PHP.

Optimizing...

I don't see to much you can do. Your query is already quite minimal, but I'm not an expert there.


Simplify the constructor of class Library
You have a default value of None for the parameter books, but then immediately proceed to convert that None to an empty list. Why not use [] as the default value?
class Library:
    def __init__(self, books = []):
        self.books = list(books)

    ...

Note that to prevent the issue of mutable default arguments as mentioned by ojdo, you should make a copy of the initial list.
Be consistent
You take an optional list of books in the constructor of class Library, but there is no such thing in class ReadingList. That is a bit surprising.
Also be consistent with naming things. In class Library, the list of books is called books, but in class ReadlingList you named it list. I would name it books in both cases.
Also be consistent with the names of functions:

get_library() should be get_books(), since it only returns the list of books, not an object of type Library.
pages_over_n() should be get_books_with_over_n_pages() or something similar, to indicate that it returns Books, not pages.
total_pages() should be renamed get_total_pages() or calculate_total_pages(). Prefer using verbs for function names, and nouns for variables.

And I also wonder why a ComicBook has an artist, but a Novel has no author? And why is there a get_artist() but no get_title(), get_publication_date() and so on? Making everything consistent will make using your classes much easier.
Removing books from the Library
As you noticed, you can remove a book from the library, but it won't be removed from any reading lists. But that is fine. Why would a book magically disappear from a real life reading list if your library removes that book? Note that your code is perfectly fine, Python won't actually delete the Book object from memory until the last reference to it is gone.
However, if you want a book to disappear from the ReadingList when it is removed from the Library, then somehow there needs to be some communications between those two objects. There are two options:

A Library keeps a list of ReadingLists that reference its Books, and when you call remove_book() on a Library, it will in turn iterate over all the ReadingLists and call remove_book() on them as well.

A ReadingList keeps a reference to the Library whose Books it contains. Whenever you call a member function that accesses the list of books on the reading list, this member function first has to filter out all the books that are no longer in the Library.


Interview adjacency list graph problems in C++: proper graph implementation

I'll be honest: if you've completed a task in 20 minutes during an interview, I'll probably forgive a lot. I'd assume you made a lot of assumptions about the compilation environment, and you may or may not have had access to reference materials, and that your code is basically as close to pseudocode as it is to actual code. Anyone who can't at least give you that benefit of the doubt is probably someone you don't want to work for.

Given that, there are a few things I'd recommend working on.

Naming

They say that naming things is one of the hardest things in computer science. (And not just computer science - biology has a hold field of taxonomy that classifies and names things. It's hard work!) Looking at your code, it's not immediately obvious to me what the difference between a directed and a directed_node is. They both declare a list of things they're adjacent to, but one has an m_t member and an iterator.

Also, what is m_t? It looks like you're using m_ to represent member variables. That's not my favorite way of doing things, but it makes sense and is a common way of naming things, so I wouldn't ding you for it. But m_t tells me nothing beyond that it's a member of the struct. Is t in this case just an instance of T? I'd prefer something generic like value or data over t, if that's the case. But if you can clarify with a better name than any of those, all the better.

Information Hiding

It's often a good idea to hide the details of how something works from the code which calls it. That allows you to swap out something with the same interface but a different implementation. Given that, I'm wondering why all your member variables are public in directed_node and directed? You probably don't want code outside of the struct changing those values out from underneath you. So make them protected or private.

Simplify

I don't know if this is possible, but you've used std::shared_ptr<directed_node<T> in several places. Would it be possible to define it as a type? You'd probably have to do it twice - once in directed_node and once in directed, which feels wrong. Maybe it's not worth it. Likewise, you've defined adjacency_t twice but with the same definition (assuming that you use the same type for your directed_node and directed). That feels weird, but maybe it's unavoidable? Certainly, I wouldn't ding you for doing this in only 20 minutes. But in a real project, I'd expect to have a code review where we would figure out some way of simplifying that, if possible.


Changing the width of a centered progress bar

You may put your text "Boost" in a seperate element and position it.
Check this:

var inner = document.querySelector(".inner");
var cb = function() {
  var k = 1 - Date.now() % 1500 / 1500;
  inner.style.width = (k * 100).toFixed(2) + "%";
  window.requestAnimationFrame(cb);
};
cb();
.boost {
  border: 2px solid #999;
  width: 300px;
  position: relative;
  font: 16px mono;
}

.boost .inner {
  margin: 0 auto;
  background-color: #999;
}

.boost .text {
  position: absolute;
  text-align: center;
  top: 0;
  left: 0;
  width: 100%;
}

&nbsp;

BOOST

Note how position: absolute; behaves inside position: relative;.

After all I suggest you to drop this part and code it with canvas. Even CSS animations will outperform requestAnimationFrame.

Example with CSS animations:

var inner = document.querySelector(".inner");
inner.addEventListener("animationend", function () {
  // Animation just ended
  inner.parentNode.style = 'display:none;';
})
inner.style.animationDuration = '2s';
inner.style.animationName = 'boost';
.boost {
  border: 2px solid #999;
  width: 300px;
  position: relative;
  font: 16px mono;
}

.boost .inner {
  margin: 0 auto;
  background-color: #999;
  animation-timing-function: linear;
}

.boost .text {
  position: absolute;
  text-align: center;
  top: 0;
  left: 0;
  width: 100%;
}

@keyframes boost {
  0% { width: 100%; }
  100% { width: 0; }
}

&nbsp;

BOOST


It has been a while since I worked with jQuery so I may not get specific API's correct.

You are repeating ("slide", { direction: "left"}, 250), if you ever changed one of the properties I would assume you'd want them to be consistent with each other. You can set an array then destructure that when calling show or hide. You can also apply this theory to your strings such as slide-out-overlay and slideout-active for example, if you find yourself typing the same strings out, generally you want to put them in a variable (ideally a const)

// OLD
$('.slide-out').on('click', function() {
    ...
    item.hide("slide", { direction: "left" }, 250);
    ...
});

$('.slide-out-overlay').on('click', function () {
    ...
    item.hide("slide", { direction: "left" }, 250);
});

// NEW
const toggleArguments ["slide", { direction: "left" }, 250]
$('.slide-out').on('click', function() {
    ...
    item.hide(...toggleArguments);
    ...
});

$('.slide-out-overlay').on('click', function () {
    ...
    item.hide(...toggleArguments);
});

It's common practice to use guard clauses, to reduce nesting. Closely related is early return's too, you should never really need the else statement.

// OLD
$('.slide-out').on('click', function() {
    let data = 'slideout-item';
    if($(this).data(data)) {
        let item = $('.slide-out-' + $(this).data(data));
        if (something) {
            ...
        } else {
            ...
        }
    }
});

// NEW
$('.slide-out').on('click', function() {
    let data = 'slideout-item';
    if (!$(this).data(data)) {
        return;
    }

    if (item.hasClass('slideout-active') {
        ...
        return;
    }

    // do code for !item.hasClass('slideout-active')
});

It is sometimes clearer to put a $ in front of variables that are jQuery objects

// OLD
let item = $('.slide-out-' + $(this).data(data));

// NEW
let $item = $('.slide-out-' + $(this).data(data));

In your .slide-out-overlay click function, you are finding .slide-out-overlay again within the function block, when you already have the element in this

// OLD
$('.slide-out-overlay').on('click', function () {
    ...
    $('.slide-out-overlay')...
});

// NEW
$('.slide-out-overlay').on('click', function() {
    $(this)...
});

In your .slide-out-overlay click function you are looping over any array of strings and then checking if the relevant element has class slideout-active. Could you not just look for elements that have slideout-active?

// OLD
$('.slide-out-overlay').on('click', function () {
    let items = ['content', 'system', 'account', 'other'];
    let item = '.slide-out-';
    for (i = 0; i < items.length; i++) {
        if($(item + items[i]).hasClass('slideout-active')) {
            ...
});

// NEW
$('.slide-out-overlay').on('click', function () {
    const $items = $('.slideout-active');
    $items.hide("slide", { direction: "left"}, 250); // .hide works on an array of elements, as do most jQuery methods
    ...
});

You seem to be using let where you can use const. Only ever use let if you are modifying the value later on. Otherwise use const
String interpolation is also an option to concatante your strings. Although with jQuery may look a little confusing

// OLD
let item = $('.slide-out-' + $(this).data(data));

// NEW
let item = $(`.slide-out-${$(this).data(data)}`);

I would also challenge you to write this without jQuery and use vanilla javascript and CSS transitions on the classes.

Hopefully that helps!


No, it doesn't work like that because you're not escaping your PHP strings to be a safe JavaScript string. What you're doing is encoding them as JSON but if - for example - $res->token contains \ then it will produce a broken JavaScript string and JSON.stringify() won't fix it.

Correct code must use json_encode() for this purpose.

echo '<script>localStorage.setItem("id", "'.json_encode($data->id).'")</script>';

Also note that you don't need to repeat <script> tag each time:

echo '<script type="text/javascript">';
// Write all lines here, don't forget semicolon at the end of each one
echo 'localStorage.setItem("id", "'.json_encode($data->id).'");';
echo '</script>';


Is this the only or best method for classes serializing in Java?

All of your variables should be local, except for maybe the FileChooser.

You swallow exceptions.  Printing a stack trace is no substitution for proper exception handling.  (By the way, logging should be done using java.util.logging.  If you must print a stack trace manually, print it to System.err instead of System.out.)  Serialization could completely fail, and the function will still return true.  The most appropriate behaviour should be to propagate the exception to the caller.

For greater flexibility and clarity with little additional effort, I suggest overloading serialize() and deserialize() with several variants which call each other:

public class InputOutput {
    private static final FileChooser seleccionador = new FileChooser();

    /**
     * Serializes an object to a file chosen by the user using a FileChooser.
     * @return true if completed, false if user cancels the FileChooser.
     */
    public static boolean serialize(Object o) throws IOException {
        seleccionador.setTitle("Dónde guardar el estado del programa");
        File f = seleccionador.showSaveDialog(null);
        if (f == null) return false;
        serialize(o, f);
        return true;
    }

    public static void serialize(Object o, File f) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(f)) {
            serialize(o, fos);
        }
    }

    public static void serialize(Object o, FileOutputStream fos) throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(o);
        }
    }

    /**
     * Deserializes an object from a file chosen by the user using a FileChooser.
     * @return the deserialized object, or null if user cancels the FileChooser.
     */
    public static Object deserialize() throws IOException { ... }
    public static Object deserialize(File f) throws IOException { ... }
    public static Object deserialize(FileInputStream fis) throws IOException { ... }
}


I'd have serious doubts about its being the fastest possible code, but just for fun let's consider the simplest possible code to generate correct answers.

The standard library has next_permutation, which can generate all the possible permutations of a collection. So, let's consider how we do this. We start with a 2D array of distances between cities. We then have a collection to represent a route through the cities. Since each city must appear once in the collection, we can start with it just containing numbers from 0 to N in order. We then permute those, find the distance for each, keep the shortest, and we're (eventually) done.

#include <algorithm>
#include <vector>
#include <iostream>
#include <numeric>
#include <limits>

static const int max = 13;

void setup(int distances[max][max]) {
    for (int i = 0; i < max; i++) {
        distances[i][i] = 0;
        for (int j = i + 1; j < max; j++) {
            int d = rand() % 50;

            distances[i][j] = d;
            distances[j][i] = d;
        }
    }
}

int main() {
    int distances[max][max];

    setup(distances);

    std::vector<int> route(max);

    std::iota(route.begin(), route.end(), 0);

    int best_distance = std::numeric_limits<int>::max();
    do {
        int distance = 0;
        for (int i = 1; i < route.size(); i++) {
            distance += distances[route[i - 1]][route[i]];
            if (distance > best_distance)
                break;
        }
        distance += distances[route[max - 1]][0];

        if (distance < best_distance) best_distance = distance;
    } while (std::next_permutation(route.begin() + 1, route.end()));

    std::cout << "best distance: " << best_distance << "\n";
}

Now some might wonder why I'd question this being the fastest way to do the job. Generic algorithms are, after all, intended to provide nearly the speed of custom-written code--their runtime overhead is usually quite minimal.

While that's true, in this case an important optimization is missed. If we view the routes as a tree or a graph, we can stop traversing a branch as soon as we reach a node where the current distance is greater than the best distance so far. This can avoid visiting a large number of paths based on a single test.

Using next_permutation, however we don't get that optimization. Since we don't know the relationships between paths, information we obtain from traversing one path can't be used to eliminate other possible paths.

While probably pretty fast for small sets of data, this is likely to be substantially slower than many others when N gets large at all.

Note: this does not depend upon the triangle inequality (and the test data it generates almost certainly doesn't follow the triangle inequality either).


I agree with Gerard a little, you have made (in my eyes) a common error with interfaces where you've tried to make them specific to a certain type rather than what they actually do, I see this a lot in the wild (excuse the pun). This isn't to say that interfaces based on type are bad, they have their place but in general an abstract would be better suited for types as types will have unique properties that you could not declare in an interface (nor would you want to).

As an example I'll elaborate on the "Dog is also capable of chasing" example. Declaring a Dog as Feline makes no sense when trying to describe what a Dog is, instead, make it capable of doing something.

/**
 * Any animal that chases after things should implement
 * this interface.
 */
interface Chaser {
    /**
     * GET THE RABBIT!
     * @return void
     */
    public function chase();
}

On the flipside, you could easily have an interface such as:

/**
 * Any animal that is chased by another implements this
 */
interface Chasable {
    /**
     * RUN RABBIT!
     * @return void
     */
    public function beingChased();
}

So you now have interfaces that describe what they do. It now makes sense that both a Dog and a Lion can implement Chaser. Not only this, any animal class you create are capable of using it without semantic issues.

Your Canine interface suffers from the same problem (to a lesser degree). Having a canine interface is probably not a bad thing, declaring that canines only bark or howl is true. Is it true to say that no other animal species can bark or howl? what happens when this cat turns up on your doorstep? (stupid example but I found it amusing)

Cat videos aside, we now have a strange edge case where a cat is displaying canine behaviour, but it is not a canine. Enter the Barker interface (that I find both funny and embarrassing).

/**
 * Any animal that barks can extend this interface
 */
interface Barker {
    /**
     * WOOOF!!
     * @return void
     */
    public function bark();
}

Going into the nuances of having a single Cat that can bark out of a set of possibly hundreds of Cat instances is beyond what you're trying to learn but I'm hoping you get the gist of where I'm going with this, behaviour as interfaces generally work better than types and give you a lot more flexibility when actually determining what your classes do.

I'm making general statements a lot here, but you will see that your interfaces become very specific to actions. As such they are smaller and make more sense. I have found it much easier to have a class that implements 5 smaller interfaces than 1 or 2 monolithic interfaces due to the increased flexibility available and it keeps things DRY.

class Canine extends Mammal implements Chaser, Barker, Howler
{
    // I am a Canine. I am a mammal. I do things that all mammals do
    // (that also includes being an animal).
    // I can chase, bark and howl. I know this before I've written
    // any methods because my parent and interfaces say so.
}

Some tips for you moving forward:

Getters and setters are good, but can clog up your class with menial methods that achieve very little when you are not modifying data passed in or out.
Interfaces work best when they describe what something should do.
Don't rely on just interfaces to achieve what you need. I'd recommend getting stuck into common OOP design patterns sooner rather than later.

Example of the chaser and chasable interfaces in action:

First lets make our interfaces a little more rounded

/**
 * Any animal that chases after things should implement
 * this interface.
 */
interface Chaser {
    /**
     * GET THE CHASABLE ANIMAL!
     * @param Chasable
     * @return string
     */
    public function chase(Chasable $chasable);
}

/**
 * Any animal that chases after things should implement
 * this interface.
 */
interface Chasable {
    /**
     * RUN FROM THE CHASER!
     * @param Chaser
     * @return string
     */
    public function beingChased(Chaser $chaser);
}

Now let's create the chaser and the chasable animals.

/**
 * A chaser animal
 */
class Dog implements Chaser {
    /**
     * GET THE CHASABLE ANIMAL!
     * @param Chasable
     * @return string
     */
    public function chase(Chasable $chasable)
    {
        return "I'm chasing a {get_class($chasable)}!"
    }
}

class Rabbit implements Chasable {
    /**
     * RUN FROM THE CHASER!
     * @param Chaser
     * @return string
     */
    public function beingChased(Chaser $chaser)
    {
        return "Help! I'm being chased by a {get_class($chaser)}"
    }
}

Start the chase!

$dog = new Dog();
$rabbit = new Rabbit();

//We know the dog is a chaser and the rabbit is a chasable
//So we know that this will work
echo $dog->chase($rabbit);

//We know the rabbit is a chasable and the dog is a chaser
//So we know that this will work
echo $rabbit->beingChased($dog);


Created a DialogBuilder object, but having issues with subscribing/unsubscribing to dialog events

I would refactor it into a plugin that takes the content as an option. Then you will have two instances of "dialog controllers" each with its own events.

Have a look at the "plugin with data" example in the jQuery docs.

http://docs.jquery.com/Plugins/Authoring#Data

You'd set it up like

Otherwise I'd switch to $.unbind followed by $.bind in the subscribe functions.


I'd suggest that the switchMap operator be replaced with mergeMap. Only a single array of files (or an error) is going to be emitted from the bound callback, so it will never be necessary to switch; a merge is all that's required.

And the Observable.zip call could be simplified. You could use a map operator to pair the file name and the stats.

Observable.bindNodeCallback(fs.readdir)(pathToFolder)
  .mergeMap((files) => {
    const array = files.map((fileName) => Observable
      .bindNodeCallback(fs.stat)(path.join(pathToFolder, fileName))
      .map((stats) => [fileName, stats])
    );
    return Observable.concat(...array);
  })
  .filter(([fileName, stats]) => stats.mtime.getTime() > lastSync.getTime())
  .subscribe(([fileName, stats]) => parseFile(fileName));

It's possible to further simplify the composed observable by taking advantage of the fact that the operators in the concact and merge families also support arrays. So, concatAll can be used to flatten the array, emitting the file names from the readdir callback. And those file names can then be mapped to stats with a concatMap operator:

Observable.bindNodeCallback(fs.readdir)(pathToFolder)
  .concatAll()
  .concatMap((fileName) => Observable
    .bindNodeCallback(fs.stat)(path.join(pathToFolder, fileName))
    .map((stats) => [fileName, stats])
  )
  .filter(([fileName, stats]) => stats.mtime.getTime() > lastSync.getTime())
  .subscribe(([fileName, stats]) => parseFile(fileName));


Using GetTempFileName api function to check write access to a directory

If so I can rely on it and just decide based on if the returned string is empty or not

No, you may use second version but do not check for string content. More about this later.

  On windows, to find out if I have write access to a directory,

Depends what you exactly mean with write access. Your method is not bad (especially if you do not need an high performance check) however note that you're checking for permissions to:

Read file/directory list for a given directory (FILE_LIST_DIRECTORY).
Create a file in a directory (FILE_ADD_FILE).

As you can imagine this is different from write data into a file. Permissions are a complex thing and in a complex secure scenario you may have, for example, these permissions:

Granted: create a new file.
Granted: full write data into an existing file you own.
Granted: append data into an existing file you're not owner of.
Denied: discover existing files.
Denied: overwrite any existing data.
Denied: delete files (it doesn't matter if you're owner or not).

I hope I highlighted what your problem is, your actual check will fail but you still have write permissions to that folder. What you actually have to do is:

Obtain information about file security using GetFileSecurity().
Obtain DACL information about that file (GetSecurityDescriptorDacl() and GetAclInformation()).
Enumerate ACEs of your ACL to check for required permission (using GetAce() to obtain ACCESS_ALLOWED_ACE to read ACCESS_MASK field). Do not forget to interpolate these data with GetSecurityDescriptorOwner() and GetSecurityDescriptorGroup().

Funny enough to do it you need READ_CONTROL permission but they actually coincides.

What to do then? If you do need a fast implementation you may do the above (checking/skipping if insufficient permissions) and then try to write a test file (not just create it). Note that you may not have DELETE permission to remove this test file (and it may be a problem in production environments). Note that directory traverse in advanced scenarios is much more complex than you may imagine (see also FILE_TRAVERSE and BYPASS_TRAVERSE_CHECKING stuff).

Fortunately there are some ATL helper classes to simplify all these things, you may want to read The Windows Access Control Model: Part 2, in particular Do I Have Access? section.

If what you need is a simple check and you do not have a complex security setup then you may go with your own code (also second version if directory list permission is granted). Just few notes about it:

After each call to CString.GetBuffer() you must call CString.ReleaseBuffer() before object is usable again. Do it just before you call tmp_file_name.IsEmpty().
You actually do not need to check tmp_file_name content (which is actually an implementation detail even subject to change). To answer your answer then yes you may (see later) use second version but check GetTempFileName() return value, if it's zero then it failed (and you may check with GetLastError() if it's an unauthorized access error). Do not rely on output parameter, its content in case of errors is undefined.
I do not see any reason your code will throw exceptions, a catch-all statement may hide other (and more subtle) issues than write permission. I'd remove it.
You may want to use your first solution also writing something to that file if to check if you have FILE_APPEND_DATA permission. If file creation and writing are separate things (in your scenario) then first solution is the only one working.


Simplicity

Tuple unpacking and str.format can simplify the function so much:

def create_date_parition_from_key(key):
    a,b,c,_,year, month, day, _, name = key.split('/')
    return "{}/{}/{}/daily/dt={}-{}-{}/{}".format(\
            a, b, c, year, month, day, name)

If input key can change in the number of paths:

def create_date_parition_from_key(key):
    *_, year, month, day, _, name = key.split('/')
    return "{}/daily/dt={}-{}-{}/{}".format(\
            key[:key.index("/fh/")], year, month, day, name)

Exception handling

try:
    # Things
except Exception as ex:
    print(ex)
    print('Error paritioning key {}.'.format(key))
    raise ex

This is against re-use. I cannot re-use this function because it inevitably prints to the console on error, I have no way of working around it throwing an exception with try - except.

This kind of error notification should be done in the main function that has exactly the job of communicating errors / successes of the other functions to the end user.

Finally Exception is too vague and too much code is inside the try block. Please reduce the code inside try as much as possible and specify a precise Exception kind.

I just removed all exception handling in my version as in my opinion it was just making the code worse while there was no need for it.


Combining two clock tick vectors with NumPy

Everything apart from the for loop in your code is already vectorized which leaves only the for loop to be optimized.

You define a counter which is raised by 1 every time the entry of clock_ticks_coarse is 1. There exists a function cumsum in numpy which sums all entries of the argument like this:

import numpy as np

x = np.array([1,3,0,5,7])

np.cumsum(x)
# array([ 1,  4,  4,  9, 16])

It is a vectorized function, so it is very fast. Furthermore, it allows you to replace the for loop completely which should significantly boost the speed of your program. The if else condition can entirely be droped (if boolean is always zero in the else statement).

# This line replaces your whole for-loop and is vectorized
clock_ticks_coarse = np.cumsum(clock_ticks_coarse)-1

# the following lines are already vectorized, so they are fine
fine_time_array = clock_ticks_fine*fine_div
coarse_time_array = clock_ticks_coarse*corse_div
time_array = fine_time_array+coarse_time_array

np.set_printoptions(precision=3, suppress = True)
print time_array

# output

[  1.059   0.029   0.324   0.647   1.147   1.941   2.088   2.294   3.147
   3.559   4.029   4.176   4.794   5.588   6.206   6.235   7.029   7.235
   8.559   7.706   7.882   8.882   9.147   9.647   9.794  10.735  11.265
  11.706  11.794  12.647  13.147  13.471  13.5    14.529  16.059  15.
  15.382  15.559  16.265  16.706  17.176  17.382  18.265  18.824  19.088
  19.088  20.147  20.559  21.118  21.147  22.     23.559  22.559  23.059
  23.147  23.647  24.441  24.735  24.824  25.471  26.324  26.765  26.794
  27.294  27.912  28.412  28.794  29.176  30.     31.059  30.265  30.588
  31.324  31.882  32.206  32.294  33.029  33.588  34.206  34.235  35.147
  35.412  36.029  36.118  36.912  37.353  38.559  37.912  38.     38.853
  39.324  39.588  39.618  40.529  41.     41.706  41.735  42.647  42.971
  43.382]