How can I re-write the conditionals for this button

Narrow types with TypeScript instead of erroring There are many places in the code where you check a condition based on how the Button is being called, and if it isn't fulfilled, you log an error and return nothing. This is a reasonable approach in JavaScript, but in TypeScript, you have a much better option, which is to use types to require only certain arguments. This way, rather than an error being thrown at runtime, an error will be thrown by TypeScript at compile-time when a user of Button attempts to pass props that aren't valid. Turning typos / accidental incorrect function calls into compile-time errors is one of the greatest advantages of TypeScript, and it's great that you're using TypeScript already, so go ahead and take advantage of it.
For example, rather than:
const availableColors = ['blue', 'grey', 'dark-grey', 'white'];
const borderColors = [''];
let buttonStyle;

// Check if props.color exists in availableColors
if(!availableColors.includes(props.color)) {
  console.error(`"${props.color} color key not available for button style`);
  return;
}

You can make availableColors as a type instead, and require that the color prop matches it:
'blue' | 'grey' | 'dark-grey' | 'white'
Similarly, rather than
if(!props.content) {
  console.error(`"${props.content} is not valid as content`);

you can require that the content property is of type:
T & (T extends '' ? 'Content must not be empty' : {})

and instead of
if(props.type !== 'link') {

require a type of 'link' | '' exactly.
Using the above methods will also let you declare buttonStyle and elementType with const - or you could even inline their values into the props.
Default export? You have:
export default function Button

This will mean that the imported button is not really tied to its Button name anymore. For example, it would be easy for someone to initially type:
import button from './Button';

only to run into problems since they forgot to capitalize it. Using named exports makes these sorts of typos more difficult, because one has to intentionally rename it to get something other than Button:
// Natural import
import { Button } from './Button';

or
// Deliberate renaming
import { Button as RenamedVariableName } from './Button';

Destructure immediately Rather than referencing props multiple times in the function body, you might consider extracting the properties from the props immediately in the function definition - it makes the logic later less noisy.
Let TS infer types when possible There's no need to note that a function returns a particular type if

TypeScript can already infer the type automatically, and
The type is obvious to a reader of a code at a glance

So, you may consider removing the JSX.Element from (props: Props): JSX.Element.
buttonStyles? It sounds like buttonStyles is an object that contains strings, where the strings are class names. So buttonStyles isn't a very precise variable name - it doesn't contain styles, it contains class names. Maybe instead call it buttonClassNamesByColor?
Fragments In newer versions of React, you may use <> and </> instead of <React.Fragment> </React.Fragment>. Or, even better, since you're returning only a single JSX element regardless, you can use the conditional operator to return either one or the other element, without wrapping everything in a fragment.
export const Button = <T extends string>({
    content,
    color,
    path,
    type,
}: {
    content: T & (T extends '' ? 'Content must not be empty' : {});
    color: 'blue' | 'grey' | 'dark-grey' | 'white';
    path?: string;
    type: '' | 'link';
}) => {
    const buttonClassName = buttonClassNamesByColor[`button--${color}`];
    return type === ''
        ? <button className={buttonClassName}>{content}</button>
        : <Link to={path} className={buttonClassName}>{content}</Link>;
}


Build a flat List from a Tree structure in Java

To answer the question from the comment on RoToRa's answer:

  Thanks! I wonder if there is any way to do this by using, for example, just the Java 8 Stream API or something similar, to have it in just one line of code.

Using the Java Stream API

Assuming the following Entry class:

public class Entry {
   final String key;
   final List<Entry> entries = new ArrayList<>();

   Entry(String _key, Entry ...children) {
      key = _key;
      entries.addAll(Arrays.asList(children));
   }

   public List<Entry> getEntries() {
      return Collections.unmodifiableList(entries);
   }

   public String toString() {
      return key;
   }
}

We can build up the example input with:

List<Entry> top = new ArrayList<>();
top.add(new Entry("level1.1"));
top.add(new Entry("level1.2", new Entry("level2.1")));
top.add(new Entry("level1.3", new Entry("level2.2"), new Entry("level2.3", new Entry("level3.1"))));

From @RoToRa's answer, we'll borrow these method signatures:

public static List<Entry> flatTree(List<Entry> toFlat) {
   return flatTree(toFlat, ArrayList::new);
}

public static List<Entry> flatTree(List<Entry> toFlat, Supplier<List<Entry>> listSupplier) {

Now, to flatten with the Stream API, (the requested "one line of code"), we'd want to write something like:

   return toFlat.stream().flatMap(Entry::leaves)
                         .collect(Collectors.toCollection(listSupplier));
}

So, we'll need to define Entry::leaves to extract only the leaves from our tree:

public static Stream<Entry> leaves(Entry entry) {
   if (entry.getEntries().size() > 0)
      return entry.getEntries().stream().flatMap(Entry::leaves);
   else
      return Stream.of(entry);
}

And on the sample data:

jshell> System.out.println(Entry.flatTree(top));
[level1.1, level2.1, level2.2, level3.1]

jshell>


My teacher often tells me that I don't take full advantage of Python capabilities

Try partitioning with list comprehensions.

import random

def quicksort(s):
    len_s = len(s)
    if len_s < 2:
        return s

    pivot = s[random.randrange(0, len_s)]

    L = [x for x in s if x < pivot]
    E = [x for x in s if x == pivot]
    G = [x for x in s if x > pivot]

    return quicksort(L) + E + quicksort(G)

This is Pythonic, compact and faster than your partition function.

Furthermore, notice the pivot is random. Your original code always uses zero for the pivot. This results in worst-case O(n^2) complexity for sorted inputs. A random pivot mitigates this risk.

As for style, the answer from @janos offers solid guidance also.


Try not to use using namespace std.
You don't need an explicit return 0 at the end of main().  As reaching the end of main() already implies successful termination, the compiler will do the return for you.
In C++, use std::size_t over size_t, the former being part of the std namespace.
Consider having your function print true or false instead of 1 or 0.  You could do this by putting std::boolalpha into the output stream before the function call.

cout << std::boolalpha << arrayComparer(ptr1,asize,ptr2,bsize) << endl;

There is no need for this:

std::size_t intSize = sizeof(int);

You can just use sizeof(int) for both size calculations, so that you can only have size variables that correspond to array sizes.  Extra possible overhead is not a problem because sizeof() is actually an operator, not a function.
If your compiler supports C++11, you can use an std::array instead of C-style arrays.  If not, use an std::vector.  They both know their own sizes, and you'll no longer need your own pointers.

Raw pointer use in C++ should generally be avoided whenever possible, and passing raw pointers can introduce ownership issues.  Passing C-style arrays to functions is also bad because they will decay to pointers.  If you must use them anyway, at least for this exercise, then perhaps you can declare ptr1 and ptr2 within arrayComparer() instead of passing them from main().


Performance/Optimization of Knapsack(ish) algorithm for move generation for a game

In your recursive generateMoves method, you can reduce a huge amount of the duplicates by limiting where in the centerCards list you operate in.

My suggestion would be to pass that list through the recursion with a pointer to your current position in the array.... for example:

generateMoves(Card myCard,ArrayList<Card> CurrentMove,
          ArrayList<Card> centerCards, int centercardpos,
          ArrayList<Move> moves, int moveSum)

Then, in your method you can change the loop:

for (Card card :centerCards) { ...

to be:

for (int ci = centercardpos; ci < centerCards.size(); ci++) {
    Card card = centerCards.get(i);

        generateMoves(myCard, CurrentMove, centerCards,
               centercardpos + 1, // new increased limit.....
               moves, moveSum);

This will substantially reduce the number of possible moves (and still get the right answers). Reducing the values you gnerate will also substantially reduce duplicates, which in turn will also improve th pwerformance of removeDuplicates ...

The only time removeDuplicates will have effect is when you have something like (using your example: [5,4,3,2,1,2] ) the moves [5,2] and [5,2] (but the 'other' 2).


Function that checks if array only contains elements of a specific type

The implementation could be written more compactly using arrow functions, for example:

if (type === null || type === undefined) {
  return arr.every(e => e === type);
}

return arr.every(e => Object.getPrototypeOf(Object(e)) === type.prototype);

There are two arr.every calls at different execution paths.
You could eliminate that duplicated logic by extracting the function parameter of arr.every to a variable:

var checker;
if (type === null || type === undefined) {
  checker = e => e === type;
} else {
  checker = e => Object.getPrototypeOf(Object(e)) === type.prototype;
}

return arr.every(checker);


Converting images to greyscale using JuicyPixel

Python

What does your Python code look like? I'm sure that most of
the work is actually being done in C, not Python. JuicyPixels
allows you to write an arbitrary pixel mapping function in Haskell.
If the Python library called a user-supplied Python function to convert
every pixel I can assure you that it wouldn't be as fast as it is.

Other Libraries

That said, JuicyPixels may not be the fastest Haskell library to use.
For instance, Haskell can call routines in C libraries, and there are
Haskell bindings to the ImageMagick library via the imagemagick
package.

Another package you should have a look at is friday.
On assorted algorithms it compares favorable with ImageMagick,
It cannot produce SIMD instructions, so it's not as fast
as libraries such as OpenCV. On the other hand, it gives you the
tools to construct your own image transformations so it's a lot more
versitile than a library which gives you just a handful of canned
algorithms.

Improving pixelAvg

Obviously the function pixelAvg is the hot spot in the program, so
anything we can do to optimize it will have a significant impact on
the execution time. Here are some versions I tried:

pixelAvg (PixelRGB8 r g b) =

-- (1) original version:
   (r `div` 3 + g `div` 3 + b `div` 3) + (r `mod` 3 + g `mod` 3 + b `mod` 3) `div` 3

-- (2) use quot and rem:
   (quot r 3 + quot g 3 + quot b 3) + (quot (rem r 3 + rem g 3 + rem b 3) 3)

-- (3) use quotRem:
   let (rq,rr) = quotRem r 3
       (gq,gr) = quotRem g 3
       (bq,br) = quotRem b 3
   in (rq+gq+bq + (rr+gr+br) `quot` 3)

-- (4) simplify the expression
   (div r 3 + div g 3 + div b 3)

-- (5) just use one division
   fromIntegral $ ((fromIntegral r + fromIntegral g + fromIntegral g) :: Int) `quot` 3

-- (6) use a lookup table
   V.unsafeIndex avgVector (fromIntegral r + fromIntegral g + fromIntegral b)

Here are some timings I obtained on a 4246 x 2856 image:

(1) 0m2.796s
(2) 0m2.768s
(3) 0m2.440s
(4) 0m2.297s
(5) 0m2.198s
(6) 0m2.117s

quot/rem avoids a sign check and therefore should be marginally faster than div/mod
while giving the same answers for positive arguments. However an even bigger speed-up
can be obtained by computing both the quotient and remainder with one function call
(either quotRem or divMod) as demonstrated by (3).

Note that the formula used by (4) only differs from the original formula by at most 2
and has a lot fewer operations. Formula (5) reduces the number of divisions to
just one by converting all three pixel values to Ints, adding and then dividing the
total by 3.

As to be expected, the lookup table method is is the overall fastest. Here's the rest
of the code that initializes the table:

import qualified Data.Vector.Unboxed as V
...
avgVector :: V.Vector Pixel8
avgVector = V.generate (3*256) (\x -> fromIntegral $ div x 3)

So there are significant gains to be made by optimizing pixelAvg, but there are
also limitations to what you can achieve.  To get better results you'll likely
have to use a different library.


Showing a table for open and closed tickets

I'm going to assume that this is in fact a ruby-on-rails project - not just plain Ruby.

In that case, long story short: Stop doing everything in the view. Use Rails and its conventions.

In your model, add a proper relationship to the user, and a couple of scopes

belongs_to :user

scope :open, where(status: :open)
scope :closed, where(status: :closed)

Also add a method

def waiting_for_reply?
  # I don't quite understand your logic (or your naming) here,
  # so I'll just shorten it, but otherwise leave it
  ticketmessages.last.try(:user_id).present?
end

I say I don't understand your logic, because something called ticketmessages implies there's a class called Ticketmessage - when it should be called TicketMessage as it's two words (or simply Message). And in that case, the relation should be ticket_messages with an underscore (or, again, simply messages).
Secondly, you check whether there is a (last) ticket, and whether its user_id is non-nil/non-false. But what does that prove? If there's any system to how it's set up, a message will always have a user_id because every message was written by a user. The real question (I assume) is whether that user_id is equal to the ticket's user_id - otherwise someone else wrote it. But that's not what you're checking, so I'm confused.

Anyway, in your controller, load two collections (and eagerly load the associated users):

@open_tickets = Ticket.open.includes(:user)
@closed_tickets = Ticket.closed.includes(:user)

In your view, extract the table itself into a partial, and only include HTML for the parts that actually differ. Note the call to render where we point it to the partial template it should use, and the local variables that should be made available to that template.

Open Tickets

<% if @open_tickets.any? %>
  <%= render partial: "tickets", locals: { tickets: @open_tickets } %>
<% else %>

No open tickets

<% end %>

Closed Tickets

<% if @closed_tickets.any? %>
  <%= render partial: "tickets", locals: { tickets: @closed_tickets } %>
<% else %>

No closed tickets

<% end %>

And here's the partial

      Ticket Number
      Title
      Submitted by
      Created at
      Status

  <% tickets.each do |ticket| %>

      <%= ticket.id %>
      <%= link_to ticket.title, ticket_path(ticket.url_token) %>
      <%= ticket.user.username %>
      <%= ticket.created_at.strftime("%H:%M, %B %d, %Y") %>

      <% if ticket.waiting_for_reply? %>
        (user waiting for reply...)
      <% end %>

  <% end %>


"Human" interfaces with two implementation classes

A class is a blueprint or template or set of instructions to build a specific type of object. Every object is built from a class.
  An instance is a specific object built from a specific class. It is assigned to a reference variable that is used to access all of the instance's properties and methods.

Ryan and nate should both be an instance. They have the same properties. From the 2 classes you can extract one template and make it a Human class.

What you are doing now is hard coding their properties into the methods. Try to make it more dynamic by creating one class.

public void eat() {
    System.out.println("Nate has eaten");
}

Can then be tranformed into:

public void eat() {
    System.out.println(this.name + " has eaten");
}


Your way of indenting and placing braces is consistent, which is good.
I prefer the K&R style, which
is also recommended in the (historical) Java Code Conventions from
Sun Microsystems, or the Google Style Guides:

  Open brace “{” appears at the end of the same line as the declaration statement
  Closing brace “}” starts a line by itself indented to match its corresponding opening statement, ...

You have separated the I/O from the actual computation, which is again
good, as it keeps the main method short, and allows to add unit tests
more easily.
Reading the input can be simplified slightly by using Scanner.
Short (nondescriptive) variable names T and N are usually not recommended.
In this case it might be acceptable, since those names correspond directly
to the identifiers used in the programming challenge description.

However, it is not immediately apparent what the method names noOfBits
and numBits stand for, and what distinguished them. A better choice could
be totalSetBits (corresponding to the challenge description), and
countBits, plus short explaining comments.
I am not sure if the special treatment of powers of 2 in if ((i & i-1) == 0)
is worth the additional code, as it applies only to few numbers in the range
1...N. In any case, it should be part of the numBits() method.
The separate variable int rem in numBits() is not needed.

Summarizing the suggestions so far, the code would look like this:

import java.io.IOException;
import java.util.Scanner;

class GFG {

    // Total count of all 1 bits in the binary representation of the
    // numbers 1 ... N.
    private static int totalSetBits(int N) {
        int sum = 0;
        for (int i = 1; i <= N; i++) {
            sum += countBits(i);
        }
        return sum;
    }

    // Number of 1 bits in the binary representation of n.
    private static int countBits(int n) {
        if ((n & n-1) == 0) {
            return 1; // n is a power of 2.
        }
        int count = 0;
        while (n != 0) {
            count += n % 2;
            n /= 2;
        }
        return count;
    }

    public static void main (String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        int T = scanner.nextInt();
        for (int i = 1; i <= T; i++) {
            int N = scanner.nextInt();
            int bits = totalSetBits(N);
            System.out.println(bits);
        }
    }
}

How can we make this faster? One approach would be
to make countBits() faster, and you'll find various methods to count
the number of set bits in an integer at
Bit Twiddling Hacks.

But perhaps we can compute totalSetBits(N) better than
adding countBits(n) for all numbers n from 1 to N? This is the real
challenge here, and I don't want to deprive you from the satisfaction of
figuring out the solution yourself, so here are some hints only:

First have a look at some special values:

0
1  --> totalSetBits(1) = 1

00
01
10
11 --> totalSetBits(3) = 2 * 2 = 4

000
001
...
110
111 -> totalSetBits(7) = 3 * 4 = 12

Can you spot the general pattern?

Then try compute totalSetBits(N) for arbitrary N by using
those “special values.” This should lead to a \$ O(\log N) \$ solution
instead of the current \$ O( N) \$ solution.

And of course – when not in an interview – you can “cheat:” Compute totalSetBits(N) for the first
(e.g.) 40 values of N, and look up the resulting sequence in the
On-Line Encyclopedia of Integer Sequences®. For many
programming challenges, this leads to useful information and insights into
the problem.


15 line Rust program, which writes the numbers 1 to N to a file

I improved the performances (and simplicity) like this:

use std::fs::File;
use std::io::Write;
use std::io::BufWriter;

const N: i32 = 1e7 as i32;

fn main() {
    let mut f = BufWriter::new(File::create("numbers.txt").expect("Unable to create file"));
    for i in 1..=N  {
        write!(f, "{0}\n", i);
    }

}

I just don't store the strings in a gigantic buffer but asks the BufWriter to manage the buffering. As a side effect, it's now possible to write bigger files without holding too much RAM.


Because you

don't intend to copy/move/assign SDL2_Fonts

you could formalize that with
SDL2_Font(const SDL2_Font& other) = delete;
SDL2_Font& operator=(const SDL2_Font& other) = delete;

(the move versions of these operations won't be generated if these two are defined or deleted).
However, let's assume that one day we will want to be able to pass these fonts by value.
The code looks correct to my eye, but you could avoid having to do the memory management yourself if you use a smart pointer instead of a raw pointer for the font_ member.  If you do that, you can follow the Rule of Zero (the best of these rules) and simply let the compiler create the appropriate copy operators and constructors - see worked code below.
I notice that free() can only ever be called from the destructor. (Edit - I see it's also called from loadFont() but less obviously so, by being class-qualified.  This paragraph still applies, though.) free() does a lot of "dead writes" most times it's called - i.e. making assignments to variables that can never be read.  That's a waste of your time and mine!  Possibly also of your processor's, though a decent compiler should be able to optimise most of that away.

Here's a simplified version using shared pointer (I'm assuming that copies don't each need their own font object, as we don't ever modify it):
#include <SDL.h>
#include <SDL_ttf.h>

#include <memory>
#include <string>

namespace ktp {
    void logSDLError(const char*);
}

/* header */
class SDL2_Font {
public:
    SDL2_Font() {}

    bool loadFont(const std::string& path, int size);
private:
    struct FontInfo {};
    void queryFontInfo();

    std::shared_ptr<const TTF_Font> font_{};
    FontInfo font_info_ {};
    std::string path_ {};
    int size_ = 0;
};

// look, no constructors or assignment operators!

bool SDL2_Font::loadFont(const std::string& path, int size)
{
    font_.reset(TTF_OpenFont(path.c_str(), size),
                &TTF_CloseFont);
    if (!font_) {
        ktp::logSDLError("TTF_OpenFont");
        font_info_ = {};
        path_ = {};
        size_ = 0;
        return false;
    }
    path_ = path;
    size_ = size;
    queryFontInfo();
    return true;
}

See how reset() takes care of releasing resources for us, and we don't need to write a destructor.
I tried this with a simple main():
int main()
{
    if (TTF_Init()) {
        std::cerr << "TTF_Init: " << TTF_GetError() << '\n';
        return 1;
    }

    {
        SDL2_Font f;
        f.loadFont("/usr/share/fonts/truetype/unifont/unifont.ttf", 14);
        f.loadFont("/usr/share/fonts/truetype/unifont/unifont.ttf", 16);
        // important - f goes out of scope before TTF_Quit()
    }

    TTF_Quit();
}

This runs cleanly under Valgrind:
==29172== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==29172== Command: ./255607
==29172==
==29172==
==29172== HEAP SUMMARY:
==29172==     in use at exit: 0 bytes in 0 blocks
==29172==   total heap usage: 155 allocs, 155 frees, 615,577 bytes allocated
==29172==
==29172== All heap blocks were freed -- no leaks are possible


Using string concatenation in a loop is a no go because each time you do a += a new string object will be created because strings are immutable.

To use the right tool for the job I would suggest to use a StringBuilder instead. Using a StringBuilder doesn't have this restriction because the passed strings are just appended char by char to the internal buffer.

Using braces {} although they might be optional will make your code less error prone.

By extracting the building of the hex string representation to a separate method the responsibility is split nicely and could be reused if needed. Having this as a extension method could serve well.

private string ToHex(this byte[] values)
{
    if (values == null) { throw new ArgumentNullException("values"); }

    StringBuilder sb = new StringBuilder(values.Length * 2);
    foreach (var b in values)
    {
        sb.Append(b.ToString("X2"));
    }

    return sb.ToString();
}

resulting in the former code like this

var md5String = string.Empty;
using (var md5 = MD5.Create())
{
    var md5CRC = md5.ComputeHash(File.ReadAllBytes(destinationFilename));

    md5String = md5CRC.ToHex();
}


Simple dispatcher for an embedded system

.... have as many as 20 events lined-up, and it works as per requirement
  Any thoughts where I could improve on this?

Stress test

The queue approach is non-deterministic and would benefit in knowing how much extra CPU is left.

Presently the processor is ample and the cumulative task list is low.  There is spare CPU power.  Yet let us stress test this design to find out how close and how code handles falling behind.

Add code to detect when Dispatcher() is starving.  Did every task get serviced at least once every 0.1s say?

Append a do-nothing task that consumes a x% of CPU time, call it Administratium.    Did the queue ever fail to add because it was full?  What was the maximum queue usage?  Was task latency too great?

Armed with this adjustable idle task, preliminary testing can gauge the degree of margin in the design.


Well, if you are using Bootstrap, you should not alter the classes that Framework is using, like navabar for example.
The basic with BEM is that you should chain classes in a way to create a meaningful hierarchy, like in a component, where you have an object that contains everything else. Like that you leverage SASS nesting to create a component-like structure.
For example:

  <navbar class="navigationBar navbar">

            Item-1
            Item-2
            Item-3

  </navbar>

        Welcome To Our Studio!
        It's Nice To Meet You

In this case the SASS will be:
.navigationBar {
    width:104px;

    &--logo { width:103px; }
    &--navigation {
      width:102px;

        &--item {
          width:101px;

            &--link {width:100px; }
        }
    }
}

.content {
  width:100px;

  &--heading--primary {
    width: 101px;

    &--main { width: 102px; }
    &--sub { width: 103px; }
  }
}

Check the SASS code with SassMeister (https://www.sassmeister.com) to see how it turns to CSS


Instead of making the songidarray global, use a closure.

$(window).load(function () { // for example, or wherever you get the data
    var songidarray = [1,2,3,4,5,9];
    // var songidarray = [];

    var $button = $("<button id='addEntireFolderButton' type='button'>")
        .html("Add Entire Folder")
        .prop("disabled", songidarray.length == 0)
        .click(function () {
            applib.addentirefolder(songidarray);
        });
    $('#folderpagebackbutton').append($button);
});

The click callback above will maintain a live reference to songidarray and will pass it to the addentirefolder function when triggered. The contents of the array stay out of the HTML.

And since this is Code Review:

The type attribute on <a> elements is a hint for the MIME type of the referenced resource. Use the class attribute if you need to tag an element for styling.  On a <button>  element, type="button" makes it do nothing by default as opposed to submitting or resetting any containing form.


Find tags in text for replacement, my brute force solution

This is a lot of code for such a simple task... but how about some regex:

string text = "Hi [img-2] tst[img-3] test ttteessstt grawr[img-1-800]tet";

var ids = Regex.Matches(
     text,
     @"\[(?<tag>[a-z]+)-(?<id>\d+)(-(?<width>\d+))?\]",
     RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture
)
.Cast<Match>()
.Select(m => new ImgReplaceItem
{
    Tag = m.Groups["tag"].Value,
    Id = m.Groups["id"].Value,
    Width = m.Groups["width"].Success ? int.Parse(m.Groups["width"].Value) : 0
});

result:

Tag Id  Width

img 2   0
img 3   0
img 1   800

As to the code. I think it's well writen. There isn't actually much to correct if anything.

Just a small adjustment:

if (item.Contains(']'))

You could make it !item.Contains(']') and use the contintue to reduce nesting.


Secure way of uploading php images and GIF

Your code is insecure because:

It only relies on the file extension, so attackers can upload any backdoors.
It accesses variable $_FILES['postToUpload']['name'] without checking if it is defined and this may lead to Full Path Disclosure.
It uses function uniqid() without any arguments, so uniqueness is not guaranteed and the files that are uploaded simultaneously and have the same file name will be overwritten.
It stores the filename provided by user without removing potentially dangerous characters and this may lead to unexpected results.

Some recommendations to improve your code:

Get rid of the $uploadOk variable. You already have and handle the $errorMessage variable and this is enough to check if the file was uploaded successfully.
You should define $imageFileType as lowercase, instead of calling strtolower() for each extension.
You should define all accepted file extensions as lowercase, otherwise users won't able to upload some files (in your case WebM and Ogg, because strtolower($imageFileType) != "Ogg" and strtolower($imageFileType) != "WebM" will always be FALSE).


There's not much of a performance difference between the two (reduce is very slightly favoured in my own tests), but I prefer the more readable reduce function over the for loop. I believe it makes the code simpler, too. Also sort of a personal preference - why not use the full name? No real need in shortening it. :-)

var fetchAttributes = function(node) {
  return node && Array.prototype.reduce.call(node.attributes, function(list, attribute) {
    list[attribute.name] = attribute.value;
    return list;
  }, {}) || {};
};

http://jsperf.com/reduce-vs-for-fetch-attributes

Edit: In fact you can simplify this further, as you aren't transforming the attributes in any way.

var fetchAttributes = function(node) {
    return node && node.attributes || {};
};


Is it possible to use userList only one time?

Every time you call a FirstOrDefault, you are doing an O(n) search through the user list. You should consider keeping a dictionary of user IDs to user objects. Without knowing what kind of frameworks you're using, I can't say whether this is a job for your ORM or whether you have to do it yourself. With a dictionary, user lookup will be much faster.

So short answer, no; but you shouldn't be using a list.

  Is there an alternative of multiple foreach statement?

Not really.

Other things I see that could use some love:

Overuse of var

I find var to be useful in contexts where it's visually obvious what type a variable will take, including during instantiation statements. However, that is not the case with any of the instances of var in your code; I have no idea what's going into those variables. Unless the type is some kind of monstrous generic, just use the type.

Data model issues

You have some kind of user object, and some kind of item object with multiple references to user names. Are you sure it's a good idea to refer to the names, and not the user objects? The answer to this might be that you need the names in this case because the object is shortly destined for some kind of serialization, but if that isn't the case, it's probably a better idea to keep object references instead of string references.

In other words, why store comment.CreatedByName when you already have comment.CreatedBy?


In Insert(...) you should use TryGetValue instead of ContainsKeyfor efficiency:

  foreach (var letter in key)
  {
    if (!current.Edges.TryGetValue(letter, out var edge))
    {
      edge = current.Edges[letter] = new TrieMSNode();
    }
    current = edge;
  }

Name your methods after what they do, not after their implementation:

  DFS(...)

could be GetSumFrom(...)

public int Sum(string prefix)
{
  int sum = 0;
  var current = Head;
  foreach (var letter in prefix)
  {
    if (!current.Edges.ContainsKey(letter))
    {
      return sum;
    }
    current = current.Edges[letter];
  }

Here the sum variable is redundant because it is never changed so you could just return 0 from the loop

Again the loop can be optimized:

  foreach (char letter in prefix)
  {
    if (!current.Edges.TryGetValue(letter, out current))
      return 0;
  }

DFS()

can be simplified using LINQ:

    private int GetSumFrom(TrieMSNode current)
{
  if (current == null)
  {
    return 0;
  }

  return current.Edges.Aggregate(current.Value, (sum, kvp) => sum + GetSumFrom(kvp.Value));
}

You really don't have to check for IsTerminal because you know that only terminal nodes have a values different from 0.

You should test this LINQ-approach against your own plain foreach-loop, and you'll maybe find the latter fastest.


Implementation of disjoint set in Java with linked-list

Nitpicks

Disjoint is a single word, your class should be named DisjointSet
The correct spelling for the "sink" is representative

Formatting and Style

It's generally recommended to always put braces around blocks in if-else constructs. Yes, even when they only throw an Exception.
Binary operators usually have a space on each side. (applies curr != null and xSet.rank >= ySet.rank)

OOP vs. Functional-Style
Your way of writing OOP is... strange. union, append and findSet are defined as instance methods, meaning they need to be called on a certain instance of DisjointSet, but they don't actually use the instance at all.
Overall these could all be completely extracted into a static utility class, and nothing much would change. I strongly advise you to actually do exactly that. It should clarify responsibilities and make the code clearer to follow.
Alternatively you could make these functions actually start working in an OOP way. If you do that I'd furthermore suggest to make DisjointSet something like an immutable class (see String or Path) that will create a new instance when you union or append another Set to it. In fact I recommend you do that, even when you don't rewrite the code into a more OOP fashion.
Additionally your DNode's data could (and should) be declared final to avoid modification.


Here are some links to sorting techniques:
bubble sort ,
insertion sort, merge sortWhat you're doing in your code isn't efficient. In the worst case scenario where the array is totally unsorted it'll take quite sometime to sort it the way you're doing it.


In terms of performance this should not be an issue, because async operations don't block the event loop, meaning your server will happily accept incoming requests in between the retries. Once in 2 seconds it will be busy making the request to the 3rd party API, but other than that your will not be blocking the main thread.

(You can verify that by shooting requests to your API while it is in the while loop).


Security feedback sought on Perl code running command on unsafe filename in Unix env

Interesting approach with link.
If the only vulnerable parameter is filename,
this technique protects from malicious input,
because the filename parameter will not be part of the `...` bit executing shell commands.
I don't think it's possible to trick link into command execution.

On the other hand, although you say that "file_base_dir is a directory with only alphanumerics in the name",
this function doesn't ensure that, simply trusts it to be true.
It would be good to add a call in this function to another function that validates the directory parameter.

I tried to think of other ways to validate the filename parameter,
without creating a link.
You could forbid certain characters such as ; and $ to prevent command injection,
but I'm not sure that's an exhaustive list.
So while the link trick seems hackish,
it does give comfort that vulnerable parameters never participate in a `...` shell expansion.


Project Euler #5 - Lowest common multiple of 1 through 20

There is a far more efficient approach to finding the least common multiple (\$\operatorname{lcm}\$) of a set of integers which, unlike your and rolfl's code, involves no trial-and-error. Recall that for any pair \$(a, b)\$ of natural numbers, we have
$$\operatorname{lcm}(a, b) = \frac{ab}{\operatorname{gcd}(a, b)}.$$
This reduces the implementation of \$\operatorname{lcm}\$ to the implementation of \$\operatorname{gcd}\$, which is easily done using the simple and efficient Euclidean algorithm. Then, calculating the least common multiple of \$\{1, 2, ..., 20\}\$ is as simple as \$\operatorname{reduce}(\operatorname{lcm}, \{1, 2, ..., 20\})\$.

You can find a simple Python 3 implementation of this idea in ideone here. Even in a slow interpreted language like Python, this is several orders of magnitude faster than your or rolfl's code, running in about .04 milliseconds.


Overall this is looking pretty. I do have a few questions and suggestions based on what I see.

Constructor
Your class extends MovieClip therefore it IS a Movieclip. What is the purpose of the inner _square class variable? Is SquareSpace meant to be purely a logic controller class with _square being the visual representation of the square? If so there is no need for SquareSpace to extend MovieClip. I would look at EventDispatcher or just plain Object.
addSquare/sendClick
I'm not sure I'm understanding the purpose of these methods. Can you explain your thought behind them?
changeSquareState
For state control/detection you generally want to use a switch statement. That way adding more states in the future is much easier.
The State Constants
This is more of a cosmetic comment but I usually prepend any constants with the word STATE_ so that you/other developers can easily tell that those are values intended to be used for state control and passed into changeSquareState.
Argument Error
A really minor comment but I like to include the state which is not acceptable in the error statement. Makes debugging in the future easier. Not a big deal though.
Future Design
As you build out this game do you plan on using the Flash timeline to position and configure your assets or are you going pure AS3?
Package
Generally you want to organize each of your classes into a package. If you're not using a proper IDE like FlashBuilder, FlashDevelop, or FDT this will be a bit of a pain but it's good practice none the less. Packages generally look like reversed domain names so for example your SquareSpace class might be in the following package com.alex.ultimatetictactoe.square


I'd suggest you select a random number that's from 0 to the total weight of your fish.  Then, each fish can have a piece of that random range according to it's weight which gives it the weighting you want.  This ends up giving each fish a number of buckets that corresponds to it's weighting value and then you pick a random number from 0 to the total number of buckets and find out who's bucket the random number landed in.

It's the same idea as turning each weighting number into a percentage change and then picking a random number from 0 to 99.

This code should do that:

var FISH = {
    "level1": [
          //["name",      xp, weight]
            ["Shrimp",    10, 95],
            ["Sardine",   20, 85],
            ["Herring",   30, 75],
            ["Anchovies", 40, 65],
            ["Mackerel",  40, 55]
        ]
};

function getRandomFish(level) {
    var fishForLevel = FISH[level];
    var fishTotalWeight = 0, fishCumWeight = 0, i;
    // sum up the weights
    for (i = 0; i < fishForLevel.length; i++) {
        fishTotalWeight += fishForLevel[i][2];
    }
    var random = Math.floor(Math.random() * fishTotalWeight);
    // now find which bucket out random value is in

    for (i = 0; i < fishForLevel.length; i++) {
        fishCumWeight += fishForLevel[i][2];
        if (random < fishCumWeight) {
            return(fishForLevel[i]);
        }
    }
}


Follow-up: Find sum of number of times that each character of source occurs in the target

Sorry, but this looks worse. I guess, you've been confused by the different ideas presented in the answers. And I am, confused, too. I don't understand it, so just some minor comments:

//reset the single counter

This is a sign that you've defined the counter in a wrong scope. Define it inside of the loop.

tempMap, temp... everything is temporary, we too. But this doesn't mean that it can't be properly named. Or removed... you need no temp String anymore.

I think I sort of understand it. The tempMap keeps track of the number of occurrences per character. So name it like it....

I don't think it really works. However, why not use a Set to keep track of what chars you've seen already? The logic is then trivial: "already seen -> skip it".

Enough for now.


Depth First Search vs Breadth First Search

I solved it. It turns out my looping logic was a bit out. No need for both a while and a for! (and while we're at it, we don't have to check for visited. Thanks @vnp in comments)

edit: since I'm not actually using a queue, I missed that I don't now need to maintain two arrays! Thanks @Ry in the comments!)

Wrote it again for speed and here it is:

  function bfsElementsInTree(input) {
    // perform a breadth first search in order to have elements ordered by depth. (Deepest last)
    let output = [];

    if (Symbol.iterator in input)
      // input is a HTMLcollection
      for (let i = 0, max = input.length; i < max; i++)
        output[i] = input[i];
    else
      output.push(input);

    for (let i = 0; i < output.length; i++) {
      const children = output[i].children;
      for (let j = 0, max = children.length; j < max; j++)
        output.push(children[j]);
    }

    return output;
  }

And new benchmark: https://jsben.ch/F1zzW


Java method to load random paragraph from text file

Some assumptions based on the limited explanation of the question you posted:

A new question starts with the word "Question" at the beginning of the line
The first line in the file starts with "Question". (not really required but otherwise we have to add a check).
A question can have any number of lines. It ends either at the end of the file, or right before a line that starts with the word "Question" (at which point the next question starts).
If a question contains more than 40 lines, we are only interested in the first 40. The rest of the question is ignored.
You want to randomly select a single question from the file as a result of the program

What I would do is split this up into 2 main parts.

1) read the file and split it up into separate "Questions"
2) select a random question

To me this looks a lot like I want to have List<Question> questions somewhere. Where Question is a new class to hold a single question.

Once we have that step 2 becomes almost trivial. (You've shown in your code you know how to do this).

Let's split step 1 up into specific parts as well.

1) read a file line by line
2) for each line:
2.a) Check if it is the start of a new Question.
2.b) add it to the current question if it's not 40 lines yet, otherwise ignore

Let's skip step 1 for a moment and look at how to process each line. (We'll come back to reading the file later).

