Method to count interior nodes of a binary tree

So after our little discussion, I hope you see that you're missing some key cases here, when the root given is None.

Some things that should be pointed out, when comparing to None, you should be checking if it is or is not None.  Don't use (in)equality here, it is just not correct.

Assuming this is a method on your tree node objects, I'd rewrite this to make use of self.  That way we don't even need to worry about the case when self is None, that just shouldn't happen.

def count_interior_nodes(self):
    count = 0
    hasLeft, hasRight = self.left is not None, self.right is not None
    if hasLeft:
        count += self.left.count_interior_nodes()
    if hasRight:
        count += self.right.count_interior_nodes()
    if (hasLeft or hasRight) and self.parent is not None:
        count += 1
    return count


Module Design

The trouble with your design is that you need to know how it works before you can use it. This is not true for strtok (OK to a slight extent it is true for strtok).

When designing a software system the user should not need to know how it operates, but rather the interface to the system. Doing it this way has two distict advantages.

User does not need to learn how it works thus making it easier for them to use.
This means it is easier to distribute in binary form if you want.
User is less likely to break it by making assumptions that do not hold (as they have not read the code to understand it).
You can change how it works without affecting the user code.

Thus I would have provided this functionality with a couple of functions and some opaque data types that the user never needs to know or understand.

String Copying

while (i < length) {
result[i] = *start;
start++;
i++;
}

This is done in the std lib look up strncpy().

Also this can be written much more succinctly as:

for(loop = 0; loop < length; ++loop)
{
   result[loop] = start[loop];
}

Code Review

I don't think you need to define this.

#define NULL_TERM '\0'

Putting the literal '\0' into your code is very readable and people know what it means. The macro NULL_TERM may seem self explanatory but I would go look it up.

The function printcharlist assumes the list is NULL terminated.

int printcharlist(char **tok_list)

This is asking for people to do it incorrectly (and forget the NULL terminator). You even mention yourself that this is akward:

/* It feels awkward to add one more token after the while loop. Is it standard? Should/can I avoid this? */

I would change the interface to pass the number of values in the list:

int printcharlist(char **tok_list, size_t count)

Then you make people explicitly fill in the length and they can not accidentally pass you an array that will cause problems.

Alternative design

One advantage of strtok() of your function is that it does not parse the whole string. It only fetches the next token. Thus in a situation where you only need the first couple of tokens it is much more efficient.

I would change your algorithm so that it behaves in a similar manor. Retrieve one string (and store it in your data structure). Next call retrieves the next string etc (this would be a lot easier to change it you had made a modular design).

Questions

  Would make you react badly if someone sent you this code in a patch/pull-request? If yes, what?

No. But I would want to see the test cases the validate it.

  Consider this code is going to production. What are the edge cases that I miss and how can I solve them?

I would set up some unit tests.

""
";"
";;"
";;;"
"Some Text;"
"Some Text;;"
";;SomeText;;"
"Some\nText"
"Some\nText;"
"Some\nText;;"
"Some\n;Text"
"Some\n;;Text"
"Some;\n;Text"
"Some;\n;;Text"
"Some;;\n;Text"
"Some;;\n;;Text"


All the indexing can be deleted. You only need the transpose function plus a custom function that grabs the diagonals of a matrix (list of lists, all of the same length).
import Data.List (transpose)

-- | The 'diagonals' function returns the diagonals of a matrix
diagonals :: [[a]] -> [[a]]
diagonals matrix = lowerDiags matrix ++ upperDiags matrix
    where lowerDiags = reverse . transpose . zipWith drop [1..]
          upperDiags = transpose . zipWith drop [0..] . transpose

You can invoke it as shown below. If any of the vectors has four in a row, you have a winner.
board = ...
vectors = board ++ transpose board ++ diagonals board ++ diagonals (reverse board)


Ruby Symbol Table implementation using Binary Search

It's a good implementation, I can make the following improvement suggestions:

size/n aliasing: either add a comment explaining its purpose (a legitimate one could be the need to comply with some external interface), or pick one name and use it throughout the class.
rank(key) < @n checks: change rank to return nil when the key is not found. This is a common Ruby idiom. In Ruby 0 is truthy unlike many other languages.
@keys[i] == key: This check may be better off in a separate method, i.e. instead of a single rank method have one method that returns the rank when finding and one that returns the place for insertion.
Exception raises: the idiomatic Ruby way is to define needed exception classes (you could nest them in the BinarySearchST class) rather than raising strings.
Further on exception raises, it is a good practice to provide a descriptive message when raising each exception.
It's understandable if you want to move array elements yourself, but Ruby standard library does provide the Array#insert method which would do that for you.


This looks pretty good. A few changes I would make:
Performance
10^10, 20^20, and all higher powers will always end in 0000000000, which means they don't affect the sum. You should be able to get an approximately 10% performance improvement by not computing these powers. This would be easy to do in your loops case but would require a little syntactical cleverness in the streams way.
Magic Numbers
You have a magic number 9110846700L in your code. It's not immediately clear what this is, especially if you are unfamiliar with the UBench library. This should be refactored into a magic number constant, in this case. Further reading on this subject
Static methods
Even for a program as simple as this, I would always shy away from putting your business logic in static methods. Obviously, in this case it isn't a problem, but for an application could grow at all, you will quickly regret it. More further reading
Inconsistent method scope
One of your methods is private, the others are public. Again, this issue is not super relevant for such a short program, but allowing encapsulation to be broken starts to matter as soon a program reaches two classes.


I agree with the comment above about IP-based restriction perhaps not being the best approach here, or at least not using it as the only means to detect duplicates.

I think GeoIP is reasonable for blocking at a country level (though certainly not foolproof).

I think IP address might be a reasonable component to duplicate detection.  You could also add other duplicate detection mechanisms including:

User ID (which is something you seem to have but are not using - I would think this would be most authoritative piece of information if there is authentication/login attached to this user ID)
setting a cookie
inspecting user agent
setting value in browser localStorage and then have browser add to request (localStorage is a little harder for a typical user to clear out than cookies)

With regards to the code itself, you should get in the practice of inverting conditions when you have large blocks of code nested in a conditional (or really just in general to provide clear, early exit paths from a section of code).

For example:

if(!in_array($countryCode, $allowedCountries)) {
    // set location header and exit
}
if (checkForBlockedIP($projectID, $ip)) {
    // set location header and exit
}
if (checkForDuplicateResponse($projectID, $ip)) {
    // set location header and exit
}
// happy path code follows

There is no reason for your else blocks at all here from what I can tell.  As a general rule of thumb, the less nested code and code branches you have, the less prone your code is to bugs, so you should actively look to design away such constructs where possible.


int productNum[10];
int productCount[10];
double productPrice[10];

That's not exactly OOP what you did here. A single product is apparently defined by the combination of productNum, productCount and productPrice. So these 3 attributes should have been grouped together in a product class:

class product {
    int productNum;
    int productCount;
    double productPrice;
}

I'll let it to your exercise to decide on the visibility of these attributes, and to add a constructor.

And the inventory class then correspondingly holds a collection of products instead:

product products[10];

Well, except that this isn't exactly a clean way to manage a collection of products in C++ either, better use a dynamically growing data type with checked bounds:

std::vector<product> products;

This also brings us to the next point, your use of these two:

int locator;
int counter = 0;

I assume your locator variable was actually supposed to indicate the fill level of the original inventory tracking mechanism. Please try to name it properly the next time. There is also a second problem with locator, you made it public even though any external modification to this variable would break the integrity of your implementation.

void inventory::init() {
    ...
}

This method should have been called void inventory::inventory(), which makes it the constructor for the inventory class and is called automatically every time a new inventory is instantiated. Have a read on the RAII principle.

void inventory::store();
void inventory::retrieve();

These two have a rather strange signature for what they are called. Your task was to create an inventory class which manages an inventory. No less, no more. What you actually did, was cramming all the input and output logic into that class as well. That's a direct violation of the Separation of Concerns principle.

What that part of the API should look like is simple:

void inventory::store(product p);
double inventory::getTotal();

These methods shouldn't contain any input/output logic, but only the algorithms relevant to storing products, respectively to query all stored products for the grand total.

The input/output belongs into the scope working with the inventory instance, not into that class.

class inventory {...} inv1;

That's a global variable you created here. Unless you have a very good reason to do so (and trust me when I say you almost never have), don't. You should have instantiated inventory inside the main() function instead.

  I defined the member functions outside of the class by direction of the prof. I personally like seeing it all in one place, but this is an OOP class, so I guess it makes sense to define them outside.

Not quite. You should probably be familiar by now with the concept of splitting your source code into header and source files. With headers containing structural information, and source files containing implementations.

In this case, they class definition should have gone into a file called inventory.h and the implementation of the class would have belonged into inventory.cpp.

If take a look back at the section about the global variable inv1, it should strike why that was a mistake.

  We are required to create a class with both private and public member functions.

You don't have any private methods yet. Just food for thought, in regard to the Separation of Concerns, you could actually structure your API like this:

class inventory {
    private:
        // Actually stores the product
        void storeUnchecked(product p);
        ...
    public:
        // Validates that the product fulfills the requirements
        // If yes, passes down to storeUnchecked()
        bool store(product p);
        ...
}

Since adding a product can obviously fail if validation fails, you want to account for that by allowing your API to signal the success or failure back to the calling location.


Virtually all of your comments are visual noise. Comments should explain why things happen, not what is happening. If you can’t read the code to see what is happening, the code is not clear enough.

Use curly braces and whitespace consistently. Open curly braces don’t take a line by themselves. Put whitespace before the open curly brace.

Queue

Your class is called Queue but it is a Stack.

All your member variables should be private. Your methods should probably be public and not default scope.

queue should be final, since it’s never being reassigned.

top and bottom can have their base values assigned when they’re declared as member variables. top will be assigned zero by default if you don’t explicitly assign it, but there’s some disagreement as to whether that’s more or less clear.

