This looks fairly good, which is why I'll be fairly harsh.

generate_file_name

Even with single arguments, I'd suggest using a line like my ($title) = @_; rather than shift: Using @_ is the dominant idiom, and it will be less confusing for non-Perl programmers.

The two substitutions can be performed in one go: s/[\s']/_/g – but why are you removing unacceptable characters before the unidecode step, which might introduce them. I find it interesting that you do not prevent characters like ", \, /. It might be more sensible to specifically allow a certain set of characters rather than disallowing some other set (where you are bound to forget something important).

But why are you even using Text::Unidecode? Not only is this module extremely limited in what it can do, but most filesystems also have some degree of support for Unicode filenames.  If we ignore this last point, I would write:

sub generate_file_name {
    my ($title) = @_;
    my $ascii_title = unidecode($title);    # transliterate Unicode
    $ascii_title =~  s/[^a-zA-z0-9.-]+/_/g;  # remove unwanted characters
    return $ascii_title;
}

set_content_file

The first problem is the word order in this function's name, it should be set_file_contents. But this still isn't a terribly good name, I'd rather say write_file. By the way, a function with this name and functionality is already provided by File::Slurp, but we might as well write it ourselves.

Using the object oriented IO::File instead of the builtin open is OK. I don't like it, but it probably makes it easier for non-Perl programmers to understand.

But there is one problem: While a file may only contain bytes, the input string may contain Unicode: You have to encode the string either explicitly, or through a PerlIO encoding layer.

The undef $fh is highly unusual. The $fh is a lexical variable – once the variable goes out of scope, the contained data's refcount is decremented and the object destroyed. Destroying a file handle will close it. undef $fh resets the scalar, which will effectively do the same thing. So it is a very confusing way of doing nothing, or saying $fh->close. Leave it.

Instead of ignoring any errors when opening a file handle fails, you should probably terminate an error or at least output a warning message.

Performing the generate_file_name transformation should happen inside this code, the details of storage are irrelevant for the other code.

We should not overwrite a file if our normalization produces the same name twice. Instead: detect this error, and at the very least produce an error message.

sub write_file {
    my ($file, $contents) = @_;
    # technically, we have a concurrency bug here between the `-e` and the `open`, but I'd ignore it.
    die qq(The file "$file" already exists. Will not overwrite) if -e $file;
    open my $fh, "<:utf8", $file or die qq(Can't open "$file": $!);
    print { $fh } $contents;
    return;
}

...

use Try::Tiny;

...

try {
    write_file($title, pQuery($_)->html);
}
catch {
    warn $_;
};

mediawiki_login

Does this function add any abstraction to the code? I think not, considering also its proximity to its only point of use.

main code

For some reason, you are using HTTP::Request::Common instead of the available LWP::UserAgent methods (which admittedly are just a wrapper).

my $response = $user_agent->post('http://johbuc6.coconia.net/mediawiki2dokuwiki.php', [ mediawiki => $article->{'*'} ]);

You should also at least check for success:

if (not $response->is_success) {
    warn qq(Request for article "$page->{title}" failed: ), $response->status_line;
    next;
}


You are right, your code is indeed very insecure. I'm not sure which part of using prepared statements you are having trouble with, and rewriting your code for you seems off-topic, but the guide for PDO prepared statements is very clear. It's first example is even an INSERT. The guide for Mysqli prepared statements also contains an example for an INSERT. Just choose either Mysqli or PDO and follow the example.

Your code is quite short, so I only have a couple of points about it:

your comment is not needed, as it doesn't add any information.
your code could use more spaces to increase readability. Eg after , and between ..
I would use the same names for the variables as the db columns have to avoid confusion. Your db column names also seem to be more accurate. I can easily understand the meaning of max_cost and total_cost, but it's not that clear what cost and price stand for.


Getting SharePoint users and comparing them with SPList

The my prefixes are unnecessary, I'd call the variables sourceList, sourceListQuery, sourceItems etc.
I'd create a method for this:

name = name.Substring(name.IndexOf("#") + 1);

I guess removeId could be a good name. The method name would help readers to understand the intent of the writer.


Static constructors generally do lead to the problems you have encountered, where the implementation tends to be procedural, and complexity increases as the constructed classes become more intricate.

This can be made more manageable by using a builder pattern, which is implemented as a class that exists for the purpose of constructing the final class. This allows you to maintain an object-oriented approach.

The builder class can be used in the static parse function, so the interface can stay the same if needed.

Ideally, the parse function should be implemented as a convenience initialiser since it is constructing an object instance.

To answer your questions:

  Should local variables such as allInput that are passed in to more than one function be instance variables?

Yes. These should be instance variables of the builder. See the example below.

  Should functions like 'determineMeetingFormat' and 'parseParticipants' be called directly into the Meeting constructor or be assigned to local constants that clearly defines what's being returned?

Yes. Local constants/variables are self documenting to some degree and hence improve readability. They also give you an easy reference to trace during debugging if needed.

  Would it be better to make location and description optional Strings rather than empty strings?

Yes. By making these optionals the compiler can help you in those places where you might need to check if the string exists. The alternative is to use isEmpty which you can only see at runtime / unit tests. Compile time checking gives more immediate results.

  Is making all my functions and instance variables static the best way to make this behave like a static class?

Not always. Static methods behave like singletons in many ways, which has many disadvantages, such as being hard to test and debug. They are often provided as conveniences which delegate to an equivalent instance method. You are essentially creating a constructor, which would be better implemented as a convenience initializer (i.e. init).

Example 1:

The example below shows one way that the builder pattern could be implemented:

Builder class

class MeetingParser {
    let input: String

    // Instance variables for the parsed values.
    // These can be optionals for more safety.
    var parsedHostCodes: [HostCode]!
    var parsedPassCodes: [PassCode]!
    var parsedPhoneNumbers: [PhoneNumber]!
    var meetingFormat: MeetingFormat!
    var participants: [Participant]!
    var isAtt: Bool
    var host: String!

    init(input: String) {
        self.input = input
    }

    func parse() {
        // The functions below would access the instance variables.
        parsedHostCodes = parseHostCode()
        parsedPasscodes = parseParticipantCode()
        parsedPhoneNumbers = parsePhoneNumber()
        meetingFormat = determineMeetingFormat()
        participants = parseParticipants()
        isAtt = input.contains(pattern: attRegex)
        host = retrieveHost()
    }
}

Meeting convenience initialiser

extension Meeting {
    init(event: EKEvent) {
        let allInput = "\(event.title)\n\(event.location)\n\(event.description)"
        let parse = MeetingParse(input: allInput)
        parser.parse()
        self.UUID = event.eventIdentifier
        self.title = event.title
        self.description = event.description
        self.location = event.location
        self.host = parser.host
        self.startTime = event.startDate
        self.endTime = event.endDate
        self.allday = event.isAllDay
        self.passcodes = parser.parsedPasscodes
        self.hostcodes = parser.parsedHostCodes
        self.phoneNumbers = parser.parsedPhoneNumbers
        self.attendees = parser.participants
        self.isAtt = parser.isAtt
        self.meetingFormat = parser.meetingFormat
    }
}

Example 2

Below is a second example, also using a builder class, although this one assumes the properties of the Meeting class are implicit optionals, which simplifies the construction to some extent. This comes at the cost of reducing safety as it potentially allows nils to be unwrapped which would result in a runtime crash.

class MeetingParser {
    let event: EKEvent
    let meeting: Meeting

    init(event: EKEvent, meeting: Meeting) {
        self.event = event
        self.meeting = meeting
    }

    func build() {
        meeting.UUID = event.eventIdentifier
        meeting.title = event.title
        meeting.description = event.description
        meeting.location = event.location
        meeting.host = retrieveHost()
        meeting.startTime = event.startDate
        meeting.endTime = event.endDate
        meeting.allday = event.isAllDay

        // Class methods re-use the values in meeting.
        // Could instead use instance variables to hold intermediate values.
        meeting.parsedHostCodes = parseHostCode()
        meeting.parsedPasscodes = parseParticipantCode()
        meeting.parsedPhoneNumbers = parsePhoneNumber()
        meeting.meetingFormat = determineMeetingFormat()
        meeting.participants = parseParticipants()
        meeting.isAtt = input.contains(pattern: attRegex)
    }
}

extension Meeting {
    // Meeting properties are defined as simplicity unwrapped optionals:
    // var title: String! = nil
    init(event: EKEvent) {
        let builder = MeetingBuilder(event: event, meeting: self)
        builder.build()
    }
}

Example usage:

let meeting = Meeting(event: event)

Other advice:

Try to reduce the overall size of the Meeting class to simplify the parser. Try to encapsulate related data into smaller classes. As an example, group the time and date information into an object to the properties for startTime, endTime and isAllDay into a single property:

enum MeetingTime {
    case allDay
    case range(start: Date, end: Date)
}

class Meeting {
    // ... other properties
    var time: MeetingTime?
    // ... other properties
}

let meeting: Meeting
meeting.time = .allDay // All day meeting.
meeting.time = .range(start: .now, end: .now) // Meeting between 2 times.


Review

property Interval and methods ExternalStart, ExternalStart should throw ObjectDisposedException if _isDisposing is true
property Interval and methods ExternalStart, ExternalStart should also acquire a lock on _syncObject
when implementing the dispose pattern make sure to include a destructor ~DisposableSafeTimer or seal your class
_isDisposing should be renamed to _disposed
when disposing, you should also clean your event listeners Elapsed = null to avoid a memory leak
do you really want to put Elapsed?.Invoke(sender, e); inside the lock? Think about possible race conditions or other side effects. What if a registered listener calls Dispose in the listener?
check out different suggestions to reset the timer. Yours is fine though.
a tiny enhancement might be to create the lock only when it is null using Interlocked.CompareExchange, instead of immediately creating an instance.


I have a nit-pick with the logic in your Either.or(A) method. You have:

public Either<A> or(A value) {
    return new Either<A>(this.value, value);
}

but, since Either is immutable (oh, should Either be a final class? ... I think so...), it makes sense that the or method can return the exact instance if it is valid.... why does it have to create a new instance each time? In a stream that can create a lot of GC churn....

I would write that method:

public Either<A> or(A value) {
    return value == null ? this : new Either<A>(value);
}

I know that essentially duplicates the constructor, but, doing it this way avoids the constructor in (hopefully) many places entirely.

This leads on to your question:

  One question I wasn't sure of the the semantics of multiple calls.
  Should I carry along the original default value, or does each new
  value become the default? So in psuedo code, should

Either.with("A").or("B").or(null)

  result in "A" (the original default) or "B"? I thought "B" made more
  sense.

If the or(A) method does not need to construct a new instance, then it makes sense to me that the semantics should return "A", since that allows skipping new instances for "B" and null.


From a short review;

ascending should probably be a parameter in the sortFunc
sort (sortKey) should probably be a parameter in the sortFunc
I feel things should be Spartan (1 char) or spelled out

sortFunc -> sortFunction -> sorter?

I would strongly consider the closure concept (example ion proposal)
I would harmonize the sort values with the object fields,or create a map
There is no need to initialize aParam and bParam with null, the default undefined should do
You probably want to add a comment as to why you compare name at the end
I prefer the if/else if approach even when if performs a return, it's one line less and increases readability

This is my counter-proposal;

const sortAscending = true;
const sortDescending = false;

function createSortFunction(key, ascending){

  const keyMap = {
    brand : 'brand.title',
    weight: 'metadata.weight',
    price: 'price.unit_amount',
    style: 'metadata.style',
    arrival: 'created'
  }

  key = keyMap[key]? keyMap[key] : 'brand.title';

  return (function sortFunction(a, b){

    //Minor magic, derive the property from a the dot notation string
    key.split('.').forEach(part=>{a = a[part], b = b[part];});

    // Sort by property, ascending or descending
    if (a < b) {
      return ascending ? -1 : 1
    }else if (b > a) {
      return ascending ? 1 : -1
    }

    // Sort by name if the properties are same
    if (a.name < b.name) {
      return -1
    } else if (a.name > b.name) {
      return 1
    }
    //a and b are equal
    return 0;
  });
}

products = [
 { name : 'Bob',   metadata: { weight: 160, style: 'sage'}, price: { unit_amount: 145}, created : '19750421', brand : { title: 'Sir' } },
 { name : 'Skeet', metadata: { weight: 130, style: 'ninja'}, price: { unit_amount: 160}, created : '20010611', brand : { title: 'Bro' } }
]

products.sort(createSortFunction('weight', sortAscending));
console.log(products);


I would recommend removing count if all it does is represent the number of items in movies. Otherwise, you'll have 2 sources of truth in the data (count and the length of movies) and code that takes sides down the line (one that believes in count and one that believes in the length of movies). So as much as possible, avoid duplicating data.

Now it's not always feasible to recompute data all the time (i.e. if you had to filter thousands of rows to count "selected" items). This is one case where I'd put a fixed number instead of recomputing it from some property. Just make sure it's documented somewhere.

for (var i in movieData.movies) {

Use regular for loops when looping through arrays. The problem with for-in is that it runs through all enumerable properties, indices and other enumerable properties. You might be getting more than what's just in the array. An even better suggestion is to use array.forEach.

$('#films').append(movieDiv);

The problem with this approach is that you're doing a jquery.append on every item. That means the browser has to re-render every time you add an item. What I suggest is to create a DOM element in memory and append to that in your loop. Then, at the very end, slap the contents of that DOM element onto the page once. This way, the browser only ever renders once.

// Creates a
 that's in memory, not yet appended to the DOM.
const replacementFilms = $('
', { id: '#films' })

movieData.movies.forEach(movie => {
  var movieDiv = '...the markup...'

  // Appends to our
 that's "in memory".
  replacementFilms.append(movieDiv)
})

// Replace the #films in the DOM with the one in memory in one go.
$('#films').replaceWith(replacementFilms)

In this example, I replaced the existing #films in the DOM. But you could also create a dummy element, append the items to it, then append its contents to a container element in the DOM. The operation doesn't have to be a total replace. But the idea is that you only ever touch the DOM once.

     '
' +
        '' +
           '' +
           '

' + movie.title + '' +
        '' +
     '
';

See Template Literals for multi-line strings and string interpolation.


Is there a circular reference in a set of template substitutions?

If you convert your dictionary into directed graph, you should be able to do a topological sorting. Kahn's algorithm works fairly well, and is easy to implement, especially if you drop all the stuff related to actual sorting.

static void ValidateIsNotCircular(Dictionary<string, IEnumerable<string>> dict)
{
    var edges = dict.SelectMany(x => x.Value.Select(y => Tuple.Create(x.Key, y))).ToList();
    var topLevelNodes = new Stack<string>(dict.Keys.Where(n => !edges.Any(e => e.Item2.Equals(n))));

    while (topLevelNodes.Any())
    {
        var node = topLevelNodes.Pop();
        var outgoingEdges = edges.Where(e => e.Item1.Equals(node)).ToArray();
        foreach(var edge in outgoingEdges)
        {
            edges.Remove(edge);
            var childNode = edge.Item2;
            var childHasIncomingEdges = edges.Any(e => e.Item2.Equals(childNode));
            if (!childHasIncomingEdges)
            {
                topLevelNodes.Push(childNode);
            }
        }
    }

    if (edges.Any())
    {
        throw new CircularPathException(edges.Select(e => e.Item1).Distinct());
    }
}

This way you don't have to deal with iterators.


Producing a nested data set from flat data

The number of nested loops can be reduced and doing so provides an opportunity to check your data for duplicate ids. This may not be necessary if you trust your source to provide good data.

var objectByCode={};

objects.forEach(function(o){
    // if( objectByCode[o.code] ) throw 'Duplicate codes';
    objectByCode[o.code]=o;
});

objects.forEach(function(o){
    if(o.areas){
        o.areas.split(",").forEach(function(c){
            if(objectByCode[c]){
                o.child.push(objectByCode[c]);
                objectByCode[c].remove=1;
            } // else { throw 'Code not found'; }
        });
    }
});

var sortedSet=objects.filter(function(o){ return !o.remove; });

Personally I would worry less about how many nested loops you have used and more about the potentially recursive data structure you are creating. This may prove difficult to work with if any of the children turn out to be their own ancestors. If for example the object with code C had area P then the resulting sortedSet would be empty. If B was a child of C then any naive attempt to list all descendants of B would result in a infinite loop.

If you are sure that your data will never contain this situation then you should be safe. If you are worried that this problem might occur a quick and dirty way to test for it is to use JSON.stringify which will throw an error when asked to produce the string equivalent of recursive objects.

try{
    JSON.stringify(sortedSet);
}catch(e){
    // how you decide to handle this is up to you
}

It might not be important to your application if this is the case, but be aware that your code may need to handle these situations.


Setting and clearing JavaScript intervals depending on browser state

I can think about two ways of doing this.

Using server

You can make your browser work as a 'listener' from the server using the
Push API, its probably the best way, but sometimes you will not have access to make changes in the server.

Using client

Create a run loop.

var interval;
var hasBeenOffline = true;
var loop = function() {
   // this will be to function that will run every X seconds
   if(online) {
      // if the server are online
      if (hasBeenOffline) {
          interval = setInterval(function() { /* code */ } )
      }
   } else {
      // server offline
      clearInterval(interval)
   }
};

setInterval(loop, 1000);

In this way you will have the a better control of the application flow, and will not be required to create the same interval twice in your code.

Some frameworks use a similiar approach, read about the Ember Run Loop to know more about the concept.


There's always a choice, even if you need some additional state:

You can add the class directly to the class and provide methods for it in the interface or go for your solution.

Adding to the class directly would look like this:

public interface IsBusyMixin {
    boolean isBusy();
    void dumbToggleBusy();

    void overlayTheComponentWithASpinner(); // implement here or not

    void removeTheSpinnerOverlay(); // implement here or not

    public void toggleBusy();
        dumbToggleBusy();
        if (isBusy) {
            overlayTheComponentWithASpinner();
        } else {
            removeTheSpinnerOverlay();
        }
    }
}

public class Foo extends Widget implements IsBusyMixin {
    @Getter private boolean isBusy;
    public void toggleBusy() {
        isBusy = !isBusy();
    }
}

I'd say, it's always somehow possible. However, it may get way uglier then your solution. Moreover, all interface methods must be public and this exposes too much of the inner state.

So when things get a bit more complicated, I wouldn't misuse default methods that hard and would go with your approach instead.

Then you may consider to to use a default method exposing the mixin and maybe another one like

default void toggleBusy() {
    this.mixin().toggleBusy();
}

  Method name overlapping, which is why multiple inheritance is bad (i.e., Widget may have a getSize() method, and IsResizeableMixin may also declare a getSize()). The solution is to give mixin methods distinctive names.

In case one of the methods always delegates to the other, you should probably keep the names the same. Otherwise it can get confusing whatever you do.

The name IsResizeableMixin should probably be just Resizeable or ResizeableMixin.


Add an HTML body class depending on specific conditions if a block region is present on the web page or not

You really do need to explain the overall purpose of your code, where this $var comes from and where this is going.

You might be suprised at the insights and thoughts you get in response.

But if we limit it to just the following code, here are my thoughts:

// Preface columns.
  if (!empty($vars['page']['preface_first']) && !empty($vars['page']['preface_second']) && !empty($vars['page']['preface_third'])) {
    $vars['attributes']['class'][] = 'preface-three';
  }
  elseif (!empty($vars['page']['preface_first']) && !empty($vars['page']['preface_second'])) {
    $vars['attributes']['class'][] = 'preface-two';
  }
  elseif (!empty($vars['page']['preface_first']) && !empty($vars['page']['preface_third'])) {
    $vars['attributes']['class'][] = 'preface-two';
  }
  elseif (!empty($vars['page']['preface_second']) && !empty($vars['page']['preface_third'])) {
    $vars['attributes']['class'][] = 'preface-two';
  }
  else {
    $vars['attributes']['class'][] = 'preface-one';
  }

More efficient is a bit vague, especially as time and memory performance wouldnt differ enough to worry about unless you were iterating over this a great many times.

But with regards to readability, its largely about consistency and purpose clarity. Your writing style WILL change over time, sometimes in drastic ways but mostly a matter of verbosity and style.

There is nothing wrong with the above code per-say, but it is a bit 'cluttered', so readability can be improved by shortening. Exactly how far depends on you at this time, as consistency and personal readability are also key, especially for others or yourself having to read this code later on for any reason.

Im not saying this is the best way to do it, but personally I might try something like this to make it shorter and more efficient:

$checks = [!empty($vars['page']['preface_first']), !empty($vars['page']['preface_second']), !empty($vars['page']['preface_third'])];
$classes = [];

// other code

$vars['attributes']['class'] = array_merge($vars['attributes']['class'],$classes);

Then maybe one of the following flavours, largely depending on whether you expect this to grow more complicated and what seems more clear to you:

very explicit/verbose:

if(!empty($checks[0]) && !empty($checks[1]) && !empty($checks[2]))
{
    $classes[] = 'preface-three';
}
elseif(!empty($checks[0]) && !empty($checks[1]))
{
    $classes[] = 'preface-two';
}
elseif(!empty($checks[0]) && !empty($checks[2]))
{
    $classes[] = 'preface-two';
}
elseif(!empty($checks[1]) && !empty($checks[2]))
{
    $classes[] = 'preface-two';
}
else
{
    $classes[] = 'preface-one';
}

more compact:

if(!empty($checks[0]) && !empty($checks[1]) && !empty($checks[2]))
{
    $classes[] = 'preface-three';
}
elseif(!empty($checks[0]) && (!empty($checks[1]) || !empty($checks[2])))
{
    $classes[] = 'preface-two';
}
elseif(!empty($checks[1]) && !empty($checks[2]))
{
    $classes[] = 'preface-two';
}
else
{
    $classes[] = 'preface-one';
}

very compact:

if(!empty($checks[0]) && !empty($checks[1]) && !empty($checks[2]))
{
    $classes[] = 'preface-three';
}
elseif((!empty($checks[0]) && (!empty($checks[1]) || !empty($checks[2]))) || (!empty($checks[1]) && !empty($checks[2])))
{
    $classes[] = 'preface-two';
}
else
{
    $classes[] = 'preface-one';
}

There is also the ternary operator, which i do use frequently when there is one condition, but rarely when there are many.

http://php.net/manual/en/language.operators.comparison.php

$classes[] = (!empty($checks[0]) && !empty($checks[1]) && !empty($checks[2]))
            ? 'preface-three'
            : ((!empty($checks[0]) && (!empty($checks[1]) || !empty($checks[2]))) || (!empty($checks[1]) && !empty($checks[2])))
                ? 'preface-two'
                : 'preface-one';

As a side note, there is also something like the following, but i dislike it as it doesnt feel natural to me, so i stopped before finishing it

if(!empty($checks[0]))
{
    if(!empty($check[1]))
    {
        if(!empty($checks[2]))
        {
            $classes[] = 'preface-three';
        }
        else
        {
            $classes[] = 'preface-two';
        }
    }
}
elseif(!empty($checks[1])
{
    // ect. ect. - not recommended in my mind
}


C++11 Singly Linked List with raw pointers

Item 1. swap does not handle sz member

Item 2.
No move constructor or operator= (no move semantic at all)

Item 3. Functions like contains get parameters by value - which is Ok for primitive types T and could be expensive for complex types

Item 4. No iterators - so not usable with algorithms. And also implementing something like remove_all is almost impossible - no indication of the remove success (except comparing size before and after), no possibility to continue scanning from the last location...

I suggest to take the std::forward_list http://en.cppreference.com/w/cpp/container/forward_list and try to emulate its API a lot closer then current attemp. Or justify your design choices explaining in more details why you think your change in the standard list API is superior to the stl approach.

Generally I like how the code looks and compiles. :)


Instead of using explicit recursion, you can build your solution out of standard Prelude functions. This frequently ends up being more readable when the functions you're writing are more complex as common patterns are expressed by familiar names instead of properties of your recursive step.
hello_worlds n = putStrLn $ unlines (replicate n "Hello World")

In this case we have n repetitions of the string "Hello World", joined by newlines, and printed to stdout.
All top-level function definitions should include type annotations as well. It's a good source of documentation, it serves as a good check that you and the type checker agree on what your function is supposed to be doing, and it often gives the type checker enough information that you don't need to use type annotations inside the body of a function. In this case, by giving a type to hello_worlds you don't need to say what the return value of readLn is, because it can be seen that the n in main must be an Int since it's the argument to hello_worlds.
hello_worlds :: Int -> IO ()
hello_worlds n = putStrLn $ unlines (replicate n "Hello World")

main :: IO ()
main = do
    n <- readLn
    hello_worlds n

The last small change I'd make is to rename hello_worlds to helloWorlds. Haskell style prefers CamelCase.


Indentation and formatting for chained jQuery methods

My suggestion:

$('.footnote[id^="ret_"]')
   .removeAttr('title')
   .removeAttr('alt')
   .mouseenter(function(e) {
      var footnote = $('#footnote_cont_' + this.id.substring(4)).html();
      $footnoteTooltip.stop(true, false);

      //only completely hide and change text/position if we are hovering over a different footnote
      if($footnoteTooltip.html() != footnote)
         $footnoteTooltip.hide().html(footnote).css({ left: e.pageX + 10, top: e.pageY + 15});

      $footnoteTooltip.fadeTo(fadeTime, opacity);
   }).mouseleave(function() {
      $footnoteTooltip.delay(fadeTime).fadeOut(fadeTime);
   });

Three or four spaces indentation - your preference. My opinion is that two spaces is more difficult to read (although Lisp uses it).
Semicolon on same line as last method call. The only time I approve of having it on it's own line is an empty while.
}).mouseLeave() I put the call on the same line as the end of the block to make it clear that you're calling the method of the object returned.


hlint

You should run hlint on your program - it's a good way to become
familiar with techniques and practices used by expert Haskellers.

Running hlint on your code returned the following suggestions:

* use camelCase instead of underscores

./passwd.hs:7:20: Warning: Redundant bracket
Found:
  (randomRIO (lo, hi) :: IO Int)
Why not:
  randomRIO (lo, hi) :: IO Int

./passwd.hs:19:5: Error: Use mapM
Found:
  sequence $ map (\ x -> random_char) [1 .. length]
Why not:
  mapM (\ x -> random_char) [1 .. length]

./passwd.hs:19:21: Warning: Use const
Found:
  \ x -> random_char
Why not:
  const random_char

sequence . map

You're right that the code for random_passwd feels hacky since
the value x is ignored. The canonical way to write this is:

import Control.Monad (replicateM)

random_passwd = replicateM length random_char

replicateM repeats a monadic action a specified number of times collecting the
results in a list.

!!

You probably already know that using !! to index into a list
is inefficient. A better data structure to use for alphabet is
Text from Data.Text which gives you O(1) indexing.

import qualified Data.Text as T

alphabet = T.pack $ ['A'..'Z'] ++ ['a'..'z'] ++ ...

random_char = do
  index <- randomR (0, T.length alphabet - 1)
  return $ T.index alpha index


Reproduce the system() function of linux

Enable compiler warnings and fix all of them

I immediately see that your function my_system(), which should return an int, does not contain a return statement. That means the return value is undefined. If you enable compiler warnings, the compiler will complain about such mistakes.

Don't add unnecessary forward declarations

Why add a forward declaration of my_system() right before the actual implementation? This is an unnecessary repetition of code. It's best to always try to not repeat yourself.

Read the man page again and pay attention to the details

You implemented the call to execl() exactly as written in the man page, but that is only the easy part. You have to ensure that the return value and the behavior in the presence of errors is exactly as the man page describes.

In particular, system() does not call error() when there is an error, instead the return value and the value of errno is used to convey the type of error that has occurred.

Create a test suite before making any changes to my_system()

You could change my_system() right now to fix any immediately obvious errors, but the temptation is very high that afterwards you consider the implementation to be complete. Instead, try to create a test suite first that calls my_system() in different ways to ensure that its behavior matches that given in the man page.
Also, instead of making assumptions of what the required behavior is, in this case you can just check what the actual system() function does.

So such a test suite could look like:

#include <assert.h>
...
const char *commands[] = {
    "/bin/true",
    "/bin/false",
    // add more commands here
    "",
    NULL,
};

for (int i = 0; ; i++) {
    int my_ret = my_system(commands[i]);
    int my_errno = errno;
    int ret = system(commands[i]);
    assert(my_ret == ret);
    if (ret == -1)
        assert(my_errno == errno);

    if(!commands[i])
        break;
}
```


I don't think you can do too much better. The things I would have done differently would be:

Make the helper methods private using private_class_method ...
I'm not quite sure why you are stripping out the leading # in several places. If you know that all searches are going to start with # then I would strip it out at the beginning (or expect the caller not to pass it in).
if text[1..text.length] =~ /[[:punct:]]/ could be written as if text =~ /.[[:punct:]]/
text[1..text.length].gsub(/([[:punct:]])/){|punc| "\\#{punc}"} There are two better ways to do this (1) Using backreferences text[1..text.length].gsub(/([[:punct:]])/, '\\\1') but (2) it really looks like you are trying to duplicate RegExp.escape
phrase.match(/#{punc_text(text)}/i).nil?, I would think that phrase.downcase.include?(text.downcase) would be cleaner


When values are pasted into a bigger range, the values should be repeated as needed to fill the range

ECMAScript 6

If you're able to use ECMAScript 6 then arrow functions could help clean up some of your code.

var dataArr = data.split('\n').map(row => row.split('\t'));

Unit Testing

You're logging the results, but it would be extremely helpful for your refactoring process to create some test cases for your function.

function test(input, expected) {
  var result = fillIn(input.data, input.numRows, input.numCols);

  function matrixEquals(m1, m2) {
    if (m1.length !== m2.length) return false;

    for (var r = 0; r < m1.length; r++) {
      if (m1[r].length !== m2[r].length) return false;

      for (var c = 0; c < m1[r].length; c++) {
        if (m1[r][c] !== m2[r][c]) return false;
      }
    }

    return true;
  }

  if (!matrixEquals(expected, result)) {
    throw "Test Failed for: input=" + JSON.stringify(input) +
      ", result=" + JSON.stringify(result);
  }
}

test({
  data: "foo\tbar",
  numRows: 2,
  numCols: 2
}, [
  ["foo", "bar"],
  ["foo", "bar"]
]);

test({
  data: "foo\tbar\nfat\tcat",
  numRows: 4,
  numCols: 4
}, [
  ["foo", "bar", "foo", "bar"],
  ["fat", "cat", "fat", "cat"],
  ["foo", "bar", "foo", "bar"],
  ["fat", "cat", "fat", "cat"]
]);

If you write your test cases well, you'll be able to tell if you broke your function simply by running the test cases.

Do you really even need to create all the arrays?

You could just extend the initial array directly:

function fillIn(data, numRows, numCols) {
  var matrix = data.split('\n').map(row => row.split('\t'));

  var missingRows = numRows - matrix.length;
  for (var r = 0; r < missingRows; r++) {
    matrix.push(matrix[r].slice());
  }

  var missingCols = numCols - matrix[0].length;
  for (var c = 0; c < missingCols; c++) {
    matrix.forEach(function(row) {
      row.push(row[c]);
    });
  }

  return matrix;
}


Different return types with same function

I prefer something like this, as its less to type and compile-time, you probably always know what kind of time you need on compile-time and even if not you can hack around that problem, so:

template<TimeUnit time>
struct TimeUnitImpl
{ using type = decltype(m_milliseconds); };

template<>
struct TimeUnitImpl<Seconds>
{ using type = decltype(m_seconds); };

template<>
struct TimeUnitImpl<Minutes>
{ using type = decltype(m_minutes); };

template<>
struct TimeUnitImpl<Hours>
{ using type = decltype(m_hours); };

template<>
struct TimeUnitImpl<Days>
{ using type = decltype(m_days); };

// used member function
template <TimeUnit unit = Seconds>
typename TimeUnitImpl<unit>::type getTime()
{
    switch (unit)
    {
    case Milliseconds: return m_milliseconds;
    case Seconds: return m_seconds;
    case Minutes: return m_minutes;
    case Hours: return m_hours;
    case Days: return m_days;
    default:
        break;
    }
}

In order to fetch a specific time unit you would have to use something like this:

getTime<Time::Milliseconds>()

Try it online!

In order to keep a "good style" I would change the function name here, too. Probably simply to time rather than getTime, that get-prefix is pretty much useless here.

But anyways, you might consider just using getTimeMilliseconds or something like that.


There is no implicit inference that S = S[S,T] = Problem[S,T]. But you can add an explicit one:

abstract class Problem[T <: SolutionFinder[S, T], S <: Problem[T, S]](solutionFinder: T) {
  this: S =>
    def solve(): Unit = solutionFinder.findSolution(this)
}

A better design might be to disentangle the Problem and Solution. Perhaps the solve could be moved out of Problem, and require the Solution only at the point of use?

trait Problem
trait Solution[P <: Problem] {def solve(p: P): Unit }
class ConcreteProblem extends Problem
class ConcreteSolution extends Solution[ConcreteProblem]
def solve[P <: Problem](p: P, s: Solution[P]) = s.solve(p)

If you need a more sophisticated relation between Problem and Solution, you could create a typeclass for the "relationship", with implicit instances available:

trait KnowsHowToSolve[P <: Problem, S <: Solution] {
  def solve(p: P, s: S): Unit
}
implicit object ConcreteProblemKnowsHowToSolveConcreteSolution extends KnowsHowToSolve[ConcreteProblem, ConcreteSolution] {
  def solve(p: ConcreteProblem, s: ConcreteSolution) = s.findSpecificSolution(p)
}
def solve[P <: Problem, S <: Solution](p: P, s: S)(implicit ks: P KnowsHowToSolve S) = ...


Python has a philosophy of "Batteries Included".  Don't reinvent what's in the standard library!

In particular, this code is much more easily written if we take advantage of IPv6Address:

import ipaddress

address = input('Please enter an IP address: ')

try:
    addr = ipaddress.IPv6Address(address)
except ipaddress.AddressValueError:
    print(address, 'is not a valid IPv6 address')
else:
    if addr.is_multicast:
        print(address, 'is an IPv6 multicast address')
    if addr.is_private:
        print(address, 'is an IPv6 private address')
    if addr.is_global:
        print(address, 'is an IPv6 global address')
    if addr.is_link_local:
        print(address, 'is an IPv6 link-local address')
    if addr.is_site_local:
        print(address, 'is an IPv6 site-local address')
    if addr.is_reserved:
        print(address, 'is an IPv6 reserved address')
    if addr.is_loopback:
        print(address, 'is an IPv6 loopback address')
    if addr.ipv4_mapped:
        print(address, 'is an IPv6 mapped IPv4 address')
    if addr.sixtofour:
        print(address, 'is an IPv6 RFC 3056 address')
    if addr.teredo:
        print(address, 'is an IPv6 RFC 4380 address')


A ValueService is used to share data among objects

You have built a system of components and shared objects, but don't use its potential. In fact, for your use case the complete setup is an overkill.

There is no component hierarchy
There are no component-sensitive or -specific values
You only need a single component to verify any incoming request

 public IActionResult postData(
        [FromRoute] string norm,
        [FromRoute] string component,
        [FromBody] ValueViewModel[] data)
    {
        Project project = new Project(norm);
        project.SetValues(data);
        return Ok(project.Valid(component));
    }

For the aforementioned reasons, I don't see a need for having a list of components and values. I would rewrite the API to be as simple as possible:

Let the factory retrieved by FactoryGenerator get the requested component
Let that component validate the input values

code:

public IActionResult postData(
        [FromRoute] string norm,
        [FromRoute] string component,
        [FromBody] ValueViewModel[] data)
    {
        var component = FactoryGenerator.GetFactory(norm).GetComponent(component);
        return Ok(component.Valid(data));
    }


Reads paragraphs of common artists separated by commas

Does this really have to be a class?
You have alot of classmethod's making me wonder if this really has to be a class.
Review

Change the datatype of Artists
You can change it to a set making the lookup a O(0)instead of O(n) operation

You never close the file
It is better to use with open(a) as a: context so python will automatically close the file

We can use collections.Counter to count the elements

Code
from collections import Counter

ARTISTS_FILE = 'list_of_artists.txt'

def read_file():
    with open(ARTISTS_FILE, "r") as f:
        return [
                    set(artist.strip().split(','))
                    for artist in f.readlines()
                ]

def make_ordered_list(artist):
    artists = read_file()
    counts = Counter()
    for similar in artists:
        if artist in similar:
            similar.remove(artist)
            counts.update(similar)
    return sorted(counts, key=lambda x: (-counts[x], x))

def main():
    artist = input("Type the artist: ")
    print(make_ordered_list(artist))

if __name__ == '__main__':
    main()


I don't understand the need for

function() {
    if (f) f();
}

put f instead of that whole thing. If it is undefined it won't get called.

e.g

.bind('show',function(event, f) {
    $(this).animate({right:0}, lag + 200, f);
});

Another thought came to me. The functions you use could be factored and used like:

function animateRight(event, f, rightValue, delay)
{
    $(this).animate({right: rightValue}, lag + delay, f);
}

(or if you can't pass that information in:

function animateRight(event, f, rightValue, delay)
{
    return new function()
    {
        $(this).animate({right: rightValue}, lag + delay, f);
    }
}


You are making it harder than it needs to be.

You just need to compare one character at a time:

private static bool IsPalindrome(string s)
{
    if (string.IsNullOrEmpty(s))
        return false;
    char[] chars = s.ToLower().ToCharArray();
    for (int i = 0; i < chars.Length / 2; i++)
        if (chars[i] != chars[chars.Length - 1 - i])
            return false;
    return true;
}

Or:

private static bool IsPalindrome(string s)
{
    if (string.IsNullOrEmpty(s))
        return false;
    char[] chars = s.ToLower().ToCharArray();
    for (int i = 0, j = chars.Length - 1 ; i < j; i++, j--)
        if (chars[i] != chars[j])
            return false;
    return true;
}


Efficient Multithreaded File Processessing in Java

I didn't look at the specific performance issue you described. However, my general review:

Readability

for (int i = 0; i < (NUM_THREADS - 1); i++) {
    docs.add(completionService.submit(new DocumentConsumer(queue)));
}

Starting at 0 and ending at somevalue - 1. Why don't you start at 1? You don't even do anything with the index, so it's not like it matters.

        e.getCause();e.printStackTrace();

Don't put multiple statements on the same line. It turns your code into a wall of code. You think understanding a wall of text is hard? Try a wall of code...

Naming

Use camelCase for methods and variables. Use PascalCase for types. Use ALL_CAPS for constants. This means that...

int NUM_THREADS = Runtime.getRuntime().availableProcessors();

should be final and

PriorityQueue<Document> Documents = new PriorityQueue<Document>();

should be renamed to documents.

public Document(int id,int Cj, HashMap<String,Integer> termMap){

Should rename Cj to cj. ... And even better would be to rename it to something that explains what it is. Right now I have no idea what a cj is.


Code review for python password generator

import string
import random
import argparse

def gen_char(lower, upper, digit, special):

    _lower_letters = string.ascii_lowercase
    _upper_letters = string.ascii_uppercase
    _digits = string.digits
    _special = "!@#$%^&*()"

Its against python convention to prefix local variables with _. Just don't do it. All of these categories would be better in a dictionary. That is create a global dict like:

CHARACTER_CATEGORIES = {
   'lower' : string.ascii_lowercase,
   'upper' : string.ascii_uppercase,
   'digits' : string.digits,
   'special' : "!@#$%^&*()"
}

Then take a list of categories as your parameters to this function instead.

    _rand = random.SystemRandom()

You should create a random number generator once in your program, not once per random choice.

    _case = ""

case? why case?

    if lower:
        _case += _lower_letters

    if upper:
        _case += _upper_letters

    if digit:
        _case += _digits

    if special:
        _case += _special

    if _case:
        return _rand.choice(_case)

    else:
        return _rand.choice(_lower_letters+_upper_letters+_digits+_special)

this is really the wrong place to do this. the decision to include all categories if non are specifically selected is part of interpretating the user's input. So you should do it when you are parsing that, not here.

def main():

    """

    The following lines of code setup the command line flags that the
    program can accept.

    """

Not a very useful comment, because its pretty obvious that's whats happening here.

    parser = argparse.ArgumentParser()

    parser.add_argument("length", type=int, help="length of password")
    parser.add_argument("--lower", "-l",
                       help="Generates passwords with lower case letters",
                       action="store_true")
    parser.add_argument("--upper", "-u",
                       help="Generates passwords with upper case letters",
                       action="store_true")
    parser.add_argument("--digit", "-d",
                       help="Generates passwords with digits",
                       action="store_true")
    parser.add_argument("--special", "-s",
                       help="Generates passwords with special characters",
                       action="store_true")

    args = parser.parse_args()

    """

    The following lines of code calls upon the gen_char() function to
    generate the password.

    """
    _pass = ""

    for x in range(args.length):

        _pass += gen_char(args.lower, args.upper, args.digit, args.special)

Its not very efficient to do it this way as other have pointed out. But its also bad because adding strings in python is expensive, better to put all the letters in a list and join them.

    print _pass

main()

Better to do

if __name__ == '__main__':
   main()

That way you could import this module elsewhere, and use its features.


Return the opposite of two known strings given one

Your first two solutions both suffer when given unexpected input.  The first is biased towards returning "maths" as a default; the second tends to return "reading".

In contrast, your colleague's function returns nil, which is probably more appropriate.  I quite like that straightforward lookup, with a minor drawback being that each string is hard-coded twice.

Here's one more suggestion.  This one crashes with TypeError: nil can't be coerced into Fixnum when given invalid input.  You should decide whether that exception is beneficial or not for your purpose.

SUBJECTS = %w(reading maths)

def matching_sub(subscription_type)
  SUBJECTS[1 - SUBJECTS.index(subscription_type)]
end


Present table of data, acquired from an endpoint, with option to sort by different values

I'm new to Vue myself so this may not be 100% accurate, just my own opinions. Kudos for learning and reaching out for feedback! You seem to have grokked a lot so I'm impressed.

Computed properties are used the same as data properties. You do not call them like methods, and you can't pass parameters to computed properties. Instead of :class="getActiveClass('recent')" you'd have to use something like :class="{active: isSortedByRecentPoints}" or :class="recentPointsHeaderClasses". But what you have works just fine IMO.
There is no penalty to importing Vue in multiple places, and it is actually good practice. Think of it like Java imports, you are declaring all of our external dependencies in your header so you know what kinds of operations this code is likely to perform without reading every single line.
The correct hook is determined by your use case. For this example any one of the hooks mentioned would work fine. For more general advise, I tend to prefer the mounted hook, but that's just me and I don't know what I don't know. Will the component get mounted multiple times? Will you have all of the data you need to make the call at created? I'm not familiar enough with the details of Vue to give more in depth advise.
For this example one Vue instance works just fine. If you want to experiment you can extract a true component from your code and create an API: The table data would be an input prop, and any actions on that data would be output events. I wouldn't consider sorting to be a reasonable output event. How about a view details event on the user?

If you're looking for extra credit I'd recommend looking into Vuex for your store. Currently you're mutating the store directly, which kind of goes against the whole point of using a store. Also a store is overkill for this example, but I'd recommend it for learning purposes. I'll give you a hint: Instead of using state in your data object you will probably want to bind directly to sortingBy and then use $store.commit to alter it in your methods. Commit will trigger a mutation to change the state, which will in turn update your component's data. You can do something similar for the table data - put it in a store and dispatch a fetchdata action to GET your data, then commit it to the state. This may seem like overkill at first (and it probably is for simple apps) until you start playing around with the time travelling debugger in the Vue devtools, hot module replacement, and the like. Super cool stuff.


Improving Custom Comparator.compare() method

You should consider using the native language/library support for work like this.

Let me prime that, by adding this private function to your clas:

private Integer getTransNombre() {
    return transportista == null ? null : transportista.getNombre();
}

That gets the number, if the transportista is not null. Now, using that function, we can create a reusable comparator instance using the tricks that Java 8 introduces. Consider these chained comparators:

private static final Comparator<SeguimientoSeccion> COMP = Comparator.comparing(SeguimientoSeccion::getYear)
        .thenComparing(SeguimientoSeccion::getMonth)
        .thenComparing(SeguimientoSeccion::getFijacion, Comparator.nullsLast(Comparator.naturalOrder()))
        .thenComparing(SeguimientoSeccion::getTransNombre, Comparator.nullsLast(Comparator.naturalOrder()));

How does that work? It gets details about the instances, if they compare as "equals" then the next test is run. You can sort nulls to the end, and you can go from there.

If you still need your comparator class, it could be:

public class SeguimientoSeccionComparator implements Comparator<SeguimientoSeccion> {
    public int compare(SeguimientoSeccion o1, SeguimientoSeccion o2) {
        return COMP.compare(o1, o2);
    }
}


How can I better the readability of inline test data?

If I'm right you could do at least two things:

Generate the array and pass only the number of items to the test method.
Rename testSequence to something more descriptive, like items, elements etc.

[TestCase(2, 1, Result = 2)]
[TestCase(2, 2, Result = 1)]
[TestCase(3, 2, Result = 2)]
[TestCase(4, 2, Result = 2)]
[TestCase(4, 10, Result = 1)]
public int TotalPageCountIsAccurate(int itemCount, int pageSize)
{
    // generates the item array with itemCount items
    var items = Enumerable.Range(0, itemCount).ToArray();

    var pagedList = new PagedList<int>(items, 0, pageSize);
    return pagedList.TotalPageCount;
}

(I can't check whether is it valid C# or not but I hope you get the idea.)

I would also create a test with an empty array.


Triangle style output, incrementing max line length

The output of your program is not as you are saying. This is the real output:

1
23
456
78910
1112131415
161718192021
22232425262728

To get your desired output, you can change this:
echo $i;

To:
echo $i." ";

This will append the extra space after each iteration.

$a
a is a poor variable name. You could make your code much clearer if you gave it a meaningful name, like $countOfNumbersToDisplay. Sure, it's a lot longer to type, but it indicates your intention much more clearly than $a.
Same goes for $b.

Avoid magic numbers
This is not very easy to understand:
      if ($i == $a){
        echo "</li><li>";

        $a = $i + 2 + $b;
        $b++;
      }

Why + 2? This really could use some clarification. I suggest to make 2 a constant with a meaningful name earlier in your code.


What can be a bit improved:

1) Some Validate.notNull() are not needed, see my comments in the code below.

2) When possible to avoid try/catch avoid it.

3) Recommended to put an error message in Apache Validate calls. See the changed isAssignableFrom().

public BaseController(final ResourceBundle configBundle, final ResourceBundle errorsBundle, final EntityManager em,
        final Class<T> clazz) throws BusinessConfigurationException {
    try {
        // Validate.notNull(configBundle);  <--- Validation for null is not needed because you will get a NPE in any case in the next line.
        this.baseURI = configBundle.getString("HOST_NAME") + configBundle.getString("APPLICATION_NAME")
                + configBundle.getString("BASE_PATH");
    } catch (NullPointerException | MissingResourceException | ClassCastException ex) {
        log.error("Cannot initialize baseURI in BaseController constructor.", ex);
        throw new BusinessConfigurationException(ex.getMessage());
    }

    if (errorsBundle != null) {
        this.errorsBundle = errorsBundle;
    } else {
        log.error("Cannot initialize errorsBundle in BaseController constructor.", ex);
        throw new BusinessConfigurationException(ex.getMessage());
    }

    if (em != null) {
        this.em = em;
    } else {
        log.error("Cannot initialize em in BaseController constructor.", ex);
        throw new BusinessConfigurationException(findErrMsg("EM_NOT_AVAILABLE"));
    }

    // No business exceptions thrown for valdidations below. This is a programmer fault.
    // Validate.notNull(clazz); <---- Not needed because the next validation will detect null clazz.
    Validate.isAssignableFrom(clazz, BaseEntity.class, "To construct BaseController the given clazz is to be of BaseEntity type but was %s", clazz);
    this.clazz = clazz;
    this.resourceName = clazz.getSimpleName().toLowerCase();
}


Character distribution
You randomly choose between uppercase, lowercase and digit characters with an equal probability, but there are more letters than digit characters. That means characters will be under-represented in your password's probability distribution. Easier and more accurate is to make one string of all eligible characters and choose from it randomly.
Redundant str
No need for str here:
str(random.choice(ascii_letters.upper()))

Move your increment
counter += 1

should not be repeated three times in if statements. You can do it once at the end of the loop. Better yet,
for _ in range(userchoice_size):

Choice list
This:
choice_list=[1,2,3]
choice_number = random.choice(choice_list)

should not use a list, and should be replaced with a call to randrange.
Secure entropy
For password generation it's crucially important to use a secure source of entropy. Read this quote carefully:

Python uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe. The Mersenne Twister is one of the most extensively tested random number generators in existence. However, being completely deterministic, it is not suitable for all purposes, and is completely unsuitable for cryptographic purposes.

Emphasis mine. A better built-in option is secrets.


Concisely handling both arrays and Backbone.Collection as parameter

setFromSongs initialises the searchResults variable and then in 2-of-3 cases it immediately overwrites it. You can rewrite the singular case to create the array containing only the single object then you don't need to initialise the variable immediately.

You are repeating the code { song: x, title: x.get('title') } in three different places - you can make the code more DRY if you create a function defined outside the class to handle the mapping of a song to its association with its title:

var associateSongWithTitle = function( song ){
  return {
    song:  song,
    title: song.get('title')
  };
};

You can then refactor the code to:

var SearchResults = Backbone.Collection.extend({
  ...
  setFromSongs: function (songs) {
      var searchResults;
      if (songs instanceof Backbone.Collection) {
          searchResults = songs.map( associateSongWithTitle );
      } else if (_.isArray(songs)) {
          searchResults = _.map(songs, associateSongWithTitle );
      } else {
          searchResults = [ associateSongWithTitle( songs ) ];
      }
      this.reset(searchResults);
  },
  ...
});


Finding shortest sequences of integers whose product is larger than n

Yes, you can improve that algorithm, by optimizing the following inequation:

$$n \le \prod_{i=1}^{k}{\lfloor\sqrt[k]{n}\rfloor+b_i} \quad \text{with} \quad b_i \in \{0, 1\}\land b_i >= b_{i+1}$$

Just initialize the guess for all factors for a given \$k\$ with \$\lfloor\sqrt[k]{n}\rfloor+1\$, and replace the factors one by one with \$\lfloor\sqrt[k]{n}\rfloor\$ while you are still above \$n\$.

That means you will effectively only need to calculate one root per \$k\$, followed by at most \$k\$ divisions, multiplications and comparisons.

Your problem would be far more complicated if being closer to \$n\$ had precedence over using the smallest factors. However, if only smallest factors are demanded, the \$k\$-th root of \$n\$ is the best approaximation you can get. Otherwise the problem would be a derivative of prime number factorization.


Removing first or last character of a string with unit-testing

You're checking both the start and end twice and you only modify when both start and end have duplicate letters. Is that intentionally?:

  if (firstName[0] != 'a' && firstName[firstName.Length - 1] != 'l' && firstName[firstName.Length - 1] != 'e')
  {
    if (firstName[0] == firstName[1] && firstName[firstName.Length - 1] == firstName[firstName.Length - 2])
    {
      return firstName.Remove(0, 1).Remove(firstName.Length - 2, 1);
    }
    else if (firstName[0] == firstName[1])
    {
      return firstName.Remove(0, 1);
    }
    else if (firstName[firstName.Length - 1] == firstName[firstName.Length - 2])
    {
      return firstName.Remove(firstName.Length - 1);
    }
  }

It could be simplified to:

  if (string.IsNullOrEmpty(name) || name.Length < 2) return name;

  if (name[0] != 'a' && name[name.Length - 1] != 'l' && name[name.Length - 1] != 'e')
  {
    if (name[0] == name[1])
      name = name.Substring(1);
    if (name.Length > 1 && name[name.Length - 1] == name[name.Length - 2])
      name = name.Substring(0, name.Length - 1);
  }
  return name;

But what about "aaronn" shouldn't the last "nn" be reduced to one 'n' in that?

If so, you'll have to check start and end separately:

string RemoveDuplicatesAtStartAndEnd(string name)
{
  if (string.IsNullOrEmpty(name) || name.Length < 2) return name;

  if (name[0] != 'a' && name[0] == name[1])
    name = name.Substring(1);
  if (name.Length > 1 && name[name.Length - 1] != 'l' && name[name.Length - 1] != 'e' && name[name.Length - 1] == name[name.Length - 2])
    name = name.Substring(0, name.Length - 1);

  return name;
}

and as shown, you'll also have to validate the input before handling it.

If you want to handle any number of duplicates chars at start and end you can do:

string RemoveDuplicatesAtStartAndEnd(string name)
{
  if (string.IsNullOrEmpty(name) || name.Length < 2) return name;

  while (name.Length > 1 && name[0] != 'a' && name[0] == name[1])
    name = name.Substring(1);

  while (name.Length > 1 && name[name.Length - 1] != 'l' && name[name.Length - 1] != 'e' && name[name.Length - 1] == name[name.Length - 2])
    name = name.Substring(0, name.Length - 1);

  return name;
}

Another way could be to use Regex:

string RemoveDuplicatesAtStartAndEnd(string name)
{
  name = Regex.Replace(name, @"^([^a])\1{1,}", m => m.Value[0].ToString());
  return Regex.Replace(name, @"([^el])\1{1,}$", m => m.Value[0].ToString());
}

Other regex approaches may be valid, but this is one way to do it.

What about upper-lower case?

Your purpose for this method is not clear, but I wouldn't be confident about it, taken all possible names into account. Manipulate names in this way seems as risky business IMO.


Finding all points on the line where distance between each of them is dividable by X

I would think that on each iteration you could remove the elements that you include in Z, i.e. your first iteration will return [-3, 0] so you could remove them from A, they will never match anything else. My solution would be:

let input      = [-3, -2, 1, 0, 8, 7, 1];
let result     = [];
let workingSet = input;

while (workingSet.length) {
  let first    = workingSet[0];
  let elements = [];
  let unused   = [];

  workingSet.forEach( value => {
    if ((value - first) % 3 == 0) {
      elements.push(value);
    } else {
      unused.push(value);
    }
  });

  console.log('elements', elements);
  if (elements.length > result.length)
    result = elements;
  workingSet = unused;
}

console.log('result', result);

One note is that you mix old style JS code like var with ES6 features like =>. I would expect code to either stick to using the older JS style for maximum browser compatibility or to stick to the newer JS style consistently.


Minor detail: I prefer putting a closing parenthesis on its own line when the content between parentheses spans more than one line. (Basically, it looks like one-true-brace style with parentheses instead of braces.) I find it makes scanning vertically much simpler. If your team/company has chosen a different convention, that's fine.

The biggest problem I see with your code is that there's no division of responsibilities. For a very simple program, this doesn't matter, but in more complex application with a bunch of different queries and behaviors, it's a huge deal. The overhead of doing it isn't that big, either, so for almost any real world program, I recommend going ahead and dealing with this. (There's nothing more permanent than a temporary, quick, and dirty solution, after all.)

Creating the connection

Start by creating the connection in one place. This lets you reuse that code in multiple places in your application, and we'll see in a minute that it makes it much simpler to execute multiple queries in a transaction.

class OraConnection {
    public static Connection openConnection(
        String db_host_name,
        String db_port,
        String db_service_name,
        String db_username,
        String db_password
    ) {
        String connection_string = String.format(
            "%s:%s:%s:@%s:%s/%s",
            "jdbc",
            "oracle",
            "thin",
            db_host_name,
            db_port,
            db_service_name
        );

        Class.forName("oracle.jdbc.driver.OracleDriver");

        return DriverManager.getConnection(
            connection_string,
            db_username,
            db_password
        );
    }
}

I also recommend hard coding the "jdbc", "oracle", "thin" string here. The main reason is that the way you're opening the connection doesn't support any other values for them. For example, you can't open a PostgreSQL connection with this code because it looks for the oracle.jdbc.driver.OracleDriver class. Since the caller can't validly pass in anything else, there's no point in providing them as arguments. If your connection opening code were more general, I wouldn't advise that. However, this exposes one of the advantages of breaking things down into smaller pieces: you could change this code to be more general and allow more connection types without changing any of your other code.

Fetching results

Then create an object to represent your query results. Callers that want to execute your query and process the results shouldn't have to worry about details like a result set, what position each column is at, and what data type each column is. All that should be sorted out by the method that executes the query, and that method should return a simple object containing the results.

class SomeTable {
    private int column1;
    private int column2;
    private String column3;
    // ...and the rest of your columns

    public SomeTable(
        int column1,
        int column2,
        String column3,
        // the rest of your cols
    ) {
        this.column1 = column1;
        // etc.
    }

    public int getColumn1() { return this.column1; }
    // the rest of your columns
}

Then put the query itself in another class.

class SomeTableQueries {
    public static List<SomeTable> fetchAllSomeTableRows(Connection connection) {
        String query = "select column1, column2, column3, /* rest of your columns */ from some_table";

        try (
            Statement statement = connection.createStatement();
            ResultSet result = statement.executeQuery(query)
        ) {
            ArrayList<SomeTable> rows = new ArrayList<SomeTable>();
            while (result.next()) {
                rows.add(SomeTable(
                    result.getInt(1),
                    result.getString(2),
                    result.getString(3)),
                    // rest of your columns
                ));
            }
            return rows;
        }
    }
}

Note that it does the following:

It hides the boiler plate of building a statement and converting the data into a simpler form from callers.
It avoids SELECT *. SELECT * is okay if you have code that can automatically figure out what the result columns are and stuff them into an appropriate object, but we haven't written code like that here. Since our column set and the order is hard coded as part of reading the data, it's better to list them explicitly.
It cleans up the Statement and ResultSet objects it creates.
Names the method to describe the query it runs

Logic that uses all this

Now that we've got separate pieces of code to do smaller pieces, we can write our main method. Note that this method must be responsible for ensuring that the connection gets closed properly.

public class PrintSomeTable {
    public static void main(String[] args) {
        try (Connection conn = OraConnection.openConnection(
            "host",
            "port",
            "service-name",
            "user",
            "pass"
        )) {
            for (SomeTable r: SomeTableQueries.fetchAllSomeTableRows(conn)) {
                System.out.println(
                    r.getColumn1() +
                    " " +
                    r.getColumn2() +
                    " " +
                    r.getColumn3()
                );
            }
        }
    }
}

Note that it would be very simple to use the same connection for more queries and operations.

Closing notes

The overall theme here is that you should use methods and classes to hide complexities that callers don't really care about, which makes understanding the code much simpler. This way, you can consider the details of each operation in an isolated scope, instead of trying to understand what each "larger" logical operation is by sorting through every little detail.

Lastly, if you have a lot of queries, seriously consider using an ORM, a micro ORM, or other similar tooling to handle a good amount of this boiler plate for you.


Minor problems and style points

The table has named columns set out already. This is problematic as the for in loop is alphabetic and thus you would be adding Name, id, mark which does not match the column headings.

It would be best to have the student fields defined as an array in the order that they are to be displayed. This can either be as dataset properties of the array or in the source code, or added to the dataset. The example has it in the source (be cause I am lazy)
Use for of rather than for(;;) and try to avoid ever using for in as it has a long list of caveats and problems associated with its use.
The function markObtained...

...seems redundant in the example you give. The data can be accessed just as easily in one pass.
...the naming is confusing withing the reduce call. names, and name are both referring to the student id. This is especially problematic as the dataset has a field called Name (which should not be capitalized)
...creates an object indexed by id, the dataset you have shown is also an Object. Both are indexed via student id, yet you don't ever use the student id to lookup a student. markObtained would be best to return an array of student id's rather than copy the student references to a new object. See Example A

The document fragment your create is not used, the last line is adding an empty fragment to the table.
A table has insertRow(), and rows have insertCell(), use them to add to the table rather than create them as DOM element via document.createElement

Extract ids

From above points regarding the function markObtained The example creates an array of student ids that can be used to locate students in the original dataset. Also renames the variables so not to be confusing.

Example A

const markObtained = Object.keys(students).reduce(function(ids, id) {
    if (students[id].mark>=20) { ids[id] = id }
    return ids;
}, []);

Adding to DOM

You are appending to the table that is on the page. Each time you add a cell or row you are forcing a re flow.

You can either create the whole table in code and add it to the DOM when ready, or you can remove the table from the DOM, modify it and put it back see Example B.

If you remove and then put back it would be best to put the table within a container to ensure it goes where it belongs without undue fuss.

Example B

const students = {
    "24": {id: 24, name: "Zuali", mark: 30},
    "25": {id: 25, name: "Famkima", mark: 52},
    "27": {id: 27, name: "Duha", mark: 77},
    "28": {id: 28, name: "Rema", mark: 81},
    "29": {id: 29, name: "Sanga", mark: 47},
    "30": {id: 30, name: "Dari", mark: 23},
};

const PASS_MARK = 20;
const FIELDS = ["id", "name", "mark"];
updateStudentsTable(students);

function addPassed(table, students, pass = PASS_MARK) {
    for (const student of students) {
        if (student.mark >= pass) {
            const row = table.insertRow();
            for (const field of FIELDS) {
                row.insertCell().textContent = student[field];
            }
        }
    }
}
function updateStudentsTable(students) {
    const table = document.querySelector("table");
    const par = table.parentElement;
    par.removeChild(table);
    addPassed(table, Object.values(students));
    par.appendChild(table);
}

                Id	Name	Mark


Filling up a numpy array using data from a list

The code to establish PxP should be in a function of its own, featuring a doc string and comments where necessary (why not use GaussianMixture(covariance_type ='spherical')?)
Same goes for kl_divergence(): when(/why?) is n_samples=10**5 appropriate?

From eyeballing your code, it would seem that you instantiate a GaussianMixture() not just once for each mixture, but (len(mixtures))²?  times.
Try to turn mixtures into GaussianMixture upfront: mixtures = [GaussianMixture().fit(mix) for mix in mixtures] (n_components=1 is default - do you need covariance_type='full'?).


Since the function may bail out without computing the result, it must signal the caller that something got wrong. Consider returning an error code.
Since you are dealing with negative numbers, testing for num > 9999999999 is not sufficient.
Along the same line, -num may overflow.
The lines

    str++;
    *(str - 1) = sign;

are a long way to say

    *str++ = sign;

That said, you seem to force a sign (a whitespace) into the output even for positives. Strictly speaking, it is not an itoa compatible behavior.
memset seems superfluous. *str = 0; after the conversion is done suffices.
I don't think that the benefits of a subtraction loop vs division/modulo are measurable. Did you profile?
The only reason to prefer itoa to sprintf is that the former supports arbitrary conversion bases. It you only need decimal conversion, I strongly recommend to stick with the latter.


1. Bugs

The special case for empty keys:

if key == "":
  yield subkey, subvalue
yield key + "." + subkey, subvalue

is missing an else: and so leads to items appearing twice:

>>> flatten_dictionary({"": {"a":1}})
{'a': 1, '.a': 1}

Even if we fix the bug by adding the else:, there's still a problem. Consider this example:

>>> flatten_dictionary({"a": {"": {"b": 1}}, "": {"a": {"b": 2}}})
{'a.b': 2}

What happened to the 1? Ignoring the empty string keys has led two different keys to be collapsed into one. It would be better to remove the special case for empty strings, so that:

>>> flatten_dictionary({"a": {"": {"b": 1}}, "": {"a": {"b": 2}}})
{'a..b': 1, '.a.b': 2}

Python has a limited stack, but dictionaries can be nested arbitrarily deeply:

>>> d = {}
>>> for i in range(1000): d = {'a':d}
...
>>> flatten_dictionary(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr186013.py", line 22, in flatten_dictionary
    return dict(items())
  [... many line omitted ...]
  File "cr186013.py", line 13, in items
    for subkey, subvalue in flatten_dictionary(value).items():
RecursionError: maximum recursion depth exceeded

This problem can be avoided using the stack of iterators pattern.

2. Other review points

The comment does not match the code: there is nothing in the code corresponding to "check if the sub-key and sub-value are inside the flatten_dict(value)" or "join on subkey array" or "clear out prev_keys". Incorrect comments like this are worse than useless: they make it harder to understand and maintain the code.

Did this comment describe an earlier version of the code, and then you changed the code but forgot to edit the comment? It is worth getting into the habit of changing the comment first so that you don't forget.
The construction of the result keys has unnecessary quadratic runtime. For example, in this situation:

>>> flatten_dictionary({'a': {'a': {'a': {'a': {'a': {'a': 1}}}}}})
{'a.a.a.a.a.a': 1}

there is only the need to concatenate one result key ('a.a.a.a.a.a'), but the code concatenates five result keys: not just the one that we need, but 'a.a', 'a.a.a', 'a.a.a.a' and 'a.a.a.a.a' as well. The way to avoid this is to keep a stack of dictionary keys currently being visited, and use str.join on the stack when you need to concatenate the result key.

3. Revised code

def flatten_dictionary(d):
    result = {}
    stack = [iter(d.items())]
    keys = []
    while stack:
        for k, v in stack[-1]:
            keys.append(k)
            if isinstance(v, dict):
                stack.append(iter(v.items()))
                break
            else:
                result['.'.join(keys)] = v
                keys.pop()
        else:
            if keys:
                keys.pop()
            stack.pop()
    return result


Review implementation for Partial Ordering of Vectors

Not much to say about it, good job!

Documentation: explain the mathematical explanation of your partial ordering unless it's really that obvious for your intended readers
Names:

In Python, names starting with uppercase letters are for class names: of course you're free to use your own convention, but this one makes it easy to share code between Python developers
Explicit is better than implicit: less is better than l which could also mean left or leave or whatever.

Style: In Python (see PEP8), we usually don't but spaces before function definitions.
Test cases: always add a test case for degenerate cases, eg. the empty list and lists of different lengths: those are the ones which usually fail.

(And +1 to the comments who should become an answer.)


It looks like you store the board after each movement for each possibility, that's a lot of arrays in memory, no wonder it fills your memory
for your second example, your code looks for 157523 positions, which is half of the total possibilities.
the number of permutations for 1:16 is enormous, the a-star algorithm is probably not sufficient
even if you look at only 1% of the total possibilities, you would need hundreds of gigabytes if not terabytes to store them
[6, 5, 4, 1, 7, 3, 9, 8, 2] solved in 26 moves after looking at 157523 positions

julia> using Combinatorics

julia> length(permutations(1:9))
362880

julia> length(permutations(1:16))
20922789888000


Calculate sum of an attribute across multiple repositories

Some quick remarks:

Why isn't PaidDate a DateTime?
What is a "Shopping"? (I realize that often naming things is hard, but be careful when inventing new English words that do not adequately describe their contents, because the next person to maintain this code will find it harder to do so when they have to first decipher various terms.)
Use descriptive names: item is way too vague.
TotalCosts and Total should be camelCased.
sum = item.Amount + sum; can be shortened to sum += item.Amount;.
Don't do if (item.ApplicationUserId == user.Id), instead use LINQ to extract the relevant records, e.g. expenseDetails.Shoppings.Where(x => x.ApplicationUserId == user.Id). And if PaidDate was a DateTime, you could easily also include that in the LINQ query and immediately calculate the sum.
Why do you do Total.ToList()? How can it be anything else?

But all of that is IMHO just plugging some small holes, while ignoring the massive dam breach elsewhere: surely this logic could be done easily in one SQL query?

On a related note: is there even a point to have a List<double> Total? I wouldn't be surprised if all you did with those is add them up.

And if you're not adding them up and always assume that the first item is the sum of Shoppings etc. and use this to display them elsewhere: please don't. In such cases always use the key-value pair structure, so you'd know that value X is definitely the sum of the Shoppings.


This problem screams "semaphore".

Have a semaphore whose count represents the number of slots available in the queue.  Enqueuers decrement the semaphore.  Dequeuers increment it.  This effectively caps the amount of nodes in the queue to some maximum, namely the initial value of the semaphore.

Likewise you can have a different semaphore represent the number of items currently enqueued.  In this case dequeuers decrement it and enqueuers increment.  For this one, the initial value is zero.  This allows dequeuers to block until an item is available.


Theres a lot of things here.

Disclaimer:

Using time stuff in JavaScript native is very hard and doesn't guarantee the cross browser. Also there are 300 of implementations of the same thing, plz don't make a new well. Please use a library like http://momentjs.com

First of all, is a little hard to read so, I started, formatting the code:

    function GetClock(){
        var d = new Date().addHours(1);
        var nday= d.getDay(),
            nmonth= d.getMonth(),
            ndate= d.getDate(),
            nyear= d.getYear();

        if(nyear<1000)
            nyear += 1900;

        var nhour= d.getHours(),
            nmin= d.getMinutes(),
            nsec= d.getSeconds(),
            ampm;

        if(nhour === 0) {
            ampm = " ";
            nhour = 12;
        } else if (nhour<12) {
            amPmSymbol =  " ";
        } else if(nhour===12) {
            ampm= " •";
        } else if(nhour>12) {
            ampm = " •";
            nhour-= 12;
        }

        if(nhour<=9)
            nhour = "0" + nhour;

        if(nmin<=9)
            nmin = "0" + nmin;

        if(nsec<=9)
            nsec = "0" + nsec;

        document.getElementById('clockbox').innerHTML =
            tday[nday] + ", " +
            tmonth[nmonth] + " " +
            ndate+", " +
            nyear + " " +
            nhour + ":" +
            nmin + ":" +
            nsec + "" + ampm + "";
    }

So, i can see some issues and repeated code on this.

This function doesn't return anything. So, why is called as Get?, I recommend use updateTime
I can split date format, from hour/time format and am/pm symbol (I guess).
also, I eliminate the unused/usefulness variables from the clock creation. Now all additional functions return strings, so, can be concatenate with the template.

function updateTime(){
    var aDate = new Date().addHours(1);
    var ndate = aDate.getDate(),
        nyear = aDate.getYear() ? ;

    if(nyear<1000)
        nyear += 1900;

    document.getElementById('clockbox').innerHTML =
        tday[aDate.getDay()] + ", " +
        tmonth[aDate.getMonth()] + " " +
        ndate + ", " +
        nyear + " " + getTimeAsFormatString(aDate);
}

function getTimeAsFormatString(aDate) {
    var hour = aDate.getHours(),
        mins = aDate.getMinutes(),
        secs = aDate.getSeconds();

    if(hour === 0) {
        hour = 12;
    } else if(hour>12) {
        hour-= 12;
    }

    hour = hour<= 9  ? "0" + hour : hour;
    mins = mins<= 9  ? "0" + mins : mins;
    secs = secs <= 9  ? "0" + secs : secs;

    return hour + ":" + mins  + ":" + secs +  "" + getAmPmSymbol(hour) + "";

}

function getAmPmSymbol(hour) {
    return (hour >= 12) ? " •" : " ";
}


Simplified if return suggestion from Android Studio

I prefer your method, because it's a lot clearer. But I would turn the if around (first check the input, then the normal action):

private boolean isTheParticipantTalking(ParticipantID participantId){
    if(mCurrentParticipant == null) {
        return false; // no one is talking
    }
    return participantId.equals(mCurrentParticipant.getId());
}

Another question is if this is actually the best approach.

Is a non-existing participant talking? That question really doesn't make so much sense.

You could use Objects.requireNonNull which seems to have been written exactly for cases like this, or throw your own NullPointerException if you want to.


Your code is not complete but perhaps I've got your idea.

self.status = get_wrapper(self.status) looks slightly strange to me (while it works, sure).

I would prefer to use class decorators:

import asyncio
import functools

import aiohttp
import requests

def public(func):
    func.public = True
    return func

def sync_api(cls):
    def wrapper(func):
        @functools.wraps(func)
        def wrapped(self, *args, **kwargs):
            url, params = func(self, *args, **kwargs)
            response = requests.get(url, params)
            _json = response.json()
            return self.process_response(_json)

    for name in dir(cls):
        func = getattr(cls, name)
        if getattr(func, 'public'):
            setattr(cls, name, wrapper(func))

def async_api(cls):
    def wrapper(func):
        @functools.wraps(func)
        @asyncio.coroutine
        def wrapped(self, *args, **kwargs):
            url, params = func(self, *args, **kwargs)
            session = self.session
            try:
                resp = yield from session.get(url, params=params)
            except Exception as ex:
                logger.exception(ex)
                raise
            try:
                _json = yield from resp.json()
                yield from resp.release()
            except Exception as ex:
                logger.exception(ex)
                resp.close()
                raise
            else:
                return self.process_response(_json)

    for name in dir(cls):
        func = getattr(cls, name)
        if getattr(func, 'public'):
            setattr(cls, name, wrapper(func))

class BaseApi:

    @public
    def status(self):
        return 'http://example.com', {}

@sync_api
class ThreadedApi(BaseApi):
    pass

@async_api
class AsyncApi(BaseApi):

    def __init__(self):
        self.session = aiohttp.Session()

P.S. Please keep in mind that yield from resp.json() may raise an exception too.

P.P.S.
If you are using Python 3.4 I strongly suggest upgrading to 3.5.

Otherwise please use famous async def/await syntax.
async with session.get() could simplify the snippet a little.


Improving and optimizing Tic-Tac-Toe game written in Python 3

#!/usr/bin/env python3

import random

board = [0]*9

Having global variables that change is considered a bad idea. You'd be better off putting this variable and the methods inside a class.

def resetBoard():
    for index, i in enumerate(board):
        board[index] = 0

You could also do board[:] = [0] * 9

def printBoard():
    counter = 0

In python you rarely need to keep track of counters like this

    s = ""

In python, you should avoid building strings by adding different pieces together

    print("|-----|-----|-----|")
    for index, i in enumerate(board):
        s += "|  "
        if(board[index] == 0):

The point of enumerate is that i is the value in board. Use it rather then refetching it here.

            s += str(index)
        if(board[index] == 1):
            s+= "x"
        if(board[index] == 2):
            s += "o"
        s += "  "

By building the string this way its hard to follow exactly what the string is.

        counter += 1
        if(counter == 3):

Instead of making the counter use `if index % 3 == 2:' Also you don't need the parens

            s += "|"
            print(s)
            print("|-----|-----|-----|")
            s = ""
            counter = 0

Your whole algorithm here is rendered more complicated because you are iterating over cells rather the rows. Your algorithm would be much more natural with rows

def getPlayers():
    return input("1 or 2 Players?")

Shouldn't this return an int, not a string?

def moveSquare(xOro, ai):

variable names are recommended to follow x_or_o as a naming convetion

    square = 0
    flag = 0

If this is a boolean flag, use False not 0

    while(board[square] != 0 or flag == 0):

No need for the parens around the while expression

        if(ai == 0):

Again use True/False for boolean flags. No need for parens

            if(xOro == 1):
                square = eval(input("Choose a square to place X: "))
            if(xOro == 2):
                square = eval(input("Choose a square to place O: "))

Avoid magic numbers like 1 and 2 to denote X and O. In this case, I'd probably pass 'x' or 'o' strings.

        if(ai == 1):

Use an else:

            square = random.randint(0, 8)
        flag = 1

Flag is really terrible variable name because I don't know what it means. Boolean flags are usually an ugly solution

    board[square] = xOro
    print("\n\n")

def checkForWin():
    if(board[0] == board[1] and board[1] == board[2] and board[2] != 0):
        return 1

Don't use magic numbers like that. Instead create some global constants to return or something

    if(board[3] == board[4] and board[4] == board[5] and board[5] != 0):
        return 1
    if(board[6] == board[7] and board[7] == board[8] and board[8] != 0):
        return 1
    if(board[0] == board[3] and board[3] == board[6] and board[6] != 0):
        return 1
    if(board[1] == board[4] and board[4] == board[7] and board[7] != 0):
        return 1
    if(board[2] == board[5] and board[5] == board[8] and board[8] != 0):
        return 1
    if(board[0] == board[4] and board[4] == board[8] and board[8] != 0):
        return 1
    if(board[2] == board[4] and board[4] == board[6] and board[6] != 0):
        return 1

A lot duplication here.

    for index, i in enumerate(board):
        if(i  == 0):
            break
        if(index == 8):
            return 2
    return 0

def gameOver():
    return eval(input("\nPress 0 and then ENTER to play again!"))

Eval is a bit dangerous because the user can put in anything they want.

# Main

You should your main logic in a function

random.seed()
quit = 0
while(quit == 0):

Make quite a boolean variable

    players = 0
    win = 0
    while(players != 1 and players != 2):
        players = eval(getPlayers())
    resetBoard()
    game = 0 #game = 1 when game is finished

Game becoming 1 when the game is finished seems backwards

    while(game == 0): #game loop
        printBoard()
        moveSquare(1, 0)
        game = checkForWin()
        if(game > 0):
            win = game
            break

Not much point checking game == 0 above if you are just going to break anyways

        printBoard()
        if(players == 1):
            moveSquare(2, 1)
        if(players == 2):
            moveSquare(2, 0)
        game = checkForWin()
        if(game > 0):
            win = game + 1
            break

See how the two parts of the loop are very similar? Suggests that you should get rid of the duplication.

    if(win == 1):
        print("\nX Wins!")
    if(win == 2):
        print("\nO Wins!")
    if(win == 3):
        print("\n The game is a draw!")
    quit = gameOver()

Having gameOver() return whether or not you should quit seems confusing. The name doesn't suggest that

exit()

Not much point in calling quit, the program is about to terminate anyways

And just to demonstrate how I'd do this:

#!/usr/bin/env python3
import random

WINNING_LINES = [
    [0, 1, 2],
    [3, 4, 5],
    [5, 6, 7],

    [0, 3, 5],
    [1, 4, 6],
    [2, 5, 7],

    [0, 4, 7],
    [2, 4, 5]
]

STALEMATE = '!'

class TicTacToe(object):
    def __init__(self):
        self.board = [' '] * 9

    def print(self):
        # make a copy of the board
        cells = self.board[:]

        # put a digit in every blank cell
        for index, cell in enumerate(cells):
            if cell == ' ':
                cells[index] = str(index)

        # put spaces around the cells
        cells = [' %s ' % cell for cell in cells]

        # print the actual board
        print('|---|---|---|')
        for start in range(0, 9, 3):
            row = cells[start:start+3]
            print('|', '|'.join(row), '|', sep = '')
            print('|---|---|---|')

    def move_square(self, player, ai):
        square = -1
        while square < 0 or square >= 9 or self.board[square] != ' ':
            if ai:
                square = random.randrange(9)
            else:
                question = "Choose a square to place {}:".format(player.upper())
                square_text = input(question)
                print(square_text)
                try:
                    square = int(square_text)
                except ValueError:
                    # user didn't enter a number
                    square = -1
        self.board[square] = player
        print("\n\n")

    def status(self):
        # check for a win
        for a, b, c in WINNING_LINES:
            if self.board[a] == self.board[b] and self.board[b] == self.board[c] and self.board[a] != ' ':
                return self.board[a]

        if not any(cell == ' ' for cell in self.board):
            return STALEMATE
        return ' '

def get_players():
    while True:
        text = input("1 or 2 players")
        try:
            value = int(text)
        except ValueError:
            pass
        else:
            if 0 < value < 3:
                return value

def play_again():
    return input("\nPress 0 and then ENTER to play again!") == '0'

GAME_OVER_MESSAGES = {
    'X' : 'X wins!',
    'O' : 'O wins!',
    '!' : 'The game is a draw!'
}

def main():

    while True:

        # create a list to denote whether
        # a player is AI
        ai_players = [False, False]
        if get_players() == 1:
            ai_players[1] = True

        tic_tac_toe = TicTacToe()
        player_turn = 0
        player_codes = 'XY'
        while tic_tac_toe.status() == ' ':
            tic_tac_toe.print()
            tic_tac_toe.move_square(player_codes[player_turn], ai_players[player_turn])
            player_turn = (player_turn + 1) % 2

        print(GAME_OVER_MESSAGES[tic_tac_toe.status()])

        if not play_again():
            break

if __name__ == '__main__':
    main()


Getting time since Unix epoch on both Windows NT and *NIX systems

Using static file-scope variables

static struct timeval lnm_current_time;
// ...
static FILETIME lnm_win32_filetime;

makes your code thread-unsafe: Two “simultaneous” invocations of your function from different threads access the same memory. (For other potential drawbacks of static file-scope variables see for example Are file-scope static variables in C as bad as extern global variables? on Software Engineering.)

And there is no reason to use static variables here. With function local variables

uint64_t lnm_getus(void) {
    uint64_t us;
#if defined(__unix__) || defined(unix) || defined(__unix) || defined(__CYGWIN__)
    struct timeval lnm_current_time;
    gettimeofday(&lnm_current_time, NULL);
    // ...
#elif defined(_WIN32) || defined(__WINDOWS__)
    FILETIME lnm_win32_filetime;
    GetSystemTimeAsFileTime(&lnm_win32_filetime);
    // ...
#endif
    return us;
}

the variables are defined exactly where they are needed, which makes the code easier to read and to argue about, and avoids the threading problem.


With regard to your question about adding ,, just do

$new_user_id = $_COOKIE['user_id'];

if ($subs['subscribed_user_id'] === '') {
  $new_user_id = $subs['subscribed_user_id'] . ',' . $new_user_id;
}

With that said, the details of how you add the comma is not the issue here.

I began rewriting the code, but since the db interactions make the code hard to test and work with, I honestly couldn't be bothered to properly finish it.

You should

Wrap the functionality in a actual function taking parameters to remove use of $_ globals.
Stop using the ancient and deprecated mysql extension. In fact, don't use (the much better) mysqli either, at the very least, adopt PDO, or better yet, a tool that removes the low level details of managing the DB.
Fix the injection vulnerability in your update query.
Consider whether you really should be comma separating values in the column. Perhaps you should instead add a new row?

Some code I started writing, but didn't finish because I have better things to do than setting up the db I would need.

function update_user_id($user_id, $subs, $cookie) {
  $subs = mysql_fetch_array(mysql_query("SELECT subscribed_user_id FROM users WHERE user_id = " . (int) $user_id));

  $subs_array = explode(',', $subs['subscribed_user_id']);

  if (!in_array($cookie['user_id'], $subs_array)) {
    $new_user_id = $cookie['user_id'];

    if ($subs['subscribed_user_id'] === '') {
      $new_user_id = $subs['subscribed_user_id'] . ',' . $new_user_id;
    }

    mysql_query("UPDATE users SET subers = subers + 1, subscribed_user_id = '" . $new_user_id . "' WHERE user_id = ". (int) $user_id);
  }
}