Calculating Euclidean norm for each vector in a sparse matrix

I wasn't aware that scipy's sparse matrices did not support broadcasting. What a shame that you can't simply do D = X - p! Your construction of stacked_p can be sped up quite a bit, but you need to access the internals of the CSR matrix directly. If you aren't aware of the details, the wikipedia article has a good description of the format.

In any case, you can construct stacked_p as follows:

rows, cols = X.shape
stacked_p = ss.csr_matrix((np.tile(p.data, rows), np.tile(p.indices, rows),
                           np.arange(0, rows*p.nnz + 1, p.nnz)), shape=X.shape)

With some dummy data:

import numpy as np
import scipy.sparse as sps

p = sps.rand(1, 1000, density=0.01, format='csr')

In [15]: %timeit sps.vstack([p for n in xrange(1000)]).tocsr()
10 loops, best of 3: 173 ms per loop

In [16]: %timeit sps.csr_matrix((np.tile(p.data, 1000), np.tile(p.indices, 1000),
                                 np.arange(0, 1000*p.nnz + 1, p.nnz)), (1000, 1000))
10000 loops, best of 3: 94.1 µs per loop

That is close to 2000x times faster...


Multiple Formats: Reading Working Routine From File

Avoid pointers

In this case, there seems to be no particularly good reason for your map to store pointers to the data instead of just storing the data directly. It'll simplify your code a bit if you just have it store something like a vector<exercise>. Alternatively, you could consider using a std::multimap<std::string, Exercise> (which has a similar effect).

Note that many people are likely to give advice more like: "avoid raw pointers". While that's good advice in itself, I prefer to avoid (explicit use of) pointers entirely if possible. If you find that you can't avoid using a pointer, then use a smart pointer. But if you can avoid using any sort of pointer at all, so much the better.

Distribution of responsibilities

You've defined an Exercise class (or struct), but all the responsibility for reading an Exercise from a file has been assigned to Routines. At least IMO, it would be better if an Exercise knew how to extract itself from a file, and a Routine just made use of that to read the exercises in a routine.

map data type

Right now, your Routines is basically just a map with an overload of operator>> to extract data and populate that map from the file. We don't need to define a new class just for that purpose though. map already uses a template to define the type of data it stores--we can just use that (and give it a name, if we like):

using routine = std::pair<std::string, std::vector<Exercise> >;

Putting those together we get extraction operators for routine and exercise that look something like this:

std::istream &operator>>(std::istream &in, Exercise &e) {
    std::string temp;
    std::getline(in, temp);
    std::istringstream is(temp);
    std::getline(is, e.name, ',');
    is >> e.reps;
    if (is.peek() == ',') {
        is.ignore(1);
        is >> e.weight;
    }
    else
        e.weight = 0;
    return in;
}

std::istream &operator>>(std::istream &is, routine &r) {
    std::getline(is, r.first, ',');
    int count;
    is >> count;
    is.ignore(1024, '\n');
    for (int i=0; i<count; i++) {
        exercise e;
        is >> e;
        r.second.push_back(e);
    }
    return is;
}

So now we've restricted the messiness of reading an exercise correctly to a somewhat smaller area. A Routine just reads a name and a some number of Exercises.

With those in place, initializing a map of routines from a file can look something like this:

std::ifstream in("routines.csv");

std::map<std::string, std::vector<exercise>> routines {
    std::istream_iterator<routine>(in), {} };

Of course, if you really want to define your own complete class for Routine, you can do that--but I'd still keep the responsibility for reading an Exercise in an extractor specifically for an Exercise.


Default initialization of items using Scrapy

You can use Field() default values as suggested.

class MalCrawlerItem(Item):
    mall = Field(default='null')
    store = Field(default='null')
    bonus= Field(default='null')
    per_action = Field(default='null')
    more_than = Field(default='null')
    up_to = Field(default='null')
    deal_url = Field(default='null')
    category = Field(default='null')
    expiration = Field(default='null')
    discount = Field(default='null')
    is_coupon = Field(default='null')
    code = Field(default='null')

You can also use Item copy in the constructor.

#initialize default item
default = MallCrawlerItem()
default['mall'] ='null'
default['store'] = 'null'
default['bonus'] = 'null'
default['per_action'] = 0
default['more_than'] = 0
default['up_to'] = 0
default['deal_url'] = 'null'
default['category'] = 'null'
default['expiration'] = 'null'
default['discount'] = 'null'
default['is_coupon'] =  0
default['code'] = 'null'

#copy to new instance
item = MallCrawlerItem(default)

The benefits of this approach are:

constructor copy is the fastest method outside of class definition
you can create specific default item for your current function. e.g. initializing fixed fields of item before entering a for loop


Finding the longest common substring of multiple strings in Haskell

intersect runs in quadratic time. Sets can use Ord information to speed that up.

-- find the longest common substring of multiple strings
longestCommonSubstring :: [String] -> String
longestCommonSubstring xs = go 0 $ length (head xs) + 1
 where
  -- find a substring of a given length n that is common to all strings
  commonSubstrings n = foldr1 S.intersection (map (S.fromList . ngrams n) xs)
  go l r
    -- if the binary search ended, pick one common substring
    | r - l == 1 = S.findMin $ commonSubstrings l
    | otherwise
    = if S.null $ commonSubstrings m
      then go l m    -- the length is too big, try a smaller one
      else go m r    -- try longer length to find longer substring
   where
    m = (l + r) `div` 2    -- the middle point

For comparison, here's an implementation that skips the binary search part:

-- find the longest common substring of multiple strings
longestCommonSubstring :: [String] -> String
longestCommonSubstring = maximumBy (comparing length)
  . foldr1 S.intersection . map (S.fromList . map inits . tails)


Your code will work, of course, but you go to a lot of trouble to grind the result set into an array when that capability is already available. Mysqli would provide the fetch_all() function if you had the mysqlnd drivers available; fortunately, PDO has provided it since PHP 5.1.

You will need to create a PDO connection with

$dsn = "mysql:host=" . $hostname . ";dbname=" . $dbname . ";";
$dbh = new PDO($dsn, $dbuser, $dbpass);

then your function would be

function gd($query)
{
    global $dbh;
    $result = $dbh->query($query);
    $array = $result->fetchAll(PDO::FETCH_NUM);  // fetchAll() does the same as most of your original code
    return $array;
}


onKeyValidate is an okay name, but a better name could be validateKeypress.
It seems very silly to store a RegExp as a string, and then construct it every time. Why not just declare var alpha = /[ A-Za-z]/?
keyChars appears to check against \x00, the null character, and \x08, the backspace character. Neither of these can ever be passed to onKeypress, so you can just take it out.
The standard way to get the character code is event.which || event.keyCode.
event is a global; I don't think you need to pass it in.

Here's a proposed rewrite:

var alpha = /[ A-Za-z]/;
var numeric = /[0-9]/;
var alphanumeric = /[ A-Za-z0-9]/;

function validateKeypress(validChars) {
    var keyChar = String.fromCharCode(event.which || event.keyCode);
    return validChars.test(keyChar) ? keyChar : false;
}

The HTML will have to change to onkeypress="validateKeypress(alpha);".


Making VBA generated dynamic SQL statements safe against injection

Error Handling / Execution Flow: Beware of Raptors
I realize you haven't implemented it yet, but you've set yourself up for some twisted execution flow:
    Exit Function 'fixed indentation
ErrorHandler:
    EvaluateQuery = ""
End Function

When you do implement error handling, you'll likely be cleaning up resources (closing recordsets, connections, etc.) - you'll want to do that in case of error, and in normal execution paths too.
I'd remove Exit Function and rework the ErrorHandler: part:
ErrorHandler:
    'todo: cleanup
    If Err.Number <> 0 Then
        'todo: handle errors
    End If
End Function

This way you'll avoid introducing another label (Cleanup:?) and a GoTo Cleanup, and raptors won't get you.

SQL Injection
I know only 1 way of preventing SQL injection: let the server handle the parameters. I don't know what 3rd party you're using nor what a NetRs is (why not use ADODB?), but the code in EvaluateQuery seems to be concatenating the parameters into the query.
This means a String parameter would have to be surrounded by single quotes, and that a string that says "Robert'); DROP TABLE Students;--" would be concatenated - and executed as such. Thus you are correct, this code is screaming SQL injection vulnerability.
Don't even try "sanitizing" the strings before concatenating them into your query. It's the server's job to deal with the parameters. With ADODB you'd be sending the server a query like:
"SELECT SomeField FROM SomeTable WHERE SomeOtherField = ?"

Where ? is replaced by the server, by its parameter value - no need to worry about single quotes around string parameters, the parameter itself has all the information needed for the server to know how to handle.
On top of being more secure, such queries are more performant: if you execute them in a loop, the server receives the same query everytime, only with different parameters - it reuses the same query plan every time and only calculates it once. If you send the parameter values embedded in the query, the server receives a different query every time, and has to recalculate a query plan each time.
See MSDN for more info on parameterized ADODB queries.


Creating SwiftReachability Class in Swift 2.2

Improvements of your code

Let's start with your isConnectedToNetwork() method.

var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))

As of Swift 1.2(?), all imported C structs have a default initializer which sets all
members to zero:

var zeroAddress = sockaddr_in()

let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
    SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
 }

Here defaultRouteReachability is an optional which is later force-unwrapped.
Better check with guard and optional binding if the call succeeded:

guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
    SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else {
    NSLog("Could not create reachability reference")
    return false
}

