What would be proper way to store data from file and validate data from file

from what I understood, you need a Model class, since you don't have one for the current data. I assume the file that holds the information is saved by other third-party application, and you're working on a middle-ware application in which would take that file and insert the data into the database.

If possible, try to find another approach than reading the file and try parse each line of it to convert them into an object model. If the other end can process CVS, a table view from the database if any, or an API that would retrieve the information you need, these would be a much safer approaches.

If there is no other way than reading the file and parsing each line. You can still do your idea, but hence, you must know that you need the replace both (the other end application, and this one) with an application that process the data better (combining both application processes into one).

The class you need :

// Book Model
public class Book
{
    // position start index: 0
    //  Length: 4
    public int LineNumber { get; set; }

    // position start index: 4
    //  Length: 25
    public string Author { get; set; }

    // position start index: 29
    //  Length: 8
    public DateTime Publish { get; set; }

    // position start index: 37
    //  Length: 5
    public int PageNumber { get; set; }

    // position start index: 43
    //  Length: 5
    public string Code { get; set; }

    public Book(string line)
    {
        // normal validation
        if (string.IsNullOrEmpty(line)) { throw new ArgumentNullException(nameof(line)); }

        // business validation
        if (line.Length != 48) { throw new InvalidOperationException(nameof(line)); }

        LineNumber = int.TryParse(ParseValue(line, 0, 4), out int lineResult) ? lineResult : -1;

        Author = ParseValue(line, 4, 25);

        Publish = DateTime.TryParse(ParseValue(line, 29, 8), out DateTime publishResult) ? publishResult : DateTime.MinValue;

        PageNumber = int.TryParse(ParseValue(line, 37, 5), out int pageResult) ? pageResult : -1;

        Code = ParseValue(line, 43, 5);
    }

    private string ParseValue(string line, int startIndex, int endIndex)
    {
        // get
        var value = line.Substring(startIndex, endIndex).Trim();

        // check if is it a white space return null
        // we need to discard whitespace initialization.
        // this could be a business requirment where all data should have real data
        // if this is a requirment, then throw an exception instead of null
        if (value.Length == 0) { return null; }

        return value;
    }
}

Then, you stream the file and create a Book from each line or implement GetBooks method example :

public IEnumerable<Book> GetBooks(string filePath)
{
    if(string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException(nameof(filePath)); }

    using (var fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (var bs = new BufferedStream(fs))
    using (var sr = new StreamReader(bs))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            yield return new Book(line);
        }
    }
}

then you could do this :

var books = GetBooks(@"filepath");

foreach(var book in books)
{
    // do something with each book object.
}

or you can use LINQ if you need as well.

UPDATE

Since you're looking for using Attribute you need to keep in mind, using attributes would put more work on your hands, as you would define them, and use Reflection to access its values, which would add more processing time to your code performance.

To create a new custom attribute you can do this :

/// <summary>
/// Implement StringPosition custom attribute
/// To define the start position and the length of the extracted string
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class StringPositionAttribute : Attribute
{
    public int StartPosition { get; set; }

    public int Length { get; set; }

    public StringPositionAttribute(int startPosition, int endPosition)
    {
        StartPosition = startPosition;
        Length = endPosition;
    }
}

Now, you can use [StringPosition(startIndex, length)] attribute on the class properties.

Example :

// Book Model
public class Book
{
    [StringPosition(0, 4)]
    public int LineNumber { get; set; }

    [StringPosition(4, 25)]
    public string Author { get; set; }

    [StringPosition(29, 8)]
    public DateTime Publish { get; set; }

    [StringPosition(37, 5)]
    public int PageNumber { get; set; }

    [StringPosition(43, 5)]
    public string Code { get; set; }
}

now, by doing this, we can create a method where it loop over all of these properties and extract the targeted string based on the values of their attributes, then save the results for each.

private void ParseValues(string line)
{
    foreach(var property in this.GetType().GetProperties())
    {
        // Get property attribute
        var attribute = (StringPositionAttribute)property.GetCustomAttribute(typeof(StringPositionAttribute));

        // Get the start index value from the attribute
        var startIndex = attribute.StartPosition;

        // Get the length value from the attribute
        var length = attribute.Length;

        // parse the values to get the string
        var value = ParseValue(line, startIndex, length);

        // set the value of the property for this instance
        property.SetValue(this, Convert.ChangeType(value, property.PropertyType), null);
    }
}

now use this method in the constructor :

public Book(string line)
{
    // normal validation
    if (string.IsNullOrEmpty(line)) { throw new ArgumentNullException(nameof(line)); }

    // business validation
    if (line.Length != 48) { throw new InvalidOperationException(nameof(line)); }

    // do the parsing
    ParseValues(line);
}

this is a quick examples to give you a boost start, the attribute can be useful in many cases, such as validation, or messages ..etc. But I believe your work does not need that much of work.

I hope this would give you the boost you need.


A few things strike me as fairly obvious possibilities to consider here.

Use functions where appropriate

if(a<0) a=-a;

I think I'd prefer to have a separate little function to compute the absolute value.

Be consistent

    while((a%2 == 0)&&(b%2 == 0)){
//        printf("step2\n");
        a=a>>1;
        b=b>>1;
        c*=2;
    }

I'd pick either bit-oriented or mathematically-oriented operations, and use them consistently. That would mean either using shifts and bit-tests throughout:

 while(((a & 1) == 0) && ((b & 1) == 0)){
        a >>= 1;
        b >>= 1;
        c <<= 1;
    }

...or else using mathematical operators throughout:

 while((a % 2 == 0) && (b % 2 == 0)){
        a /= 2;
        b /= 2;
        c *= 2;
    }

Also note the compound assignment operators--at least in my opinion, they're much clearer than things like A = A >> 1. Maybe it's just a background in math, but I've never like things like A = A + 1; that always look to me like they're just clearly false statements.

Better variable names

Most of your variable names are so short they're basically meaningless--a, b, d, x1, x2, and so on. I'd much rather see names that made their intended use/purpose easier to understand.

Type checking

Although it can quickly get into extremely advanced programming, I'd at least consider adding some type-checking to your templates. Just for example, I'd guess all the templates in this code really only make sense if T is some integer type, not floating point, a string, etc. That being the case, it's fairly easy to add at least minimal type-checking to enforce that. One simple form of that would use static_assert:

template <typename T>
T gcd(T a, T b){
    static_assert(std::is_integral<T>::value, "Only integer types allowed");

The code almost certainly won't compile if somebody attempts (for example) to get the GCD of two strings--but with the static_assert, you're pretty much guaranteed that at least part of the error message they get will say "Only integer types allowed". Without it, they're likely to get a giant avalanche of error message telling them about things like there not being an >> overloaded for string and int, followed by a 5-page list of the overloads of >> that it considered and rejected in trying to figure out a way to compile the code.

Note: there's work in progress on a set of extensions to C++ called "Concepts" to support this a little more directly in the language. Some compilers already have experimental support, in case you want to try it.


Sending file[type="file"] multiple content as list of base64's

while (files_obj.length < files.length) {}

That's not the correct way to wait for the FileReader. onload will get called whenever a file has been successfully read, so you can check for files.length there, and call the rest of the function as needed. Right now you're spin-looping during at least partly CPU intensive (base64 encoding) operations. Which is a huge waste.


I also changed the Reversal code and got rid of all the variables.  from the looks of it you did what I did only you did it with out the use of for loops

I used one loop to go through the rows(or the first dimension of the multi-dimensional array) and then I nested a second loop inside the first to loop through the elements of each array.   now in doing this I needed some independent variables to be incremented for the output matrix so I made sure that I declared them in the right places and incremented them in the right places.   the output matrix was declared using the input matrix so that I didn't have to declare any magic numbers and so that I could minimize the number of variables that I had to declare as well.

enough chit chat here is the code.

    static int[,] ReverseMatrix(int[,] inputMatrix)
    {
        var outputMatrix = new int[inputMatrix.GetLength(0), inputMatrix.GetLength(1)];
        var x = 0;
        for (int i = inputMatrix.GetLength(0) - 1; i >= 0; i--)
        {
            var y = 0;
            for (int j = inputMatrix.GetLength(1) - 1; j >= 0; j--)
            {
                outputMatrix[x, y] = inputMatrix[i, j];
                y++;
            }
            x++;
        }
        return outputMatrix;
    }

Posted as a question also Reversing a Matrix

one thing that I did differently was that I used an input and an output for my method, I personally don't like the way that your code changes a variable outside of the scope like that, if the purpose were to change the original then I wouldn't change my code at all, I would just change how I call the code, I would do it like this

matrix = ReverseMatrix(matrix);

I don't like the way that you did it, I am sure there is a reason for it and a good and bad way to do it, but I don't think this is a good place to use code like this.


Some minor notes.

I love the ternary operator and f strings, but...

Here are three ways to express the same thing.  There is the original way, a DRY version of the original way, and a more traditional if/else.  Which is easier to read and understand what is going on?

# variant 1
build_type = f"go build -buildmode=c-shared" if kwargs["buildtype"].lower() == "dll" else "go build -tags exe"

# variant 2
build_type = f"go build {'-buildmode=c-shared' if kwargs['buildtype'].lower() == 'dll' else '-tags exe'}"

# variant 3
if kwargs["buildtype"].lower() == "dll":
    build_type = "go build -buildmode=c-shared"
else:
    build_type = "go build -tags exe"

In this case I would argue that the third variant is MUCH easier to understand what the distinction is between the two build types.  EG: What question is being asked (buildtype) and what is the difference in the result based on the answer.

Environment has a "n" after the "o"

This:

enviroment["CGO_ENABLED"] = "1"

should likely be:

environment["CGO_ENABLED"] = "1"

Click is the thing.

Not sure this is immediately relevant as a code review, but...

I much prefer click to argparse.  In this simple case there is not likely a huge advantage for Click, but there is little downside.  And if you get comfortable with click and the size of your project increases, I think Click can be quite advantageous.


Cropping faces from images in a directory

So there are a couple of improvements that can be made to your code,

The first one would be, you are creating a new CascadeClassifier object for every picture this is a costly operation.

The next is the fact that you are resizing the image, to the size of the image? I am unsure why you are doing that, depending on the size of the faces in your images you could resize them to be smaller and the search for faces in the picture.

Harr cascade detection is costly you can customize the parameters depending on the sizes of faces in your image.

Your code draws a box around every face and then isolates it, why is that? Lots of this code looks to be vestiges of old code. Removing old code can help make it more clear what is going on.

You number the face images based on the y value of the box; it would be much cleaner to simply report the index of the face (e.g. face 0, 1, 2, 3, etc...)

Based on this, here is some straightforward revised code that is much cleaner, but detectMultiScale is still ~99% of the running time

import os

import cv2

image_path = "images"

def save_faces(cascade, imgname):
    img = cv2.imread(os.path.join(image_path, imgname))
    for i, face in enumerate(cascade.detectMultiScale(img)):
        x, y, w, h = face
        sub_face = img[y:y + h, x:x + w]
        cv2.imwrite(os.path.join("faces", "{}_{}.jpg".format(imgname, i)), sub_face)

if __name__ == '__main__':
    face_cascade = "haarcascade_frontalface_default.xml"
    cascade = cv2.CascadeClassifier(face_cascade)
    # Iterate through files
    for f in [f for f in os.listdir(image_path) if os.path.isfile(os.path.join(image_path, f))]:
        save_faces(cascade, f)


Basic API wrapper around a Restful service

I would personally prefer to use HttpClient directly as it provides full control and perfect testability - see here.

We can define our REST API as:

// see https://jsonplaceholder.typicode.com/
// this site exposes some REST API example to automate
public interface ITypicode
{
    Task<BlogPost[]> GetPostsAsync();
    Task<BlogPost> GetPostAsync(int id);
}

public class Typicode : JsonRestApi, ITypicode
{
    public Typicode(HttpMessageHandler handler = null)
        : base("https://jsonplaceholder.typicode.com", handler)
    {
    }

    public Task<BlogPost[]> GetPostsAsync() => GetAsync<BlogPost[]>("posts");
    public Task<BlogPost> GetPostAsync(int id) => GetAsync<BlogPost>($"posts/{id}");
}

public class BlogPost
{
    public int UserId { get; set; }
    public int Id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
}

Where base class to simplify API definition is:

public abstract class JsonRestApi
{
    static readonly JsonSerializerSettings Settings = new JsonSerializerSettings()
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver(),
        Converters = new [] { new StringEnumConverter() }
    };

    protected JsonRestApi(string baseAddress, HttpMessageHandler handler = null)
    {
        Client = handler == null ? new HttpClient() : new HttpClient(handler);
        Client.BaseAddress = new Uri(baseAddress);
        Client.DefaultRequestHeaders
            .Accept
            .Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    protected async Task<T> GetAsync<T>(string uri) =>
        await ParseJson<T>(await Client.GetAsync(uri));

    protected async Task<T> PostAsync<T>(string uri, object data = null) =>
        await ParseJson<T>(await Client.PostAsync(uri, JsonContent.From(data)));

    protected HttpClient Client { get; }

    async Task<T> ParseJson<T>(HttpResponseMessage response) =>
        JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync(), Settings);

    class JsonContent : StringContent
    {
        public static JsonContent From(object data) =>
            data == null ? null : new JsonContent(data);

        public JsonContent(object data)
            : base(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json")
        {
        }
    }
}

This code is fully testable.


Extracting Multiple Associative arrays in PHP

I think this will work. You'll have to have PHP version 5.3 though, otherwise you'll have to remove the lambda functions and define actual functions in their place. Disclaimer, not to say that this is easier to read or easier to understand, but I think it fits the "cleaner" request.

$track_paths = array_map( function ( $array ) { return $array[ 'track_path' ]; }, $row );
$track_ids = array_map( function ( $array ) { return $array[ 'track_id' ]; }, $row );
$track_names = array_map( function ( $array ) { return $array[ 'track_name' ]; }, $row );
$track_desc = array_map( function ( $array ) { return $array[ 'track_desc' ]; }, $row );
$track_artist = array_map( function ( $array ) { return $array[ 'track_artist' ]; }, $row );


I'm going to have to heavily disagree with Tolani Jaiye-Tikolo's answer. Using ID's isn't good CSS authoring generally (however this rule can be broken, like all rules.) This is because you create overly specific CSS that can only be used once.

Another point i'd like to make about their feedback: please only use tables for tabular data. Using them as structural elements is not the way to go. If you want to use the properties of a table element, use display: table;.

That said, onto some critique of your code. You asked what the best way to center align content is. There's several methods for achieving this, some very common ways are:

use text-align: center; on a parent container. This only affects inline or inline-block elements.
use margin: 0 auto; on a element. This only works on block type elements.

I noticed you're also looking to vertically align an element. This is a little more complex than horizontally aligning an element (But only slightly). I personally use the following two methods often:

Place display: table; on the parent/container element. Place display: table-cell; and vertical-align: middle; on the child element (the one you want to vertically center). The child element should sit in the middle of your parent vertically.
Other method is to make your element display: inline-block; and give it vertical-align: middle. It will center vertically according to its siblings.

There's other things you can improve on but unfortunately I'm at work so I can't provide examples and a more comprehensive answer, sorry!


SqliteParameter setParam = new SqliteParameter ("@setValue", setValue);
        SqliteParameter whereParam = new SqliteParameter ("@whereValue", whereValue);

        dbCommand.Parameters.Add (setParam);
        dbCommand.Parameters.Add (whereParam);

instead of doing this, you could actually do this

dbCommand.Parameters.AddWithValue("@setParam", setValue);
dbcommand.Parameters.AddWithValue("@whereValue", whereValue);

that is how I would do with with SQL Server, I don't think it is any different with SqlLite.

also,  I would do this a little differently as well

using (var dbConnection = new SqliteConnection ("URI=file:" + Application.dataPath + connection))
{
    dbConnection.Open ();

    using (var dbCommand = dbConnection.CreateCommand ())
    {

I would instead write it like this

using (var dbConnection = new SqliteConnection ("URI=file:" + Application.dataPath + connection))
using (var dbCommand = dbConnection.CreateCommand ())
{
    dbConnection.Open ();

it looks a lot cleaner and removes some of the nesting.

also, try to limit what you do inside the using statements, to whatever you actually need in the using statements and not more than that.

Another thing, don't spread your string onto 3 lines like that, it looks messy.

pull your SQL statement out of the using statements, and make it a simple string, then pass it into the constructor of the dbCommand.

this:

public void UpdateData (string tableName, string whereHeader, object whereValue, string setHeader, object setValue)
{
    using (var dbConnection = new SqliteConnection ("URI=file:" + Application.dataPath + connection))
    {
        dbConnection.Open ();

        using (var dbCommand = dbConnection.CreateCommand ())
        {

            dbCommand.CommandText = string.Format ("UPDATE {0} " +
                                                   "SET {1} = @setValue " +
                                                   "WHERE {2} = @whereValue",
                tableName, setHeader, whereHeader);

            SqliteParameter setParam = new SqliteParameter ("@setValue", setValue);
            SqliteParameter whereParam = new SqliteParameter ("@whereValue", whereValue);

            dbCommand.Parameters.Add (setParam);
            dbCommand.Parameters.Add (whereParam);

            Debug.Log (dbCommand.CommandText);

            dbCommand.ExecuteNonQuery ();
        }
    }
}

should look more like this

public void UpdateData (string tableName, string whereHeader, object whereValue, string setHeader, object setValue)
{
    var sql = string.Format ("UPDATE {0} SET {1} = @setValue WHERE {2} = @whereValue", tableName, setHeader, whereHeader);
    Debug.Log (sql.ToString());

    using (var dbConnection = new SqliteConnection ("URI=file:" + Application.dataPath + connection))
    using (var dbCommand = dbConnection.CreateCommand (sql, dbConnection))
    {
        dbConnection.Open ();

        dbCommand.Parameters.AddWithValue("@setParam", setParam);
        dbcommand.Parameters.AddWithValue("@whereValue", whereValue);

        dbCommand.ExecuteNonQuery ();
    }
}


Use jQuery to force two checkboxes mirror each other's state

As said in other answer, cache the DOM elements references so you don't have to dive into DOM to get the elements again and again on each check/uncheck of the checkboxes.
Use $(document.body) to refer to <body> element, this is slight faster. See this post.
Use a common class on all the interested checkboxes. $('input:checkbox') is a general selector and it'll select all the checkboxes on the page.
You can use toggleClass() with second param which can be used to decide whether to add or remove class from elements. If the second param is true class is added and if it is false class is removed.
As the checkboxes are by default checked, add the class on the <body> by default.
this.checked is faster than $(this).is(':checked'). It just checks the property on the current elements. Whereas in jQuery, it has to call the is() function and check if the passed argument status on the element.
IF POSSIBLE, update the jQuery version to latest one. It has many performance improvements and bug-fixes.

Live Demo:

// Cache the elements
var $myCheckbox = $('.myCheckbox'),
  $body = $(document.body);1

// On change of the checked state of checkbox
$myCheckbox.live('change', function() {
  // Update the checked property of all other checkboxes
  $myCheckbox.prop('checked', this.checked);

  // Add/Remove the class on body
  $body.toggleClass('checked', this.checked);
});
/* For DEMO purpose */
body.checked {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>

<body class="checked">
  <input type="checkbox" checked='true' class="myCheckbox" id='1' />
  <input type="checkbox" checked='true' class="myCheckbox" id='2' />
</body>


You have neglected to escape your keys and values. If any of the data contains a special character such as &, the generated URL will be wrong.

To perform the escaping, I recommend calling encodeURIComponent().


Because you specifically ask about security:

For comparing hashes like SHA, you should use hash_equals().

If you are requiring the use of a password, you shouldn't use SHA-512. While it's certainly better than MD5, instead use bcrypt. Bcrypt is heavily recommended for password storage, especially long-term.
With bcrypt, instead of using hash() and hash_equals(), you would use password_hash() and password_verify().

Should new directories really have read and execute permissions for the group and other users? Likewise, I would check the permissions of the file itself.
I would personally have the files as 0600 and directories as 0700 unless other permissions are needed.

Checking the file extension is only helpful for preventing naive false uploads. On Linux and most UNIX-like operating systems, a file extension means very little (if anything). It could be any type of file with a JPEG extension, likewise anything could have a JPEG file extension.

I don't know about the rest of the code.


Filtering data stored using classes via user-called function the proper way?

if name:
            if name.lower() == team.name.lower():
                all_args.append(True)
            else:
                all_args.append(False)
        if country:
            if country.lower() == team.country.lower():
                all_args.append(True)
            else:
                all_args.append(False)
        if rank_exactly:
            if rank_exactly == team.rank:
                all_args.append(True)
            else:
                all_args.append(False)
        if rank_higher:
            if int(rank_higher) > int(team.rank):
                all_args.append(True)
            else:
                all_args.append(False)
        if rank_lower:
            if int(rank_lower) < int(team.rank):
                all_args.append(True)
            else:
                all_args.append(False)
        if score_exactly:
            if score_exactly == team.score:
                all_args.append(True)
            else:
                all_args.append(False)
        if rank_change:
            if rank_change == team.rank_change:
                all_args.append(True)
            else:
                all_args.append(False)
        if team_id:
            if team_id == team.team_id:
                all_args.append(True)
            else:
                all_args.append(False)
        if score_higher:
            if int(score_higher) < int(team.score.replace(',','')):
                all_args.append(True)
            else:
                all_args.append(False)
        if score_lower:
            if int(score_lower) > int(team.score.replace(',','')):
                all_args.append(True)
            else:
                all_args.append(False)
        if partial_name:
            if partial_name.lower() in team.name.lower():
                all_args.append(True)
            else:
                all_args.append(False)

You're being needlessly specific with your if statements here.
If you do something like this...

        if name:
            all_args.append(name.lower() == team.name.lower())
        if country:
             all_args.append(country.lower() == team.country.lower())

and so on, you'd reduce the needless verbosity.


Bad practices in this procedure to calculate player statistics?

the first thing that I see here is that it is going to be hard to read because you don't use standard ...  "notation" like indentation and new lines for each column you are selecting in a SELECT statement.  all of this is going to matter when you are going to be returning to the code to read it again or maintain it later.

where you have this:

WHERE stage = 0 AND playerid = userID

the playerid = userID part should really be in a join statement if possible.

some of your SET statements look very similar, you should look at these and see if you can't create a Temp Table with them, or even a CTE (I don't remember if this is possible with MySQL or not)


Simple ring/circular buffer c++ class V2

Instead of a char array you can use std::aligned_storage.

You aren't consistent with your macros you have both constexpr and _CONSTEXPR17. Pick one and stick to it.

destroy_at is standard only from C++17 onward. The equivalent syntax is location->~_Ty(); However it may be worth to put this and the placement new into a helper function to move the ugly syntax elsewhere and clarify the function.

You don't have a move variant of push or a bulk add/remove using iterators.


Your solution:

seems legit :)
One thing I'd suggest here is to use ArrayDeque instead of Stack

Another possible solution:

Basically, for every subtree we have constrain, that every node in it should be in range (X, Y).

For root this range will be (-inf; +inf) - in other words, there could be any value in root.

For root's left subtree range will be (-inf, value-in-root), for right - (value-in-root, +inf).

Last thing - on each iteration we should check, that value in node is within this range, like so:

public boolean doInOrderTraversal(TreeNode root, int min, int max) {
    if (root == null) {
        return true;
    }
    if (root.val <= min || root.val >= max) {
        return false;
    }

    return doInOrderTraversal(root.left, min, root.val) && doInOrderTraversal(root.right, root.val, max);
}


efficiency
Yes, this can be improved.
One obvious problem is that you're re-computing your average and your standard deviation on every iteration of a loop, even though only the last result (after the last iteration) is ever actually used.
For example:
for (int i = 0; i < arrSize; i++)
{
    sum += grades[i];
    average = (sum / arrSize);
}

You're computing average on every iteration, but only need or use the last value you compute. You can compute it once with code like:
for (int i = 0; i < arrSize; i++)
{
    sum += grades[i];
}
average = (sum / arrSize);

Your computation of the standard deviation is much the same way.
Use of pow
I'd avoid using pow to compute a square. It often imposes quite a bit of overhead, so pow(deviation[i], 2) will often be substantially slower than deviation[i]*deviation[i].
Formatting
Looking at the code more generally, you really need to fix your indentation.
std::endl
I would advise against using std::end. Normally, you just want '\n', which also gives you a new line, but will nearly always be (much) faster. In the case above, it won't make much difference, but if you're writing a lot of data to a file (for example) the difference can get very large, very quickly (e.g., a slowdown of 8:1 or 10:1 is fairly typical).


Inline assembly correctness (especially __volatile__)

Your use of volatile appears to be correct, but I think you should do a couple of things for safety:

Add a clobber constraint for the flags (AKA "condition codes") to ckAsmSetEFlag. I believe this is "cc" for x86 machines.
Add clobber constraints for CR0 and CR3 to ckSetCr0 and ckSetCr3, respectively. [edit] This appears to be impossible with GCC. Not sure if this is a problem or not.[/edit]

While GCC's inline assembly syntax is very powerful, it can be horribly unintuitive. Since you're writing a kernel and messing with control registers, you really should be checking the assembly listings for every module you compile, to verify that the compiler is honouring your intentions.


Returning the result of whichever method finishes first

Tasks can have results, you should take advantage of that, instead of assigning a local variable from a lambda. And WaitAny() returns the index of the Task that finished first. This means you can do something like:

public static bool IsPrimeHybrid(BigInteger number)
{
    var byPureCalc = Task.Run(() => IsPrimeNaive(number));
    var bySearchFirst = Task.Run(() => IsPrimeBySearch(number));
    var tasks = new[] { byPureCalc, bySearchFirst };
    int firstIndex = Task.WaitAny(tasks);
    return tasks[firstIndex].Result;
}

Also, CPU and memory are also resources that you shouldn't waste. So, you may want to cancel the slower Task, after the faster one finished. For that, you can use CancellationToken, which the two computations will periodically check (you can use ThrowIfCancellationRequested () for that):

public static bool IsPrimeHybrid(BigInteger number)
{
    var cts = new CancellationTokenSource();

    var byPureCalc = Task.Run(() => IsPrimeNaive(number, cts.Token));
    var bySearchFirst = Task.Run(() => IsPrimeBySearch(number, cts.Token));
    var tasks = new[] { byPureCalc, bySearchFirst };

    int firstIndex = Task.WaitAny(tasks);

    cts.Cancel();
    return tasks[firstIndex].Result;
}


If you are not going to create a long running thread pool (and manage the threads over many jobs), then I would let the system do it for you; the async() function potentially runs stuff in parallel and manages a thread pool for you.

// Not tested.
// You may need to play with it.
template<class T, class C>
void parallel_for_each(std::vector<T>& ts, C callable)
{
    size_t index =;
    std::vector<std::future> results;

    for(auto const& value: ts)
    {
        results.emplace_back(async(callable, value));
    }
    for (auto& result : results)
    {
        result.wait();
    }
}

Other notes

Don't pass pointers around.

One of your parameters is:

std::vector<T>* ts
          //  ^  Pointer

Passing by pointer is very rare in C++ (very common in bad C++ written by old C programmers). The reason for this is there are no ownership semantics associated with the pointer and thus potential for misunderstanding the interface and thus leading to memory leaks.

In C++ we want to very clearly define the ownership of pointers as it is the owner of the pointer (and nobody else) that is responsible for deleting the pointer. The language has introduced smart pointers that allow us to specify ownership so that when the pointer is passed we are explicit in passing ownership with the pointer. In other situations were ownership is not passed we use references.

If I was using your function for the first time I could not tell if I need to dynamically create the vector or not. Is your function going to delete the passed pointer? I can't tell from reading the interface because raw pointers have no ownership semantics.

If you change your interface to pass by reference then it works just as well and there will be no confusion. If you want to pass ownership, you need to use smart pointers to indicate the type of ownership that is being transferred.

Prefer prefix increment.

ts->at(index++)

It makes no difference for integer types. But when using other types (including iterators) the default implementation for increment usually makes the prefix version more efficient. So when it makes no difference to your code, prefer the prefix version. This allows the types of your objects to be changed without having to update the code and it will still be the most efficient version.

Prefer operator[]() to at()

If you know that your access to an array will always be in bounds then prefer operator[] as it performs no accesses checks and is thus quicker.

Note: throwing an exception that is not caught inside a thread will cause the application to terminate. Throwing an exception inside an async will catch the exception and transfer it to the future object allowing the main thread to detect it.

Don't know why you are using r-value reference here

for (auto&& thread : threads)
         ^^

Don't know what that gives you. Note: an named r-value reference is treated liked an r-value when passed as a parameter (because it is named). You would still need to call std::move() on it to make it bind to the r-value reference function.

  Sorry I don't know the X/R/L/V value naming scheme very well yet so I am using an older terminology. Please have a look at appropriate documentation.

Personally I would just use a reference:

for (auto& thread : threads)


Program to Check If string is Palindrome (in C)

Bug
Given the input "racebar", the function returns true.  The problem is that your boolean variable is reset after each character pair, so you are only really testing the first character with the last.  I would do the following:

Get rid of the boolean variable and return false on the first mismatch.
Fix the loop iteration to only iterate through half the string instead of the whole string.
Mark the input parameter as const, since you do not modify the input string.  This allows your function to accept both const strings and non-const string as arguments.
In C99, you can declare loop variables inside the loop itself, which helps to reduce the scope of these variables to only where they are used.

Here is a rewrite showing all of the above:
int palindrome(const char *s)
{
    for (int i = 0, n = strlen(s) - 1; i < n; i++, n--) {
        if (toupper(s[i]) != toupper(s[n]))
            return 0;
    }

    return 1;
}


If you're currently learning Python you should probably look at Python 3
more so than Python 2.

There are only two violations for PEP8 (caught by the command-line tool,
pep8), that's very good; line 9 can be split in a multitude of ways to
go below the 80 character limit and there are more than one space before
the plus in the last line.

i = raw_input('Please input your type of residency, I for in-state, O for '
              'out-of-state, and G for graduate: ')

Also, constants should be uppercase with underscores, I'd say that
applies to inState etc.

IN_STATE = 10000
OUT_STATE = 24000
PROF_GRAD = 40000

That said, it would be easier to use a dictionary for this kind of
selection (BASE_TUITION[i]) - that might be a bit less descriptive
though.  Btw. i isn't very descriptive either.

Personally, I'd also stick with one kind of quotation marks, but YMMV.

Now for the code and other conventions.

First, code would usually be put into functions to make it reusable.  I
don't know if you're that far ahead, just to note that it would be nice
to split the input, processing and output parts into separate units.

There is no error handling for invalid input.  If I enter foo I'd
expect a (helpful) error message from the program, not a NameError as
in the current state.  For example, using the following loop, the
program will only handle valid input and print at least an indicator
that something went wrong:

costOfTuition = None
while costOfTuition is None:
    i = raw_input('Please input your type of residency, I for in-state, O for '
                  'out-of-state, and G for graduate: ')

    if i == 'I':
        costOfTuition = IN_STATE
    elif i == 'O':
        costOfTuition = OUT_STATE
    elif i == 'G':
        costOfTuition = PROF_GRAD
    else:
        print("Invalid input.")

The while loop would be more readable using for and range.  Since
x isn't actually used, _ can be used instead.

for _ in range(5):
    intMath = costOfTuition * 0.03
    tuitionIncrease.append(intMath)
    fnlMath = intMath + costOfTuition
    years.append(fnlMath)
    costOfTuition = fnlMath

The assignments to academicYear1 to 5 should be a warning sign.  If
that happens in code it's usually an indicator that it can be more
easily achieved with less variables (and less typing).

years = []
tuitionIncrease = []
academicYear = []
academicYear1Inc = []

for _ in range(5):
    intMath = costOfTuition * 0.03
    tuitionIncrease.append(intMath)
    fnlMath = intMath + costOfTuition
    years.append(fnlMath)
    costOfTuition = fnlMath
    academicYear.append("${:,.2f}".format(fnlMath))
    academicYear1Inc.append("${:,.2f}".format(intMath))

If you want it in separate loops, that's fine too.  Same goes for the
sum call at the end.  It's nicer to look at, so I kept it around.

Lastly, the formatting is mostly good with using format.  The last
print statements can be written in a nicer way though.

All in all:

IN_STATE = 10000
OUT_STATE = 24000
PROF_GRAD = 40000

costOfTuition = None
while costOfTuition is None:
    residency = raw_input('Please input your type of residency, I for '
                          'in-state, O for out-of-state, and G for graduate: ')

    if residency == 'I':
        costOfTuition = IN_STATE
    elif residency == 'O':
        costOfTuition = OUT_STATE
    elif residency == 'G':
        costOfTuition = PROF_GRAD
    else:
        print("Invalid input.")

years = []
tuitionIncrease = []
academicYear = []
academicYear1Inc = []

for _ in range(5):
    intMath = costOfTuition * 0.03
    tuitionIncrease.append(intMath)
    fnlMath = intMath + costOfTuition
    years.append(fnlMath)
    costOfTuition = fnlMath
    academicYear.append("${:,.2f}".format(fnlMath))
    academicYear1Inc.append("${:,.2f}".format(intMath))

totalTuitionIncreaseSum = sum(tuitionIncrease)
totalTuitionIncrease = "${:,.2f}".format(totalTuitionIncreaseSum)

print('UNDERGRADUATE TUITION FOR THE NEXT FIVE YEARS ')
print('ACADEMIC YEAR          TUITION       INCREASE ')
print('-------------     ------------       -------- ')

for i, year in enumerate(range(16, 21)):
    print('{}-{}             {}        {}'.format(year + 2000, year + 1,
                                                  academicYear[i],
                                                  academicYear1Inc[i]))

print('TOTAL TUITION INCREASE              ' + totalTuitionIncrease)


The code looks mostly fine to me. If you feel that the code isn't as clean as it should be, or just want it to pass the metric, what you could do is split it into functions:

            $this->scraper->queryBuilder()->adage($this->currentAdAge)->page($this->currentPage);
            $parser = $this->scraper->extract()->parse();
            $items = $parser->items();
            $this->targetPage = $parser->maxPages();

That goes into a private function which sets targetPage and returns $items... you could call it parsePageToItems

And this

            foreach ($items as &$item)
            {
                $item->age = (new DateTime('now'))->modify("-{$this->currentAdAge} day");
                $this->collection->push($item);
            }

            unset($item);

Could go into a separate function mapItems.

You could then write a test for mapItems in particular, increasing coverage and further reducing your CRAP score.


It is pretty solid for saving images on a single web server. Some optional/extra things you could do are:

Host the images on a CDN. That way if there was any PHP or JS injected in, it would not be able to access any cookies or directories on the web server you use to serve content.
Your code would block out PHP files in disguise from being uploaded because of the getimagesize() and the exif_imagetype(). You can add this bit to an htaccess file in the images directory as well to disable PHP files from being executed on their own. This wouldn't stop the file from being executed though if your code automatically included the "image" in the code somewhere.

<IfModule mod_php5.c>
php_flag engine off
</IfModule>


Unless you'll be maintaining an accumulated number for multiple operations, this may not be the best use of classes.  For your code, you'd get the same effect by just performing these calculations within the switch statement (something similar to this).  Right now, you're just using a class to contain similar functions, including a trivial output function.

Some additional notes:

Try not to use using namespace std.
Indent everything within main() as well.  Not doing so may make it hard to tell that the code is being contained within something.
You don't need <conio.h> here, so just remove it.
It may be useful to prevent the user from dividing by 0, which is undefined behavior.


Updating multiple membership plan expiration dates at once

You want to set the same values on multiple rows.  The query you want should be UPDATE Requests SET offered_membership_plan=…, expires=… WHERE id IN (…, …, …), and a way to achieve that would be:

Request.objects.filter(id__in=selected).update(
    offered_membership_plan=plan,
    expires=expires
)


This is pretty trivial example for review, but you are right to question use of this function from within a view.

Personally I think this is information that needs to be determined upstream of this decision point, making the function unnecessary.

If you always used this format for loading language:

$this->lang->load($lang_file, $lang);

where $lang here could be a variable, constant, call to static class method, or some other way to get to the current language preference (with this preference determined somewhere outside the logic for actually loading the localization).


If run is called from multiple threads, the task may execute multiple times because this code is checking and setting the flag in separate operations:

    if self.running or self.finished:
        return
    self.active_lock.acquire()
    self._running = True
    self.active_lock.release()

Make it an atomic operation by holding the lock. Note also how the with statement releases the lock automatically:

    with self.active_lock:
        if self._running or self._finished:
            return
        self._running = True


Disclaimer, I'm a beginner level Swift programmer, so take my feedback with a grain portion of salt.

First off, a minor improvement for your newQuestion function, you can leave out the breaks, in Swift, cases don't fall through by default:

func newQuestion() {
    switch brain.binaryOperation {
    case .Addition:
        performAddition()
    case .Multiplication:
        performMultiplication()
    default: break
        // operation not implemented yet
    }
}

Secondly, I see no reason you need to put binaryOperation and difficulty into a Settings struct. Furthermore, from what I can see, they should be final. I'd suggest you rewrite thing to:

private let binaryOperation: BinaryOperation
private let difficulty: Difficulty

...

init(operation: BinaryOperation, difficulty: Difficulty) {
    self.binaryOperation = operation
    self.difficulty = difficulty
    super.init()
}

Then, to generalise your perform functions, I'd add two functions to your BinaryOperation enum:

enum BinaryOperation {
    case Addition
    case Subtraction
    case Multiplication
    case Division

    func rangesForDifficulty(difficulty: Difficulty) -> (Range<Int>, Range<Int>) {
        switch self {
        case .Addition:
            switch difficulty {
            case .Easy: return (1...10, 1...10)
            case .Intermediate: return (10...100, 1...100)
            case .Difficult: return (109...999, 109...999)
            }
        case .Subtraction:
            switch difficulty {
            case .Easy: return (1...10, 1...10)
            case .Intermediate: return (10...100, 1...100)
            case .Difficult:  return (109...999, 109...999)
            }
        case .Multiplication:
            switch difficulty {
            case .Easy: return (1...10, 2...4)
            case .Intermediate: return (1...50, 3...7)
            case .Difficult: return (10...100, 4...15)
            }
        case .Division:
            switch difficulty {
            case .Easy: return (1...10, 2...4)
            case .Intermediate: return (1...50, 3...7)
            case .Difficult: return (10...100, 4...15)
            }
        }
    }

    func apply(number1: Int, _ number2: Int) -> Int {
        switch self {
        case .Addition:
            return number1 + number2
        case .Subtraction:
            return number1 - number2
        case .Multiplication:
            return number1 * number2
        case .Division:
            return number1 / number2
        }
    }
}

This allows you to write a single the newQuestion function much more elegantly:

func newQuestion() {
    let (range1, range2) = binaryOperation.rangesForDifficulty(difficulty)
    number1 = Int.random(range1)
    number2 = Int.random(range2)
    answer = binaryOperation.apply(number1, number2)
}

Some people might argue, that the BinaryOperation enum has gotten unwieldy now and they might be right. You could consider putting the rangesForDifficulty function somewhere else to alleviate this, I do think that the apply function should stay where it is though.


Pretty good for a beginning, but I would have a lot of feature requests if I were a user.

Allow the user to provide a full file specification so that the file appears where the user expects it.
The logger should get the day and time of day and report that in each message.
The logger should be initialized with the program name so that the all the messages contain the program name, this way if multiple processes are writing to the same file one will know which process made the log entry.

Make it into a library by providing a header file and a C++ source file.


The name make_sure_rvm_rubies_installed describes very well what the function does,
but it's a bit too much.
Maybe check_installed_rubies would be good enough.

You didn't indent the body of the function.
It's better to indent the inner part of large { ... } blocks for readability.

No need to use the function keyword when declaring functions, though you can if you like.

Instead of cat ... | grep it's better to omit the cat and use the file as a parameter of grep.

No need to save the exit code of the grep in the version_search_result variable,
you can do this directly:

  if grep -q $version $TMP/local_ruby_versions.txt
  then
    echo "Required RVM Ruby version $version confirmed as present on this machine"
  else
    echo "*** EXITING SMOKE TEST *** - not all required ruby versions are present in RVM"
    echo "Please install RVM ruby version: $version and then re-run this program"
    exit
  fi

The exit there is a bit unexpected.
The script could be reusable if you return 1 instead,
to give a chance to the caller to recover gracefully if necessary.
(In your example use case it doesn't matter, but this is a tip for the future.)

I'm not sure what you're expecting from the $? check in this code:

for version in "${local_ruby_versions[@]}"
do
  # ...
done
if [ $? = 0 ]
  then echo "All required Ruby Versions confirmed as present locally"
fi

When a version is not found the original loop exits the entire script (I recommended above to return from the function).
So in case of failures this if is not reached.
Otherwise the last command to evaluate is an echo,
which should just succeed,
so this if condition seems pointless, you can omit it.

Although arrays are cool, and it's great that you can use them,
in simple situations like this I would use a normal variable:

local_ruby_versions='1.8.7 1.9.3'

for version in $local_ruby_versions; do ...; done

You create the file temporary file $TMP/local_ruby_versions.txt but you don't clean it up when finished.


If you turn the arrival and departure times into objects that give +1 or -1 to a truckCounter variable, then sort this array (\$O(n log(n))\$), then you can iterate over the list of events.

As a result, you'll have 6 iterations after sorting, and the algorithm will bound on not the length of the durations but the amount of trucks.

So read inputs, sort the array, and then...

//assuming there is an array "sortedTruckEvents" of type TruckEvent containing an object which has
//getModifier as -1 for truck leaving and +1 for truck arriving
//and getTime for retrieving when this happens
//and assuming there is an array "prices" containing 0 at index 0, priceA * 1 at index 1, priceB * 2 at index 2, priceC * 3 at index 3
int result = 0;
int truckCounter = 0;
int currentTime = 0;
for(int i = 0; i < sortedTruckEvents.length; i++) {
    TruckEvent event = sortedTruckEvents[i];
    result += prices[truckCounter] * (event.getTime() - currentTime);
    truckCounter += event.getModifier();
    currentTime = event.getTime();
}
//now result contains the total price

It's as easy as that.

The trick here is to realize that the points of interest in this case is where things change. And the problem variables don't change per timestep; they change per truck arrival and departure.

The problem has even made it easy for you by guaranteeing all the trucks will arrive before they leave and that the trucks will leave at all.


Refining an ASP.Net MVC VeiwModel for a Table to display worked hours

I don't think there is anything necessarilly wrong with your approach especially if it works.  However I personal might consider trying to leverage the DayOfWeek enumeration of c# and avoid the individual day timesheets.

This way you could loop over weeks more easily as well as potentially leverage Linq to do things such as calculating the TotalHours as part of the viewModel.

My viewModel for this case might then look like this:

public class TimesheetWeeklyTableVM
{
    public int TimesheetHeaderID { get; set; }
    public DateTime WeekEndingDate { get; set; }
    public decimal TotalWeekHours { get; set; }

    public List<TimesheetDailyVM> DaysOfWeek { get; set; }

    public TimesheetWeeklyTableVM()
    {
        DaysOfWeek = new List<TimesheetDailyVM>();

        foreach (DayOfWeek dayOfWeek in Enum.GetValues(typeof(DayOfWeek)))
        {
            DaysOfWeek.Add(new TimesheetDailyVM()
            {
                DayOfWeek = dayOfWeek
            });
        }
    }
}

public class TimesheetDailyVM
{
    public DayOfWeek DayOfWeek { get; set; }

    public double TotalHours
    {
        get { return TimeSpan.FromSeconds(Tasks.Sum(p => (p.StartDateTime - p.EndDateTime).TotalSeconds)).TotalHours; }
    }

    public IEnumerable<TimesheetDailyHoursVM> Tasks { get; set; }

    public TimesheetDailyVM()
    {
        Tasks = new List<TimesheetDailyHoursVM>();
    }
}

public class TimesheetDailyHoursVM
{
    public int TimesheetID { get; set; }

    public DateTime StartDateTime { get; set; }
    public DateTime EndDateTime { get; set; }
    public string ProjectCode { get; set; }
    public string TaskCode { get; set; }
    public string ProjectDescription { get; set; }
    public string TaskDescription { get; set; }
}

Note, I'm not sure if TotalHours is calculated differently but if it's just a sum of the Task times then you could include that logic into the Viewmodel itself as in.

public double TotalHours
{
    get { return TimeSpan.FromSeconds(Tasks.Sum(p => (p.StartDateTime - p.EndDateTime).TotalSeconds)).TotalHours; }
}

If you wanted to add properties for each individual day to make it easier to access say for example Monday then you could easily do this such as.

public TimesheetDailyVM Monday { get { return Day(DayOfWeek.Monday); }
public TimesheetDailyVM Tuesday { get { return Day(DayOfWeek.Tuesday); }

private TimesheetDailyVM Day(DayOfWeek day)
{
    return Days.Single(p => p.DayOfWeek == day);
}


Print a character frequencies as a vertical graph

This is a pretty good start.  You should be warned that K&R describes a very early version of C, and the language has evolved considerably since the 1980s.
For example, we normally always write function declarations as prototypes, i.e. specifying the argument types, and we don't depend on the implicit int.  So:
int main(void)

Also, we don't need to declare all variables at the start of their scope any more; instead, we can declare them where they are initialised:
for (int i = 0;  i < 26;  ++i)

Although the problem statement says that you should chart the frequency of different characters, we have implemented something different here, because we're only counting the characters between a and z and between A and Z.
While looking at that, there's a non-portable assumption in this code that 'Z'-'A' and 'z'-'a' are both 25.  That is true on ASCII systems, but definitely not true on EBCDIC systems, for example, where this code will index af outside its bounds.
You could solve this by declaring af differently:
#define AZ_COUNT ('z' - 'a' + 1)
unsigned int af[AZ_COUNT] = {0};

I think I would store counts of all different characters, and filter to just the alphabetic ones later (and use isalpha() for that, from <ctype.h>):
#include <limits.h>
unsigned int af[UCHAR_MAX+1] = {0};

That can make it easier to adapt the printing part (e.g. to show digits and punctuation characters) later.  (Note the use of unsigned int, too - a negative count makes no sense).
I think the printing part would be better if it didn't modify the counts.  We can ensure that if we split the counting and printing into separate functions:
void count_chars(FILE *in, unsigned int *frequencies);
void print_graph(FILE *out, const unsigned int *frequencies);

That const helps us write code that's more reusable.

With my changes, the code looks more like this (not perfect, but I hope it has some items to learn from):
#include <ctype.h>
#include <limits.h>
#include <stdio.h>

/*  print a graph of the frequencies of different characters */

#define GRAPH_HEIGHT 20

static void count_chars(FILE *in, unsigned int *frequencies)
{
    int c;
    while ((c = fgetc(in)) != EOF) {
        ++frequencies[(unsigned char)c];
    }
}

static void print_graph(FILE *out, const unsigned int *frequencies)
{
    /* start at 1 to avoid division by 0 later */
    unsigned int max = 1;
    for (unsigned int i = 0;  i <= UCHAR_MAX;  ++i) {
        if (frequencies[i] > max) {
            max = frequencies[i];
        }
    }

    /* print characters on a graph */
    for (unsigned int i = GRAPH_HEIGHT;  i > 0;  --i) {
        fprintf(out, "%2d |", i);
        for (int c = 0;  c <= UCHAR_MAX;  ++c) {
            if (!isalnum(c)) { continue; }
            char bar = frequencies[c] >= i * max / GRAPH_HEIGHT ? '|' : ' ';
            fprintf(out, " %c ", bar);
        }
        fputs("\n", out);
    }

    /* print the base line */
    fputs("   +", out);
    for (int c = 0;  c <= UCHAR_MAX;  ++c) {
        if (!isalnum(c)) { continue; }
        fputs("---", out);
    }
    fputs("\n", out);
    for (int c = 0;  c <= UCHAR_MAX;  ++c) {
        if (!isalnum(c)) { continue; }
        fprintf(stdout, "%3c", c);
    }
    fputs("\n", out);
}

int main(void)
{
    unsigned int af[UCHAR_MAX+1] = {0};
    count_chars(stdin, af);
    print_graph(stdout, af);
}


Your problem is clearly caused by that decent_number function of yours. Once you have the number of '5' digits and  the number of '3' digits, just dump the number to the console - building an std::string to hold it is totally redundant:

Your program currently takes Time: 1.71979 on my system when running Test 9 (which fails in the HackerRank test environment).
If instead of building that string you simply print the digits it takes: Time: 0.026608.

Alternatively you could simply build the whole strings from the start (instead of using the loop to append one character at a time) - this works even faster: Time: 0.000818.

dn = std::string(j, '5');
if (n-j) {
    dn += std::string(n-j, '3');
}


Check if clicked element has specific tagname

I see two big problems with the code:

You are doing the recursive call inside the loop, so you will do each level four times. That will quickly escalade to a lot of calls. You should do the call after the loop, where you have determined that the node is not one in the array.
You are ignoring the result of the recursive call.

So:

function isClickable(elem) {
  for (i in ignore) {
    if (elem.nodeName.toLowerCase() === ignore[i]) {
      return true;
    }
  }
  if (elem.parentNode.nodeName.toLowerCase() !== 'body') {
    return isClickable(elem.parentNode);
  }
  return false;
};


Whole user management system is very hard to do properly even with structural code. When you get a grasp of entire logic & security nuances OOP itself takes it to the next level, because this logic will be hard to encapsulate in objects of separate concerns - session, cookies, http request and response, domain models, view models, factories, routing... potential abstraction leaks are everywhere. That said, let's take a look at your class...

From OOP perspective

Output:

This class is not concerned about output - you don't know its format (json/html) nor channel/destination (http/console/log file) - you will validate passed values against your data model, but nothing more. For example when registering new user, the response should be the same user data (withut password - not needed anymore) with user id or class specific validation errors attached like (bool) usernameConflict, (bool) emailConflict - that's it. The rest is up to clients of this class (they might not want to reveal users' emails in this indirect way)

Database:

You should separate yourself from database - it's not relevant to your application where data comes from. Use port & adapter technique - interface to query methods (taking only required parameters) and its PDO implementation.

Session:

Session at this point is a global dependency and hidden structural dependency (there needs to be session_start() somewhere). Remove it from this class and return what it needs instead. It should be something that provides user id & not only that. There will be other parties interested in authentication result, so return user data without password hash and other "secrets".

Handling hashes:

This is the only concern of your class: get credentials for concrete user (defined by username, email, cookie token id) and its hash signature (password hash, persistent cookie token, ...), compare result & return data useful to others - beyond this class hashes should be no use to anyone. You won't have methods covering entire login and logout procedure - just a part of it.

and side-effects...

There will be also some side-effect logic in this class like possible password rehashing on algorithm's change (after succesful match), removing cookie tokens (id+hash) on mismatch, hashing token (id+token is generated outside and passed as response cookie)... etc.

Some security concerns:

After succesful login session id should be regenerated (see: session
fixation attack)
After failed login/registration - don't inform that same email is in database (mentioned in "output" section). Registering user with existing email might be handled by sending some (merge/restore) options in activation email.
Session code doesn't protect you from anything - it
all happens inside application environment (only session id goes outside). Holding user's id for authentication (in case user is deactivated/removed) is enough
Make sure that httpOnly and Secure flags are set for session-type cookies (https might be hard to setup for localhost env, but it's neccessary on remote)
All forms should be signed/marked with CSRF tokens - new session id = generate new token is most convenient approach (every form with new token doensn't add much to protection, but causes problems with multiple open tabs, back button...)
More...


Solution

After reviewing many answers, I believe I have two options:

Make two queries, like I am doing now,
Use a pagination plugin for mongoose

My decision was the second one and so I am now using mongoose-paginate.

Hope it helps.


Your code looks nice. The only suggestion I have is to separate the bijection check out of the main, and make it, say, a static method. All in all, I had this in mind:

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class FunctionUtils {

    public static boolean isBijection(final Map<Integer, Integer> function) {
        final Set<Integer> domain = new HashSet<>(function.keySet());
        final Set<Integer> range  = new HashSet<>(function.values());
        return range.equals(domain);
    }

    public static void main(String[] args) {
        final Map<Integer, Integer> function = new HashMap<>();

        try (final Scanner in = new Scanner(System.in)) {
            final int n = in.nextInt();

            for (int i = 1; i <= n; i++) {
                function.put(i, in.nextInt());
            }

            System.out.println("Bijection: " + isBijection(function));
        }
    }
}

Hope that helps.

Edit

Validating general bijections \$f \colon X \to Y\$ is not any harder:

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;

public class FunctionUtils {

    public static <E> boolean isBijection(final Map<E, E> function) {
        return function.size() == new HashSet<>(function.values()).size();
    }

    public static void main(String[] args) {
        final Map<Integer, Integer> function = new HashMap<>();

        try (final Scanner in = new Scanner(System.in)) {
            final int n = in.nextInt();

            for (int i = 1; i <= n; i++) {
                function.put(i, in.nextInt());
            }

            System.out.println("Function:  " + function);
            System.out.println("Bijection: " + isBijection(function));
        }
    }
}


In other words, you're trying to validate that the parsed JSON matches the data structure you're expecting :)

I recommend creating a JSON Schema, updating it as you develop your front-end, and using a Schema Validator library to validate that the object you're creating is consistent with the schema.

This way, the schema will serve both as API documentation and as your test.


Repetitive code for different Database Entities with same implementation

Fix your method name getUser, getAdmin for starters. If you do not use the returned User object for example except for checking if it is null then consider returning boolean. But I suspect there are more fields in User and Admin.
Fix your parameter types.
Why are you passing in User if you get the user from the data store. If it is only for grouping user name and password try defining a value object.
Once you saved your User type from the burden of holding the password remove password field from the User object. The returned type of the authentication method should not contain the password but contain roles of the user etc. Passwords are an authentication concern, whereas Roles etc are an authorization concern.
Unsuccessful authentication attempt is an exceptional case. Returning null from a service in an exceptional case burdens the user of the service with remembering the null check. In this case having a NullPointerException is not the worst that could happen. Not having the exception and letting unauthenticated users access your secure resources is worse.
In the below code:

if(user == null)
     return user;

If you want to return null say so. Do not confuse the reader of your code. (Reader of the code is probably yourself in a few months.)

Why are you returning null. If null is not a valid argument, as in this case, throw an IllegalArgumentException. I will give you an example to demonstrate the importance of this. Since you did not provide the code that uses this service it will be an imaginary usage:

User user = new User();
user.setUsername(request.getParameter("username");
user.setPassword(request.getParameter("pass");

UserDb = null;
user = loginService.isValid(user); // I'm guessing usage is as horrible as this

if (userDb == null) {
   return UNSUCCESSFUL_LOGIN;
}

saveUserToSession(userDb);
return WELCOME_PAGE;

Programmer made a mistake but the user sees "Login Unsuccessfull" message for correct username and password.
Do not get the real password hash out of your datastore and do not pass around the cleartext password.

User db_user = userDao.getUserByUsername(user.getUsername());

Instead your dao method should be something like this:

User db_user = userDao.getUserByUsername(username, passwordHash);

which eventually translates to some sql or ldap or hql or whatever query like this

select blah1, blah2, blah3
 from myschema.myusertable
 where username=:username and hashedpass=:hashedpass

This reduces the chance of your hashed passwords to leak into logs or such, removes the need to pass around passwords in the clear makes it harder for you to let users know if a username is valid without knowing the password. I am not a security person, so I will not comment on its effect on the timing attacks. But need to know is a good Object Oriented design principle.
Do a shortcut return here:

    if (db_user != null) {
    //several lines of code
     }
     return null;

This should return a boolean. If it doesn't and you cannot change it or find one that does you can always wrap it.

     PasswordHash.validatePassword(user.getPassword(),db_user.getPassword())

Do not catch Exception as it is too general and include unchecked exceptions such as nullpointerexception and illegalargumentexception.

 } catch(Exception e){ e.printStackTrace(); }

Exception.printStackTrace(); is not proper exception logging. It has no use case in any production environment.

My suggestion

 public User getUser(UserCredential credential) throws SecurityException {
    if (credential == null) throw new IllegalArgumentException("credential required");

    User user = userDao.getUser(credential);

    if (user == null) throw new InvalidCredentialException();

    return user;
  }

static class UserCredential {
    //fields, all of them final
   // ..........
     UserCredential(String userName, String hashedPass) {
        //You can use org.apache.commons.lang.Validate to shorten
       //some common validations
         Validate.notNull(userName);
         Validate.notNull(hashedPass);
          this.userName = userName;
          this.hashedPass = hashedPass;
     }
    //getters no setters
   // ..........
 }

By validating the constructor arguments you catch some errors more easily and remove the need to check them again when used as a parameter type.

String userName = request.getParameter("username");

// case 1
user.setUsername(userName);
User userDb = loginService.isValid(user);

// case 2
User user = loginService.getUserValid(new UserCredential(userName, hashedPassword));

Note what happens in each case if you misspell the request parameter name. In the second case you will get an illegal argument exception close to the source of the illegal argument whereas in the first case you may tell user his password wrong or you may get some unspecified error in the depths of your ORM or JDBC driver or something.


For loop that iterates through files and iteratively appends lists storing values from the read file

Variable naming

Your variable's names do not convey their purpose and are even misleading.
E.g. fp and fp_2 suggest file pointers, but are actually strings.
Notwithstanding, for a better reference, I will use your variable names below.

You should also implement PEP8 (poseList vs. pose_list etc.).

Recurring declaration

You keep redefining the same constants fp and fp_2 in a loop:

for dir_name in dirs:
    fp = '/home/Set/left'
    fp_2 =  '/home/Set/fc/fc2_0.npy'

Better declare them beforehand:

fp = '/home/Set/left'
fp_2 =  '/home/Set/fc/fc2_0.npy'

for dir_name in dirs:

Avoiding race conditions

By checking for existing files and folders using

if os.path.exists(fp) and os.path.exists(fp_2):

you've created yourself a race condition.
It is better to just try to open the file and handle the respective exception raised if something goes wrong.

Joining paths

Your path concatenation

fp+"/*.txt"

might work for you.
But there is os.path.join to do this safely and get a sanitized path:

os.path.join(fp, "*.txt")  # Leading "/" removed!

Just for the record: In Python 3 (which you are not using assuming from your print statement) you can use pathlib.Path to handle your paths:

fp = Path('/home/Set/left')
…
str(fp.joinpath('*.txt'))

Reading lines

Files are iterable, so you can get a file's lines more easily:

for f in files:
    with open(f) as pose:
        pl = [line.strip() for line in pose]
        …


clear() is buggy

The following code causes a NoSuchElementException:

DynamicQueue queue = new DynamicQueue();
queue.offer("First");
queue.clear();
queue.offer("First");
queue.poll();

You can ealy fix it by adding tail = null; to your clear() method.

Use selfexplaing exception messages

An exception name (in this case NoSuchElementException) already describes the kind of error accurred. The cause should explain why this happened. A better message for exaple could simply be "this queue is empty".

Suggestion: add a return type to poll()

If poll() returns the current head, the user doesn't need to do call peek(). This wouldn't even change your main(String[]), since the user is not forced to use the returned object at all.

Of course, you could also add a generic type to your class instead of using Object inside your Node, but I guess that was not your intension, since you are already familiar with the Java Collections.


Generic method to split provided collection into smaller collections

Your implementation is not bad for a no-LinQ solution. But there's always room for improvement. First I'll provide a LinQ solution that provides a clean way to return a chunked list:

public static List<List<T>> Split<T>(List<T> collection, int size)
{
    var chunks = new List<List<T>>();
    var chunkCount = collection.Count() / size;

    if (collection.Count % size > 0)
        chunkCount++;

    for (var i = 0; i < chunkCount; i++)
        chunks.Add(collection.Skip(i * size).Take(size).ToList());

    return chunks;
}

Basically it comes down to this:

calculate the count of chunks that are needed
loop over the length of chunks
use the Enumerable.Skip and Enumerable.Take methods to get chunks
return the list of chunks

Now, you implemented a no-LinQ solution so I created one myself too. My implementation doesn't have to calculate the amount of chunks or use two loops to create the list of chunks:

public static List<List<T>> SplitNoLinq<T>(List<T> collection, int size)
{
    var chunks = new List<List<T>>();
    var count = 0;
    var temp = new List<T>();

    foreach (var element in collection)
    {
        if (count++ == size)
        {
            chunks.Add(temp);
            temp = new List<T>();
            count = 1;
        }
        temp.Add(element);
    }

    chunks.Add(temp);
    return chunks;
}

The code iterates over the collection and keeps a counter, adding the iterated item to a temporary list. If the counter equals the desired length of a chunk it will add the temporary list to the return list. At the end, the last chunk is added.

The var keyword:

From the C# Programming Guide:

  The var keyword can also be useful when the specific type of the variable is tedious to type on the keyboard, or is obvious, or does not add to the readability of the code.

So lines like:

List<List<T>> splitChunks = new List<List<T>>();

would become:

var splitChunks = new List<List<T>>();

Furthermore you could place the code in an extension method, also using an IEnumerable<T> instead of List<T>:

public static class Extensions
{
    public static List<List<T>> Split<T>(this IEnumerable<T> collection, int size)
    {
        var chunks = new List<List<T>>();
        var count = 0;
        var temp = new List<T>();

        foreach (var element in collection)
        {
            if (count++ == size)
            {
                chunks.Add(temp);
                temp = new List<T>();
                count = 1;
            }
            temp.Add(element);
        }
        chunks.Add(temp);

        return chunks;
    }
}

//USAGE::
var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
var chunked = numbers.Split(5);


Linked list implemented as classes, not imperative code

Since we have no clean implementations:

The thing to notice is that the push_back() and erase() become trivial if you use a sentinal. This is because you do not need to test for NULL in any part of the code.

    Node(Node* after)
    {
        prev          = after;
        next          = after->next;
        prev->next    = this;
        next->prev    = this;
    }
    ~Node()
    {
        prev->next  = next;
        next->prev  = prev;
    }

    iterator push_back(T const& value)
    {
        tail    = new ValueNode(value, tail);

        // If new succeeded then increment count
        ++count;
        return iterator(tail);
    }

    void erase(iterator const& i)
    {
        // Get the value we will set as tail if the delete works
        Node*   newTail = (tail == i.node)
                            ? i.node->prev
                            : tail;
        delete i.node;
        // Delete worked now we can update the state.
        tail    = newTail;
        --count;
    }

Here is the whole code

#ifndef THORS_ANVIL_UTILITY_LINKED_LIST
#define THORS_ANVIL_UTILITY_LINKED_LIST

#include <algorithm>
#include <functional>

template<typename T>
class LinkedList
{
    struct Node
    {
        Node*   prev;
        Node*   next;
        Node(Node* after)
        {
            prev          = after;
            next          = after->next;
            prev->next    = this;
            next->prev    = this;
        }
        ~Node()
        {
            prev->next  = next;
            next->prev  = prev;
        }
        void swap(Node& rhs) throw()  { std::swap(prev, rhs.prev); std::swap(next, rhs.next);}
    };
    struct ValueNode: Node
    {
        ValueNode(T const& value, Node* after)
            : Node(after)
            , data(value)
        {}
        T       data;
    };

    Node    head;
    Node*   tail;
    int     count;

    public:
        struct Iterator: std::iterator<std::input_iterator_tag, T, ptrdiff_t, const T*, const T&>
        {
            Iterator(Node* node): node(node){}

            T&       operator*()        {return  static_cast<ValueNode*>(node)->data;}
            T*       operator->()       {return &static_cast<ValueNode*>(node)->data;}
            T const& operator*()  const {return  static_cast<ValueNode*>(node)->data;}
            T const* operator->() const {return &static_cast<ValueNode*>(node)->data;}

            Iterator& operator++()     /*prefix*/  { node = node->next; return *this;}
            Iterator& operator--()     /*prefix*/  { node = node->prev; return *this;}
            Iterator  operator++(int)  /*postfix*/ { Iterator result(*this);this->operator++(); return result;}
            Iterator  operator--(int)  /*postfix*/ { Iterator result(*this);this->operator--(); return result;}

            bool operator !=(Iterator const& rhs) const    { return node != rhs.node;}
            bool operator ==(Iterator const& rhs) const    { return !(*this != node);}

            mutable Node*   node;
        };

        LinkedList()
            : tail(&head)
            , count(0)
        {}

        ~LinkedList()
        {
            clear();
        }

        void clear()
        {
            while(head.next != &head)
            {
                Node*   old = head.next;
                head.next   = head.next->next;
                --count;
                delete old;
            }
        }

        LinkedList(LinkedList const& copy)
            : tail(&head)
            , count(0)
        {
            std::for_each(copy.head->next, copy.head, std::bind1st(std::mem_fun(&LinkedList::push_back), this));
        }
        LinkedList& operator=(LinkedList rhs)
        {
            rhs.swap(*this);
            return *this;
        }
        void swap(LinkedList& rhs) throw()
        {
            std::swap(head,     rhs.head);
            std::swap(tail,     rhs.tail);
            std::swap(count,    rhs.count);
        }

        bool    isEmpty()   const { return &head == tail; }
        size_t  size()      const { return count; }

        typedef Iterator           iterator;
        typedef Iterator const     const_iterator;

        iterator push_back(T const& value)
        {
            tail    = new ValueNode(value, tail);
            ++count;
            return iterator(tail);
        }

        void erase(iterator const& i)
        {
            Node*   newTail = (tail == i.node)
                                ? i.node->prev
                                : tail;
            tail    = newTail;
            --count;
            delete i.node;
        }

        iterator begin()                {return iterator(head.next);}
        const_iterator begin() const    {return iterator(head.next);}
        iterator end()                  {return iterator(&head);}
        const_iterator end() const      {return iterator(&head);}
};
#endif

Then Main

#include <LinkedList.h>
#include <iostream>

int main()
{
    LinkedList<int> list;
    list.push_back(5);
    LinkedList<int>::iterator item = list.push_back(7);
    for(LinkedList<int>::iterator loop = list.begin(); loop != list.end(); ++loop)
    {
        std::cout << *loop << "\n";
    }
    list.erase(item);
    for(LinkedList<int>::iterator loop = list.begin(); loop != list.end(); ++loop)
    {
        std::cout << *loop << "\n";
    }
}

Diagram of Node Insertion:

Node Before Insertion Starts

      after
      #########                         #########
   -->#  Next #------------------------>#  Next #----
      #       #                         #       #
   ---#Prev   #<------------------------#Prev   #<---
      #########                         #########

                       NewNode(this)
                       #########
                       #   Next#
                       #Prev   #
                       #########

prev          = after;

      after
      #########                         #########
   -->#  Next #------------------------>#  Next #----
      #       #                         #       #
   ---#Prev   #<------------------------#Prev   #<---
      #########   |                     #########
                  |
                  |    (this)
                  |    #########
                  |    #   Next#
                  -----#Prev   #
                       #########

next          = after->next;

      after
      #########                         #########
   -->#  Next #------------------------>#  Next #----
      #       #                  |      #       #
   ---#Prev   #<-----------------|------#Prev   #<---
      #########   |              |       #########
                  |              |
                  |    (this)    |
                  |    ######### |
                  |    #   Next#--
                  -----#Prev   #
                       #########

prev->next    = this;

      after
      #########                         #########
   -->#  Next #------            ------>#  Next #----
      #       #     |            |      #       #
   ---#Prev   #<----|------------|------#Prev   #<---
      #########   | |            |      #########
                  | |            |
                  | |  (this)    |
                  | |  ######### |
                  | -->#   Next#--
                  -----#Prev   #
                       #########

next->prev    = this;

      after
      #########                         #########
   -->#  Next #------            ------>#  Next #----
      #       #     |            |      #       #
   ---#Prev   #<--- |            |   ---#Prev   #<---
      #########   | |            |   |  #########
                  | |            |   |
                  | |  (this)    |   |
                  | |  ######### |   |
                  | -->#   Next#--   |
                  -----#Prev   #<-----
                       #########


Your initialize and DeInitialize do the job of connecting and disconnecting your SQL Connection,  but not the SQL Command that you create in each method.

I am sure that closing and disposing the connection will take care of the Command but I like to make sure.

so what I would do is to use a using statement

initialize();
using (SqlCommand cmd = new SqlCommand() {
    .Connection = conn,
    .CommandText = Spname,
    .CommandType = CommandType.StoredProcedure
})
{
    cmd = GetParam(Params, cmd);
    cmd.ExecuteNonQuery();
}

your try/catch works, but I would rather have my connection opened and closed inside each method and not have to call 2 other methods and a try/catch to make it work. I would much rather just do this

using (SqlConnection conn = new SqlConnection(Const.ConnectionString))
using (SqlCommand cmd = new SqlCommand() {
    .Connection = conn,
    .CommandText = Spname,
    .CommandType = CommandType.StoredProcedure
})
{
    cmd = GetParam(Params, cmd);
    cmd.ExecuteNonQuery();
}

and that gets rid of the try catch and all the ugly close/dispose calls.

It also gets rid of the need for a check connection method because when you use a using statement there is no open connection outside of the using block.

And OCD tells me to change this as well

public  DataTable ExecuteAdapter(string Spname, Dictionary<dynamic, dynamic> Params)
{
    try
    {
        initialize();
        cmd = new SqlCommand();
        cmd.Connection = conn;
        DataTable dt = new DataTable();
        cmd.CommandText = Spname;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd = GetParam(Params, cmd);
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        sda.Fill(dt);
        return dt;
    }

    finally
    {
        DeIntialize();
    }
}

and make it look like this instead

public  DataTable ExecuteAdapter(string Spname, Dictionary<dynamic, dynamic> Params)
{
    using (SqlCommand cmd = New SqlCommand(){
        .Connection = conn,
        .CommandText = Spname,
        .CommandType = CommandType.StoredProcedure
    })
    {
        cmd = GetParam(Params,cmd);
        using (DataTable dt = new DataTable())
        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
        {
            sda.Fill(dt);
            return dt;
        }
    }
}

Naming

initialize();

should be capitalized for standards sake

Initialize();

Method names are PascalCase
variables are camelCase

I know this probably isn't the real SPROC name but Spname should be spName even though  Hungarian name scheme is no longer a recommended name scheme.


csvshuf: a tool to shuffle CSV columns written in Python

There are no docstrings. It's hard to review code when we don't know what it is supposed to do.
The various shuffle functions both modify their items argument and return it. It would be clearer if these functions either modified their argument without returning it (like random.shuffle) or returned a new list without modifying the original (like random.sample). Doing both is redundant and confusing.
The shuffle functions can be simplified using reversed and range:

def shuffle_sattolo(items):
    """Shuffle items in place using Sattolo's algorithm."""
    _randrange = random.randrange
    for i in reversed(range(1, len(items))):
        j = _randrange(i)  # 0 <= j < i
        items[j], items[i] = items[i], items[j]

Note that I've cached random.randrange in a local variable. This is to avoid having to look it up again each time around the loop.
The shuffle_kfy function is redundant because random.shuffle already implements the Fisher–Yates shuffle.
Using a string argument to select a mode of operation is error-prone. If you mistyped the string, for example shuffle(items, 'satolo'), then you would not get an error, it would just silently do the wrong thing.
The shuffle function is redundant. Instead of assigning a search mode while parsing the arguments, assign a shuffle function:

shuffle = random.shuffle

# ...

if '-k' in opts:
    shuffle = shuffle_kfy
elif '-s' in opts:
    shuffle = shuffle_sattolo

Having code at the top level of a module makes it hard to test — for example, you can't test the shuffle function by itself, because you can't import the module without running all the top-level code. It is a good idea to put top-level code into a main function and guard it with if __name__ == '__main__':.
The code processes the command-line options by transforming them into a dictionary and then looking up each valid argument. But this means that there are no error messages for invalid arguments. If you look at the getopt examples in the manual, you'll see that they do:

for o, a in opts:
    if o == '-v':
        # process option
    else:
        # report error

The name i is normally used for index variables, so it's misleading to use it for an input file.
Error messages should go to standard error, not standard output:

sys.stderr.write("Invalid column 0. Columns are 1-based.\n")

This is particularly important here, because this program writes its results to standard output, and so probably the user is redirecting standard output to a file. If you write error messages to standard output, they will go to the file and the user will not see them.
It's a better idea to use the argparse module for parsing command-line arguments. With argparse the code is more explicit, it automatically emits error messages for invalid arguments, it has various types of built-in argument validation and conversion, and it has built-in support for the --help option. Something like this:

def column_list(string):
    """Validate and convert comma-separated list of column numbers."""
    try:
        columns = list(map(int, string.split(',')))
    except ValueError as e:
        raise argparse.ArgumentTypeError(*e.args)
    for column in columns:
        if column < 1:
            raise argparse.ArgumentTypeError(
                "Invalid column {!r}: column numbers start at 1."
                .format(column))
    return columns

def main():
    parser = argparse.ArgumentParser(
        description="Shuffle columns in a CSV file")
    parser.add_argument('infile', type=argparse.FileType('r'), nargs='?',
                        default=sys.stdin, help='Input CSV file')
    parser.add_argument('-s', '--sattolo',
                        action='store_const', const=shuffle_sattolo,
                        dest='shuffle', default=random.shuffle,
                        help="Use Sattolo's shuffle.")
    col_group = parser.add_mutually_exclusive_group()
    col_group.add_argument('-c', '--columns', type=column_list,
                           help="Comma-separated list of columns to include.")
    col_group.add_argument('-C', '--no-columns', type=column_list,
                           help="Comma-separated list of columns to exclude.")
    delim_group = parser.add_mutually_exclusive_group()
    delim_group.add_argument('-d', '--delimiter', type=str, default=',',
                             help="Input column delimiter.")
    delim_group.add_argument('-t', '--tabbed', dest='delimiter',
                             action='store_const', const='\t',
                             help="Delimit input with tabs.")
    parser.add_argument('-q', '--quotechar', type=str, default='"',
                        help="Quote character.")
    parser.add_argument('-o', '--output-delimiter', type=str, default=',',
                        help="Output column delimiter.")
    args = parser.parse_args()

    reader = csv.reader(args.infile, delimiter=args.delimiter,
                        quotechar=args.quotechar)

    # ... and so on ...


JS code that search through every property in a nested object

Too much messing about in hyper space.

You have way too much messing about. Object.assign is slow and more so when you don't need it.

RegExp is fast

If you are going to search strings use a RegExp it is far far quicker. And if not don't convert the same value to lower (or upper) case every time you need to check it. Once is all you need to do.

I can not quite workout where you are getting element.key from.

Set and Map for lookups

Rather than search manually over an array of keys you can use a Set that will provide fast hash table lookup

// at the very start of the search create an empty set
var foundKeys = new Set();

...

// then rather than loop over iwoList check if the set already has the key
if (!foundKeys.has(object.key)) {
    foundKeys.add(object.key);  // if not add the new one
    this.iwoList.push(object);
}
// saving a mass of cycles.

Look for the quick answer

It would be better to check the foundKeys set right at the start before you search the object. No point searching for a match only to dump the result because you have that key. Make it the first thing to check before you search the object, first thing inside the loop would be the best way to avoid many cycles.

Bloat also eats cycles

Its all a little hanging out and bloated at the start.

 let object = Object.assign({}, element);  // object is copied from element
 object['key'] = element.key;  // then you copy key, but key will be in object from the line above
 let keys = Object.keys(object)   // then create a keys array and a iterator index
 for (let i = 0; i < keys.length; i++) {
   let prop = keys[i]  // another variable
   let item = object[prop]  // and another

Why not just the one line, same as the 6 above just much quicker...

for(const item of Object.values(element)){

The rewrite

Without more info, I read your code to find the first instance of the search term and add the object that it was part of from the objectArray to the result.

Checking arrays, and objects, and matching any strings or numbers found, case insensitive.

As a standalone function the following returns an array of objects that contain a property that matches keyword. I would assume that the objects come from a JSON so have ignored any cyclic references problems (which can be checked with a Set if needed)

The string matching is via a regExp

The whole thing is just an extended Array.filter call

function search(array, keyword) {
  const regExp = new RegExp(keyword,"gi");
  const check = obj => {
    if (obj !== null && typeof obj === "object") { return Object.values(obj).some(check) }
    if (Array.isArray(obj)) { return obj.some(check) }
    return (typeof obj === "string" || typeof obj === "number") && regExp.test(obj);
  }
  return array.filter(check);
}


Calculate mean, median, and mode in Rust

Learn to love rustfmt. For example, the Rust standard is 4-space indents.
Learn to love Clippy, which can show you the more idiomatic way to iterate over a collection:

warning: it is more idiomatic to loop over references to containers instead of using explicit iteration methods
  --> src/main.rs:43:18
   |
43 |         for x in times.iter() {
   |                  ^^^^^^^^^^^^ help: to write this more concisely, try: `&times`
   |
   = note: #[warn(explicit_iter_loop)] on by default
   = help: for further information visit https://github.com/Manishearth/rust-clippy/wiki#explicit_iter_loop

There's no reason to declare your variables early in the function. That's the kind of thing you would do in very old C or JavaScript and isn't required in modern languages. Declare them as late as possible.
Extract methods for each of the operations you'd like to perform. This allows you to remove the artificial blocks inside the main function and makes the comments into code identifiers. This removes the need for the variables in the main function at all.
There's no need to use a Vec as you never add or remove items from the list. A plain array will suffice.
As mentioned in the comments, Iterator::sum already exists. If it didn't, you could use something like Iterator::fold.
Your implementation of median is incorrect. When there are an even number of values, the median is defined as the average of the two middle values. I've not changed your code for this because doing so would require changing the type of median and I'm not sure how you'd prefer to do so.
There's no need to cast the value to usize when counting the number of occurrences; storing the i32 in the HashMap makes more sense.
You can dereference the number using &value in the for loop binding.
Once you have built your mapping of occurrences, you can iterate over it, taking the maximum value with Iterator::max_by_key, throw away the count using Iterator::map, then have a single expect call.
Use a better error message than "Fatal" - describe what the problem was.
Don't use nth(0) - that's just .next()

use std::collections::HashMap;

fn average(numbers: &[i32]) -> f32 {
    numbers.iter().sum::<i32>() as f32 / numbers.len() as f32
}

fn median(numbers: &mut [i32]) -> i32 {
    numbers.sort();
    let mid = numbers.len() / 2;
    numbers[mid]
}

fn mode(numbers: &[i32]) -> i32 {
    let mut occurrences = HashMap::new();

    for &value in numbers {
        *occurrences.entry(value).or_insert(0) += 1;
    }

    occurrences
        .into_iter()
        .max_by_key(|&(_, count)| count)
        .map(|(val, _)| val)
        .expect("Cannot compute the mode of zero numbers")
}

fn main() {
    let mut numbers = [42, 1, 36, 34, 76, 378, 43, 1, 43, 54, 2, 3, 43];

    println!("AVERAGE: {}", average(&numbers));
    println!("MEDIAN: {}", median(&mut numbers));
    println!("MODE: {}", mode(&numbers));
}

A clever one-pass solution for mode is also possible:

fn mode(numbers: &[i32]) -> Option<i32> {
    let mut counts = HashMap::new();

    numbers.iter().copied().max_by_key(|&n| {
        let count = counts.entry(n).or_insert(0);
        *count += 1;
        *count
    })
}