size does nothing for you and can be removed. n should be renamed size.

x is a poor name for a char variable. Traditionally it would be c.

pop doesn’t need a variable in it. Just return this.queue[this.top++].

You should consider whether using ++ as part of your array index value is a good idea or if it makes the code hard to read. The code might be more clear if you separate the array indexing from the variable change.

The body if isEmpty() can be reduced to return this.top > this.bottom.

Your class will only work for one round of pushing and popping. The class breaks because bottom and top only get larger. To make the class reusable, you need only one variable which goes up and down as items are pushed and popped. You’ll still have out of bounds errors if they try to pop from an empty stack or push to a full one.

Main

Imp is a poor name for a method that reverses a String. Why wouldn’t you name it reverse?

Methods should start with a lowercase letter.

Your comment says Imp “reverses theString”, but it doesn’t. It reverses a StringBuffer.

Curly braces should never be treated as optional. That's a bug waiting to happen.

StringBuffer is thread-safe, and should really only be used in multithreaded environments for performance reasons. Prefer StringBuilder.

Unless there’s a reason you need to do the reverse in O(1) space, it would be more idiomatic to create a new StringBuilder and push the characters into that. Your method could accept a CharSequence, and interface which String, StringBuilder, and StringBuffer all implement. I’ll assume O(1) space is a hard requirement, since it would really be preferable to not mutate the input parameter.

n is a poor variable name. You don’t really need a variable there anyway, since you can just reference length() directly when you need it.

obj is a poor variable name. Variable names should describe what is being referenced. stack would be generic, but at least it’s a bit more descriptive.

You should declare i inside the scope of the for loop.

The ch variable does nothing for you and can be folded into the assignment.

If you were to apply all my suggestions, your Main class might look something like:

public class Main {

    public static void reverse(final StringBuilder characters) {

        final Stack stack = new Stack(characters.length());

        for (int i = 0; i < characters.length(); i++) {
            stack.push(characters.charAt(i));
        }

        for (int i = 0; i < characters.length(); i++) {
            characters.setCharAt(i, stack.pop());
        }
    }

    public static String reverse(final CharSequence charSequence) {
        final Stack stack = new Stack(charSequence.length());

        for (int i = 0; i < charSequence.length(); i++) {
            stack.push(charSequence.charAt(i));
        }

        final StringBuilder reversedCharSequence = new StringBuilder(charSequence.length());
        while (!stack.isEmpty()) {
            reversedCharSequence.append(stack.pop());
        }
        return reversedCharSequence.toString();
    }

    public static void main(final String args[]) {
        final StringBuilder a = new StringBuilder("bob");
        final StringBuilder b = new StringBuilder("eat too much");
        final StringBuilder c = new StringBuilder("I love greasy food");
        final StringBuilder d = new StringBuilder("FORTRAN 77 RULES");

        reverse(a);
        reverse(b);
        reverse(c);
        reverse(d);

        System.out.println(a + "\n" + b + "\n" + c + "\n" + d);

    }
}

and your Queue class might look something like:

class Stack {

    private final char[] stack;
    private int top = -1;

    public Stack(final int size) {
        this.stack = new char[size];
    }

    public char push(final char c) {
        this.top++;
        this.stack[this.top] = c;
        return c;
    }

    public char pop() {
        final char c = this.stack[this.top];
        this.top--;
        return c;
    }

    public boolean isEmpty() {
        return this.top >= 0;
    }
}


Naming

Your variables, class and methods aren't very well named.

The class Roundrobin1 should be Pascal case. It's also discouraged from using numbers in class names. If you are thinking of doing implementations of Round Robin, perhaps DefaultRoundRobin would be okay. If not, just RoundRobin is fine.

You have a local variable named Local. Variables should always be camel case to distinguish them from classes.

You also have a few inconsistencies such as timepassed, which should be timePassed, and waitingMAp which should be waitingMap.

It's not clear what the method mainL is supposed to do. Give it a more specific name.

Fields

Fields should be declared with the lowest access possible. Your fields can be private as they are not required outside of the class. Fields should be declared as final if you do not expect them to change.

Whitespace

Consider using it more liberally, especially between operators.

entry.getValue() > commonInt

is easier to read than

entry.getValue()>commonInt

Compound Statements

Specifically this line:

waitingTimeList.add(entry.getValue()>3?timepassed=timepassed+3:     (timepassed=timepassed+entry.getValue()));

has way too much going on. You could refactor it to:

timepassed += (entry.getValue() > 3) ? 3 : entry.getValue();
waitingTimeList.add(timepassed);

which is much more readable.

Magic Numbers

You have a few seemingly random 3s and 9s. Consider using constants (static final fields) with appropriate names.


A small app-crawler created using python

Good job improving the modularity of your code under reviews.

We can improve the following:

follow Python's naming convention and use camel-case style names for your classes
let's as usual reuse a Session instance
let's also use findtext() to get element texts
I would either use namedtuple for your "processor"s or use __slots__

Improved code:

from lxml import html
import requests

class AppScraper:
    start_url = "https://itunes.apple.com/us/app/candy-crush-saga/id553834731?mt=8"

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

        self.links = [self.start_url]
        self.vault = []

    def crawler(self):

        for url in self.links:
            self.get_app(url)

    def get_app(self, url):
        print("Scraping now "+ url)

        page = self.session.get(url)
        tree = html.fromstring(page.text)

        name = tree.findtext('.//h1[@itemprop="name"]')
        developer = tree.findtext('.//div[@class="left"]/h2')
        price = tree.findtext('.//div[@itemprop="price"]')

        item = Processor(name, developer, price)
        self.vault.append(item)

        p_links = tree.xpath('//div[@class="lockup-info"]//li/a[@class="name"]/@href')
        for p_link in p_links:
            if len(self.links) < 5:  # It'll stop crawling until it meets the limit whatever it is
                self.links += [p_link]

class Processor:
    __slots__ = ['name', 'developer', 'price']

    def __init__(self, name, developer, price):
        self.name = name
        self.developer = developer
        self.price = price

    def __str__(self):
        return self.name + " " + self.price + " " + self.developer

if __name__ == '__main__':
    crawl = AppScraper()
    crawl.crawler()

    for info in crawl.vault:
        print(info)


Shell command for the normal program termination of Skype from the command line

As the comments have pointed out, there exist tools to match processes by name. This is roughly equivalent (better than) what you're trying to do:

pkill skype

It's better because:

It's shorter and cleaner
It won't kill itself

By the second point I mean that ps -e | grep skype will match the grep process itself too. That won't happen when using pkill.

Code review

If we wanted to imitate pkill, I would suggest writing like this:

ps -e | awk '/[s]kype/ { print $1 }' | xargs kill

That is:

Replace two processes with one (grep + cut with awk)
Use [s]kype instead of skype is a common trick to make the awk itself not match
Drop -s term from kill, as TERM is the default signal anyway


Setting controller, action, and values based on the number of URL chunks

There seems to be some code repetition. Perhaps this could be improved like this:

if ($url_chunks_num >= 1)
   $this->controller = $this->pageData[0];
if ($url_chunks_num >= 2)
   $this->action = $this->pageData[1];
if ($url_chunks_num > 2)
   $this->values = array_slice($his->pageData, 2);

Or

if ($url_chunks_num >= 1) {
   $this->controller = $this->pageData[0];
   if ($url_chunks_num >= 2)
      $this->action = $this->pageData[1];
   if ($url_chunks_num > 2)
      $this->values = array_slice($his->pageData, 2);
}


This is a generally good solution. Pretty good adherence to naming conventions, and generally quite easy to read. It's probably just fine as it is, but if you do want to make it better, there are some improvements that can be made:

Extracting the outermost method

First off, we have:

static int[] LifeCycle(int[] input)

We know right from the start that for this method:

The processing of each individual element is independent from the processing of each other individual element
Operations performed on individual elements (calculating the growth of a tree) are non-trivial
Operations performed on entire collections (input and output) are trivial

So this is screaming to have the individual tree processing extracted out:

static int LifeCycle(int input)

Then the contents of your original method can be nice and concise, using LINQ:

static int[] LifeCycle(int[] input)
{
    return input.Select(i => LifeCycle(i)).ToArray();
}

Aside: Naming

Actually, now that we're here, extracting this method has brought into sharper focus that maybe the naming isn't ideal. input is extremely vague- why not lifeCycleCount, which is what you actually use it as inside the method? Likewise LifeCycle would be better as a description of something the method is doing, like CalculateGrowth.

Initializing the height

One of the uglier pieces of logic is the special case for the number of cycles being 0. Is that necessary? What are we actually getting at with this:

if (lifeCycleCount == 0)
{
    output[i] = 1; //no growth
}

If there aren't any cycles, there's no growth, so we go to the magic number 1. But where's 1 coming from? It's the starting height. Is that encoded somewhere? Yes! Just two lines later:

var treeHeight = 1;

But the starting tree height is 1 no matter whether the cycle count is 0 or not, right? So we can move that outside the if statement. And once we do, immediately it becomes clear the if statement doesn't need to be there at all. If the cycle count is 0, then the for loop will never be executed and you'll stay with the default value of 1, which is what you want.

There's a bit more inconsistency here too. Like you needlessly call Convert.ToInt32 on an integer, and in once place you assign it to a variable with another name (lifeCycleCount), and in another place you keep it as input[i]. This may be left over detritus if you refactored from passing in input as an array of strings.

Extract one more method

At this point, you could happily stop and you'll have a nice piece of code. But there's one more thing that may be an improvement. This:

if (j % 2 == 0)
{
    treeHeight = treeHeight + treeHeight; //Monsoon Growth
}
else
{
    treeHeight++; //Summer Growth
}

Looks to me like its own method. There's quite a lot of information here that the brain has to do some reading/calculation to work out:

The code alternates between executing the two blocks
The first block is always executed first of the two
Both blocks use the tree height as their sole input
The only effect of either block is to change the tree height
From the comments, both blocks represent tree growth