var flags = SCNetworkReachabilityFlags(rawValue: 0)

This can be shorted to

var flags = SCNetworkReachabilityFlags()
// or
var flags : SCNetworkReachabilityFlags = []

let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

SCNetworkReachabilityFlags is an OptionSetType and that has a set-like interface,
there is no need for rawValue and UInt32 conversion:

let isReachable = flags.contains(.Reachable)
let needsConnection = flags.contains(.ConnectionRequired)

Finally, there is no reason to make this an instance method because it does not use
any state, you could make it a type method instead. Then it would look like this:

class func isConnectedToNetwork() -> Bool{

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
        SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
    }) else {
        NSLog("Could not create reachability reference")
        return false
    }

    var flags : SCNetworkReachabilityFlags = []
    SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags)

    let isReachable = flags.contains(.Reachable)
    let needsConnection = flags.contains(.ConnectionRequired)
    return isReachable && !needsConnection
}

Your notification mechanism is far too complicated in my opinion. Instead of
scheduling an NSOperation which reschedules itself with dispatch_after, you could
simply create a repeating NSTimer. Also you should check if the
startNotifier/stopNotifier calls are properly balanced.

Even better, you can register a notification callback which is automatically called
when the reachability status changes. I'll come back to that later.

The SwiftReachability class should not do any UI-related stuff like displaying
alerts. Use NSNotification or callback methods to make the class reusable.

A different design

Let's have a look at the "Supporting IPv6 DNS64/NAT64 Networks"
document from Apple:

  Connect Without Preflight

  The Reachability APIs (see SCNetworkReachability Reference) are intended for diagnostic
  purposes after identifying a connectivity issue. Many apps incorrectly use these APIs
  to proactively check for an Internet connection by calling the SCNetworkReachabilityCreateWithAddress
  method and passing it an IPv4 address of 0.0.0.0, which indicates that there is a
  router on the network. However, the presence of a router doesn’t guarantee that an
  Internet connection exists. In general, avoid preflighting network reachability.
  Just try to make a connection and gracefully handle failures. If you must check for
  network availability, avoid calling the SCNetworkReachabilityCreateWithAddress method.
  Call the SCNetworkReachabilityCreateWithName method and pass it a hostname instead.

Your method can only test for general Internet connectivity (reachability of 0.0.0.0),
but not for reachability of a given host (as recommended by Apple).

To add this feature, it makes sense to make the SCNetworkReachability reference
a (private) instance variable, and provide multiple init methods:

class SwiftReachability {

    private let reachability: SCNetworkReachability

    init?() {
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)

        guard let reachability = withUnsafePointer(&zeroAddress, {
            SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
        }) else {
            return nil
        }
        self.reachability = reachability
    }

    init?(hostname : String) {
        guard let reachability = SCNetworkReachabilityCreateWithName(nil, hostname) else {
            return nil
        }
        self.reachability = reachability
    }
}

More init methods (e.g. for SCNetworkReachabilityCreateWithAddressPair) can be added
if necessary. The initializers are failable.

Checking the connection status consists of two parts:

retrieve the SCNetworkReachabilityFlags,
evaluate the SCNetworkReachabilityFlags.

For reasons that become more apparent later, I suggest to implement these as separate
methods. Retrieving the flags is done as above, only as an instance method:

class SwiftReachability {
    // ...

    func flags() -> SCNetworkReachabilityFlags {
        var flags: SCNetworkReachabilityFlags = []
        SCNetworkReachabilityGetFlags(reachability, &flags)
        return flags
    }
}

Computing the (boolean) connection status from the flags can be done as an extension
method of SCNetworkReachabilityFlags:

extension SCNetworkReachabilityFlags {
    func connected() -> Bool {
        let isReachable = self.contains(.Reachable)
        let needsConnection = self.contains(.ConnectionRequired)
        return isReachable && !needsConnection
    }
}

The reachability status can now be determined like this:

if let reachability = SwiftReachability(hostname: "google.com") {
    let connected = reachability.flags().connected()
    print(connected)
} else {
    print("Could not determine reachability status")
}

Change notifications

Instead of polling the connection status in regular intervals, you can register
a callback function which is called automatically if the status changes.

class SwiftReachability {
    // ...

    private var notifierActive = false
    var callback : ((SwiftReachability, SCNetworkReachabilityFlags) -> Void)?

    func startNotifier() {
        if notifierActive { return }

        var context = SCNetworkReachabilityContext(version: 0, info: nil,
                                                   retain: nil, release: nil, copyDescription: nil)
        context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque())

        SCNetworkReachabilitySetCallback(reachability, { (_, flags, info) in
            let mySelf = Unmanaged<SwiftReachability>.fromOpaque(COpaquePointer(info)).takeUnretainedValue()
            mySelf.callback?(mySelf, flags)
        }, &context)

        SCNetworkReachabilitySetDispatchQueue(reachability, dispatch_get_main_queue())
        notifierActive = true
    }

    func stopNotifier() {
        if !notifierActive { return }

        SCNetworkReachabilitySetCallback(reachability, nil, nil)
        SCNetworkReachabilitySetDispatchQueue(reachability, nil)
        notifierActive = false
    }

    deinit {
        stopNotifier()
    }
}

This is a bit tricky because the callback  is a pure C function. In Swift, this must
be a global function or a closure which does not capture any context. It is therefore
not possible to use self in the callback closure. Instead, the self instance
pointer must be to a Void pointer, passed to the callback, and converted back to
an instance pointer (mySelf), compare
How to cast self to UnsafeMutablePointer type in swift.

Here is a simple example how this could be used in view controller for regular
updates of the connection status:

class ViewController: UIViewController {

    var reachability : SwiftReachability?

    override func viewDidLoad() {
        super.viewDidLoad()

        reachability = SwiftReachability()
        if let reach = reachability {
            reach.callback = { (_, flags) in
                let connected = flags.connected()
                print("Connected:", connected)
                // Update display, show alert, whatever ....
            }
            reach.startNotifier()
        } else {
            print("Could not determine connection status")
            // Update display, show alert, whatever ....
        }
    }
}

Note that the view controller must hold a reference to the reachability object.
The connection flags are passed to the callback, so now we can use the
connected() extension method which we defined above.

Of course, one could also use the NSNotificationCenter to inform clients of
changes in the connection status instead of a callback method.

Remark: There is an excellent implementation of Reachability in Swift: https://github.com/ashleymills/Reachability.swift.
Similarities between that code and the code suggested here are not intentional but could not be avoided.


Set an attribute to change an objects behavior, at specific times and for a specific period

Rather than making your times a dictionary indexed by an int just make it a list of tuples (start, end) and iterate through the list of trading times.
Input the list in order or sort it before starting so you can be assured that time[n].start < time[n].end and time[n].end < time[n+1].start.

For something as simple as your example it is clear enough what the code is doing.  It doesn't scale as you add more complexity to the decision to trade or not.  Consider different exchanges, different products, order types, etc.  Your single check_times function is going to get very complex.

To prepare for such coming complexity I would have a Trader class for each combination of things that could influence trading time, each with its own check_times function.  A Controller class would be responsible for choosing the appropriate Trader to handle things based on the attributes at hand.  Currently the only attribute you are looking at is the current time and so there would only be two Traders, and ActiveTrader and a DeactivatedTrader.

Again, depending upon the complexity of what is being implemented, these Trader's could be classes that descend from a common Trader class or could be duck-typed to have the same API.  Let Don't-Repeat-Yourself be your guide here.  If you are writing more Python code to set up the inheritance than you have saved by inheriting from a common ancestor you are doing it wrong.


Update the value of a user based on the click of a checkbox