I suggest creating a sort of "factory" class. This class will store that List<Question> that I wanted, and to make it easy for ourselves it will also store the Question currentQuestion. That way we can do step 2.b by just adding the line to the currentQuestion.

But first let's look at the Question class:

class Question {
    private List<String> lines = new ArrayList<>();

    public void addLine(String line){
        if(lines.size()>=40){
            return;
        }
        lines.add(line);
    }

    public List<String> getLines(){
        //we might want to make a new list here to prevent other classes from modifying it.
        return lines;
    }
}

Notice how I also made sure to only keep track of the first 40 lines. By doing this here, we can safely keep calling the add method while parsing all the lines without worying about it anymore.

Now for that factory class. This turns out to be rather easy as well:

public class InterviewQuestionFactory {
    private List<Question> questions = new ArrayList<>();
    private Question currentQuestion = null;

    public InterviewQuestionFactory(){
        //TODO read lines from file
        // for each ... {
        String line = "";
        process(line);
        //}
    }

    private void process(String line){
        if (line.startsWith("Question")) {
            currentQuestion = new Question();
        }
        currentQuestion.addLine(line);
    }
}

That was everything for step 2. All that's left is step 1 and we're done.

For step 1 here it's best to take a look at this post. Your current solution to read all lines at once might not work for large files.
Since java 8 you can easily do something like this instead:

try (Stream<String> lines = Files.lines(Paths.get(filename), Charset.defaultCharset())) {
    lines.forEachOrdered(line -> process(line));
}

And that's how I would have solved the problem. I left some parts up for you to actually complete but it should be almost trivial at this point.

To complete this review let's point out some things about your current piece of art:

doesn't work as intended

If your random start happens to be the line just after the start of a really long question you don't return anything.

unnecessary whitespace

this:

for (int i = 0 ; i < subList.size() - 1 ; i++){
    m = p.matcher(subList.get(i).toString());
    boolean b = m.find();

    if (b)
        {

        start= i + 1;
        textBlock.append(subList.get(i) + "\n");
        break;
    }else{

should look like this instead:

for (int i = 0; i < subList.size() - 1; i++) {
    m = p.matcher(subList.get(i).toString());
    boolean b = m.find();
    if (b) {
        start = i + 1;
        textBlock.append(subList.get(i) + "\n");
        break;
    } else {

variable names

In that last bit of code, what is the meaning of the variables m p b and start? This reads like:

You match the string from the sublist to something. If it matches you update start to the next index in the sublist and append the current String to the textblock.

Most of it can be solved by using sublist(i).startsWith("Question") instead. If we then also inline the b to get rid of it entirely and rename start to nextLineIndex it turns into this:

for (int i = 0; i < subList.size() - 1; i++) {
    if (sublist.get(i).startsWith("Question") {
        nextLineIndex = i + 1;
        textBlock.append(subList.get(i) + "\n");
        break;
    } else {

actually the start name was fine if you had set it to start = i instead. And start the following for loop at for(int j = start + 1; ... instead. At least then we would know you start looping at the second line of the question.

string.toString()

sublist.get(i) is already a String. No need to call toString() on it.


Not a fan of LINQ, yet? Then look here... You could start by grouping Child by Sex into a new lookup, this would replace the two Wheres. In the next step you Zip them together and take one item from each collection at a time. You create from then new tiny collections that you finally flatten with SelectMany. No calculation necessary.

var groups = items.ToLookup(i => i.Sex);
var alternating =
    groups["male"]
        .Zip(groups["female"], (x, y) => new[] { x, y })
        .SelectMany(t => t)
        .ToList();

This will however require that both collections have the same length because Zip will go only as far as the shorter collection.

Some nice improvement to you method would be to make it work for any group of items. When you pass it a custom comparer you can GroupBy the items and iterate over each group until there is nothing left to yield. Since enumerators are disposable you need to make sure to dispose them properly at the end thus the finally block.

public static IEnumerable<T> Interleave<T>(this IEnumerable<T> source, IEqualityComparer<T> comparer)
{
    var groups = source.GroupBy(x => x, comparer);
    var enumerators = groups.Select(g => g.GetEnumerator()).ToList();
    try
    {
        var any = false;
        do
        {
            any = false;
            foreach (var e in enumerators)
            {
                if (e.MoveNext())
                {
                    any = true;
                    yield return e.Current;
                }
            }
        } while (any);
    }
    finally
    {
        foreach (var e in enumerators)
        {
            e.Dispose();
        }
    }
}

An example usage could then look like this:

var innerComparer = StringComparer.OrdinalIgnoreCase;
var comparer = EqualityComparerFactory<Child>.Create
(
    (x, y) => innerComparer.Equals(x.Sex, y.Sex),
    obj => innerComparer.GetHashCode(obj.Sex)
);
var result = items.Interleave(comparer);


The TryLock class shouldn't be netested.

I'd also add a factory method to it and make it much simpler like this and create an instance only when a lock could be accuired:

private class Locker : IDisposable
{
    private object _locked;

    private Locker(object obj)
    {
        _locked = obj;
    }

    public static Locker Create(object obj)
    {
        return Monitor.TryEnter(obj) ? new Locker(obj) : null;
    }

    public void Dispose()
    {
        Monitor.Exit(_locked);
    }
}

Later instead of checking the property you check if the instance isn't null:

using (var tryLock = Locker.Create(_executeLock))
{
    if (tryLock == null)
    {
        return;
    }

    ...
}

@variable

This kind of naming can and should really be avoided. I'm sure you can come up with a better name then just a delegate which says pretty nothing about the method.


Improvement in file management system based on the file names

It would be better to design the system so that each collection of signals has a canonical filename, regardless of the order of the signals in the collection. This is most easily done by sorting the signals in the collection:

def canonical_filename(signals):
    "Return canonical filename for a collection of signals."
    return file_name(sorted(signals, key=lambda s: (s.amp, s.fq, s.phases)))

Since there is now only one filename for each collection of signals, there is no need to list the directory or generate the permutations:

def is_computed(signals):
    "Return True if the file for signals exists, False otherwise."
    return os.path.isfile(canonical_filename(signals))

I recommend designing the filename so that it does not contain shell meta-characters like spaces, parentheses, and brackets. This is a convenience that means we don't need to quote the filenames when manipulating them via the shell. For example:

def file_name(signals):
    "Return filename for a list of signals."
    amplitudes = ','.join(str(s.amp) for s in signals)
    frequencies = ','.join(str(s.fq) for s in signals)
    phases = ':'.join(','.join(map(str, s.phases)) for s in signals)
    return f'A{amplitudes}_F{frequencies}_P{phases}.pkl'


The OO equivalent of this is one of:

interface Component {
   public function init();
}

class Authenticator implements Component {
}

// OR

abstract class Component {
   abstract public function init();
}

class Authenticator extends Component {
}

Yes, you will have to create objects without using static.  Its really not so bad though.

What are the benefits?  I created my own framework that is pure OO.  So here is an example of what OO code looks like with dependency injection.  I'll describe what it does afterwards so that you get an idea of some of the benefits.

<?php
class Page_XML_Site_Locations extends Page_XML_Site
{
   public function contentMain()
   {
      $model = $this->app->getModelDB(
         'Model_DB_Joint',
         array('Table_Name'       => 'Location',
               'Table_References' => $this->app->getTableReferences(
                  array('References' => array(
                           'Image_List_ID' => array(
                              'Child_Field' => 'List_ID',
                              'References'  => array(
                                 'Image_ID' => array(
                                    'Child_Field' => 'ID',
                                    'Table_Name'  => 'Image')),
                              'Table_Name'  => 'Image_List'),
                           'Map_ID'        => array(
                              'Child_Field'  => 'Map_ID',
                              'Table_Name'   => 'Map')),
                        'Table_Name' => 'Location'))));

      $processing = $this->app->getProcessingNone();
      $settings = $this->app->getSettings();

      $data = $this->app->getData(
         array('Image_List_ID' => $this->app->getNew(
                  'Data_Image_List',
                  array('Dir'         => $settings['Web']['DB_Storage'] .
                        'img/location/',
                        'Empty_Image' => $settings['Web']['No_Photo'],
                        'Formats'     => array('W_Min'),
                        'Image'       => $this->app->getShared('Image'),
                        'Image_Sizes' => $this->app->getShared('Image_Sizes'),
                        'References' => array(
                           'Image_ID' => $this->app->getData()),
                        'Translator'  => $this->tr)),
               'Map_ID'        => $this->app->getNew(
                  'Data_Map',
                  array('References' => array(),
                        'Sensor'     => 'false',
                        'Size'       => '320x320'))));

      $view = $this->app->getView('View_XML_Locations',
                                  array('Data'         => $data,
                                        'Image_Format' => 'W_Min'));

      $controller = $this->app->getController();
      $controller->execute();
   }
}
// EOF

$this->app is my application container responsible for creating and retrieving resources.  It is a dependency injection container.  There are no calls to new or evil getInstance singletons.  All of the objects are managed via the container.

Distinct objects are created (model, processing, settings, data, view, controller).  They stand alone (except data which is only created for injection into the view).  I don't have to worry about their interface to each other.  It is all handled by my event manager and controller.  The objects each handle their own area.  The Model gets joint data from its referenced tables.  The processing handles any POST or GET requests.  Everything does its job (which produces a list of stores in the correct language with their details, images and maps for finding them).  There is nothing complex to worry about with who is calling who.

That is the top level view.  What did I have to do to complete that page?

Model, Processing, Settings, Controller - Nothing, that is straight from the framework.
Data_Image_List - calculate the image file name from the DB table and constructor settings.
Data_Map - calculate the google static map string from the DB table and constructor settings.
View - This is where most of the work goes.  Loop through the data, writing the elements.

If you don't like the look of the code that I use with my framework then you should probably ignore my suggestions.

What will your Authenticator component do?  How tightly will it be coupled to the rest of your system?  Can it stand alone allowing you to kepp all your logic for each part of your system distinct?


Your code is pretty good. Nice job.
I'd personally change the first else to an elif so you don't have as much indentation.
Rather than using that while loop you can just use one % per number.

For each number if you get the modulo then you can find out how much to add. 7 % 5 is 2. Where 5 - 2 is not less than 3.

And so you can easily change the while to just difference = 5 - grade % 5
You can merge grade % 5 == 0 into the else.
You can change the order and content of the ifs. This is as we don't need to call list.append three times, just mutate grade.

def gradingStudents(grades):
    rounded_grades = []
    for grade in grades:
        if grade >= 38:
            difference = 5 - grade % 5
            if difference < 3:
                grade += difference
        rounded_grades.append(grade)
    return rounded_grades

Since we know the range that anything modulo 5 is 0-4, we can just make a small lists that holds how much to round.

ADDITIONS = [0, 0, 0, 2, 1]

def gradingStudents(grades):
    rounded_grades = []
    for grade in grades:
        if grade >= 38:
            grade += ADDITIONS[grade % 5]
        rounded_grades.append(grade)
    return rounded_grades

You can also change the code to a list comprehension if you're that way inclined.

ADDITIONS = [0, 0, 0, 2, 1]

def gradingStudents(grades):
    return [
        grade if grade < 38 else grade + ADDITIONS[grade % 5]
        for grade in grades
    ]


Download and print reddit page which can be redirected to file

Configuration
Your reddit_config.Config needs to be changed so that, rather than hard-coded strings in a Python module, these are externalized to environment variables, or a permissions-restricted configuration file.
List construction alternatives
There are some alternatives to your concatenate-and-return in get_full_page: you can either make this a generator function -
    yield {
        # content of post
        "id": post.id,
        "parent": post.id,
        "body": post.selftext,
        "author": post.author.name,
        "ups": post.ups,
        "title": post.title
    }
    # ...
    yield from (
        {
            "id": comment.id,
            "parent": comment.parent_id.replace('t1_', '').replace('t3_', ''),
            "body": comment.body,
            "author": comment.author.name,
            "ups": comment.ups
        }
        for comment in list_of_comments
    )

or you can star-expand -
return [
    {
        # content of post
        "id": post.id,
        "parent": post.id,
        "body": post.selftext,
        "author": post.author.name,
        "ups": post.ups,
        "title": post.title
    },
    *(
        {
            "id": comment.id,
            "parent": comment.parent_id.replace('t1_', '').replace('t3_', ''),
            "body": comment.body,
            "author": comment.author.name,
            "ups": comment.ups
        }
        for comment in list_of_comments
    ),
]

Truthy lists
Your
if not children

is too broad. This statement will pass if children == [], which it doesn't need to - instead, consider
if children is None:

or better yet, replace this whole mechanism with a defaultdict.
Unused return
org() returns '', which both has no meaning and is unused, so you can just delete that line.


You could initialize min with Integer.MAX_VALUE and max with Integer.MIN_VALUE, this would make the inner if obsolete. You could also use this for your output condition and get rid of the count completely.

Without knowing the complete assignment, it's hard to optimize your code in any direction.

If you don't want to use your library and do it in 'plain' Java have a look at Scanner.


dnaof() - inheritance made easy, my own make inheritance tool

From a once over, and borrowing from the comments:

__proto__ is bad news, MDN mentions this in a big red box of doom.
There is no means to pass parameters to the constructor, that does not make it simple
X, x, k, r and p are terrible variable names
dnaof is an unfortunate name
lowerCamelCase is good for you, kindof -> kindOf,
You can get the parent class thru Object.getPrototypeOf(Object.getPrototypeOf(this)) in dnaof
I have mixed feelings about the can trick. It is shorter than typing prototype, but it's also a candidate for nameclashes.
You have no comments at all in your code, combined with 1 letter variables that makes for not good code
If I were to build an OO library, I would also play with constructor and add some support for private.

All in all, this is something I would not mind using, but that I would hate to have to maintain.


Style

POSIX reserves type names ending with _t. This means that in the future, standard c may create standardized types with the same name as string_list_node_t, and your code would not compile. See https://stackoverflow.com/a/12727104 for more details. A common alternative is to use upper camel-case for typedefs, e.g. StringListNode.
There is a strong case against typedefing structures. The major benefit of this is to save keystrokes, but it removes important information available to programmers. To see some opinions on this, here is another stack overflow question.
I have never seen code that has spaces between -> when accessing struct members. Just  use prepended_node->id instead. You wouldn't write prepended_node . id, would you?

Code Review

Use the bool type

A boolean type, bool, was introduced in C99. Unless you have really good reasons not to, you should use this for true/false values instead of an integer. This type is found in the <stdbool.h> header.

Multi-use functions

Finding nodes in a linked list is a relatively common procedure. If your list supports lookup, it is better to have a separate function that can handle all of your lookup cases:

static void _find_node_by_id(int id, str_node *head,
                str_node **prev, str_node **node) {
  *prev = NULL;
  *node = head;
  while(node && (*node)->id != id) {
    *prev = *node;
    *node = (*node)->next;
  }
}

This way, you can use the search implementation in multiple places:

bool delete_first_by_id(string_list_node_t **source,
                       int id,
                       string_list_node_t ** deleted_value_out){
  string_list_node_t *prev = NULL;
  string_list_node_t *current = *source;

  _find_node_by_id(id, *source, &prev, &current);

  if(current){
    if(!prev){
      *source = current -> next;
      *deleted_value_out = current;
    } else {
      *deleted_value_out = current;
      prev -> next = current -> next;
    }
    return true;
  } else {
    return false;
  }
}

bool find_node_by_id(str_node *head, int id, str_node **return_ptr) {
  string_list_node_t *prev = NULL;
  *ret_ptr = head;

  _find_node_by_id(id, *source, &prev, return_ptr);

  if(*return_ptr) {
      return true;
  } else {
      return false;
  }
}

Note that I didn't test any of this code.

Try to avoid pointers to pointers

More specifically, don't use them when it's not necessary. There isn't a great reason for string_list_alloc to return string_list_node_t **. It makes much more sense to just return a pointer to the node. This does two things for you:

Non-destructive operations don't need a pointer to a pointer, so it avoids either
you or the function from needing to deference them.
It makes destructive operations more explicit, as you need to take the address of
the pointer to use the function.

Edit addressing question in comments:

  In case I want to preserve it across different function calls I should not allocate it on the stack shouldn't I?

There seems to be some confusion on how malloced memory and pointers work, especially in the context of function return values.

First, remember that a variable holds a value. In this case, the variable contains a memory location, whose value could be any integer greater than or equal to 0. We really don't care about the variable itself, we care about its value.

Second, lets talk about return values. When you return a value from a function, it is copied so that the code calling the function has access to it. Here's a little program that illustrates this:

#include <stdio.h>

struct test_struct {
  int a;
  int b;
};

struct test_struct return_struct() {
  struct test_struct test = { .a = 1, .b = 2 };
  printf("The pointer in the function is: %p\n", &test);
  return test;
}

int main(void) {
  struct test_struct main_struct;
  main_struct = return_struct();
  printf("The pointer in main is: %p\n", &main_struct);
  return 0;
}

On my system, this program prints out

The pointer in the function is: 0x7fffef30f048
The pointer in main is: 0x7fffef30f070

Notice that the addresses are different. Since the value being returned is copied, we don't need to worry about manually manipulating memory, as the compiler takes care of that for us. It works the same way when returning a pointer from function: the value we care about is copied, so that we can access it when the variable that originally held it no longer exists.

Lets look at this in a different context.

// what your alloc function is doing:
int *malloc_add(int a, int b) {
    int *result = malloc(sizeof(result));
    *result = a + b;
    return result;
}
// what it should be doing:
int add(int a, int b) {
    int result;
    result = a + b;
    return result;
}

While we get the value we want in both cases, in the first we need to perform two extra steps: we need to dereference the pointer to get the value, and we need to free the memory allocated on the heap.


I would advise you to look at wicked gem: https://github.com/schneems/wicked.

Using this gem you could write:

include Wicked::Wizard
steps <list_of_your_steps>

def new
  session[:order_id] ||= Order.create.id
end

def show
  @order = Order.find(session[:order_id])
end

def update
  @order = Order.find(session[:order_id])
  @order.assign_attributes(params[:order_params])
  @order.current_step = step
  render_wizard @order
end

It will also separate your forms for each step. To add any  step-related action you can use step reader:

def update
  @order = Order.find(session[:order_id])
  @order.assign_attributes(params[:order_params])
  @order.current_step = step
  @order.do_sth if step == :my_step
  render_wizard @order
end

render_wizard automatically tries to save an object and redirects you to the next step or renders current form depending on a result.


Get all points within given radius for a given vector

Here are some things that may help you improve your code.

Use the appropriate #includes

In order to compile and link, this code requires at least following line:

#include <vector>

This too, should be part of the interface.

Provide complete code to reviewers

This is not so much a change to the code as a change in how you present it to other people.  Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code.  This affects not only code reviews, but also maintenance of the code in the future, by you or by others.  One good way to address that is by the use of comments.  The test code was helpful, but would have been slightly more so if a representative main had been include for a whole program.

Take advantage of symmetry

Given the simple case of 2D space, the "sphere" of course becomes a circle.  For a given radius \$r\$, we know that the coordinate \$(r,0)\$ is, by definition, the outer bound of the "sphere".  Also, no calculation is needed to determmine that the points \$(0, r), (-r, 0),\$ and \$(0, -r)\$ are also on the perimeter.  This principle can easily be expanded for any N-dimensional space.

Additionally, now that we know that \$(r,0)\$ and \$(-r, 0)\$ are among the desired points, it is clear that every point between them must also be inside the "sphere."  In general, one can iterate each dimension from \$r\$ to \$0\$, to follow the perimeter of the sphere (as with a modification of Bresenham's algorithm) and then simply include all points between there and the origin.

Precompute if practical

If you happen to know in advance a maximum size \$x\$ that will be used and the dimensionality \$d\$ of the space in which you'll work, you may be able to precompute the point clouds from 1 to \$x\$.  Since the point clouds are nested, (that is, the cloud for \$x=3\$ completely contains that of \$x=2\$, etc.) the points could be stored in a vector and for each integer  \$x\$, the program could store the matching index \$i\$ into the vector.  If the vector is sorted by increasing distance from the origin, then all points within a particular radius \$x\$ would be stored in indices \$[0 ... i]\$.

Consider writing an iterator

The code functions very much like an iterator but isn't quite.  Consider refactoring it so that it's an actual iterator and you may find that it's somewhat easier to use.

Reconsider the interface

Right now, the code doesn't actually return all points within the sphere.  Rather it returns the set of points, centered at the origin that are within the given radius.  It seems to me that it would be nicer to do the x+d calculation for the caller.


Working with pandas dataframes for stock backtesting exercise

Pandas allows you to filter dataframes efficiently using boolean formulas.

Instead of using a for loop and conditional branching, use the following syntax:

df = portfolio[(portfolio['sell'] == True) & (portfolio['Tok'] < maxtokens)]

To sort a dataframe, you can also simply write:

portfolio = portfolio.sort('VTI', ascending=False)
sold_positions = portfolio[portfolio['BL'] == True].sort('upperlower', ascending=True)


The OOP design doesn't seem to be doing much for you.  It feels like you could get basically the same effect using just a function.  On the other hand, the operator<< method is basically a state machine, and it looks somewhat nastier than it needs to be.  There is copy-and-paste code, with bits of ASCII art all over the place, and a mini-Turing machine using the magic number 0x201.

Assuming that the to_bits() helper function isn't important to you (I assume it isn't that important, because you wrote #include <bitset> then changed your mind), you could do better by defining a filtering output stream.  Here's my attempt to implement such a thing:

#include <climits>
#include <iostream>
#include <sstream>
#include <streambuf>
#include <string>

class waveform_ostream : public std::streambuf
{
public:
    explicit waveform_ostream(std::ostream &sink) : sink(sink) {}

protected:
    // Accept a byte of data
    virtual std::streambuf::int_type overflow(std::streambuf::int_type c) {
        output_bit(0, 'S');             // Start bit
        for (int i = 0; i < CHAR_BIT; ++i) {
            output_bit((c >> i) & 1);   // Data bits, LSB first
        }
        output_bit(1, 'P');             // Stop bit
        return c;
    }

    // Flush
    int sync() {
        for (int row = 0; row < 4; ++row) {
            std::string s = lines[row]->str();
            sink << s << '\n';
            lines[row]->str("");
        }
        sink << std::flush;
        return 0;   // success
    }

private:
    bool state = 1;
    std::ostream &sink;
    std::stringstream level[2], risefall, captions;
    std::stringstream *const lines[4] = {
        &level[1],
        &risefall,
        &level[0],
        &captions
    };

    void output_bit(bool b, char caption='\0') {
        level[!b] << ((b == state) ? "    " : "+   ");
        risefall  << ((b == state) ? "    " : "|   ");
        level[ b] <<                          "+---";
        captions  << "  " << (char)(caption ? caption : b ? '1' : '0') << ' ';
        state = b;
    }
};

int main()
{
    waveform_ostream wout(std::cout);
    std::ostream out(&wout);
    out << std::string("ST") << std::flush;
}


If you can't use the suggestions in the comments by t3chb0t or tinstaafl, you could maybe use the Open XML SDK.

In your current code it is rather inefficient that you are calling datasource.ElementAt(i)... for each property on the same data element. Depending on how ElementAt(i) is implemented, it can be a considerable bottleneck, to search for the same element each time calling ElementAt(i).

The solution is obviously to create a temporary Plans_Result-reference for each loop:

for (int i = 0; i < datasource.Count(); i++)
{
  Plans_result item = datasource.ElementAt(i) as Plans_result;
  ws.Cells[i + 2, 1].Value = item.ACC_DATE;
  ws.Cells[i + 2, 2].Value = item.DUE_DATE;
  ws.Cells[i + 2, 3].Value = item.IDENTIFIER_VALUE;
  ws.Cells[i + 2, 4].Value = item.INSTALLMENT_NO;
  ws.Cells[i + 2, 5].Value = item.PRINCIPAL_AMT_DUE;
  ws.Cells[i + 2, 6].Value = item.SPA;
}

Alternatively you could use a foreach-statement while counting the rows in a separate index variable:

int index = 2;
foreach (Plans_result item in datasource)
{
  ws.Cells[index, 1].Value = item.ACC_DATE;
  ...
  index++;
}

I would use the latter as it is more efficient, because ElementAt(i) may be rather slow for large vectors.


Asynchronously assembling a complex object

As for me it looks fine except one thing. You have already completed Task in .ContinueWith block, thus you may use .Result then instead of await and avoid redundant async State Machine.
By the way, if you're using async/await, probably there's no continuations needed.
Consider this continuations-free implementation of 1st Task.WhenAll() job.
public async Task<Account> Retrieve(AccountId input1, DateTime input2)
{
    var account = new Account();

    // probably try-catch wrapper maybe useful here as replacement of !mapTask.IsCompletedSuccessfully
    await Task.WhenAll((Func<Task>)(async () =>
    {
        T_AccountMapper map = await _tAccountMapperRepo.Retrieve(input1);
        // continuation:
        AccountMap accountMap = new AccountMap(map.AccountId, map.Login, map.Namespace);
        account.SetAccountMap(accountMap);
    })
    //, (Func<Task>)(async() => {...})
    );

    return account;
}

As you can see, TranslateAccountMap method isn't needed anymore.
Finally, it's up to you.
P.S. Here's a useful link.


SocketEnhancer socketEnhancer = new SocketEnhancer(serverSocket.accept());

Currently, this is a not very advanced chat application as you can only have one client. It'll be a 1-1 conversation. It will just be one server and one client talking to each other. You can run the serverSocket.accept() in a loop to allow you to have more clients. The server then needs to loop through all the available clients (so you need some Collection for those) and then send the incoming message to all clients.

public static void main(String[] args) throws Exception{
    ServerSocket serverSocket = new ServerSocket(4545);
    SocketEnhancer socketEnhancer = new SocketEnhancer(serverSocket.accept());
}

You don't need to declare the socketEnhancer variable as you're not using it any more in the method. The compiler should give you an unused variable warning here.

DataReceiver dataReceiver;
DataSender dataSender;
Socket socket;

private final, private final, private final. All of those should be private final.

The same goes for all your fields in other classes.

dataReceiver = new DataReceiver(this);
dataSender = new DataSender(this);

So you create a DataReceiver and a DataSender and give them both the SocketEnhancer reference? Let's see how you use that in the classes then.

new InputStreamReader(socketEnhancer.getSocket().getInputStream())

and

socketEnhancer.getSocket().getOutputStream()

You send the entire socketEnhancer only so that you can use the getSocket method on it once to create the OutputStream. It is much better to give them the InputStream / OutputStream directly. This is what is called Tell, Don't Ask!

When possible, don't give your classes an object they can ask about something, give them what they need directly.

public class DataSender implements Runnable {

    Scanner scanner = new Scanner(System.in);
    ...

I would recommend moving the Scanner to your main method, and letting your main method call a method on your SocketEnhancer object whenever it wants to send a message. The SocketEnhancer can then call a method on dataSender to perform the sending.

Overall, I have to say that your code is quite clean and easy to read. Good job.


F# functions implementing polynomial arithmetic

| (x,y::ys) when x > 0    -> x * y::mulC x ys

| (x::xs, y::ys)      -> (x + y) :: addE xs ys

Why the inconsistency in parentheses and whitespace? For what it's worth, I think the second is more readable.

let rec mulC x ys =
match (x,ys) with
| (_,[])                    -> []
| (x,y::ys) when x > 0    -> x * y::mulC x ys

What about the case x = 0, ys is non-empty? Don't you get a warning? (I also find it odd that the test is >. I infer that you're only intending to handle non-negative coefficients, but that seems like an unnecessary restriction).

let rec addE xs ys =
match (xs, ys) with
| ([],[])                   -> []
| ([], y::ys)            -> y::ys
| (x::xs,[])             -> x::xs
| (x::xs, y::ys)      -> (x + y) :: addE xs ys

There's no need to pattern-match a structure if you're not using the structure. This could be simplified to

let rec addE xs ys =
  match (xs, ys) with
  | ([], ys)            -> ys
  | (xs,[])             -> xs
  | (x::xs, y::ys)      -> (x + y) :: addE xs ys

Why are the three auxiliary functions in the top-level scope? I admit that I don't know F#, but the languages that it's heavily inspired by would allow them to be defined in a let clause inside the definition of mul, keeping the top-level namespace clean.


As you seem to specifically ask for: Is there a better way for calculating the position of the user controls that are being added? I don't like the way the if/else looks but I am not sure how else to do it.

My answer will address only this. You can make a better use of the variable and instead of -1 use Top + 10 and later = Bottom + 2. The code:

    int nextTop = this.Top + 10;

    foreach (var item in MonthDisplaying.Days)
    {
        DayView dayDisplay = new DayView(item);

        dayDisplay.Top = nextTop;

        nextTop = dayDisplay.Bottom + 2;

        this.Controls.Add(dayDisplay);
    }


Rather than implementing this yourself, Python by default has webbrowser. This allows you to open one link in a; new tab, or new window. And so, to open all links in the list with the default web-browser you can:

import webbrowser

for link in links:
    webbrowser.open_new_tab(link)

Since you say you don't trust the source of these urls, you can make sure they are actually URLs, and check there is no shell injection going on. This question says how you could do that.

And so I personally would use:

import webbrowser

import rfc3987

def open_links(links):
    links = (
        link
        for link in links
        if rfc3987.match(link, rule='IRI') is not None
    )
    # Get default webbrowser, change if you want to force a specific browser
    browser = webbrowser.get()
    try:
        browser.open_new(next(links))
    except StopIteration:
        pass
    else:
        for link in links:
            browser.open_new_tab(link)


Python Sum of Pairs Codewars Solution requires optimization

your solution first maps all of the numbers, and then check for pairs.
what if, for instance, the list of numbers is very long, and the first two items already sum up to the desired sum?
I think that the optimal solution would iterate over the list only once.


Using method return types

Instead of relying on static int[] arrays, you should return the appropriate results from getting the user input and generating the lottery numbers so that their interaction is slightly clearer.

Validating user input

Scanner.nextInt() throws an InputMismatchException when the next input is not parsable as an integer. You should have a method that handles that safely.
For example (prompted by @KonradMorawski's comment):

private static int getInteger(Scanner scanner) {
    System.out.println("Enter an integer:");
    while (!scanner.hasNextInt()) {
        System.out.println("Not an integer, please try again.");
        scanner.next();
    }
    return scanner.nextInt();
}

Comparing arrays

Arrays.equals(int[], int[]) can be used to compare two int[] arrays.

Using other types for comparison

You may also want to consider using other types to compare the lottery numbers. For example, a plain integer works as well:

private static int getNumber(int a, int b, int c) {
    return a * 100 + b * 10 + c;
}

edit:

try-with-resources

If you are on Java 7 and above, you should use try-with-resources for efficient handling of the underlying I/O resource:

public static void main(String[] args) {
    try (Scanner scanner = new Scanner(System.in)) {
        // ...
    }
}


Filtering queries based on the current user state

You can try to use SQLFilter for this purpose. It allows you to tune SQL query based on some logic. You can pass information about your user's state into filter through DI container and use this information to tune your SQL query. Please note that unlike repositories - SQLFilter works on SQL level, not on DQL. More information can be found into Doctrine's documentation.


Overall

Your approach is fine, and your code (including ≠⊆⊢) is fairly idiomatic. Handling the edge case by always appending a space and dropping it at the end is standard procedure, so no, you don't need a branch here.

Split up your code in sections

You begin with setting up a couple of constants. Consider inserting a blank line to gently separate these from the main code.

Inline comments

Well-written APL code tends to have short lines, so there's generally enough space to include comments. This allows a simple hierarchy of comments:

Full-line comments for introductions to sections.
End-of-line comments for code explanations.

Consistency

You use intermediary variables for rotating and appending "w" but not for appending "ay ".

Array approach to conditional concatenation

(,∘'w')¨@(1∘=≢¨) does two loops:

(1∘=≢¨) (which could be (1=≢¨) too) to determine which words need appending.
(,∘'w')¨ (which could be ,∘'w'¨ or 'w',¨⍨ too) to do the appending.

A more holistic array approach is to append to every word, and instead modify what is appended. That is, collapse the appendix to shape 0 for words of length different from 1. Rephrased, this becomes keep the appendix as-is for words of length equal to 1, or 'w'/⍨1=≢. It becomes a "conditionally" append function in the form of ⊢,'w'/⍨1=≢, which you could then apply to each with (⊢,'w'/⍨1=≢)¨. However, you might want to…

Reduce ¨pepper¨

Some APLers call code with too many ¨s "too peppered" referring to the many tiny dots in foods that contain lots of black pepper. You may want to consider fusing the loops by defining the constituent transformation functions and applying them together in a single loop. Appropriate naming of the functions allows shortening the comments to become clarifications of the names, which can even make a comment obsolete.

Revised code

PigLatin←{
  ⍝ Monadic function expecting character scalar or character vector and returning character vector.
  ⍝ Translates an English sentence into Pig Latin.
  ⍝ e.g. 'I always run fast' becomes 'Iway alwaysay unray astfay'.

  vowels ← 'aeiouAEIOU'
  Words ← ' '(≠⊆⊢),

  Rotate ← {⍵ ⌽⍨ ¯1+⊃⍸ ⍵∊vowels}  ⍝ all words until a vowel is at the front
  Add_w ← ⊢,'w'/⍨1=≢              ⍝ if word has length 1
  Add_ay ← ,∘'ay '

  ¯1↓∊ Add_ay∘Add_w∘Rotate¨ Words ⍵
}

Other approaches

Writing APL is fun*, so APLers tend to write everything from scratch every time, instead of using the tools at hand. In this case, Perl-style regular expressions might be a help.

Using regex to process words

It is easy to apply a function to each word using '\w+' ⎕R {MyFn ⍵.Match}:

PigLatinWord←{
  vowels ← 'aeiouAEIOU'

  Rotate ← {⍵ ⌽⍨ ¯1+⊃⍸ ⍵∊vowels}
  W ← ⊢,'w'/⍨1=≢
  Ay ← ,∘'ay'

  Ay W Rotate ⍵
}
PigLatinRegex ← '\w+' ⎕R {PigLatinWord ⍵.Match}

The \w+ pattern matches runs of word characters.

If this was a common thing, we could define a utility operator that applies a text transformation on words:

_OnWords ← {'\w+' ⎕R (⍺⍺{⍺⍺ ⍵.Match}) ⍵}
PigLatinOnWords ← PigLatinWord _OnWords

An alternative coding which avoids passing the operand multiple times:

_OnWords ← {'\w+' ⎕R (⍺⍺⍎∘'Match') ⍵}
PigLatinOnWords ← PigLatinWord _OnWords

Doing the entire job with regexes

That said, ⎕R actually has a fancy feature that allows running multiple search patterns in parallel (for every starting character the patterns are tested in order) each with their own substitution pattern. This makes it easy to catch and process edge cases before the main transformations have a chance to kick in.

PigLatinRegexes ← '\w\b' '([^aeiou ]*)(\w+)' ⎕R '&way' '\2\1ay' ⍠1

Here, we have two patterns:

\w\b word character, word boundary: a 1-character word.
([^aeiou ]*)(\w+) any consonants (group 1), word characters (group 2): any other word

And the corresponding substitution patterns:

&way the match followed by "way"
\2\1ay group 2, group 1 (which can be empty), "ay"

Finally, ⍠1 makes the derived function ignore case.


Documentation
/**
 * Searches through an array for a case-insensitive string match.

Excellent!

 * Attempts to imitate Array.indexOf where it can.

I'm not quite sure what you want to say with this.

 * @param arr The array to search through

There's no need to shorten the variable name a few characters. array is a better name, but still says absolutely nothing about what it is used for. In this case, I actually have to say that I like the variable names that PHP uses. haystack. Can it be any clearer? Nearly everyone knows about the saying "Finding a needle in a haystack". So the name haystack is a quite good one.
 * @param searchingFor The string to search for

Using the needle-haystack analogy, this can be called needle.

 * @param fromIndex Optional, an index to start searching at.

From an IDE perspective, I think it is not necessary to state that the parameter is optional. All ActionScript IDEs that I know of have built-in features for this, by stating parameter = defaultValue. Your documentation doesn't state what the default value is, so the IDE is more helpful here than your documentation. Of course though, one would expect it to start at index 0. I would follow how others have done and simply state "index to start searching at." Or, even better "The location in the array from which to start searching for the item."

 * @returns The index of the array that a match was found at (zero-indexed), or -1 if no match was found.

First of all, everyone who uses arrays should be aware that array indexes in AS3 is zero-indexed. Secondly, the term 'index' was also mentioned in the previous documentation line but there was no stating there that it was zero-indexed. I would leave the (zero-indexed) part out. The rest is perfectly fine, and is what one would expect out of the function.
Code
I would prefer a space after each colon, but that's just my personal preference. At least you are consistent about it.
It's great that you use uint in your code and not int or some other, shorter, type. A minor problem would be if the match was found at index >= 2147483648 though, as you return an int. This is however the same in many other indexOf functions because you want to return -1 if no match was found, and I doubt that you will get an array of length > 2147483647 as input. Also, retuning Number would be horribly overkill so there is really no other option here.
I personally find your comments in the code unnecessary, but they are definitely not "clutter" so they are fine. Although //It wasn't found in the array. can be removed as that behavior is described in the documentation of your method.
Now, there's only one thing left to say; Why not use the Vector.<String> type? Then you wouldn't have to check element is String for each element. Also, IIRC, Vector is faster than Array.
Overall, well done. Your code looks quite fine overall.
Null and undefined
You explicitly ask this question:

Should I handle null and undefined?

I would recommend that you at the beginning of the method check if the array or the search string is null or undefined and that you throw an error with a clear message if that is the case. It is often frustrating when a method throws an error because something is null, but as it is automatically thrown, it is harder for the programmer to find out what is null. Checking for preconditions at the start of the method is good practice!


Show one form that corresponds to the selected radio button

Though your conditions are fine, I'd suggest you for a radical change in the code.

Change the ids as follows:

ContactFormOne to informed
ContactFormTwo to release
ContactFormThree to intake
ContactFormFour to checklist
ContactFormFive to health

The code will get a lot shorter now.

The code will be:

$(document).ready(function () {
    $('.Form').hide();
    $('input').on( 'change', function () {
        <!--check if its One-->
        var ValUe = $(this).val();
        $('.Form').hide(); //Replace the '.Form' selector with the element that is containing your contact forms.
        $('#' + ValUe).show();
    })
});

where, I'm assuming you have jQuery 1.9.1.

For a better answer, please include your HTML in the question too.


As mentioned in the comments, it would be useful if you included more than just the models here. As a result, I can only really do a design review of what appears to be a fairly generic quiz application.

Right now your models are set up this way

So exams can share questions, and questions can share answers. This is useful in cases where exams typically share questions, and questions share common answers, but it can (and often will) cause issues down the road. I'll get to those later.

Typically the next step is to build out the models for making selections on an exam. You might consider a adding a new many-to-many relationship on the exam that holds the selections (assuming a single exam per person). Here's a rough diagram of what that would look like, where the "selection" is the many-to-many relationship. This can either be implemented as a single property, or as a separate model with two foreign keys.

But then there is a problem: How do you handle questions/answers duplicated on exams? There's no easy way to determine what selection tied to which question, because the answer that was selected is shared across multiple questions in the same exam. This means that you can't properly associate selections with questions, and you can't share answers across an exam, because there are multiple ways traverse the tree.

My recommendation would be to remove the flexibility of sharing questions and answers in favor of a more rigid, single-directional tree structure.

So a question has a defined set of answers, and those answers are unique to the question and cannot be shared. And those questions are specific to the exam that are specified for, and cannot appear across multiple exams. This means that a selection (the "glue" between the answer and the exam) cannot be duplicated across a single exam, so there will always be a clear path from an exam to an answer, and the reverse.

So the revised models would look like

from django.db import models

class Exam(models.Model):
    """
    Exam's model, works as a wrapper for the questions
    """
    name = models.CharField(max_length=64, verbose_name=u'Exam name', )
    slug = models.SlugField()

    def __str__(self):
        return self.name

class Question(models.Model):
    question_text = models.CharField(max_length=256, verbose_name=u'Question\'s text')
    is_published = models.BooleanField(default=False)
    exam = models.ForeignKey(Exam, related_name='questions')

    def __str__(self):
        return "{content} - {published}".format(content=self.question_text, published=self.is_published)

class Answer(models.Model):
    """
    Answer's Model, which is used as the answer in Question Model
    """
    text = models.CharField(max_length=128, verbose_name=u'Answer\'s text')
    is_valid = models.BooleanField(default=False)
    question = models.ForeignKey(Question, related_name='answers')

    def __str__(self):
        return self.text

All diagrams were created using nomnoml.


Custom database Lock - implemented with IDisposable

The IDisposable was primarily added in order to be able to release acquired unmanaged resources in a deterministic fashion. However it also provides a nice way of releasing other resources in a deterministic fashion as you have found.

I would not say that this is an abuse of the disposable pattern: You acquire a lock which is a resource and you need to release it at a given point in time. For me this is good enough especially since you said it's some kind of db lock which I assume lives outside of the application (that is unmanaged for me). It provides you with native support through using to make sure it's released in case the executing code throws an exception.

However I don't particularly like your two public static methods on there. Now you all of a sudden have two interfaces into the class. If you want a factory like interface then make the DoLock method a proper factory method returning the lock which was acquired (in which case the ctor should become private):

public class MyLock : IDisposable
{
    private string _id;

    private MyLock(string id)
    {
        _id = id;
        DoLock();
    }

    public static MyLock Acquire(string id)
    {
        return new MyLock(id);
    }

    private void DoLock()
    {
        // get the lock
    }

    public void Release()
    {
        // release it
    }

    public void Dispose()
    {
        Release();
    }
}

While you could do without a public Release method having Dispose calling Release is semantically useful in case you can't use using and need to release the lock explicitly. In this case the code will be clearer when you call Release rather than Dispose. The .NET stream classes do a similar thing (where Dispose calls Close).

Some things to consider:

Add an "object is disposed" flag so you don't try to release the same lock twice.
Add a finalizer to try and release the lock in case it was not properly released. Add  a Debug.Assert at least for that case. Note that adding a finalizer will make all MyLock objects go through the finalizer queue which will add overhead for the GC. You could wrap the finalizer into a #ifdef DEBUG to only do that in debug builds - depends how many of these locks you create (although I guess if you create lots of them you have another problem altogether).


Implementation simplicity
As code is incorrect in too many cases, simplicity assessment is moot.
Ability to be used on different sorts of streams (writing into a file, a string, etc)
Code assumes it can pass a void * like a FILE *.  Reasonable, but not specified by C.
Writing to a string deserves a size parameter.
Rather than attempt to use fprintf(), sprintf(), consider providing interface functions.
Reasonable corrrectness
corrrectness -->  correctness
OP is brave.  Quality conversion of a string to a double is hard.
To assess, I set up a test harness.
void test(double x) {
  // Reference output
  printf("R%.*e %20a\n", DBL_DECIMAL_DIG - 1, x, x);
  // OP's output
  printf("<");
  print_number((printfn_t) fprintf, stdout, x);
  puts(">\n");
}

int main(void) {
  const double x[] = {1.0, 1.0 / 7, DBL_MIN, DBL_TRUE_MIN, DBL_MAX, INFINITY,
      NAN, -DBL_MAX, -0.0, 1.0 + DBL_EPSILON, 1.0 - DBL_EPSILON};
  size_t n = sizeof x / sizeof *x;
  for (size_t i = 0; i < n; i++) {
    test(x[i]);
  }
}

Outright discrepancies included
R4.9406564584124654e-324            0x1p-1074
<0.-9223372036854775808e-324>                          ???

Rinf                  inf
<-9223372036854775808.-9223372036854775808e2147483647> ???

Rnan                  nan
<-9223372036854775808.-9223372036854775808>            ???

R-0.0000000000000000e+00              -0x0p+0
<0>                                                    Missing sign

R9.9999999999999978e-01 0x1.ffffffffffffep-1
<0.1000000000000000>                                   Off by 10x!

Non-finite
For NAN and infinity, consider a !isfinite(x) test and then handle those special cases.
Sign
For -0.0 correctness,
//if (number < 0) {
if (signbit(number)) {
    print("-");
    ...

Precision
double deserves up to DBL_DECIMAL_DIG (e.g. 17) places of output to properly distinguish all double from other double.  OP's precisions output wobbles with inconsistent significant precision output.
I adjusted OP's code to int PRECISION = DBL_DECIMAL_DIG;, then used select values like 1.0 - DBL_EPSILON (and many others) are not quite correct.
R9.9999999999999978e-01 0x1.ffffffffffffep-1
<0.99999999999999984>

As a reference, to print the exact value of a finite double. See Function to print a double - exactly
Numeric correctness.
Each *, / and some pow(10, ) inject 0.5 [ULP] or more error into the math and there is little code compensating for these accumulating errors.  Without internal extended math, I see OP's approach as unable to achieve a high quality result.
Code assumes double precision < 64 bits.  Reasonable, but not specified by C.

Recommendation
Test with the usual suspects as in the test harness, with values near powers of 10 and with various random values.


The code almost works.
To make it work in all cases, test the program with Valgrind, which detects undefined behavior because of invalid memory access. This will prove that the buffer needs to be 11 bytes long, not only 10.
What about platforms where int has 64 bits instead of just 32? For these you need a larger buffer. Until then, you should use a compile-time assertion (static_assert) to ensure this implicit assumption.
What about negative numbers? -6 is a valid integer as well, and it should be converted appropriately.
If this function is the bottleneck of your whole program because it is too slow, have a look at how the Go programming language converts integers to strings. It's in the strconv package and uses lots of nice tricks to cut down the number of integer divisions, since that's the most expensive machine instruction in your code.
You can get rid of the get_digits function if you have the end of the string at a fixed address. Start with:
char *p = buf + sizeof buf - 1;
*p = '\0';

and then continue to fill the buffer from right to left by doing *(--p) = '0' + digit. At the end just return p, which will point to the first digit.
The return type should be const char * instead of char * since the caller is not supposed to do anything to the buffer.