A method lets us encode a lot of that in a way that we can read right away:

static int GrowTree(int initialHeight, bool season)

Then, we can just call it inside the loop like:

treeHeight = GrowTree(treeHeight, j%2==0);

Now this reads much more clearly. The tree height is changing because it is growing, how much it grows depends on its initial height and the season, and the season alternates every time the loop is run.

There are other options with the alternation too which, depending on taste, you may find more readable. Like:

season = j%2==0;
treeHeight = GrowTree(treeHeight, season);

or

treeHeight = GrowTree(treeHeight, season);
season = !season;

(In both cases, season would be a bool initialized outside the loop)

Putting it together

And just so you can see how nice it is with all those changes, here's roughly what it would look like:

static int[] CalculateGrowth(int[] cycleCounts)
{
    return cycleCounts.Select(c => CalculateGrowth(c)).ToArray();
}

static int CalculateGrowth(int cycleCount)
{
    var treeHeight = 1;
    var season = true;

    for(int i=0; i<cycleCount; i++)
    {
        treeHeight = GrowTree(treeHeight, season);
        season = !season;
    }

    return treeHeight;
}

static int GrowTree(int initialHeight, bool season)
{
    return season ? initialHeight * 2 : initialHeight + 1;
}


Move two element of an array to the front - Javascript

Find the index of the green and red items, then remove them from the array with splice. Then you can make a properly ordered array by combining the removed items with the rest of the items in the original array:

const colors = [{name: 'yellow'}, {name: 'blue'}, {name: 'green'}, {name: 'red'}, {name: 'orange'}]
const removeColor = colorToRemove => (
  colors.splice(
    colors.findIndex(({ name }) => name === colorToRemove),
    1
  )[0]
);
const green = removeColor('green');
const red = removeColor('red');
const newColors = [green, red, ...colors];
console.log(newColors);