So chalk this one up to me not giving it enough thought (although I've had this in the back of my mind for about two weeks and today just decided to use my Saturday to actually sit down and refactor the entire application):
The answer is that I put the state of the checkbox in a variable and I don't need to check for it at all, I can just pass it through into my postingValues object. The code now looks like this:

const chkBox = document.querySelectorAll("input[type=checkbox]");

for (box of chkBox) {
    box.addEventListener("change", updateUser, false);
}

function updateUser() {

// Getting the state of the checkbox and the DOM element to display the message
    const messageBox = document.getElementById("message");
    const validated = this.checked;

// Getting the values to post to the server and the initialization requirements
    const postingValues = JSON.stringify({id:this.value, validated:validated});
    const fetchInit = {method: "POST", headers: {"Content-type": "application/json"}, body: postingValues};

// Making the fetch call and returning the message to the user
    fetch("index.php?action=updateLogin", fetchInit).then(function(response) {
        response.text().then(function(value) {
            messageBox.innerHTML = value;
        });
    });
}


Actually I have resolved my own problem. My problem was that the query was taking too long to display data and this problem came from my join to a view! After I found the tables that were creating the view I extracted the one were I found my needed columns and used it in my join.
Probably the problem in joining views is with indexes. I need to read more about indexing a view but I suspect that this was my problem.


This isn't much more elegant, but maybe you like it:

$text = "Some text

> Foo
> Bar
>> Baz
> Foo
";

function clean($text) {
  $result = "";
  $lines = explode("\n", $text);
  foreach($lines as $key => $line) {
    $lines[$key] = preg_replace('/(>)+ /', '', $line);
  }
  return join("\n", $lines);
}

function quotes($text, $level = 1) {
  $search = str_repeat(">", $level);
  $fstpos = strpos($text, $search);
  $sndpos = strrpos($text, $search);
  $sndpos = strpos($text, "\n", $sndpos);
  $middle = substr($text, $fstpos, $sndpos + 1);
  if($fstpos === false or $sndpos === false)
    return clean($middle, $search);
  $fst = clean(substr($text, 0, $fstpos), $search);
  $snd = clean(substr($text, $sndpos), $search);
  return $fst . "<blockquote>\n" . quotes($middle, $level + 1)  . "</blockqoute>" . $snd;
}

echo quotes($text);


More efficient way of doing this hide()/show() jQuery

Try this:

http://jsfiddle.net/VYSXn/

Change your HTML to (note the data attributes):

  <button id="btn-post" class="btn btn btn-primary active" type="button">Post</button>
  <button id="btn-game" data-target="game_container" class="btn btn btn-primary" type="button">Game</button>
  <button id="btn-video" data-target="video_container" class="btn btn btn-primary" type="button">Video</button>
  <button id="btn-giveaway" data-target="giveaway_container" class="btn btn btn-primary" type="button">Giveaway</button>

game stuff

video stuff

giveaway stuff

and now your javascript can just be:

$(document).ready(function() {

    $('.container').hide();
    $('.btn-group button').click(function(){
        var target = "#" + $(this).data("target");
        $(".container").not(target).hide();
        $(target).show();
    });

});


Memoizing a tree's parent pointers in Python

Nodes are usually used internally within the tree and are created inside the insert function of your tree. This is to hide the implementation for users as well as prevent any corruptions that could occur due to external mutability. This isn't Python specific, but more about data structures in general. Data is encapsulated in the structure and use specific operations (functions) for retrieval/mutations.
I'm not sure what your use case is here, but I'd deter you from allowing Nodes to be used outside of the Tree class (if possible).
To traverse the tree bottom up, here are two methods you can try:

Reverse level order traversal

implement the binary tree with a list internally. Then if you wanted to traverse from the bottom up, the last item in the list would certainly be the node at the bottom of the tree and you can get its parent via a list index (you can work this out by reading the previous link).


Applying TrimSideSpaces() method to multiple string properties

single letter variables shouldn't be used except for loop variables
shortening variables names removes readability of the code
if you don't need List<T> specific methods consider to change List<ITemplatePart> _options to IList<ITemplatePart>. You should if possible code against interfaces instead of implementations.
instead of calling the TrimSideSpaces() method, which in reality does only return an empty string, you should just use the built in Trim() method of the String class which removes any leading and trailing space

Refactoring

By using the overloaded CreateTemplatePart() method

public static TemplatePart CreateTemplatePart(string partName, string basePart)
{
    return new TemplatePart
    {
        PartName = partName.Trim(),
        BasePart = basePart.Trim()
    };
}

public static TemplatePart CreateTemplatePart(DataTable table, DataRow row, int rowIndex)
{
    TemplatePart templatePart = CreateTemplatePart(row.Field<string>(Strings.TemplateSpreadSheet_Column_PartName),
              row.Field<string>(Strings.TemplateSpreadSheet_Column_BasePart));
    templatePart.Key = rowIndex;
    templatePart.Category = ExtractVendor(table.TableName).Trim();
    return templatePart;
}

Update based on the comments

  In regards to your 4th point, TrimSideSPaces() returns the content of the property without it's leading and trailing spaces. "which in reality does only return an empty string" how?

Using the method in your code the first test fails while the second one passes.

[TestMethod()]
public void TrimSideSpacesTest_WillFail()
{
    SnippetsCodeReview target = new SnippetsCodeReview();
    string value = "     g     ";
    string expected = "g";
    string actual = target.TrimSideSpaces(value);
    Assert.AreEqual(expected, actual);
}
[TestMethod()]
public void TrimSideSpacesTest_WillPass()
{
    SnippetsCodeReview target = new SnippetsCodeReview();
    string value = "     g     ";
    string expected = String.Empty;
    string actual = target.TrimSideSpaces(value);
    Assert.AreEqual(expected, actual);
}

  The suggested overloaded CreateTemplatePart() improves the code. how?

Improvement could be the less repetitions because we use the overloaded CreateTemplatePart() method in which we call the Trim().
Also, this "improvement" comes obviously with a lack of readability. This is partly because the Strings constants have some really long names.

An improved refactoring after renaming the overloaded methods to Create.

public static TemplatePart Create(DataTable table, DataRow row, int rowIndex)
{
    TemplatePart templatePart = Create(row);

    templatePart.Key = rowIndex;
    templatePart.Category = ExtractVendor(table.TableName).Trim();

    return templatePart;
}

private static TemplatePart Create(DataRow row)
{
    String partName = row.Field<string>(Strings.TemplateSpreadSheet_Column_PartName);
    String basePart = row.Field<string>(Strings.TemplateSpreadSheet_Column_BasePart);

    return Create(partName, basePart);
}

public static TemplatePart Create(string partName, string basePart)
{
    return new TemplatePart
    {
        PartName = partName.Trim(),
        BasePart = basePart.Trim()
    };
}


The extend method is being applied to jQuery.expr which is the set of selectors jQuery will apply when selecting elements (see here) -- jQuery.expr[":"] are the pseudo selectors jQuery acknowledges. The extend is useful if you want to add multiple jQuery selectors succinctly but for adding pseudo selectors I think its just a norm noting you can also add the selector as below

//extends :contains to be case insensitive
$.expr[':'].containsi = function(elem, i, match, array){
    return (elem.textContent || elem.innerText || '').toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
};

One more note: you probably want to add your custom selectors near the top of your code (and definitely outside of your keyup event handler!) in case you want to use your selector somewhere else in your code.

Now some nitpicks

Your Javascript near the end becomes difficult to read because the formatting of your keyup handler. Try pasting your code through an automatic formatter and notice how much easier it will be to follow (eg http://prettydiff.com)

if(itemCount == '0'){ //dont compare to '0' mate we know its an integer as its the length of a collection
  $('.empty-item').show();
}
else {
  $('.empty-item').hide();
}

I would write that as simply: $('.empty-item').toggle(itemCount === 0);

You can also write the following code in this similar one liner:

$("#list li:containsi('" + searchSplit + "')").each(function(e) {
    $(this).removeClass('hidden');
});

//more elegant:
$("#list li:containsi('" + searchSplit + "')").removeClass('hidden');


You shouldn't use chr or str as names because they shadow the builtin chr and str methods. If you then wanted to use str() you'd be out of luck because str is now a string instead of a function. Given that your function deals with both strings and character ordinals it is not unlikely that these could be used. string is a potential improvement, it can occasionally cause trouble if you're trying to use the string module of the same name.

You should also add comments and a docstring. Docstrings are basically comments that are programmatically accessible so that other users can understand how to use your function.

def chrtodec(str):
    """Converts a string to a float using character ordinal positions."""

I think you have another big problem though, which is invalid input handling. Take a look at these:

>>> chrtodec("hello")
619663
>>> chrtodec("12.21")
11821
>>> chrtodec("523.32f")
5228374

Clearly there are problems here when you have characters other than numbers, so I think what you should do is raise a ValueError when an invalid string is passed. You already have the tools to do this figured out of course if you just check that a character's ordinal fits in the right range.

if not (ord('0') <= ord(chr) <= ord('9')):
    raise ValueError("Invalid character {} in string {},"
                     "only digits are parseable.".format(chr, str))

You could also just use chr.isdigit() as @Barry pointed out.

Also you could add support for negative numbers by checking at the start if the first character is ord('-').

negative = ord(str[0]) == ord('-')

This evaluates the expression str[0] == ord('-') and sets negative as the boolean result. Note that to make this compatible with the error handling I suggested, you should then remove the first character from str. And probably update the error message and docstring too.

if negative:
    str = str[1:]

Then just return with a ternary that checks negative.

return dec if not negative else -dec


How to better process csv file with pandas and further dealing with set

main guard

It is common to put the code you want to run behind an if __name__ == "__main__":, so you can later import the functions that might be reused in a different module

naming

You use both snake_case and CamelCase. Try to stick to 1 naming convention. PEP-8 advised snake_case for variables and functions, CamelCase for classes

functions

split the code in logical parts

pandas settings

def settings_pandas():
    pd.set_option("display.height", None)
    pd.set_option("display.max_rows", None)
    pd.set_option("display.max_columns", None)
    pd.set_option("display.width", None)
    pd.set_option("expand_frame_repr", True)

filename input

The way you ask the filename is very fragile. A more robust way would be to ask the filename in a different function, and then validate it

from pathlib import Path
def ask_filename(validate=True):
    """
    Asks the user for a filename.
    If `validate` is True, it checks whether the file exists and it is a file
    """
    while True:
        file = Path(input("Please input the CSV File Name: (CTRL+C to abort)"))
        if validate:
            if not file.exists() and file.is_file():
                print("Filename is invalid")
                continue
        return file

IO

def read_host_data(filename):
    """reads `filename`, filters the unix platforms, and returns the `Target system address`"""
    df = pd.read_csv(filename, usecols=["Platform ID", 'Target system address']).dropna()
    unix_platforms = df['Platform ID'].str.startswith("CDS-Unix")
    return df.loc[unix_platforms, "Target system address"]

There is no need to save the intermediary data to a file. You could use a io.StringIO. An alternative if you need a temporary file is tempfile.

But in this case, where you just need the set of the values of a pd.Series, you can do just set(host_data), without the intermediary file.

putting it together:

if __name__ == "__main__":
    settings_pandas()  # needed?
    filename = ask_filename()
    host_data = set(read_host_data(filename))
    with open("hostfile2") as hostfile2:
        host_data2 = set(hostfile2)
    for item in sorted(host_data2 - host_data):
        print(item.strip())

since the i is not used, I dropped the enumerate. Since host_data2 is directly read from a file, there are no conversions, and it are all strs, so the conversion to str is dropped too.

Since I don't see any printing of pandas data, This part can be dropped apparently.


Since checklist is a list, a "not in" operation has to iterate over all elements to give the correct answer. In other words, it has a complexity of \$O(n)\$. Use a set() instead, to lower the complexity of the operation to \$O(1)\$, making it much faster.

Also don't forget to close open file handles.


Appropriate separation of concerns for this case?

You should move fileFormat to parameters, this method is doing too much
Use IProgress<T> instead of handler to properly report progress back to the UI thread (see Enabling Progress and Cancellation in Async APIs for examples).
Add CancellationToken parameter if necessary


You code is very crushed together; you hardly have any spaces in a single line.

Your code would be a lot more legible if you added spaces.

For example, you could turn this line:

result[a][b]=(result[a-1][b]+result[a-1][b-1]*points[a-1])%MODULO;

Into:

result[a][b] = (result[a-1][b] + result[a-1][b-1] * points[a-1]) % MODULO;

This is highly debatable topic, but I have been taught by people that it is always better to use the pre-increment operator over the post-increment operator.

By that I mean this:

++i

Over this:

i++

This is a little nit-picky.

In the signature of main, since you aren't looking for any command like arguments, you should put void in the arguments space.


You don't have to put content as a prop, you can do this:

{this.props.children}

and then you can use your component as:

 <MySection bgColor="bg-gray">
    <MediaObject heading="today's rates!" />
    <MediaObject heading="some other heading" />
    <MediaObject heading="other other heading" />
 </MySection>

<MySection bgColor="bg-gray">
  <MediaObject heading="today's rates!" />
</MySection>

So whatever is written inside the "body" of the component, is passed on as this.props.children.

Regarding VSCode yelling at you about the apostrophe is that you were closing the apostrophe before the string end:

heading={'today's rates!'}

If you use a single quote inside a string, use double quotes:

heading={"today's rates!"}

or, you can escape the quote:

heading={'today\'s rates!'}


JavaScript Spiral Matrix Coding Challenge

Travel directions
You can imagine this problem being extended to a 3D array. That would mean you have 6 directions, which using your approach would mean half as much code again, and 4D array would have 8 directions. That would double the amount of code. This becomes impractical as you get to higher dimensions.
If you break the problem into a simpler model. Move in a direction for distance collecting items as you go then turn, every second turn decrease the distance, until zero.
A direction can be represented as a vector {x,y} that is right {1,0}, down {0,1} and so on. You store them in an array of vectors in the order you need to use.
I have solved assuming that the array given is a rhombus . You have not indicated if this is true or not. However it only requires a small modification to handle non rhombus arrays.
The result is something like
function spiral(arr) {
    var count, curDir, dist, size, x = 0, y = 0, dir = 0;
    const res = [], directions = [{x: 1, y: 0}, {x: 0, y: 1}, {x: -1, y: 0}, {x: 0, y: -1}];
    curDir = directions[0];
    dist = size = arr.length;
    count = size ** 2;
    while (count--) {
        res.push(arr[y][x]);
        if (!--dist) {
            curDir = directions[++dir % 4];
            if (dir % 2) { size -- }
            dist = size;
        }
        x += curDir.x;
        y += curDir.y;
    }
    return res;
}

To test the function create some readable test arrays. The snippet has arrays that when processed will have values in order, so that it is easy to see if the result is correct.

[[
      [1, 2, 3, 4, 5, 6],
      [20, 21, 22, 23, 24, 7],
      [19, 32, 33, 34, 25, 8],
      [18, 31, 36, 35, 26, 9],
      [17, 30, 29, 28, 27, 10],
      [16, 15, 14, 13, 12, 101]
  ], [
      [1, 2, 3, 4, 5],
      [16, 17, 18, 19, 6],
      [15, 24, 25, 20, 7],
      [14, 23, 22, 21, 8],
      [13, 12, 11, 10, 9],
  ], [
      [1, 2, 3, 4],
      [12, 13, 14, 5],
      [11, 16, 15, 6],
      [10, 9, 8, 7],
  ], [
      [1, 2, 3],
      [8, 9, 4],
      [7, 6, 5],
  ], [
      [1, 2],
      [4, 3],
  ], [[1]]
].reverse().forEach(arr => console.log(spiral(arr).join(",")));

function spiral(arr) {
    var count, curDir, dist, size, x = 0, y = 0, dir = 0;
    const res = [], directions = [{x: 1, y: 0}, {x: 0, y: 1}, {x: -1, y: 0}, {x: 0, y: -1}];
    curDir = directions[0];
    dist = size = arr.length;
    count = size ** 2;
    while (count--) {
        res.push(arr[y][x]);
        if (!--dist) {
            curDir = directions[++dir % 4];
            if (dir % 2) { size -- }
            dist = size;
        }
        x += curDir.x;
        y += curDir.y;
    }
    return res;
}


Method 1 sometimes gives wrong solution because it has a bug:

def solution(X, Y, D):
    if (X == Y):
        jumps = 0
    elif Y-X % D == 0:
        jumps = (Y-X)/D
    else:
        jumps = ((Y-X)/D) + 1
    return jumps

In the elif there, Y-X should have been within brackets, because % has higher precedence than - operator. In other words, Y - X % D is not the same as (Y - X) % D.

Other than that, they are practically equivalent. I would clean up the formatting and remove some obvious temporary variables, like this:

def solution(X, Y, D):
    jumps = (Y - X) / D
    if (Y - X) % D > 0:
        return jumps + 1
    return jumps

In particular, in the if instead of incrementing with jumps += 1, I return the value immediately, because I prefer to avoid mutating variables in general.


The images are often off center and unaligned

That is because those images are probably not 100% accurate compared to the user_input.

You could make use of something like opencv to find the individual pieces.
Afterwards you can crop and save those pieces. This will be a big improvement as you could give it a different image, and it would create individual pieces from it... no more measurement from the user!


More correct way to avoid using a list for dropdown

Lists are optional, but most people feel that you should use some sort of block level element to contain inline elements (some of the reasoning you'll hear is that the content still makes sense even if there's no styling or that you have a "list of options").  If you don't want to use a list, you'd be looking at elements like paragraph (which is wrong here since you're looking at text fragments) or the semantically void div to fill this role.

How does one look at inactive items from yesterday?  To me, this looks like a misuse of form elements.  The submit element isn't for changing state in a form, it is for submitting the contents of the form.

If you're only allowed to look at inactive or active items and never both, then a select element is what you should be using.  If the data is allowed to be filtered by any combination (some/all/none), then you should be looking at checkboxes grouped together by a fieldset:

<form>
    <fieldset>
        <legend>Status</legend>

<input type="checkbox" checked /> Active

<input type="checkbox" /> Inactive

    </fieldset>

    <fieldset>
        <legend>Date</legend>

<input type="checkbox" checked /> Today

<input type="checkbox" /> Yesterday

    </fieldset>
</form>

http://jsfiddle.net/kx4w7/1/


Product of all ints in array besides that an index i

First, some comments on the existing code:

/*
 * You have an ordered array X of n integers. Find the array M containing
 * elements where Mi is the product of all integers in X except for Xi.
 * You may not use division. You can use extra memory
 */

You don't have anything called X in the code, or generate M, so this comment could be better

static const int N = 3;
std::stack<int> stk;
std::queue<int> que;

Why use globals? Also, try to name variables by what they do or represent, rather than their type.

int main(int argc, char *argv[]) {

For that matter, why put the logic in main where you can't test it?
I would hope to see something structured like:

std::vector<int> products(std::vector<int> const &X)
{
    auto n = X.size();
    std::vector<int> M(n, 1);

    // ... algorithm ...

    return M;
}

int main()
{
    static const int N = 3;
    std::vector<int> seq(gen_seq(1), gen_seq(N + 1))
    std::vector<int> result = products(seq);
    // print the result
    // or assert correctness
}

Or possibly several test functions, each called from main.

As for the algorithm itself, its working isn't really clear, and that's where comments would be useful. I'm sure you have a deep intuitive understanding of why your nameless stack and queue generate the right results, but without a lot of effort I don't. In six months' time, you may not either.

Your loop can be cleaner anyway; instead of:

  for (int x = 0, y = N - 1; x < N && y >= 0; ++x, --y) {
    if (x == 0 && y == N - 1) {
      stk.push(1);
      que.push(1);
    } else {
      stk.push(stk.top() * seq[x - 1]);
      que.push(que.back() * seq[y + 1]);
    }
  }

we can:

move the special case if (x == 0 ... outside
then, you only have to iterate over the values used in the second branch (so 1 <= x < N, N-2 >= y >= 0)
but we only use x-1 and y+1 in the body of the loop, so simplify this to 0 <= x < N-1 and N-1 >= y >= 0 and just use x and y in the body
notice that the two conditions (x < N-1 && y >= 0) will always agree, so we don't have to test both

to get:

  stk.push(1);
  que.push(1);
  for (int x = 0, y = N-1; x < N-1; ++x, --y)
  {
    stk.push(stk.top() * seq[x]);
    que.push(que.back() * seq[y]);
  }

and a simpler implementation:

std::vector<int> products(std::vector<int> const &X)
{
    auto n = X.size();
    std::vector<int> M(n, 1); // initialise all values to 1

    for (int i = 0; i < n; ++i)
    {
        // set Mj <= Mj * Xi for all j != i
        for (int j = 0; j < n; ++j)
            if (j != i) M[j] *= X[i];
    }
    return M;
}

This one uses no extra memory but is O(n^2)


Questions regarding the use of Requests Futures for accessing REST URLs

Nice code, clearly written.

I understand the rate limiting requirement.
Having the drain() call within the loop doesn't seem like the caller's responsibility, better to let the BG callback handle it, or defer until finish() as written, which does make sense. Each url fetch could take more or less than the delay time. So this seems to be a bug / wart still lurking within the code.


I would hesitate to implement Mod<T> * Mod<T>, and instead implement Mod<T> * T (and vice-versa). This is because you make no attempt to preserve the rhs' modulo, so you probably shouldn't have one there.

Consider the code

let mut x: i32 = *self;
while x.signum() != n.signum() {
    x += n;
}
x % n

That while loop makes this operation \$\mathcal{O}(n)\$, whereas a simpler implementation

((x % n) + n) % n

is \$\mathcal{O}(1)\$.

Performance elsewhere is probably uninteresting, since it devolves to basic integer operations.

Extending to other T should probably be done by being generic over the Mod and Add traits, as well as whatever particular operation is needed to implement. Something like

impl<T> Sub<T> for Mod<T>
    where T: Add<T> + Mod<T> + Sub<T>
{
    type Output = Mod<T>;
    fn sub(self, other: T) -> Mod<T> {
        Mod::new(self.modulo, self.i - i)
    }
}

The Add and Mod are needed by Mod::new, the Sub is needed inside the sub call.


Here are some thoughts to ponder:

If you are to access a car short cut, then you would need to know:
(i) that you want to get a car short cut, and (ii) you would have to call the relevant property, and (iii) presumably you’d have to enumerate till you found the shortcut of your choice.
There seems to be some duplication: values are being stored in at least two dictionaries: (i) either the car or truck short-cut dictionary and (ii) the Allshortcuts dictionary – is there are reason for this duplication? If you don’t know where the short cut is, then there are only two possible choices: it’s either in the truck dictionary or the car dictionary.  You could possibly write a method if you really wanted which searches both the dictionaries and returns the appropriate value.
Since you have access directly to the dictionaries as properties – then why have a AddShortCut and RemoveShortCut method – you can directly access the dictionary via the property. Sure an OOP diehard might insist on you using a getter method – but you still have one location, one point of all when accessing those dictionaries via the property.
Is there any reason to have a static class?

Something like this may be easier.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace practiceConsole
{///
    internal class Program
    {
        #region public properties and variables

        private Dictionary<string, Type> _truckShortCuts = new Dictionary<string, Type>();

        public Dictionary<string, Type> TruckShortCuts
        {
            get { return _truckShortCuts; }
            set { _truckShortCuts = value; }
        }

        private Dictionary<string, Type> _carShortcuts = new Dictionary<string, Type>();

        public Dictionary<string, Type> CarShortCuts
        {
            get { return _carShortcuts; }
            set { _carShortcuts = value; }
        }

        #endregion public properties and variables

        private static void Main(string[] args)
        {
        }

        public Type GetShortCut(string key)
        {
            Type truckValue;
            if (TruckShortCuts.TryGetValue(key, out truckValue))
            {
                return truckValue;
            }
            else
            {
                // couldn't find the key in trucks.
                // so let's search for it in Cars

                Type carValue;
                if (CarShortCuts.TryGetValue(key, out carValue))
                {
                    return carValue;
                }
                else
                {
                    // couldn't find the key.
                    // throw exception
                    throw new KeyNotFoundException("\nCouldn't find the key in either the car or trucks shortcut dictionaries, my regrets.");
                }
            }
        }
    }
}


Perhaps you could wrap bare Sockets in an auxiliary datatype that enabled buffering. Something like:

data BufferedSocket = BufferedSocket [ByteString] Socket

Then you could define your own recv function like

recv :: BufferedSocket -> Int -> IO (BufferedSocket,ByteString)

which looked at the buffer before actually trying to read data from the socket. Note that this version of recv returns a modified copy of the BufferedSocket, because now we carry some state that isn't captured in the mutable Socket reference.

(Perhaps this extra buffer state should be put in a separate mutable reference, an IORef for example. We are already in mutable-land after all.)

We also need a function

putBack :: ByteString -> BufferedSocket -> BufferedSocket

for prepending the data.

Another option could consist in using a streaming library like streaming or streaming-bytestring and build a Stream of ByteStrings out of the Socket. Prepending would consist simply in concatenating a pure Stream that yields the ByteString to the effectful stream that reads from the socket, using >> or *>.

let socketStream' = S.yield someByteStringValue *> socketStream

Note that the old socketStream value should not be reused!

This might have the disadvantage that you lose some control about how many bytes to "physically" read at each step, because typical Streams don't take "feedback" from downstream about the number of bytes to receive next.


Unit testing for concatenating two int arrays

Testing

concat isn't a great name for a test, it doesn't tell me anything about what it is that the test does, it simply copies the name of the method being called.  Something like concatShouldReturnConcatenationForTwoPopulatedArrays might be a better description
Personally, for a test this simple, I'd tend to define the expected results for the test within it rather than calculating it on the fly.  This makes it less likely that you'll get a failure because your test is wrong.  It also allows you to use the junit array comparison.

Assert.assertArrayEquals( expectedResult, result );

You've only got one test, I'd tend to add at least 3 more for:

concat([], numbers2)
concat(numbers1, [])
concat([], [])


Test your program with a variety of inputs.
Include "abcdefghijklmnopqrstuvwxyz".

Have a look what happens for 'n'.
Always try to make sure you test low values, high values and edge cases.
'Wrapping round' is a classic edge case.

Then look at this line:

if ((currentLetter - 'a') + key > 26)

This program only works for lower case 'passwords'.

You might look at the functions in #include <ctype.h> such as tolower(.) or islower(.) to extend to mixing upper and lower case.

NB Obviously ROT13 has no real cryptographic value of any kind.
I mention that because I have seen it (and things not better) used in applications.
You're doing this as a learning exercise. Right?


You have a bug. Lists are 0-indexed in Perl.

Take a closer look at this:

my @doors = (0) x 100;

sub check_hallway {
    say "door ". ++$_ , $doors[$_] ? ' is open' : ' is closed' foreach 0 .. $#doors;
}

@doors has 100 elements, indexed from 0 to 99.
In check_hallway, you have a loop from 0 to 99, but due to the ++$_ earlier on the line,
$doors[$_] will be used with indexes 1..100.
$books[0] is not used, and $books[100] is used, out of bounds.

To make the problem more visible, simply add $books[$_] in the say statement:

say "door ". ++$_, $doors[$_], $doors[$_] ? ' is open' : ' is closed' foreach 0 .. $#doors;

When accessing $doors[0], the program will emit an error:

  Use of uninitialized value in say at prog.pl line 11.

So then why does it appear to be working?
Because in walk_hallway you are not using index 0..99,
but 1..99.

As it is, the last door is missed. Door 100 should be open, but the program shows it closed.

An easy fix is to use 101 doors and ignore index 0. Only the first part of the code needs to change to make that work:

my @doors = (0) x 101;

sub check_hallway {
    say "door ". $_, $doors[$_] ? ' is open' : ' is closed' foreach 1 .. $#doors;
}

But if take a look at the open doors in the output, a pattern becomes obvious:

door 1 is open
door 4 is open
door 9 is open
door 16 is open
door 25 is open
door 36 is open
door 49 is open
door 64 is open
door 81 is open
door 100 is open

The only doors open are the square numbers. This is because all other numbers have an even number of unique divisors. Only square numbers have an odd number of unique divisors.
So, to print the open and closed doors, we can use a much simpler and faster algorithm, for example:

my $doors = 100;

my %squares;
foreach (1..sqrt($doors)) {
    $squares{$_ * $_} = 1;
}

foreach my $door (1..$doors) {
    print 'door ', $door, ' is ', $squares{$door} ? 'open' : 'closed', "\n";
}


ptr_str_cat function:

The ISO C90 strcat requires the string dest to have sufficient space to hold the result of the concatenation. On the other hand strncat takes another argument size_t n and won't copy more then n characters to dest (+ the null terminator). You should definitely consider to implement one of these approaches, since the macro seems rather randomly chosen (you don't know whether dest is big enough to hold src).

Edit: See @JS1's answer to take a look at the approach of strncat. He also has a good catch with the Off-by-one-error.
If you want to completely leave out library function calls, you could even replace the strchr call with a simple loop.

while(*dest != '\0')
  dest++;

There is no need to explicitly overwrite the null terminator in dest. It will get overwritten by the contents of src and in the case of an empty src the null terminator is actually wanted.
The while-loop doesn't require extra curly braces. The NULL statement is sufficient.

while((*dest++ = *src++) != '\0')
    ; /* Intentionally left blank */

This is what you would come up with:

char *ptr_str_cat(char *dest, const char* src){
  char *original = dest

  while(*dest != '\0')
    dest++;

  while((*dest++ = *src++) != '\0')
    ;  /* Intentionally left blank */

  return original;
}

You don't even need to include <stdlib.h> using this implementation (since you don't use exit anymore).

main function:

Minor: dest[strlen(dest) - 1] = '\0'; will overwrite valid input (not the '\n'), when the first input line is longer than MAX_SIZE.

EDIT:

Good question regarding how to handle large input. I think this somehow depends on the target. I'd say our goal here is to create a piece of software, which is able to read in two strings (of any unknown size, separated by '\n') and later on have a pointer to the concatenation of these two strings.

One approach would be to allocate MAX_SIZE bytes of memory using malloc. Using fgets we fill the allocated memory and each time the string does not end on '\n' we reallocate MAX_SIZE more bytes and read in more characters. This will work until you run out of memory.


Copying data from various sources into a master list

This:

With ThisWorkbook.Sheets("Orderlist P25 2017")
Range("Z10").Formula = "=VLookup(C10,  '" & vbaPath & vbaFile & Orderlist2017 & "'!C14:Z90, 8, False)"
Range("Z10").Select
    Selection.Copy
    Range("Y10").Select
    Selection.End(xlDown).Select
    Range("Z85").Select
    Range(Selection, Selection.End(xlUp)).Select
    ActiveSheet.Paste
    Application.CutCopyMode = False

End With

might work changed to that:

Range("Y10:Z85").FormulaR1C1 = "=VLookup(RC[-23],  '" & vbaPath & vbaFile & Orderlist2017 & "'!R[4]C[-23]:R[80]C, 8, False)"

Mastering the R1C1 reference style will change the way you deal with formulas on the VBA side. For more details, read my blog post here.

In addition, your With / End With logic is useless since you don't have any references to it (e.g. a .Range)


Get element at a specific position in a string with separator

TL;DR

  Your function seems fine and is suitable and is likely to perform well unless you pass in large expression pushing the varchar(max) limit. However, I would edit it to check if the first index in the expression is the separator since if it isn't, your function would return undesired results. For example,
  SELECT dbo.getStringElement_Expr_Pos_Sep(N'aaa|zzzzz|cc|mmmmm|e', 2, N'|') with your current function returns cc not zzzzz and calling it with 3 returns mmmmmm. So your function is 0 index based (not 1) which you stated, but isn't intuitive for the SQL language as most functions are 1 based. It also doesn't account for the first element being the separator (potentially)

Long Version

One alternative option would be to use a string splitter and avoid the while loop in your current function. So, using Jeff Moden's splitter located here where he explains some performance issues with other splitters, you could achieve your results as such:

declare @EXPR nvarchar(MAX),
        @POSI int,
        @SEP nchar

set @EXPR = '|zzzzz|cc|mmmmm|e'
set @POSI = 2
set @SEP = '|'

select *
from dbo.DelimitedSplit8K(@EXPR,@SEP)
where ItemNumber = @POSI

Generally speaking, loops are slow in SQL Server and most RDMS. Also, as you can imagine, you can use the string splitter to bring back and entire table of elements which have a greater use case than your current function, reducing code maintenance. In this case, however, it depends on the length of your expression

Here is the test I ran:

set statistics time on

select *
from dbo.DelimitedSplit8K('|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|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cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e|zzzzz|cc|mmmmm|e', 66, '|')

set statistics time off

Results in Avg

Position 66
Splitter = 3ms
YourFun  = 6ms

Position 12
Splitter = 2ms
YourFun  = 4ms

Position 3
AVG
Splitter = 2ms
YourFun  = 3ms

Bias

However, if you are reduce the size of the expression to something small like your original use case, your function will run faster by a millisecond, so if you don't expect large expressions, or don't care about milliseconds, your function seems quite suitable.

Here is the full function

/****** Object:  UserDefinedFunction [dbo].[DelimitedSplit8K]    Script Date: 05/01/2017 9:42:33 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[DelimitedSplit8K] (@pString VARCHAR(8000), @pDelimiter CHAR(1))
--WARNING!!! DO NOT USE MAX DATA-TYPES HERE!  IT WILL KILL PERFORMANCE!

RETURNS TABLE WITH SCHEMABINDING AS
RETURN

/* "Inline" CTE Driven "Tally Table" produces values from 1 up to 10,000...
enough to cover VARCHAR(8000)*/

  WITH E1(N) AS (
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
                ),                          --10E+1 or 10 rows
       E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
       E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
 cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
                     -- for both a performance gain and prevention of accidental "overruns"
                 SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                ),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
                 SELECT 1 UNION ALL
                 SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
                ),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
                 SELECT s.N1,
                        ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
                   FROM cteStart s
                )
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
 SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
        Item       = SUBSTRING(@pString, l.N1, l.L1)
   FROM cteLen l
;
GO


Warning! Arm Chair Quarterbacking in progress. Given that I offer this.

Game Class

Why is this Board.moveList in the Board class?  You need a "driver" for a chess game and that would be a Game class. "A game consists of (has) moves" makes more sense.

The Game gives us a conceptual framework for a richer chess game. A Game has players, may have a timer for speed chess, and can keep track of pieces removed from the board; and of course records the moves.

Board Class

The chess board is a data structure. Don't make more of it than it is; nor less.

In the Visitor Pattern the data structure has-a element that has an accept method. That element seems to be a Square. I'm not certain if it's better than the Board being visited, but certainly the point is that we're evaluating the state at that one square? I don't see a big deal in giving a board reference to each square.

OR .. maybe the Pieces are visited. To test if the piece is "inCheck" for example. This perspective makes more sense than a square is in check. Is this why your board is Piece[][] and not Square[][]?

Whether we are visiting the board and iterating the squares; or iterating the board and visiting the squares; or iterating the squares and visiting the pieces may be more than semantics. I vote for whatever best reflects intent, gives me good code expressions, and sensible building blocks.

In any case I agree with @bowmore about refactoring Piece[][] to Square[][].

Pieces

Even given a rich Piece class, I like the idea of using an enumeration for names. This makes for nicer coding  and expressability overall (and my pet peeve - it avoids strings). Maybe two enumerations. As in White.Knight and Black.Queen; or Pieces.WhiteKnight, Pieces.BlackQueen And a value to represent an empty square might be nice Pieces.none or Pieces.undefined.

Maybe Piece has a Square reference so it knows where it is. This may have a nice effect on the visit code.

Visitor Pattern

Nice call.

I agree with @MarcoForgerg, the visitors do not need to keep state. Just pass in the needed parameters and forget-about-it when done. And, instead of Singletons perhaps just static.

Nested visitors? Ok, so the board gets "visited" which in turn "visits" each square, which in turn, finally gets to Piece.accept(Evaluator xxxx). Visitors, by definition, understand their visited data structure so I'm thinking board iteration is wrapped in the board visitor, and the square visitor knows to check for an occupying piece and knows what Evaluator(s) to pass to the piece. It feels like nicely layered (code) logic to me. And note how the iteration logic is in the visitors, not the board (data structure). And subsequently all the business logic is in the visitor as well.

SO instead of this

public void accept(BoardVisitor bv) {
    for (Square square : board) {
       bv.visit(square);
    }
}

THIS - Let the Visitor do the walking and talking (decision making). And the decision to evaluate empty squares is delayed as long as possible - push details down. Note that Board, Square, Piece visiting logic is decoupled/layered.

// in Board class
public void accept(BoardVisitor bv) { bv.visit(this));}