Or, without mutation (it's good to avoid mutation when not necessary, it can make code a bit more predictable in most cases):

const colors = [{name: 'yellow'}, {name: 'blue'}, {name: 'green'}, {name: 'red'}, {name: 'orange'}]
const getColor = colorToRemove => colors.find(({ name }) => name === colorToRemove);
const green = getColor('green');
const red = getColor('red');
const newColors = [green, red, ...colors.filter(({ name }) => name !== 'green' && name !== 'red')];
console.log(newColors);

Also note:

String literals require delimiters. {name: yellow} won't work - you want {name: 'yellow'}.
If you aren't going to reassign a variable name (most of the time you should be able to avoid reassignment), always use const. Only use let when you must reassign.
For readability, better to indent your code when entering a new block (such as a function).


Refactoring asynchronous JS pre-rendering code

Is this code hard to comprehend? Yes.

That is because there are a lot of unknown functions: view.render, page.fetchUnlessReady, token.catchItself ,token.throwIfCanceled or window.st.Helper.CancellationToken.getNone() etc. etc.

In my mind, I would approach this more like :

function scheduleRenderView( page )
{
  //Load and display the page
  var promise = model.loadPage( page ).then( function(){
    view.renderPage( model.getPage( page ) );
  });
  //Load the next page
  model.loadPage( page.next() );
  return promise;
}

loadPage would either return immediately if we retrieved already the data once ( from cache ) or download the page model.

getPage gets a page model from cache

renderPage would do the obvious

This means I would forego the pre-rendering which really sounds like pre-mature optimization, how long could that take?

2 other minor comments:

Why access some variables through window, that does not seem to make sense
In my mind, adding functions to the window.st.viewer.Helper is terrible global variable abuse, not to mention that you probably should add it to Helper.prototype.


Language switch based on parameters and session state

Yes.  Definitely.  You can use a lookup array.

$langs = [
    'en' => 'gb',
    'tr' => 'tr',
];

$defaultLang = 'it';

if (isset($_GET['lang'])) {
    $lang = strtolower($_GET['lang']);
    $_SESSION['lang'] = $langs[$lang] ?? $defaultLang;
} elseif (!isset($_SESSION['lang'])) {  // meaning, no $_GET['lang'] and no $_SESSION['lang']
    $_SESSION['lang'] = $defaultLang;
}
// if there is no $_GET['lang'] and there is a $_SESSION['lang'], then nothing to update

A lookup array is concise and a breeze to maintain.  You only need to update the lookup or the fallback value; never the processing block.

?? is the null coalescing operator, so if the lang value is not found in the lookup, the fallback value will be used.

If your php version is not over 7 (then I urge you to upgrade) then you will need a longer condition syntax.

$_SESSION['lang'] = isset($langs[$lang]) ? $langs[$lang] : $defaultLang;


Factory that chooses between factories based on XML element name

You can ignore and suppress this warning in your case. This warning is intended to force you to have Dictionary<TypeWithReasonableName1, TypeWithReasonableName2> instead of Dictionary<Action<int>, List<Enumerable<string>>>, but your code is readable enough and shall not produce confusion.


You can hugely reduce your __str__ using loops, e.g. using join() and a couple of generator expressions:

def __str__(self):
    return '\n-----------\n'.join('   |   |\n '+' | '.join(str(self.spaces[x]) for x in [0+y, 1+y, 2+y])+'\n   |   |' for y in [6, 3, 0])

Output:

   |   |
 x | x | x
   |   |
-----------
   |   |
 x | x | x
   |   |
-----------
   |   |
 x | x | x
   |   |


From a once over:

Naming

variable names should start with a lower case letter, unless they are constructors

Server -> server
Cpwd -> password

pwd contains all the connections, any reader would guess it contains passwords

More on variables

There is no good reason to have a separate array ip, since it always contains as many entries as pwd which already contains the the ip addresses in remoteAddress.
Having the password inside your scrip is ok for a prototype, it is not for production

Functions

You encapsulated sendMessage into a function, you should also have a leave or quit function and a joinChat function.

Flow

You announce that a user joins the chat before checking the password
In on 'end' you could just use indexOf on conn instead of manually looping over all connections.

Other than that I think you are doing fine with the asynchronous model of Node.


ASP.NET MVC using Repository pattern - code review

You code shows not only your definition of your repository but also it's usage.

What worries me is that i don't see how the DbContext (AddressBookDB in this case) is disposed off.

I think i'd rather pass in the AddressBookDB object as a paramter to the repository constructor for usage so you can ensure it is diposed off properly by creating it in a using block.


Read database from IO context and update UI from Main context in Kotlin

One thing that makes it kludgy is using GlobalScope, which is discouraged by the coroutines design lead. In this case, if this were a very long-running job, you would be leaking your UI elements because they are captured by the coroutine.
Also, since you are using Room, you can make your DAO's getAllWidgets() a suspend function, in which case, there's no reason to use a specific dispatcher to call it. A properly composed suspend function doesn't block the dispatcher it is called from, so you never should have to specify a dispatcher to call a suspend function. The proper way to do this would be:
private fun updateList() {
    getListJob = lifecycleScope.launch {
        widgetList = db.widgetDao().getAllWidgets()
        val recyclerView = findViewById<RecyclerView>(R.id.deck_recycler_view)
        var widgetListAdapter = WidgetListAdapter(widgetList)
        recyclerView.adapter = widgetListAdapter
        widgetListAdapter.notifyDataSetChanged()
    }
}

No Dispatcher specifying needed at all, because the coroutine doesn't call any blocking code and lifecycleScope defaults to Dispatchers.Main.


You can do this with jQuery.map extremely elegantly as the function allows you to do a filtered map (.map excludes any item when you return null or undefined). As $.map produces an array you can then just use Array.prototype.join and get the same output as our original code. If you want to add a period to the string after that then you can check if your string isn't empty, append a period and be on your way.

var text = $.map(obj, function(val, key) { if(val) return key; } ).join(", "); //Create an array of an objects keys where its value is truthy. Next, join the keys.
if(text !== "") text += "."; // Append a period if not an empty string

$(self).append(text);

Also you should reconsider using a try catch block around the JSON parsing as you shouldn't expect that to fail without good reason.


Can I improve this progressive enhancement?

I believe this is more trouble than it is worth. You may be shooting yourself in the foot since your complicated solution might not work as you expect for the different configurations you want to support. Designing for accessibility is not only "turn off CSS and JS and see how it works out", but "test that my code works for all these settings". I believe you're doing it wrong here.

A simple proposal

Did you consider the simplest approach?

My Course Name
  ✎ ✕

CSS:

.tools { float: right }

This is going to work for CSS haters (?), old browsers and lynx. As for "accessibility users", most of them use real browsers, but need bigger fonts or high contrast designs. This means that my solution will not work only for speech synthesis (the speech synthesis of Google Translate skips complicated Unicode characters) but will work on any normal browser (even if the old-old browsers doesn't understand "float", the Unicode symbols will be displayed next to the course title).
The title attribute (thanks to ANeves) will help confused users hovering on the icons! I do this all the time for StackOverflow icons. This is great accessibility for normal users, but probably won't help for speech synthesis and the like.
Extra bonus: the CSS is simple to understand

I don't know how well your width:1em trick is going to work on browsers. It might be perfect, but it might not work as you expect at all.

If you really care about speech synthesis and make sure that your website really supports it (eg. do you follow the Web Content Accessibility Guidelines?), then go on with your solution as long as it doesn't hurt other users.

(Also note that you're using a multiplication mark, why not using something like "BALLOT X" which I feel has better semantics and might be rendered in a way that might make it look better http://en.wikipedia.org/wiki/X_mark ?)

Update: added a title attribute, as ANeves proposed in comments.


I can't really judge if it's a good idea, but one way could be creating an NSArray (or NSSet) containing NSDictionaries with the keypaths that should be compared, and then enumerating through that. Something like this:

#define keyOriginal = "original"
#define keyComparisonItem1 = "comparisonItem1"
#define keyComparisonItem2 = "comparisonItem2"

    NSMutableArray * evaluations = [NSMutableArray array];

    [evaluations addObject:@{keyOriginal : @"idag3_orig", keyComparisonItem1 : @"idag2", keyComparisonItem2 : @"idag3"}];
    [evaluations addObject:@{keyOriginal : @"igar3_orig", keyComparisonItem1 : @"igar2", keyComparisonItem2 : @"igar3"}];
        // and so on...

    for (NSDictionary * evaluation in evaluations) {

        if ([statisticsObject valueForKey:keyOriginal] != 0) {
            tmp = (int)[statisticsObject valueForKey:keyOriginal];
        } else {

            tmp = [self compareValue:[statisticsObject valueForKey:keyComparisonItem1]
                           withValue:[statisticsObject valueForKey:keyComparisonItem2]];
        }

        [self formatText:[statisticsView valueForKey:keyOriginal]];

    }


Better filereading and print formating in R

This should not be a complete review, but the base R function round has an optional second argument digits. It works like this

> round(1.234567, digits=1)
[1] 1.2
> round(1.234567, digits=2)
[1] 1.23

Therefore there is no need for your function f.


Parameter checks

First of all, I'd be very strict about the check of the parameters: I do not see any use in gracefully trying to work around unset or illegal parameters instead of throwing an exception.

Thus, I recommend you start out with:

    Objects.requireNonNull(type);
    Objects.requireNonNull(scope);

These throw NullPointerException if the respective parameter is null. This is the clearest way to tell your user that this was unexpected. (If you use some kind of validation framework like javax.validation, you might even annotate the parameters as @NotNull).

Furthermore, I recommend IllegalArgumentException for illegal types instead of returning null.

DRY

Then, you repeat yourself with the check scope.equalsIgnoreCase("singleton") - you could refactor that into a variable.

switch

String comparisons can be done via a switch statement. To be case-insensitive, you can switch over toLowerCase of the string and use lowercase constants.

delegate to specific methods

Last advice: move the concrete object creation to specific methods for objects, and simply call the sub-method from the main method.

Putting it all together

public Shape getShape(String type, String scope) {
    Objects.requireNonNull(type);
    Objects.requireNonNull(scope);
    boolean isSingleton = scope.equalsIgnoreCase("singleton");
    switch(type.toLowerCase()) {
    case "circle":    return getCircle(isSingleton);
    case "rectangle": return getRectangle(isSingleton);
    case "square":    return getSquare(isSingleton);
    default: throw new IllegalArgumentException("unknown type");
    }
}

private Shape getCircle(boolean inSingletonScope) {
    return inSingletonScope
        ? SingletonCircle.getInstance()
        : new PrototypeCircle();
}

...


You are storing the board state as a HashMap[(Int,Int), Boolean].  Why not store it as a Set[(Int,Int)] instead, containing only the live cells?  Alternatively, if you want to list every cell, whether dead or alive, a two-dimensional array seems like it would be more appropriate and efficient.

You're using a mutable HashMap.  An immutable HashMap would be a more natural fit for the Game of Life, and would also promote good functional programming practices.  You're already calling val cp = cells.clone followed by cells = cp in doCycle, which indicates that each generation involves building a new board state.

For comparison, I have written an implementation that uses immutable structures and functional programming.


Correct way to refer to a view in Android

The first is a sequence of method calls, the second is a method call chain. They are equivalent, so both are correct.

Which way is better really depends on the rest of your code.
For example, instead of this:

((TextView) rootView.findViewById(R.id.text)).setText("Some Text");
((TextView) rootView.findViewById(R.id.text)).append("more text");
((TextView) rootView.findViewById(R.id.text)).setOnClickListener(...);

This is clearly better:

TextView textView = (TextView) rootView.findViewById(R.id.text);
textView.setText("Some Text");
textView.append("more text");
textView.setOnClickListener(...);

It's better, because this does only one lookup in rootView, and it's also more compact.

On the other hand, if you only use the TextView once, then the chained call version is better, because you won't pollute your local scope with a variable you only use once, and it's more compact.

Sometimes I split chained calls for debugging purposes:
it can be hard to see which step failed in a long chain,
and easier to follow the execution step by step.


Code Review

Never use C cast

The C cast is dangerously hard to spot. In C++ we have replaced this with four distinct cast operators that all do slightly different things. They are very easy to spot (as you should not really be doing cast anyway and when you do we want to be able to spot it easily for code review).

            bin.push_back((char)('0'));

So if this was C++ that would use the static cast.

            bin.push_back(static_cast<char>('0'));

But not really. Anything that is in single quotes '0' already has a type of char so you don't actually need to cast it.

            bin.push_back('0');

Also in this situation. you only push back one character. So why not just use assignment in the first place.

            bin = "0"; // much more clear.

Actually there is no need to even use the variable bin. In the next line you can simply push back a literal string.

            binrep.push_back(bin);

            // why not just
            binrep.push_back("0");

Use C++ classes where you can.

        while (n > 0) {
            rem = n % 2;
            bin.push_back((char)('0' + rem));
            n /= 2;
        }

So you are building a binary version of the number in a string. Easier way to do that using std::bitset.

        std::bitset<8> value(n);
        bin.push_back(value.to_string()); // You may need to reverse
                                          // or something I did not pay
                                          // full attention to what you
                                          // were doing.

When looping over containers use the range based for.

    for(i=0;i<N;i++){

    // can be replaced by this.
    for(auto const& item: binrep) {

Look for standard algorithms where you have a loop:

This looks like you are counting.

                while (binrep[j][k] !='\0'){
                    if(binrep[j][k]=='1')
                        count++;
                    k++;
                }

                // I think it may have been easier to write:
                count += std::count(std::begin(binrep[j]), std::end(binrep[j]), '1');

This is also self documenting as you can see what you are doing. The algorithm is appropriately named to make your actions obvious.

###BUG

            binrep[i][k] != '\0'

You can not look for a terminating \0 on a C++ std::string. Accessing beyond the end of the string is undefined behavior. If you want a C-String version to loop over you need to call c_str() on the object (but better to use a range based for.

Style

A lot of this (style) is preference and dependent on your team. I think it is important for the community to be consistent and have describes some common practices below. Others will inevitably disagree as this is opinion, refer to your teams style guide.

But your horizontal spacing (it does not exist) makes your code hard to read it is all packed together horizontally. It just makes the code horrible (and thus harder to read). Technically nothing wrong with that, but the whole point of coding is to make it easy to read for the next human that has to decipher your code.

for(i=0;i<N;i++){

// I would write it like this:

for(int i = 0; i < N; ++i) {

Your usage of braces ( {} ) is inconsistent. Neither version is wrong. But using two different styles is jarring (and again makes it hard to read).

        while (n > 0) {
            // STUFF
        }

   // and

        while (binrep[i][k] != '\0' && binrep[j][k] !='\0')
        {
        }

Always indent sub-blocks and always use braces {} around sub blocks.

        // Not indenting the sub block makes it hard to read.
        while (n > 0) {
        rem = n % 2;
        bin.push_back((char)('0' + rem));
        n /= 2;
        }

        // Not using braces opens you up to maintenance problems.
        // larger than needed modifications when a bug is fixed.
        // thus reduced readability in the change log.
        //
        // There are also corner cases that are going where not
        // using the braces are going to be an error so prefer
        // to use them.
        if (binrep[i][k] != binrep[j][k])
            count++;

Declare variables one per line and at the point where they are used. This makes it easier to check types of local objects, and becomes much more important when your types have constructors and  destructors.

    // Also the inconsistent use of space is jarring.
    int i,j, rem, n;

Variable names. Please use them. Modern code is supposed to be self documenting. So reading the variable name and how it is used is supposed to help me to understand the context of the code.

    // I have no idea what these do (rem: short for remainder?)
    int i,j, rem, n;

    for(int loop = 0; loop < size; ++loop) // Its a loop.

With naming. It's traditional to use an initial upper case letter for user defined types while an initial lower case letter is used for objects (variables/functions). This is important in C++ because types are so much more important than in C. We want to understand when we are referring to a user type and when we are referring to an object (the distinction is important and the use of visual cues can help make the code self documenting).

NOTE: The use of identifiers that are all uppercase is still (even in C++) traditionally reserved for macros. You should avoid their use for other things. N is an all uppercase identifier.

Pick a style and be consistent. Consistency is key in making code that is easy to maintain.


Let's go through your questions.

No, it does not contradict the idea.
The base class should define the common functionality of the derived classes, that's needed by some system to operate on such objects. However, part of the code of that system, or a different part of the code base may be dedicated to working only with some of the derived classes, in which case the functions and variables should not be defined in the base class.
Using your example, a rendering system may require a Render() method and variables  defining the visual characteristics of a shape, which should be part of the colored shape interface. On the other hand, a system that works with shapes that have corners will not be expected to work on circles. In which case you would dynamic_cast a shape to the derived type in that system and call the methods specific to the derived class.

Depending on the debugger you're using, you are probably using a watch window to view the values of the circ variable. The watch window will display circ as a variable of type ColoredShapePrototype*, which only has a color variable.
In Visual studio, for example, watch window will allow you to cast the variable to a ColoredCirclePrototype*, by typing (ColoredCirclePrototype*)circ. You will then see the radius member of circ.

Smart pointers avoid common problems with managing dynamically allocated memory. unique_ptr specifically avoids leaks by deallocating the memory at the end of the scope, unless it is moved to another unique_ptr. If the clone() function returns a unique_ptr, this means the user of your prototype pattern code won't need to bother remembering to dealocate the memory. However, you are enforcing him to use a specific implementation of a smart pointer, in this case the standard library's unique_ptr. If this prototype pattern is part of a library and used in a project that has a different implementation of unique_ptr, it can become more complicated to manage this difference than if you return a plain raw pointer.

If a derived class has members that need to be deep copied, then that class needs to define a copy constructor that performs the deep copy.

My feedback

The most significant issue I see is that someone else can further derive a class from your derived classes, and there's nothing to remind them that the clone method needs to be overriden. Let's consider creating a ColoredSquarePrototype that inherits ColoredRectanglePrototype. If we create a square object and try to clone it, we would call the ColoredRectanglePrototype::clone() which copy constructs a rectangle, not a square. This is not easy to solve, one option is to declare your derived classes final, so they cannot be further derived. If you wish to allow derivations, you could read further about the issue in this blog post: https://katyscode.wordpress.com/2013/08/22/c-polymorphic-cloning-and-the-crtp-curiously-recurring-template-pattern/
I don't see the benefit of providing a default constructor in
ColoredShapePrototype, it just allows the usage of shapes with an
unitialized color ("").
You should pass a const string& to the constructors to avoid copying.
Removing "Prototype" from the name of the shape classes will convey better that these classes represent actual shapes instead of some auxiliary implementation.
The virtual void UpdateColor(int color) incorrectly takes an integer parameter instead of a string. This compiles, because the integer is converted to a char for std::string::operator=(const char) to be invoked.


Three "alias-functions" in my .bashrc file

You never validate the contents/existence of $1

for instance: grep -v "" "$HISTFILE" returns nothing, so you're deleting your entire history.

You might want to use set -x, set +x instead of echo-ing the commands about to be done.


I would have some suggestions for improvements regarding C++ in general (I'm not familiar with embedded systems).

Indentation

Make sure to use uniform indentation across the code, in order to make it more readable. (E.g., the do-while loop, the switch-block in the main method should be at the same level as the declarations at the beginning.)

Code organization

It is very good, that manual mode and default mode are two separate functions. Breaking down the code makes it easier to read. I would also export some other parts to separate functions, especially the main cycle. (Remark: this is a generic principle. It might be that in the context of embedded systems there are some further considerations, which I'm not aware of, e.g. that code should be as fast as possible, for which this advice does not apply. Please consider this.)

Variable initialization

I would initialize each variable explicitly to some default value (e.g. 0), even if it is sure to be initialized later. In this way, you can for sure prevent undefined behavior (e.g., in case the code gets modified later, and a path is introduced where the variable is not initialized anymore).

Control flow

In the do-while loop for the washing-cycle, startPause is read, but then, at the end of the loop, it is set to a constant value (independently of what has been read). So this loop only runs once. I think either the whole logic should be removed, or improved in a way that looping really depends on the input value.

Input validation

In more places, input is required from the user, but it is never checked if it is within the range of the allowed values. In a production system this would be a must, but also in your case, I would clarify if this is required.


You're not consistent with your private fields:

private readonly Dictionary<string, string> configValues = null;
private readonly FileInfo configFile = null;
private readonly ILog _log = null;
private bool _initialized = false;

Several things:

If you're going to use an _underscore prefix, then don't use a redundant this qualifier to refer to the field names later: it defeats the purpose.
If you're not going to use an _underscore prefix for private fields, then don't use one for any private field. Be consistent. Either you this or you don't.
The 3 readonly fields are initialized in the constructor. Why are they also statically initialized then?
Why bother initializing a field to its default value? Reference types are null, and a bool is false by default. The static initialization is redundant.

    private readonly Dictionary<string, string> _configValues;
    private readonly FileInfo _configFile;
    private readonly ILog _log;
    private bool _initialized;

    public ConfigManager(string filePath)
    {
        _configValues = new Dictionary<string, string>();
        _configFile = new FileInfo(filePath);
        _log = LogManager.GetLogger(typeof(ConfigManager));
    }

The first condition in the Initialize method could be inverted to eliminate a whole level of nesting:

if (_initialized)
{
    return;
}

This has the added benefit of avoiding a redundant assignment, since you don't need to set _initialized to true when it's already true.

Don't do this:

Environment.Exit(Environment.ExitCode);

The configuration manager shouldn't be allowed to terminate its client. That's a big, huge no-no right there.

Instead, throw some ConfigurationUnavailableException and let the client code deal with it - if it wants to terminate when configuration is unavailable, let it do so. If it wants to work off default values, allow it to do so. Don't just let that one component pull the plug because it's not happy with the execution path!

This isn't useful either:

catch (Exception)
{
    Console.WriteLine("opppppps");
}

I'd let System.Exception bubble up here, and catch a more generic System.IOException after dealing with the FileNotFoundException - perhaps the file was found, but the logged-in user can't read-access it?

Ideally you would just catch IOException and log the exception type instead of... wait a minute. That's not a logger, it's a console wrapper! How confusing!

this._log.Error("Unable to find the config file.\nPress any key to exit.");
Console.ReadKey(true);

Does the user-friendly message get output to the Console? If so, then what do you need ILog for? Your class is already coupled with System.Console! Or it's a logger, but you're assuming the output is configured to go to the console? Logging shouldn't interact with your code in any way, and seeing "press any key to exit" in a log file is a bit awkward.

I think I'd do this instead:

try
{
    // load configuration
}
catch(Exception exception)
{
    _log.Error(exception); // assuming overload that takes an exception.
    throw new ConfigurationUnavailableException(exception);
}

So we get a log trace of the actual exception, and bubble it up to the caller via a new ConfigurationUnavailableException that can be caught and dealt with at the call site, which would be responsible for the "press any key to continue" part.


Reducing code complexity for UsergridClient constructor

The variable self here is redundant.

The parameter name "opts" is significantly less commonly used than "options".

It is not clear immediately what can be supplied in opts. Inferring how the function can be called from the logic of the code is error-prone.

The code implies that the various optional properties might be in one of two locations, or missing. I would ensure that callers position these values in one location for the call, making testing simpler.

The objectkit library is so verbose as to obfuscate the code quite effectively.

Simply ensure the property exists and negate the need for the getIfExists at all.

Setting default values where none is supplied can be performed easily with Object.assign polyfills and similar libraries.

The following appear to always be the same, if so, do they need to be own-properties?

self.paginationPreloadPages = 0 // number of pages to preload
self.paginationCacheTimeout = 300 * 1000 // default: 300 seconds

The following check should be at the start of the function to short-circuit all the work:

if (self.orgId !== undefined && self.appId !== undefined) {

none and app are magic strings that should be pulled into a single enumeration object.

return self is redundant if the intention is to use this as a constructor function.

So applying these changes:

var AuthFallback = {
    APP: 'APP',
    NONE: 'NONE',
};

var defaultOptions = {
    orgId: null,
    appId: null,
    baseUrl: 'https://api.usergrid.com',
    clientId: null,
    clientSecret: null,
    tokenTtl: 3600,
    authFallback: AuthFallback.NONE,
};

function UsergridClient(options) {
    if (!options || !(options.orgId && options.appId)) {
        throw new Error('options.orgId and options.appId required.');
    }

    Object.assign(this, defaultOptions, options); // or polyfill
}

UsergridClient.prototype.paginationPreload = 0; // pages.
UsergridClient.prototype.paginationCacheLifetime = 300 * 1000; // ms.
UsergridClient.prototype.paginationCursors = []; // Not sure about this one...


Extracting grouped objects into a flattened list

As commented, the ES6 spread operator flattens like you want.  The syntax is a little weird for multiple invocations:

result = [].concat(...[].concat(...data.map( d => d.groups.map( g => g.configurations.map( c => ({id:c.id, code:c.code, value:c.value}))))))

The arr.flat() method does the same thing more simply.  It takes an optional depth argument to indicate how many levels to descend when flattening.  In your case, depth is 2.

.flat is a recent feature that may not exist on your platform.  Most notably, Node 10 and MS Edge do not have it, while both of those do have the spread operator:

data.map( d => d.groups.map( g => g.configurations.map( c => ({id:c.id, code:c.code, value:c.value})))).flat(2)


Our constructors would be better as failable initializers.

Nothing prevents us from passing a wrapped NSNumber to the String initializer, or a wrapped String to the Int initializer.  In your code, this would simply crash.  It would be better if our initializers were allowed to fail.

First, we need to change the protocol to define a failable initializer rather than a non-failable initializer:

public protocol UserDefaultsValue {
    var userDefault: UserDefaultsObject { get }
    init?(UserDefaultsObject)
}

Now, write the initializers as failable:

extension Int: UserDefaultsValue {
    public var userDefault: UserDefaultsObject {
        return NSNumber(integer: self)
    }
    public init?(_ object: UserDefaultsObject) {
        if let number = object as? NSNumber {
            self = number.integerValue
        } else {
            return nil
        }
    }
}

We can clean up our UserDefault constructor a bit as well.

if let object: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey(key) {
    let userDefaultsObject = object as! UserDefaultsObject // this is the crucial line
    store = T(userDefaultsObject)
}

Like our initializers which should be failable, this runs the risk of crashing if object turns out to be some type which isn't a UserDefaultsObject.  We can clean this up slightly though.  This can look cleaner and be safer:

if let object = NSUserDefaults.standardUserDefaults().objectForKey(key) as? UserDefaultsObject {
    store = T(object)
}

The conditional will fail if:

There isn't already an object for this key.
Whatever NSUserDefaults returns for this key cannot be interpreted as a UserDefaultsObject.

There is one major concern I have, however, and I don't know of the right solution right now.

Consider the following situation, I save an NSNumber object to the key "abckey".  Now, I do this:

let s = UserDefault(key: "abckey", defaultValue: "Hello World")

In your version of the code, this will happen will crash because this line:

let userDefaultsObject = object as! UserDefaultObject

Will have no problem converting an NSNumber to a UserDefaultObject (assuming you fixed it with extension NSNumber: UserDefaultsObject {}), but the following line will be problematic:

store = T(userDefaultsObject)

Because the type of T will be a String (we passed a String for defaultValue argument).

Our extension String: UserDefaultsValue will have to include several constructors which take every sort of possible thing that can be stored in NSUserDefaults.  And some of those simply won't make sense.


C# handling of images - is this best for memory usage?

Reversing the condition of if (originalImage != null) and returning early will remove one level of indentation. The less indentation some code shows the easier to read it will become.
catch to just rethrow, althought you did it in the correct way, doesn't buy you anything. Just remove the try..catch..finally and enclose the usage of graphics with an usage block.
Althought the code is mostly named well, one could stumble over tempPhoto and can't figure out at first glance wether this object is important or just temporary.
You can cast e.g ((width - (sourceWidth * percent)) / 2) directly to int you don't need a call to Convert.ToInt16() here.
percentW and percentH are first defined and on the next lines you assign a value to them. You should do it just at the declaration to save some (superflous) lines of code.
Instead of graphicController.FillRectangle(Brushes.White, 0, 0, width, height); you should use graphicController.Clear(Color.White); which is easier to read.
Comments, when used, should state, in a clear and understandable way, why the code is written as it is. I don't get the comment // The chances of hitting this ONE SPECIFIC COLOR are very slim. Where could be a problem with the code to make this comment justified?
The code validates the Image originalImage method parameter, but allows "illegal" values for int width and int height.

Implementing most of the mentioned points (validation is for you) will lead to

public static Image ImageToFixedSize(Image originalImage, int width, int height)
{
    if (originalImage == null) { return null; }

    int sourceWidth = originalImage.Width;
    int sourceHeight = originalImage.Height;
    int destX = 0;
    int destY = 0;

    float percent = 0;
    float percentW = width / (float)sourceWidth;
    float percentH = height / (float)sourceHeight;

    if (percentH < percentW)
    {
        percent = percentH;
        destX = (int)((width - (sourceWidth * percent)) / 2);
    }
    else
    {
        percent = percentW;
        destY = (int)((height - (sourceHeight * percent)) / 2);
    }

    int destWidth = (int)(sourceWidth * percent);
    int destHeight = (int)(sourceHeight * percent);

    Bitmap fixedSizedImage = new Bitmap(width, height, PixelFormat.Format24bppRgb);
    fixedSizedImage.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);

    using (Graphics graphicController = Graphics.FromImage(fixedSizedImage))
    {
        graphicController.Clear(Color.White);

        // The chances of hitting this ONE SPECIFIC COLOR are very slim
        graphicController.SmoothingMode = SmoothingMode.HighQuality;
        graphicController.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphicController.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphicController.CompositingQuality = CompositingQuality.HighQuality;

        graphicController.DrawImage(
            originalImage,
            new Rectangle(destX, destY, destWidth, destHeight),
            new Rectangle(1, 1, sourceWidth - 1, sourceHeight - 1),
            GraphicsUnit.Pixel);
    }

    return fixedSizedImage;

}


Came across this post as I was answering the same question in this book. My approach was also similar in solving this. I will post what I found
as an answer since I cannot comment.

First, I think the or condition for checking the terminating
node is incorrect. It should be a and condition to my understanding. I think we need to identify whether the current node is a leaf node before
updating depths.
For the following tree this would give a max depth of 3 and min depth of 1, which is incorrect. I did this in C++ as shown below.

      5
     /  \
    4    7
   /    / \
  1    6   8
 /
0

 void FindMinMax(int &min,int &max,Node *np,int height)
 {
     if(np==NULL) return;
     FindMinMax(min,max,np->left,height+1);
     FindMinMax(min,max,np->right,height+1);

     if(np->left==NULL || np->right==NULL)
     {
         if(min>height) min = height;
         if(max<height) max = height;
     }
 }

Second, I am not sure whether there are differences in the versions.
In my book the question 4.1 is about checking whether a binary tree is balanced. This is defined as

  heights of the two subtrees of any node never differ by more than one

If this is the requirement I think this algorithm won't work.
Check the first two answers of this question. I think this algorithms checks whether the difference between farthest and closest leaves from root differ by more than one.

Edit: Here I assumed min max corresponds to maximum and minimum depths to leaf nodes.


Python: Parse string of bracketed list items into list of strings

A Regex based solution
>>> my_string_one
'[A][B][C]'
>>> re.split(r"\[([A-Z])\]", my_string_one)[1:-1:2]
['A', 'B', 'C']
>>> my_string_two
'[A][B][C][D][E]'
>>> re.split(r"\[([A-Z])\]", my_string_two)[1:-1:2]
['A', 'B', 'C', 'D', 'E']

You can use re.split with the expression \[([A-Z])\ having a capture group for the uppercase letters. This is under the assumption that your strings always follow this pattern otherwise you may not get what you expect.


Time complexity is \$O(nm)\$. Obviously it is bound to TLE. There is an \$O(n)\$ solution, based on the following observations:

\$ x \oplus x = 0\$
\$ x \oplus y = y \oplus x\$

Let's say your initial row is a b c d e f. The next row will be a^f b^a c^b d^c e^d f^e. The second next is more interesting: the first element is a^f ^ f^e = a^e, the second is a^f ^ b^a = b^f, etc.

In general (prove it by induction), \$k\$'th row consists of \$a_i \oplus a_{i-k}\$ (where the last index is taken modulo n). Notice that the \$n\$'th row is all zeroes, and so are all the subsequent rows.
The code is extremely hard to follow. num is only used once - may be not have it at all?

    last = xor[0];

    for(int i=0 ; i<xor.length ; i++){
        if(i<xor.length-1){
            xor[i] = xor[i]^xor[i+1];
        }
        if(i==xor.length-1){
            xor[i] = xor[i]^last;
        }
    }

Notice that i == xor.length - 1 is true exactly once, at the predictable i, yet you test it at each iteration. Lift it out of the loop:

    last = xor[0];
    for(int i=0 ; i<xor.length - 1; i++){
        xor[i] = xor[i]^xor[i+1];
    }
    xor[i] = xor[i]^last;


Loading a pseudo-class instance from JSON

Instead of eval, you could create a Person constructor that accepts an object:

function Person(arg)
{
    if (typeof arg === 'string')
    {
        var name = arg;
        this._type='Person';
        this.name=name;
    }
    else if (typeof arg === 'object')
    {
        var value = arg;
        for (var prop in value)
        {
            if (value.hasOwnProperty(prop))
            {
                this[prop] = value[prop];
            }
        }
    }
}

// Move Person.hello() into the prototype
Person.prototype.hello = function()
{
    alert('Hello '+this.name);
};

Then use the _type to choose a constructor based on a predefined set of classes, rather than a (potentially) unsafe eval:

var classes =
{
    Person: Person
    /* other potential classes to deserialize from here as well */
};

function object_to_instance(key, value)
{
    if (!value._type) return value;
    return new classes[value._type](value);
}

var people = [new Person('Harry'), new Person('Sally')];
var people_json = JSON.stringify(people);
var new_people = JSON.parse(people_json, object_to_instance);
new_people[0].hello();

Basic demo: http://jsfiddle.net/mattball/VfRJn
Using multiple classes: http://jsfiddle.net/mattball/VfwRv


Modifying stress markers in Cyrillic words

Normally I would look at the PHP manual and make sure you aren't recreating a function that already exists, but I have no experience with non ASCII characters so i don't feel comfortable with the terminology to look this up. I would suggest that you make sure of this though. This sounds like something that might already exist somewhere. As to your function, there are a few things that jumped out at me.

First are those references. They are a powerful tool, but I would be careful using them. They are relatively difficult to spot and not everyone knows what they do. Sometimes its better just to use plain return statements, but that is something you will have to decide based on the scope of this project. If its something that isn't likely to be used by others, then this is fine, otherwise you might think about changing it.

When incrementing a variable by more than one, a more elegant way of doing so is by using the following syntax. By the way, where did the five come from? Unless cyrillic always has three digit entities, then you run the risk of missing some of the escape sequence. For example nbsp is a four digit entity. I would use strpos() or something similar to find the position of the semicolon instead.

$i += 5;

$stressLetter and $cleanWord definitions are redundant. You set them to the same values before the function was called. The only reason this would be necessary is if you revert back to using a return value instead of references, and then you should remove those parameters from the parameter list and from the procedural code before the function call.


The overwhelming first impression I get from your code is that without the text description above, I wouldn't have a clue what it is you're trying to do.  A lot of these types of problems have some kind of prompting which helps, however your code doesn't have that, its only output is time after it's finished.

The two main improvements I'd suggest are:

Put your code in a function that defines an interface.
Use variable names that have some kind of meaning.

Implementing these two basics would go a long way to making your code easier to follow.

For example, your vector v might be people?!?

You could have a method calculate_minimum_time_to_cross_bridge, which took in a list of people and returned the time.

Whilst your variable names might have meaning to you, they have no meaning a new reader without context.

One final point is that whilst you can do this:

vector<int> v; int n; int time;

It's generally considered bad form.  One declaration per line means the declarations are less likely to get lost.


Mergesort implementation, eliminating slice()

Alternative ?
Not to sure what you mean by alternative solution. A merge sort is a merge sort and you need to create arrays, via slice, manually, or even creating a buffer and managing virtual arrays will all incur some overhead.
Your code.
If you want to improve performance then there is plenty of room for an improved alternative to your code.
Your recursive function is inherently a poor performer but it outperforms the iterative function because the iterative function does not use a stack to optimize data processing.
Your merge function is somewhat sloppy and can be improved, it is the core of the functionality of the sort. You gain the greatest benefit via improvements in the merge function. Even greater improvement if you can side step the need to call it as often.

Recursion, a glorified stack.
In Javascript recursive code has a large overhead. Each call creates a new context that is pushed to the heap. You also can never know how deep you are in the call stack, so a recursive function is always at risk of a call stack overflow.
Recursion is in reality just a way to implement a stack. Each recursion pushes the current execution state to the stack and create the new one. Each return disposes the current state and pop the previous one of the top of the stack.
Many people forget this when writing recursive code, and don't realize that the state stack can many times be more efficiently implemented as a simple stack using a JavaScript array.
Another very common mistake in recursive code is the exit condition. Stepping into a function is expensive and should be avoided.
Annotated your code to show what I mean

function mergeSortRecursive(arr) {

   // the exit from recursion one step too deep
   if (arr.length <= 1) {
      return arr;
   }

   var leftArr =  arr.slice(0, arr.length/2);
   var rightArr = arr.slice(arr.length/2);

   // You know at this point if both recursions are going exit early
   // because the array lengths are <= 1. You should just skip the
   // recursion here rather than inside the next two calls
   var leftSorted = mergeSortRecursive(leftArr);
   var rightSorted = mergeSortRecursive(rightArr);

   return merge(leftSorted, rightSorted);
}

The merge function
Inside the while loop of the merge function you are doing too much. Each 2 values that need to be compared have the overhead of two if statements. They are true only when the loop is ready to exit. The loop should only deal with the comparison of two values and after the loop you can clean up by adding the remaining array content to the result.
Improving the merge
Remove the unneeded if statements and put them after the loop.
function merge(left, right) {
    const result = [];
    while (left.length && right.length) {
        result.push((left[0] <= right[0] ? left : right).shift());
    }

    if(left.length + right.length){
        result.push(...(left.length > 0 ? left : right));
    }
    return result;
}

Side step merge.
I you inspect the running of the code and the array sizes that merge merges you will notice that 50% of the merges are of two arrays each of length 1. In effect you are using the complicated merge function to sort two numbers.
You can side step the merge function for array sizes 1 with the following
The recursive modification
function mergeSort(arr) {
    var len = arr.length / 2;
    if (len < 1) { return arr }

    // the following avoids stepping one too deep into the recursion as well
    if (len === 1) { // if array sizes 1 then skip the merge
        return arr[0] < arr[1] ? [arr[0], arr[1]] : [arr[1],arr[0]];
    }

    return merge(mergeSort(arr.slice(0, len)), mergeSort(arr.slice(len)));
}

For the iterative function you can map pre-merged values
var split = [];;
for(var i = 0; i < arr.length-1; i+= 2){
    split.push(arr[i] < arr[i+1] ? [arr[i],arr[i+1]] : [arr[i+1],arr[i]] )
}
if(arr.length % 2) { splitArr.push([arr[arr.length -1]]) }

Implementing an iterative stack.
If you count the number of times you need to compare 2 values the recursive function does about 10% less than the iterative function. But that can be changed by making the iterative function act like a recursive function.
The splitArr replaces the call stack and heap, and holds the merged arrays. When there are no more items to merge in splitArr the job is complete.
Note turns out a queue is quicker than a stack in this case but the idea is the same
function mergeSortIterative(arr) {
    const stack = [];
    for (var i = 0; i < arr.length - 1; i+= 2) {
        const ii = i + 1;
        stack.push(arr[i] < arr[ii] ? [arr[i], arr[ii]] : [arr[ii], arr[i]] )
    }
    if (arr.length % 2) { stack.push([arr[arr.length -1]]) }

    // the loop replaces the recursive function
    while (stack.length > 1){
        stack.push(merge(stack.shift(), stack.shift()));
    }
    return stack[0];
}

Now you have an alternative solution without a slice in sight, improved memory and CPU use because you can avoid the recursive over head, and a reduction in the overall complexity by turning many of the merge call into simpler single statement sort.


Request review of sql validation trigger

Your code is correct as long as you plan to validate business integrity using triggers.

But I would question whether business validation in SQL Server is a right choice:

You have no means (other than parsing return error string) to process errors on client side.
This kind of code may cause deadlocks under heavy load (I can't find them here but it doesn't mean there aren't any :))
Each insert causes at least 2 table searches

Alternative way (how most applications works) is to rely on a business logic inside client application to enforce business rules. It's much easier (and straightforward) to verify that your parent is of a valid type.

Also, based on your PostTypes table I think each type of "posts" should be different enough to store it in its own table. In that case the whole story of validating types is gone, and all the validation will be done by foreign keys.


Const-correctness

Since you tagged this question as c++, you must take care of const-correctness:

cr54045.cpp:36:18: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
 res = strstrImp("helloworld","low");
                 ^
cr54045.cpp:36:31: warning: conversion from string literal to 'char *' is deprecated [-Wdeprecated-writable-strings]
 res = strstrImp("helloworld","low");
                              ^

There should be a

const char strstrImp(const char *input, const char *find)
{
    return strstrImp(const_cast<char *>(input), find);
}

Incorrect optimization

Try this test case, which compares your implementation against the standard strstr().

int main()
{
    const char *input = "alfalfalfa romeo", *find = "alfalfa ";
    printf("%s\n", strstrImp(input, find));  // (null)
    printf("%s\n", strstr(input, find));     // alfalfa romeo
}

Logic simplification

Since the start = p optimization is bogus, we will only end the loop with start++.  The function body would then look like:

if (*find == '\0')
    return input;
if (*input == '\0')
    return NULL;

char *start = input;
while (*start != '\0')
{
    …
    start++;
}
return NULL;

Next, notice that the if (*input == '\0') return NULL special case is redundant.  Also notice that you never refer to input again, so you might as well think of start and input as the same thing.  The outline simplifies to:

if (*find == '\0')
    return input;
while (*input != '\0')
{
    …
    input++;
}
return NULL;

Next, let's turn our attention inside the outer loop.

Since p is only ever used inside the loop, you should pull its declaration inside the loop.  p and q should both be const char *.

while (*input != '\0')
{
    const char *p = input, *q = find;
    while (*p != 0 && *q != '\0' && *p == *q)
    {
        p++;
        q++;
    }
    if (*q=='\0')
    {
        return input;
    }
    input++;
}

It turns out that the inner-loop condition can be simplified, because the *p == '\0' test is redundant:

$$\begin{array}{ccc|c|c}
\text{*p == *q} & \text{*q != '\0'} & \text{*p != '\0'} & {\begin{array}{l}\text{*p!='\0' &&}\\\text{*q!='\0' &&}\\\text{*p==*q}\end{array}} & \begin{array}{l}\text{*q != '\0' &&}\\\text{*p == *q}\end{array} \\
\hline \\
\begin{array}{c}T\\T\end{array} & \begin{array}{c}T\\T\end{array} & \begin{array}{c}T\\F\end{array} & \begin{array}{c}T\\F\ (impossible)\end{array} &  T \\
\hline \\
\begin{array}{c}T\\T\end{array} & \begin{array}{c}F\\F\end{array} & \begin{array}{c}T\\F\end{array} & \begin{array}{c}F\ (impossible)\\F\end{array} &  F \\
\hline \\
\begin{array}{c}F\\F\end{array} & \begin{array}{c}T\\T\end{array} & \begin{array}{c}T\\F\end{array} & \begin{array}{c}F\\F\end{array} &  F \\
\hline \\
\begin{array}{c}F\\F\end{array} & \begin{array}{c}F\\F\end{array} & \begin{array}{c}T\\F\end{array} & \begin{array}{c}F\\F\end{array} &  F \\
\end{array}$$

The function can now look like:

if (*find=='\0')
    return input;

while (*input != '\0')
{
    const char *p, *q;
    for (p = input, q = find; *q != '\0' && *p == *q; p++, q++) {}
    if (*q == '\0')
    {
        return input;
    }
    input++;
}
return NULL;

A well designed function shouldn't have surprising behaviour, and therefore shouldn't have special cases.  Can we get rid of if (*find == '\0') return input;?

The behaviour of strstr() is, if find is "", then the function returns input.  In order to reach the return input; statement when find == "" and input == "", we have to get rid of both the if (*find == '\0') special case and the while (*input != '\0') guard condition.

char *strstrImp(char *input, const char *find)
{
    do
    {
        const char *p, *q;
        for (p = input, q = find; *q != '\0' && *p == *q; p++, q++) {}
        if (*q == '\0')
        {
            return input;
        }
    } while (*(input++) != '\0');
    return NULL;
}

const char *strstrImp(const char *input, const char *find)
{
    return strstrImp(const_cast<char *>(input), find);
}

Suppose we make that change — then what about the case where input == "" and find is non-empty?  It turns out, that works just fine: it will flow through all of the conditions and return NULL!  There you go — a compact implementation of strstr() with reasonably simple logic and without special cases.


Binary search implementations comparison

Enhancing your benchmark

You might be able to enhance your benchmarks a little bit. Its generally worthwhile to run a test multiple times, as there are often other factors that will affect performance on your machine. This can include other programs running on your computer, available RAM/CPU to your process, etc. I find that I typically want to run something as many times as is reasonable within a given amount of time.

Once you've done that you'll have to find a reasonable metric to use; I typically go with the mean and also report on the standard error of the mean.

It's also often useful/interesting to compare performance at multiple problem sizes, but you might not be interested in that.

You'll also want to make sure that your benchmark actually takes long enough to run; I find that you at least want to be able to notice it pause to run. If that isn't the case here (I have no idea, I haven't run it) then add a few zeros at the end of numberOfRandoms. Eyeballing it, it looks like it should be fine as-is though.

One other thing to consider is that there is the possibility that you've loaded some of the values from the array into the cache, which can artificially enhance the performance of your second run. My general preferred strategy will look something like this:

repeat n times
    generate massive random array
    run version a
    do a ton of operations on a different massive array to make sure the cache is clean
    run version b
    kill cache again

My Java is rusty, but IIRC some of the newer versions allow higher order functions of some kind, in which case I'd write a function that performs the timing and cache clearing for you and takes a function as a parameter. If your version supports doing that I'd consider adding that as well.

Miscellaneous comments

You calculate the difference between finish and start multiple times in both searchUtilRecursive and searchUtil; just calculate it once at the top and then use that value.

Using a string to represent your mode in search is icky - make an enum.

Why are you sorting the array inside your BinarySearch constructor? Just pass it a sorted array. It's unexpected to me that if I call BinarySearch on an array that it will first sort it.

On that note, BinarySearch is weird to have as a class; I'd rather have your search functions be static functions (when do I ever want an instance of a BinarySearch?).

I really dislike that you have statements on the same lines as your if and else - these are small enough functions that it doesn't hurt you to put them on multiple lines, and its way more readable that way.


As long as the encoding and decoding are so similar you could use a template

template doCmd(gp: untyped, encdec: untyped, msg: string): void =
    let key = gp()
    let newContent = encdec(existingContent, key)
    write(newContent)
    notify(msg)

and then:

of "open":
    doCmd getpass, xxtea.decrypt, "Decoded"
of "close":
    doCmd getpass2, xxtea.encrypt, "Encoded"

You can also use a proc that accepts proc as arguments, more safe for checking the types of arguments passed, but at that point either getpass and getpass2 are declared with the same arguments or you have to pass an argument for each variant.

To pass a function as an argument just use proc and{.closure}

proc doCmd(gp: proc(m: string = "Password: "): string {.closure}, encdec: proc(b: string, k: string): string {.closure}, msg: string): void =
    let key = gp()


Max depth of tree when all parent pointers are provided

You shouldn't name your classes which form the data structure you operate on according to the problem you are trying to solve. The classes should be named according to their function in the data structure. Thus NodeMaxDepth should be simply Node. This also removes visual clutter when reading the code as the name is shorter yet conveys the same meaning.
I'm not 100% sure why you build the list of children for each node in a separate data structure - it seems that this should be part of the NodeMaxDepth class. It would also make for a slightly cleaner implementation of building of the children lists as each node only has to add itself to the children collection of its parent.

Something along these lines:

class Node {

    private final Node parent;
    private List<Node> children;

    public Node(Node parent) {
        this.parent = parent;
        children = new List<Node>();
    }

    public Node getParent() {
        return parent;
    }

    public void addChild(Node child) {
        children.add(child);
    }
}

public static int maxDepth(List<Node> nodes) {
    if (nodes.size() == 0) { throw new IllegalArgumentException("List of nodes is empty."); }

    Node root = null;

    for (Node node : nodes) {
        if (node.getParent() == null) {
            if (root != null) {
                throw new IllegalArgumentException("Tree must not have multiple roots");
            }
            root = node;
        }
        else {
            node.getParent().addChild(node);
        }
    }

    if (root == null) {
        throw new IllegalArgumentException("This does not seem to be a tree");
    }

    return height (root);
}

If you want to optimize for memory usage and code size you could resort to a simpler algorithm by simply walking up the tree from each node to the root and remember the longest path. Worst case this would result in O(n^2) runtime if I'm not mistaken but would not require any additional memory for building the children lists. The code would also be much simpler.

As indicated by @200_success you could sacrifice a little bit more memory and find all leave nodes and just walk up from them:

// assume all nodes are leaves
HashSet<Node> leaves = new HashSet<Node>(nodes);

Node root = null;

// remove all parents as they are not leaves
for (Node node : nodes) {
    if (node.getParent() == null) {
        root = node;
    }
    else {
        leaves.remove(node.getParent());
    }
}

if (root == null) {
    throw new IllegalArgumentException("The tree must have a root");
}

int maxHeight = 0;

for (Node leaf : leaves) {
    int height = 1;
    Node current = leaf;
    while (current.getParent() != null) {
        current = current.getParent();
        height += 1;
    }
    if (maxHeight < height) {
        maxHeight = height;
    }
}

return maxHeight;

You don't really check for cycles - just that your tree has a root (you could have a normal tree and a disconnected cycle in the list).


Pulling information from XML to insert into Word Document inside 3rd party application

A few remarks:

Variables:

I personally like declaring my Variables with a Type (the little safety needs to be used..). And while we're at it, I don't like having lists named as items

Thus I personally(more emphasis) would rather do:

Dim oNode As Variant
Dim oNodeList As Variant

Conditionals

If ReturnData Is Nothing Then
    ReturnData = ""
EndIf

This if-statement evaluates to true only once. Instead you should initialize ReturnData before your For Each and then you can completely remove it:

Set oNodeList = 'shortcutting here
Dim ReturnData = "" As Variant/String
If oNodeList.Length > 0 Then
  ' carry on


Outputs all substrings that are palindromes in a given string, in alphabetical order without repitition

Performance

These are slow operations that can be replaced with faster ones:

s1 = str.substring(j, i + j); creates new strings. A small improvement would be to use .charAt calls to access elements of str without creating copies. Another small improvement on top of that would be to convert str to a char[] using str.toCharArray() and use array indexes to access elements of the string.
s1.equals(new StringBuilder(s1).reverse().toString()) is a lazy way to check if a string is a palindrome. It creates a new string, and then iterates over values to check if palindrome. It would be a lot better to implement a function for that, comparing pairs of letters from the beginning and end, closing in toward the center.
!palindromeArray.contains(s1) is an \$O(n)\$ operation that can be easily turned into \$O(1)\$ by using a Set instead of an array.
The slowest part of all is the main algorithm of enumerating possible palindromes. The nested loop basically checks all possible substring. That's not necessary. A more clever approach would be, for each position, center on the position, and keep going outward as long as the start and end letters still form a palindrome. This way you can drastically reduce the number of comparisons made in the process of checking for palindromes.

Coding style

The coding style of your post is extremely poor.

Indentation is inconsistent, messy
Names are poor. palindromeArray is not an "array", it's a list. And you could just call it palindromes, naturally. subPal is cryptic at best. How about printUniquePalindromes?
It's recommended to use braces with single-statement if and for statements too.

Other issues

The scan != null condition is always true, so the if statement is unnecessary.

The initializer in String s1 = "" is redundant, String s1 would be enough


Well, your code is hardly a bash solution, is it? You use sort, awk, grep, and echo....

Additionally, your code is dumped on a single line, and it makes it hard to read. Why not put it in a script, and have separate commands on separate lines.... like:

#!/bin/bash

a="access.log"
for b in $(cat $a | awk '{print $1}' | sort | uniq); do
  echo $b;
  grep $a -e "GET / HTTP" | grep -c $b;
done;

Those variable names.... ouch. a and b make it hard to separate from the -c and -e too.... and they mean nothing otherwise. Why not use meaningful names like ip and log?

Then, when I ran the code, I got a lot of funny results.... like:

54.69.125.145
1
61.240.144.65
0
64.14.99.254
0
66.196.235.78
0
66.249.64.188
0
74.208.152.232
0

Why are there 0 counts.... oh, that's because those are IP's that are not accessing the home page, but are accessing other pages... they appear as $b but don't actually "GET" /.

I would consider making it more a study of bash and use the native bash structures to get things right.... no grep, awk, etc.

#!/bin/bash

# use first commandline argument if supplied
log="access.log"
if [ $1 ] ; then
    log="$1"
fi

# set a variable to match in a regular expression
match="GET / HTTP"

# create a named array.
declare -A counts

# read the file line-by-line
while IFS='' read -r line || [[ -n "$line" ]]; do

  # find lines that access GET / HTTP
  if [[ $line =~ $match ]] ; then

    # get just the IP of the client
    ip=${line%% *}
    # get the previous count, default to 0
    prev=${counts[$ip]:-0}
    # increment the count for this IP
    counts[$ip]=$(($prev + 1))
  fi
done < "$log"

for ip in "${!counts[@]}" ; do
    echo "IP $ip visited ${counts[$ip]} times"
done

EDIT: About the ${line%% *} variable substitution. The possibilities when doing variables in bash are remarkably powerful. I recommend looking at the document Parameter Substitution for details, and the man page for bash is good as well (but does not have the examples). The %% token indicates that there should be a pattern search backward from the end of $line for a space  followed by any characters (the * - this is a "glob" expression, not a regex). This pattern essentially looks for the first space, and removes it and any charaters after it. The man page document says:

${parameter%word}
${parameter%%word}

    The word is expanded to produce a pattern just as in filename expansion.
    If the pattern matches a trailing portion of the expanded value of
    parameter, then the result of the expansion is the value of parameter
    with the shortest matching pattern (the ‘%’ case) or the longest matching
    pattern (the ‘%%’ case) deleted. If parameter is ‘@’ or ‘*’, the pattern
    removal operation is applied to each positional parameter in turn, and the
    expansion is the resultant list. If parameter is an array variable
    subscripted with ‘@’ or ‘*’, the pattern removal operation is applied to
    each member of the array in turn, and the expansion is the resultant list.


Simple JavaScript library for DOM interactions

First off, consider which browsers is this DOM library supposed to support. Then test that it works in all of them.

create()

Plain for-in loop is not safe as it also loops over keys in object prototype.
temp is bad name for a variable.
You're repeatedly testing that return value is window.Element.
window.Element can be written as just Element (or perhaps use HTMLElement for clarity).

attr()

What if the value is 0 or ""?

prepend()

elem.prepend() is not supported by all browsers.

remove()

par is unnecessary abbreviation of parent.

A few general remarks:

Check your code for consistent formatting. You're missing some semicolons and the indentation is inconsistent. Use a tool like ESLint.
Escaping newlines to create multiline strings is not officially supported in ECMAScript.


Make code more memory efficient, or shorter

The code does not rename any files, it modifies the values of certain variables.

Using assignments as a parameter to your functions is confusing.

You call file_exists but do nothing with it.  It is supposed to be used to check for the existence of a file. Something like:

if (!file_exists($destination))
{
    rename($source, $destination);
}

To answer more you would need to show how the desktop_dir_xxx variables are calculated.


Take care to call strpos() correctly. If the f parameter contains a leading /, it sneaks through.


class design improvement - user validation

First of all, as mentioned by @user7212, use php filter_var() for email validation. Please see below for example:

/**
 * Validate email
 *
 * @param string $email
 *
 * @return bool
 */
public static function email($email)
{
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}

Second, why not naming your function params? If the email validation function would be called $email, if would be much easier to understand then $a.

in_array() function, according to it's documentation, returns bool. Why converting it to int? The result of the check should be bool.

In the pass() function, are you checking a string or a hash? Which brings us to the following item - write comments for your code! PHPDoc is a good example on how to do that.

And the last, but not the least - the name of the class. Check is not the most appropriate name. I would consider Validation or Valid.

Hope this helps.