// BoardVisitor class
public void visit (Board board) {
    // "board level" logic as needed
    for (Square square in board) {
        square.accept (this.squareVisitor);
    }
}

// Square class
public void accept (SquareVisitor sv) {
    sv.visit(this);
}

// SquareVisitor class
public void visit (Square square) {
   // "square level" logic as needed
   if(!square.isEmpty) {
       // maybe we target Evaluators for the particular piece on the square

       this.evaluator(square); // square has references to its piece and board.
         // maybe the square.piece has "visit"
   }
}


Using Pexpect for communication between multiple programs via I/O

here are a few ways to cleanup the code and make it more readable. This does not really go over functionality too much as I am not super familiar with pexpect or your other program you are trying to interface with. There are probably some optimizations to do the While loop in your program especially around the end where you are changing the player you are looping on but since I am unfamiliar I will leave that alone.

Without seeing the code or having a better understanding of how the checker/player works, this will be the best I can give for now.

Unused imports aren't a terrible thing, but aren't really a good thing either, best to remove them.
It doesn't seem like any naming convention is really being strictly followed. For example you have Checker = pexpect.spawn("./checker") but then later are doing check = Checker.before.strip(). It is best to follow PEP8 and stick with the snakecase naming convention. So it would be checker = pexpect.spawn("./checker")
Similarly named variables can be confusing. You have Player and player but they are different things. Best to be more specific, player_list and current_player would be better.
Use list literals instead of creating a list with aribitrary values then indexing in. You could rewrite

Player = [0,1]
Player[1] = pexpect.spawn("./player1")
Player[0] = pexpect.spawn("./player2")

as

Player = [pexpect.spawn("./player2"),pexpect.spawn("./player1")]

but that looks a little backwards, so I am gonna change all the indexing so player 1 is in index 0.

player_list = [pexpect.spawn("./player1"), pexpect.spawn("./player2")]

Use string interpolation

print "endgame   ", check

Would become

print "endgame {}".format(check)

and

print "endgame" + player + "died"

would become

print "endgame {} died".format(player)

Use the natural feel of booleans instead of check != "" where you should have done if check. Python will check for None and "" for you.

Here is my version of the script that should function the same.

import pexpect

checker = pexpect.spawn("./checker")
player_list = [pexpect.spawn("./player1"), pexpect.spawn("./player2")]

player_list[0].sendline("1")
player_list[0].expect("\n")  # delete input from before
player_list[1].sendline("2")
player_list[1].expect("\n")  # delete input from before

current_player_idx = 0
while True:
    player = player_list[current_player_idx]
    player.expect("\n")
    move = player.before.strip()
    print move

    if not checker.isalive():
        print "endgame checker died"
        break
    checker.sendline(move)
    checker.expect("\n") # delete input from before
    checker.expect("\n")
    check = checker.before.strip()
    if check:
        # Really have no idea what you are trying to do in here, so I am leaving it alone.
        print "endgame {}".format(check)
        player_list[1].kill(0)
        player_list[1].kill(0)
        checker.kill(0)
        break

    # If I understand correctly, you are trying to see if the OTHER player is still alive.
    current_player_idx = (current_player_idx + 1) % 2
    if not player_list[current_player_idx].isalive():
        print "endgame {} died".format(current_player_idx)
        player_list[current_player_idx].sendline(move)
        player_list[current_player_idx].expect("\n")  # delete input from before
        break


List of students with their classname in current year

Not entirely sure I got your schema right, but something like this should be possible.
(omitted a bit of ordering, and I assume you only have one current year)

select top 10000
    s.*,
    c.Title classname,
    row_number() over (order by s.id) rownumber,
from
    students s
    inner join years
        on years.iscurrent = 1
    inner join studentsinclass sc
        on s.code = sc.studentcode and sc.yearid = years.id
    inner join class c
        on c.id = sc.classid
where
    row_number() over (order by s.id) >= @StartRow
    and
    row_number() over (order by s.id) <= @EndRow

You could possibly swap on years.iscurrent = 1 with on years.id = year(getdate()).

If you can, you should generally try to avoid too many subqueries. At least attempt to indent them properly.

You could also benefit from having a look at common table expressions. These can help you group up the subqueries in predefined results for your query. Makes it a lot easier to read.
http://msdn.microsoft.com/en-us/library/ms190766.aspx


Finding all words without a certain character

If just looking for a single character in a set of strings, I would think basic string manipulation would be sufficient.

What is not clear to me from your question is why you are using word boundaries in your regex definition when the array itself is just single words.  Is your intent to analyze individual words in each of the array strings (with string perhaps consisting of multiple words) or are you only truly going to have single word string in the array?

For now, I will provide answer given the assumption of an array of single words.

To do that, I would simply use Array.filter() in combination with String.indexOf().

var needle = 'e';
var haystack = ["platypus", "elvis", "javascript", "stackoverflow"];
var filtered = haystack.filter( str => (str.indexOf(needle) === -1) );

Based on your comment that array entries could have multiple words, I would suggest using Array.reduce() to build all array of all words across all entries that do not have have the needle character in them.

var needle = 'e';
// note global flag here to get all matches
var regex = new RegExp('\\b([^' + needle + ']+)\\b', 'g');
var haystack = ["platypus", "elvis", "javascript", "stackoverflow", "some multi-word string"];
var result = haystack.reduce(
    (aggregator, str) => {
        while (match = regex.exec(str) !== null) {
            aggregator.push(match[1]);
        }
    },
    []
);
console.log(result); // ["platypus", "javascript", "multi-word", "string"]


Code allowed to test mail invitations by users (from another post) on an instance of Visual studio debugging

Class names shouldn't be plural except for a few exceptions, and BaseViewModels does not seem to be such a case.

Avoid this kind of logic:

if (usr != null)
{
    // lots to do
}
else
{
    // one thing to do
}

Especially here: you could have done

if (usr == null)
{
    model.Feedback.AddError("SendMailInvit User Not find ", " SendMailInvit User Not find => UserId : " + userId);
    return;
}

and then the rest of the method could be the long list of other instructions.

I've never worked with ASP.NET MVC, so I don't know whether this is the usual way of doing things, but passing a model and then setting properties to give feedback -- e.g. model.Feedback.AddError("SendMailInvit User Not find ", " SendMailInvit User Not find => UserId : " + userId); -- looks really odd to me.

Especially since this class doesn't have anything to do with the UI; which means you're mixing up tiers.

Don't use regions.

This seems like a hacky solution:

var currentHost = "localhost:57061";
var newhost = $"{GetIPAddressV4()}:90";
url = url.Replace(currentHost, newhost);

Wouldn't it be much simpler to simply have the base URL as a value in a .config file? Especially considering what's happening in GetIPAddressV4().

If I were you I'd move the whole "compile the URL" logic to a separate method.

Avoid abbreviations like UrlInvit, htmlInvit etc. It only makes you code harder to read.


Python. Refactoring a function to increase its capabilities

I can't comment much on the questions you asked about the functions that haven't been implemented yet, other than to say that passing an argument down through multiple function calls is perfectly fine.  If your code cleanly declares what arguments it expects and what each argument does it shouldn't be a problem.  I did my best to clean up the code you provided, mostly just fixing PEP8 style stuff and trying my best to fix the typing (although it's hard without having any of your dependencies to check against, I tried to tidy up stuff like having profile_data go from dict to list back to dict).  I also replaced the janky in-place dictionary modification with a comprehension.

from typing import Dict, Optional

def show_profile(
    user_id: str,
    profile_data: Optional[Dict[str, str]] = None,
    photo: Optional[str] = None
) -> Message:  # fixme: what's the actual type of this?
    """
    A profile is a message object with a photo, text (caption), and markup.
    If no profile data is specified it will be loaded from the db.
    If no photo is specified, it will be loaded from the db,
    or DEFAULT_PHOTO will be used.
    """
    # db_execute - manually created function,
    # the short version of cursor.execute (pymysql)"""
    if profile_data is None:
        goal, age, gender, country, city, comment = db_execute(
            'SELECT goal, age, gender, country, city, comment '
            'FROM users '
            'WHERE user_id = %s',
            user_id, fetchone=True, get_tuple=True
        )
        profile_data = {
            'Goal': goal,
            'Age': age,
            'Gender': gender
            'Country': country,
            'City': city,
            'Comment': comment
        }

    if photo is None:
        photo = db_execute(
            'SELECT photo '
            'FROM photos '
            'WHERE user_id = %s and id = (SELECT MIN(id) FROM photos)',
            user_id, fetchone=True
        ) or DEFAULT_PHOTO[0]

    # Get first and last name of the user.
    username = bot.get_chat(user_id).username

    # add link to user inside a message
    caption = f'Имя - {username}.\n'

    # Remove None data from profile
    profile_data = {k: v for k, v in profile_data.items() if v is not None}
    # Add it to the caption
    for k, v in profile_data.items():
        caption += f'{key} - {value}\n'

    return bot.send_photo(
        user_id,
        photo,
        caption=caption,
        parse_mode=ParseMode.HTML,
        reply_markup=get_scrolling_profile_keyboard(user_id)
    )

def get_scrolling_photos_keyboard(shower_id: str) -> InlineKeyboardMarkup:
    return InlineKeyboardMarkup([[
        InlineKeyboardButton('<', callback_data=f'back_photo {shower_id}'),
        InlineKeyboardButton('>', callback_data=f'next_photo {shower_id}')]])

def get_scrolling_profiles_keyboard(shower_id: str) -> InlineKeyboardMarkup:
    """
    Add more buttons for scrolling, group of photos and group of profiles
    (the profile is still just a message object with photo, text, and buttons)
    (The second missing feature)
    """
    keyboard_obj = get_scrolling_photos_keyboard(shower_id)
    buttons = keyboard_obj.inline_keyboard  # Get list from object
    buttons.append(InlineKeyboardButton('Back', callback_data=f'back_profile'))
    buttons.append(InlineKeyboardButton('Next', callback_data=f'next_profile'))
    return InlineKeyboardMarkup(buttons)


tcl script to parse C++ source code for type identifiers

You are checking 5 times if $state equals to "start" and several times for the other "states". You should compact this and maybe a switch would be better.

You have a spelling error CheckIdnetifier which should be corrected.


$(document).on('click', '#List01 li, #List02 li, #List03 li', function () {
        var anchor = $(this).find('a');
        sessionStorage.KenID = anchor.attr('id');
        changePage();
});

The , should do the trick.


Fill an array with last non-zero element to the end in PHP

Do you really want this function to use loose comparison $array[$i] != 0?  What should intended behavior be for other potentially falsey values at the end of the array (false, "", [], etc.)?  If you truly only want to replace only trailing zeroes, then you must use exact comparison here !==.
Your function name seems unclear with regards to what the function does.  Perhaps arrayPadOverTrailingZeroes, arrayPadOverTrailingEmptyValues (depending on desired behavior).
PHP provides built-in array functions that may clean up this code a little bit (and perhaps perform slightly better since they are compiled).

For example:

function arrayPadOverTrailingZeroes($array) {
    $length = count($array);
    while (($value = end($array)) === 0) {
        array_pop($array);
    }
    // This conditional to support case where you have all zeroes,
    // in which case, the while loop above would have discarded all array members
    // and $value would be set to false
    if (count($array) === 0) {
        $value = 0;
    }
    return array_pad($array, $length, $value);
}

Answered this before I saw your all-zeroes use case.  Added some additional logic above to handle this case.


The code isn't actually doing much, there's little to review to be honest, it's not looking complicated for what it is.  Of course don't just have everything in a couple of loops, perhaps have some handlers to dispatch on the tags or so (handlers[child.tag](child) ...).

I suppose if you wanted a relatively quick way to write the importer code, consider XPath.  If you wanted quick processing (by not building up the full DOM in memory), consider using a SAX handler.

Finally, there might be a library to automatically map the XML to a class structure, or even parse it directly into dict instances or something, if you prefer that, but I don't any off the top of my hat.


Given a Haskell list, return all sub-lists obtained by removing one element

Here's a simpler way to implement it:

subOneLists :: [a] -> [[a]]
subOneLists [] = []
subOneLists (x:xs) = xs : map (x :) (subOneLists xs)


Unit tests

Unit tests should test the smallest behavior possible in each method of tests. Why ? Because when you make changes it helps determine what has break just by looking at failing tests.

  3.3 What to Include in Your Unit Tests

  Ideally, you would like to include a test for everything which could
  possibly break. It's a good practice to have at least one test for
  each of your validations and at least one test for every method in
  your model.

I added emphasis on something I find very important, you should test each validation on it's own. That way it's easier to see every rules your code have. By looking at your tests, I should easily see what your code is about and what I should expect to see.

When you want to comment, refactor

Most of time when you add a comment it's a sign that you should refactor (this is not an absolute rule, but it's apply in a lot of case).

# Test Inclusion of city
s.city = "Santo"
assert_not s.valid?, "Address was valid with incorrect city"

Do you see what you did there ? It's a test case inside your test. If you need to reuse some constant or variable in a test, there are ways to do this without being in the same method. You can setup data in a method and call it in your test methods to keep your code clean.

You should have :

  test "shipping addresses validations" do
    s = ShippingAddress.create
    assert_not s.valid?, "Address was valid without any data"
    assert s.errors.include? :name
    assert s.errors.include? :phone
    assert s.errors.include? :address
    assert s.errors.include? :user
    assert s.errors.include? :city
  end

  test "inclusion of city" do
    s = ShippingAddress.create
    s.name = "Some"
    s.phone = "8296964737"
    s.address = "Calle #1"
    s.user_id = 1
    s.city = "Santo"
    assert_not s.valid?, "Address was valid with incorrect city"

  end

You should have a test for each validation of the fields of your class where only the one field is missing. That way if your validation on the name per example changed, then that tests failed. If you only do one tests with everything you may not be able to trap that one validation has been remove.


Crypto createCipheriv and createDecipheriv for authentication

I am using crypto.createCipheriv and crypto.createDecipheriv for authentication.

Encryption is mainly used for providing confidentiality. You'd use a MAC (message authentication code) or authenticated encryption if you want authentication.

Note that CTR decryption always succeeds, even if it may result in incorrect ciphertext. CBC decryption succeeds 1 out of 256 times if PKCS#7 compatible padding is used (and it is) if random ciphertext is fed to it. Besides that, CBC is vulnerable to padding oracle attacks. Unauthenticated ciphertext is always vulnerable to plaintext oracle attacks.

Basically, you need a MAC (such as a HMAC over the IV and the ciphertext) or authenticated encryption.

GCM mode is provided by CryptoJS, if I'm not mistaken. GCM already authenticates the IV - but make sure it does authenticate the tag!

  I will store the key in the database, and the initialization vector, IV, and encrypted data in cookies.

I presume this is a textual error, as the initialization vector is the IV.

  If the database is compromised, the hacker will not be able to use the database keys, because they will need the code to generate the IV and the data cookies.

The IV should never be considered a secret. The data may of course be considered secret, but the algorithm to generate the data should not act as a key either (see Kerckhoff's principle).

  The database key is the same for multiple sessions, only the IV and data are different.

That's right, as long as you don't create millions of "messages" (in this case cookies). If you overextend the key you may want to create a different key (for instance using key derivation). Probably this is not a problem for you though.

Let's move to the code (which we now know is not secure).

function encrypt(dataToEncrypt /*random data*/) {

Random has a very specific meaning in cryptography, so I'd try and avoid that adjective, and use "any" instead. I'd simply document your functions, and not put inline comments in the code.

let dbKey = crypto.randomBytes(32) //db

Fine, although I would use 256 / 8, preferably with a constant KEY_SIZE = 256 for the key size.

Don't use end-of-line comments either, as refactoring will make them disappear behind the right margin or trigger a nasty text wrap in editors.

Where the key is stored is not within this method, so the comment should not be present in the final code.

 let userKey = crypto.randomBytes(16) //cookie

No! An IV is not a key, and - even if it was - only the first block of ciphertext cannot be decrypted without the IV in CBC mode. Again, at least use a constant like BLOCK_SIZE_BYTES = 16 or IV_SIZE_BYTES = 16.

let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(dbKey), userKey)

Wrong mode, but yeah.

let encryptedData = cipher.update(JSON.stringify(dataToEncrypt))

JSON-ify should be performed on a separate line. Now a significant operation is hidden inside another statement.

return { userKey: userKey.toString('hex'), dbKey: dbKey.toString('hex'), encryptedData: encryptedData.toString('hex') }

Ciphertext and keys are binary. I'd not stringify them unless strictly necessary. The IV and ciphertext may be concatenated and then converted to (URL-safe) base 64 to be more efficient than hex.

Skipping some lines to the final part of the decryption:

return decryptedData.toString()

That's no good, first you JSON-ify the input, and then you don't do the reverse during decryption. These methods should be symmetric. Either you take it out of encryption or you add it to decryption (if that's possible).


Simple helper for making things "disposable"

It's a little difficult to give a full review without the removed null checks, but I'll give an observation:

In Dispose(), you depend on null to be the value of _state to judge whether or not to call the cleanup action. That's all well and good, but you should likely then constrain the generic parameter T to be class

class Usingifier<T> : IDisposable where T : class

You also have an issue with multiple-disposals calling the cleanup action with the state - both probably being stale after the fact. The class should be considered unusable after the cleanup. Or at least unusable until the initialize function has been called again. Simple boolean should take care of that:

class Usingifier<T> : IDisposable where T : class
{
    private readonly Func<T> _initialize;

    private readonly Action<T> _cleanUp;

    private bool _disposed;

    private T _state;

    public Usingifier(Func<T> initialize, Action<T> cleanUp)
    {
        _initialize = initialize;
        _cleanUp = cleanUp;
    }

    public Usingifier<T> Initialize()
    {
        _state = _initialize();
        _disposed = false;
        return this;
    }

    public virtual void Dispose()
    {
        if (_disposed)
        {
            return;
        }

        _disposed = true;

        if (_state != null)
        {
            _cleanUp(_state);
        }
    }
}

You may want to also put in some sort of nice (optional) automatic disposal if T itself happens to be IDisposable. Here's a quick take on that:

class Usingifier<T> : IDisposable where T : class
{
    private readonly Func<T> _initialize;

    private readonly Action<T> _cleanUp;

    private readonly bool _autoDispose;

    private bool _disposed;

    private T _state;

    public Usingifier(Func<T> initialize, Action<T> cleanUp, bool autoDispose = false)
    {
        _initialize = initialize;
        _cleanUp = cleanUp;
        _autoDispose = autoDispose;
    }

    public Usingifier<T> Initialize()
    {
        _state = _initialize();
        _disposed = false;
        return this;
    }

    public virtual void Dispose()
    {
        if (_disposed)
        {
            return;
        }

        _disposed = true;

        if (_state != null)
        {
            _cleanUp(_state);
        }

        if (_autoDispose && _state is IDisposable disposable)
        {
            disposable.Dispose();
        }
    }

I had a couple more thoughts: perhaps expose _state via a property (can then be accessed within your using scope) and then perhaps extracting an interface for the whole caboodle for mocking purposes during unit testing. Behold:

interface IUsingifier<T> : IDisposable where T : class
{
    T State { get; }

    Usingifier<T> Initialize();
}

class Usingifier<T> : IUsingifier<T> where T : class
{
    private readonly Func<T> _initialize;

    private readonly Action<T> _cleanUp;

    private readonly bool _autoDispose;

    private bool _disposed;

    public Usingifier(Func<T> initialize, Action<T> cleanUp, bool autoDispose = false)
    {
        _initialize = initialize;
        _cleanUp = cleanUp;
        _autoDispose = autoDispose;
    }

    public T State { get; private set; }

    public Usingifier<T> Initialize()
    {
        State = _initialize();
        _disposed = false;
        return this;
    }

    public virtual void Dispose()
    {
        if (_disposed)
        {
            return;
        }

        _disposed = true;

        if (State != null)
        {
            _cleanUp(State);
        }

        if (_autoDispose && State is IDisposable disposable)
        {
            disposable.Dispose();
        }
    }
}


What is a better (more testable) way to structure this page-specific JS?

MyPage = (function() {
    var Page = {
        addFile: function(e) {
            this._files.push($(e.target).val());
        },

        doUpload: function() {
            alert('uploading ' + this._files.length + ' files...');
        },

        clear: function() {
            this._files = [];
            $(this.options.fileCtrls).val('');
        }
    }

    // public members
    return {
        init: function(options) {
            var o = Object.create(Page, {
                options: { value: options },
                _files: { value: [] }
            });

            $(function() {
                // wire up the events
                options.clearLink.click($.proxy(o.clear, o));
                options.uploadBtn.click($.proxy(o.doUpload, o));
                options.fileCtrls.change($.proxy(o.addFile, o));
            });
        },

    }
})();

Using Object.create

Live Example

ES5-shim for browser support.

As for testing use any old testing framework you like. Use jQuery.sub() to mock out jQuery