Scraping different categories using different links through proxy

Assuming the proxy dictionary with duplicate keys is just a posting error, here are some of the things I think need to be addressed:

as usual, create a requests.Session() instance and re-use - this would not only allow to set headers and proxies once, but also improve performance
I would define headers as a constant or go even step further - rotate user agent strings as well - there is a fake-useragent project that would help
there is also this DRY principle violation - you are repeating cssselect() calls twice per element - in this case, it's not only the repetition but is also something that unnecessarily slows the HTML parsing down. Define a reusable function that would handle the problem:

def extract_field(root, selector, default=""):
    try:
        return root.cssselect(selector)[0].text.strip()
    except IndexError:
        return default

Here is the code with the above and other modifications applied:

import csv

import requests
from lxml.html import fromstring

def extract_field(root, selector, default=""):
    try:
        return root.cssselect(selector)[0].text.strip()
    except IndexError:
        return default

def crawl():
    proxy = {  # assuming is correct
        'https': 'https://188.166.154.140:8118',
        'https': 'https://198.52.44.130:53281',
        'https': 'https://46.101.2.115:8118'
    }

    with open("amazon.csv", 'r') as input_file, requests.Session() as session:
        session.headers = {'User-Agent': 'Mozilla/5.0'}
        session.proxies = proxy

        for entry in csv.DictReader(input_file):
            url = entry['Link']
            response = session.get(url)
            root = fromstring(response.text)

            name = extract_field(root, "#productTitle")
            star = extract_field(root, ".AverageCustomerReviews .a-icon-alt")
            count = extract_field(root, ".AverageCustomerReviews .totalReviewCount")

            print("Name: {}\nStar: {}\nCount: {}".format(name,star,count))

if __name__ == '__main__':
    crawl()


From a good look;

Your indentation is horrendous, it makes your question hard to review. Please do consistent indentation. Use http://jsbeautifier.org/ if you cannot be bothered.
It would have been good to document what the transformer does (drop 2 last characters)
I would have one-lined this:

 _transform(chunk,enc, transformed) {
   // process files here
      let data=chunk.toString();
       data=data.substring(0,data.length-2);
        this.push(data);
         transformed();
}

to

// process files here
transform(chunk, enc, transformed) {
  this.push(chunk.toString().slice(0,-2));
  transformed();
}

If you are going to call in a handler 1 function with a signature that matches the handler like here:

stream.on('error', function(err) {
  reject(err);  });
});

then consider to use that function as the callback:

stream.on('error', reject);

When I take a step back, then I don't like the approach. You have this modern approach of the stream which is flowing data. Then you take the stream, plug it until your entire transformation is done, and then let it flow again. I might actually try to rewrite this.

I rewrote all that code, this is how streams should work: pipe your file into your transform and pipe that to stdout.

"use strict";

let fs=require('fs'),
    filePaths=['./smurf.js','./gargamel.js'];

const Stream = require('stream');
const Transform = require('stream').Transform;

const myTransform = new Transform({
  transform(chunk, encoding, callback) {
    callback( null, chunk.toString().slice(0,-2) );
  }
});

filePaths.forEach(function (path) {
  fs.createReadStream(path).pipe( myTransform ).pipe( process.stdout );
});


Faster way of replacing strings in large pandas dataframe with regex

There is not much to say about your code then, Regex is slow.

A non-regex solution could be to use Python's endswidth, this works the same as r"road$"

mergedAllCrimes.crime_location_approx = mergedAllCrimes.crime_location_approx.apply(lambda x: 'road' if x.lower().endswith('road') else x)

I'm assuming all the conditional words are at the end of the string


You can create a generic container/entity for "data" and "metadata" and reuse it. e.g.:

data class MEntity<T>(
        var data: T? = null,
        var metadata: String? = null
)

data class User(
        var name: String? = null,
        var pid: String? = null,
        var position: MEntity<Position>? = null
)

data class Position(
        var x: String? = null,
        var y: String? = null
)

Due to type erasure you must use a TypeToken to deserialize the JSON into a generic type:

gson.fromJson<MEntity<User>>(json, object : TypeToken<MEntity<User>>() {}.type)

This isn't very convenient but thankfully Kotlin allows us to use reified type parameters to define an extension function to simplify this:

inline fun <reified T> Gson.fromJsonToGeneric(json: String): T {
    return fromJson(json, object : TypeToken<T>() {}.type)
}

Now the usage becomes much simpler:

val userMEntity = gson.fromJsonToGeneric<MEntity<User>>(json)
println(userMEntity)

Output:

MEntity(data=User(name=Start, pid=1, position=MEntity(data=Position(x=31, y=330), metadata=empty)), metadata=empty)


Jquery Selector optimization for multiple clicks

Your second selector doesn't work with the data provided input:tel#8888 is not the id= of the input.

IDs should start with a letter (for compatibility), so if you changed your input to <input id="inp8888"> then you could use input:tel#inp8888 in which case, you can use $("#inp8888") as long as your IDs are unique (which they should be).

Selecting by ID is the fastest selection method.

  jQuery uses document.getElementById(), which is faster

https://learn.jquery.com/performance/optimize-selectors/#id-based-selectors


from __future__ import with_statement

import json
import xml.etree.ElementTree as etree

def _sanitize_string(string):
    """docstring for _clean_string"""

Docstrings should contain a description of the function, not some old name for the function.

    string = string.replace('\n', '').split()

Do you really want "green\ngrass' to come through as 'greengrass'?

   return ' '.join(string)

class Event(object):
    """docstring for Event"""
    def __init__(self, date, event, organizer, time, venue):
        self.date = date
        self.event = event
        self.organizer = organizer
        self.time = time
        self.venue = venue

    def provide_data(self):
        """docstring for provide_data"""
        data = {}
        data['date'] = self.date
        data['event'] = self.event
        data['organizer'] = self.organizer
        data['time'] = self.time
        data['venue'] = self.venue
        return data

The class as it stands doesn't really do anything. If this is all its ever going to do, just use a dictionary instead.

class EventCollection(list):
    """docstring for EventCollection"""

    def __init__(self):
        super(EventCollection, self).__init__([])

Passing the [] is wasteful, because the empty argument constructor will have the same effect without building a temporary list. There is no need to override the constructor here. The default behavior will build the list just fine.

    def as_json(self):
        """docstring for as_json"""
        print json.dumps([event.provide_data() for event in self],
                         sort_keys=True, indent=2)

This would really be better as a seperate function rather then an entire class.  Its misplaced in a list class because its not really dealing with the list per se.

def read_file(event_collection, filename='events.xml'):
    """docstring for read_file"""
    try:
        with open(filename) as f:
            tree = etree.parse(f)
        for row in tree.findall('.//row'):
            # event = [_sanitize_string(node.text) for node in row]
            # if event[0] and event[0][0].isdigit():
            #     print event

Don't keep dead code in comments, delete it.

            tmpl = [_sanitize_string(node.text) for node in row]

I can't guess what tmpl is supposed to mean. This being xml, does these nodes have tags that you should be checking for correctness?

            if tmpl[0] and tmpl[0][0].isdigit():

I have no idea what this test is doing. It should probably be commented to explain the signficance of that first character being a digit.

                event = Event(tmpl.pop(0), tmpl.pop(0), tmpl.pop(0),
                              tmpl.pop(0), tmpl.pop(0))

Use:
                   date, event, time, organizer, venue = tmpl
                   event = Event(date, event, time, organizer, venue)

It makes is easier to see what is going on

            event_collection.append(event)
    except IOError as ioerr:
        print "File Error: %s" % str(ioerr)

If you catch an error, simply printing it out is insufficient. You should really either recover or abort. You could call sys.exit() here to shutdown the program. I'd probably rethrow the exception and catch it in my main() function. If the script is supposed to be quick and dirty, just don't catch the exception and let the default handling show the error when it dies.

def main():
    """docstring for main"""
    event_collection = EventCollection()

    read_file(event_collection)

Avoid functions which modify arguments. Use a return value. Have read_file create and return event_collection.

    event_collection.as_json()
    # event_collection.as_csv()

if __name__ == '__main__':
    main()

** EDIT **

Ways of doing exception handling:

Don't. Just take your try and except out. If something goes wrong, your program will die with a stack trace. Not very professional, but in some cases that's just fine
Use sys.exit()

try:
     do_stuff()
except IOError:
     print "Went wrong"
     sys.exit() # program will exit here
Use your own exception class (my preffered method)

Code:

class UserError(Exception):
     """
     This error is thrown when it the user's fault
     Or at least the user should see the error
     """

# later
try:
     do_stuff()
except IOError as error:
     raise UserError(error)

# later
def main():
    try:
         do_program()
    except UserError as error:
         print error

Its a bit bulky for a simple script like this, but for bigger programs I think its the best solution.

Two other issues:

You should really print >> sys.stderr, "your error message" so that your errors go to standard error and not standard out
You should also end by calling sys.exit(some non-zero number) when an error happens to indicate failure.


Let's do some performance tweaks.
I will measure the time simply with Stopwatch and first of all I'll cleanup your code to generate proper CSV (without reduntant empty lines as initial).
List<string> headers = typeof(Lead).GetProperties().Select(x => x.Name).ToList();
string s = string.Join(",", headers) + Environment.NewLine;

foreach (Lead lead in leads)
{
    List<object> values = typeof(Lead).GetProperties().Select(prop => prop.GetValue(lead)).ToList();
    string ss = string.Join(",", values);
    s += $"{ss}{Environment.NewLine}";
}

Environment.NewLine returns \r\n on Windows and \n on Linux.
Output will be
FirstName,MiddleName,LastName
Joe,M,DiFabio
Dave,,Palacios
Andy,A,Nevers

Looks like CSV :)
Then to measure performance I'll imagine that you have very large amount of data e.g. 30000 lines. I'll run the test in a loop of 10000 iterations.
TestOriginal
private static string TestOriginal(List<Lead> leads)
{
    List<string> headers = typeof(Lead).GetProperties().Select(x => x.Name).ToList();
    string s = string.Join(",", headers) + Environment.NewLine;

    for (int i = 0; i < 10000; i++)
        foreach (Lead lead in leads)
        {
            List<object> values = typeof(Lead).GetProperties().Select(prop => prop.GetValue(lead)).ToList();
            string ss = string.Join(",", values);
            s += $"{ss}{Environment.NewLine}";
        }
    return s;
}

Let's run.
Stopwatch sw = new Stopwatch();
sw.Start();
string s = TestOriginal(leads);
sw.Stop();
Console.WriteLine("Original: {0}ms", sw.ElapsedMilliseconds);

Original: 3162ms

Ugh. :)
Almost everyone knows that Reflection is slow. Let's somewhat optimize that.
ReflectionTweak
private static string ReflectionTweak(List<Lead> leads)
{
    PropertyInfo[] properties = typeof(Lead).GetProperties();
    List<string> headers = properties.Select(x => x.Name).ToList();
    string s = string.Join(",", headers) + Environment.NewLine;

    for (int i = 0; i < 10000; i++)
        foreach (Lead lead in leads)
        {
            List<object> values = properties.Select(prop => prop.GetValue(lead)).ToList();
            string ss = string.Join(",", values);
            s += $"{ss}{Environment.NewLine}";
        }
    return s;
}

Go go go
sw.Restart();
string sr = ReflectionTweak(leads);
sw.Stop();
Console.WriteLine("Reflection tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == sr);

Output with matching the string to original one
Reflection tweak: 3040ms, match: True

Better but still slow
One more idea - StringBuilder. Afaik, it's the fastest way to build a string (maybe except some unsafe/unmanaged code).
StringBuilderTweak
private static string StringBuilderTweak(List<Lead> leads)
{
    StringBuilder sb = new StringBuilder();
    PropertyInfo[] properties = typeof(Lead).GetProperties();
    sb.AppendLine(string.Join(",", properties.Select(x => x.Name)));

    for (int i = 0; i < 10000; i++)
        foreach (Lead lead in leads)
        {
            sb.AppendLine(string.Join(",", properties.Select(prop => prop.GetValue(lead))));
        }
    return sb.ToString();
}

Interesting...
sw.Restart();
string sb = StringBuilderTweak(leads);
sw.Stop();
Console.WriteLine("StringBuilder tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == sb);

Output
StringBuilder tweak: 24ms, match: True

WOW!!!
By the way, you may write the output directly to MemoryStream with StreamWriter.
StreamWriterTweak
private static MemoryStream StreamWriterTweak(List<Lead> leads)
{
    MemoryStream ms = new MemoryStream();
    // Encoding.UTF8 produces stream with BOM, new UTF8Encoding(false) - without BOM
    using (StreamWriter sw = new StreamWriter(ms, new UTF8Encoding(false), 8192, true))
    {
        PropertyInfo[] properties = typeof(Lead).GetProperties();
        sw.WriteLine(string.Join(",", properties.Select(x => x.Name)));

        for (int i = 0; i < 10000; i++)
            foreach (Lead lead in leads)
            {
                sw.WriteLine(string.Join(",", properties.Select(prop => prop.GetValue(lead))));
            }
    }
    ms.Position = 0;
    return ms;
}

Must be fast too...
sw.Restart();
MemoryStream stream = StreamWriterTweak(leads);
sw.Stop();
Console.WriteLine("StreamWriter tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == Encoding.UTF8.GetString(stream.ToArray()));

Output
StreamWriter tweak: 28ms, match: True

Yes!

The fastest
StringBuilder sb = new StringBuilder();
PropertyInfo[] properties = typeof(Lead).GetProperties();
sb.AppendLine(string.Join(",", properties.Select(x => x.Name)));

foreach (Lead lead in leads)
{
    sb.AppendLine(string.Join(",", properties.Select(prop => prop.GetValue(lead))));
}
string s = sb.ToString();

The whole code to reproduce and play more
internal class Program
{
    public static void Main(string[] args)
    {
        List<Lead> leads = new List<Lead>();
        Lead lead1 = new Lead();
        lead1.FirstName = "Joe";
        lead1.MiddleName = "M";
        lead1.LastName = "DiFabio";
        leads.Add(lead1);

        Lead lead2 = new Lead();
        lead2.FirstName = "Dave";
        lead2.MiddleName = "";
        lead2.LastName = "Palacios";
        leads.Add(lead2);

        Lead lead3 = new Lead();
        lead3.FirstName = "Andy";
        lead3.MiddleName = "A";
        lead3.LastName = "Nevers";
        leads.Add(lead3);

        Stopwatch sw = new Stopwatch();
        sw.Start();
        string s = TestOriginal(leads);
        sw.Stop();
        Console.WriteLine("Original: {0}ms", sw.ElapsedMilliseconds);
        sw.Restart();
        string sr = ReflectionTweak(leads);
        sw.Stop();
        Console.WriteLine("Reflection tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == sr);
        sw.Restart();
        string sb = StringBuilderTweak(leads);
        sw.Stop();
        Console.WriteLine("StringBuilder tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == sb);

        //MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(s));

        sw.Restart();
        MemoryStream stream = StreamWriterTweak(leads);
        sw.Stop();
        Console.WriteLine("StreamWriter tweak: {0}ms, match: {1}", sw.ElapsedMilliseconds, s == Encoding.UTF8.GetString(stream.ToArray()));

        Console.ReadKey();
    }

    private static string TestOriginal(List<Lead> leads)
    {
        List<string> headers = typeof(Lead).GetProperties().Select(x => x.Name).ToList();
        string s = string.Join(",", headers) + Environment.NewLine;

        for (int i = 0; i < 10000; i++)
            foreach (Lead lead in leads)
            {
                List<object> values = typeof(Lead).GetProperties().Select(prop => prop.GetValue(lead)).ToList();
                string ss = string.Join(",", values);
                s += $"{ss}{Environment.NewLine}";
            }
        return s;
    }

    private static string ReflectionTweak(List<Lead> leads)
    {
        PropertyInfo[] properties = typeof(Lead).GetProperties();
        List<string> headers = properties.Select(x => x.Name).ToList();
        string s = string.Join(",", headers) + Environment.NewLine;

        for (int i = 0; i < 10000; i++)
            foreach (Lead lead in leads)
            {
                List<object> values = properties.Select(prop => prop.GetValue(lead)).ToList();
                string ss = string.Join(",", values);
                s += $"{ss}{Environment.NewLine}";
            }
        return s;
    }

    private static string StringBuilderTweak(List<Lead> leads)
    {
        StringBuilder sb = new StringBuilder();
        PropertyInfo[] properties = typeof(Lead).GetProperties();
        sb.AppendLine(string.Join(",", properties.Select(x => x.Name)));

        for (int i = 0; i < 10000; i++)
            foreach (Lead lead in leads)
            {
                sb.AppendLine(string.Join(",", properties.Select(prop => prop.GetValue(lead))));
            }
        return sb.ToString();
    }

    private static MemoryStream StreamWriterTweak(List<Lead> leads)
    {
        MemoryStream ms = new MemoryStream();
        // Encoding.UTF8 produces stream with BOM, new UTF8Encoding(false) - without BOM
        using (StreamWriter sw = new StreamWriter(ms, new UTF8Encoding(false), 8192, true))
        {
            PropertyInfo[] properties = typeof(Lead).GetProperties();
            sw.WriteLine(string.Join(",", properties.Select(x => x.Name)));

            for (int i = 0; i < 10000; i++)
                foreach (Lead lead in leads)
                {
                    sw.WriteLine(string.Join(",", properties.Select(prop => prop.GetValue(lead))));
                }
        }
        ms.Position = 0;
        return ms;
    }

    public class Lead
    {
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
    }
}


For the most part, this looks good to me. Your api is clear and I really like that you have to activate the utility before the prototype is modified. However, there's always room for improvement :)

You provide the Utility.activate function, it would be useful to also have a Utility.deactivate function.
addUtil taking name as the second parameter seems odd to me. On a longer utility method like min, max or mean it was not immediately obvious to me what the function did - I had to skip to the end or figure it out from the code.
Be consistent with your naming scheme. In most of the code you use camelCase, but in the parameters for Number.map you use snake_case.
Why is the inputBase the first parameter in toBaseN? Presumably, if I have a number it is already in base 10. This function will also have issues if you use 0.0000001, plug 0.0000001.toString() into your console and you will get 1e-7 instead of what you expected.
toTheNthPower is just pow on the Math object. I would use the same convention here.
Don't throw strings. Throw a new Error(str) or just Error(str). This makes it much easier for error tracking systems to give you helpful stack traces.
Returning 0 as a signal number if the array is empty is not a good idea. 0 could exist in an array. I'd recommend using the convention of Math.max and Math.min and returning -Infinity and Infinity respectively.
Mapping over the array to create an array of booleans is very inefficient. If I create an array with ['hi'].concat([1].repeat(1e9)) you still go through every single item in the array. Instead of doing this, bail out as soon as you hit a failing condition. [].every and [].some can be of help here. const isAllNums = this.every(item => typeof item == 'number')
Speaking of Math.max and Math.min, you should use them! You can use Math.max.apply(Math, this) or if your environment supports the spread operator, you can just use Math.max(...this). If desired, you can check if this returns NaN and throw an error to maintain the current API instead of returning NaN for arrays with non-numbers.
Don't use for..in loops to loop over keys of objects. Either use for (const key of Object.keys(this.utils)) or Object.keys(this.utils).forEach(. This will help you avoid problems with built in values like toString.
In this case, it is probably a better fit to use a Map instead of a plain object to hold the utils.
What happens if you want to use these utils in Node? They break - window is not defined. This might not be a consideration, but quite a lot of code runs on Node now.
What happens if you want to define utilities for an object which is not exposed on the global? Instead of passing a string into the constructor of Utility, I'd recommend passing in an object instead. new Utility(Array)
Instead of looping through the array multiple times for mean, I'd recommend checking each element of the array as you add it to the sum. Maintaining your current API, here's how I'd implement that function.

function mean(arr) {
  return arr.reduce((total, item) => {
    if (typeof item !== 'number') {
      throw new Error("The array must be all numbers.")
    }
    return total + item
  }, 0) / arr.length
}


Find sequence by adding 5 or multiplying by 3

This question is a bit related to a previous question. I will give you the same advice I did to the asker of the previous question.
Work from the other direction.
Currently, you're branching out starting from 1 trying to reach 178. Instead, start from 178 and try to reach 1. I'll show you how that will make the problem a lot easier.

We're at 178. Can we divide by 3? 178 mod 3 != 0 so no. Instead we reduce by 5.
178 - 5 == 173. Can we divide by 3? 173 mod 3 != 0 so no, we reduce by 5 instead.
173 - 5 == 168. Can we divide by 3? 168 mod 3 == 0 so yes, we can. Let's do that.
168 / 3 == 56. Wait a minute... this number ends with a 6... Interesting. (56 - 1) mod 5 equals zero, so from here we can just reduce by 5 until we've reached our target of 1.

Instead of branching out in an exponential manner, we've reduced the problem to a linear approach. Simply by flipping things backwards.
Let's say that we don't want to do the end loop of reducing by 5 just because we can (we want the shortest path, right?), then I see no other solution than to branch out recursively. When checking for the division by 3, a lot of branches are removed so it will be possible to find the shortest path by branching.
I'll leave the fun part of implementing this up to you :)
Some comments about your current code
(Which, given the comments above you should remove and completely re-write using the "backwards" approach)
In Java at least, it's recommended to add braces for each if. Also, as you're using return inside each if there's no need for else.
function findSequence(goal) {
  function find(start, history) {
    if (start == goal) {
      return history;
    }
    if (start > goal) {
      return null;
    }
    return find(start + 5, "(" + history + " + 5)") ||
             find(start * 3, "(" + history + " * 3)");
  }
  return find(1, "1");
}

I would also add a parameter to allow switching the start value, it will make it more flexible very easily.
I think it's good that you're hiding the find method inside the other function.


Trying to map JSON to different classes in web API

The first thing to do is to remove duplicated code. If you do not need further processing DeserializeObject<T>() returns T and you do not need any mapping, you simply can return its result. That code is also shared between A and B then you can simply introduce a separate function:

private static bool TryDeserializeObject<T>(string json, out T result)
    where T : IModel
{
    result = default(T);

    try
    {
        result = JsonConvert.DeserializeObject<T>(json);
        return true;
    }
    catch (JsonReaderException)
    {
        return false;
    }
}

Note that I'm not catching Exception but a more specific one. OutOfMemoryException (for example) it's not intended to signal that I'm trying to deserialize the wrong type. This code is, however, sub-optimal because calling point is like this:

if (TryDeserializeObject<A>(json, out var a))
    bindingContext.Model = a;
else if (TryDeserializeObject<B>(json, out var b))
    bindingContext.Model = b;
else
    return false;

return true;

It does not scale well if I have more than few types. For that I'd love to write this:

private static bool TryDeserializeObject(string json, Type type, out IModel result)
{
    result = null;

    try
    {
        result = (IModel)JsonConvert.DeserializeObject(json, type);
        return true;
    }
    catch (JsonReaderException)
    {
        return false;
    }
}

We can now introduce another function:

private static IModel DeserializeObjectOrNull(string json, params Type[] types)
{
    foreach (var type in types)
    {
        if (TryDeserializeObject(json, type, out var model))
            return model;
    }

    return null;
}

Now calling point might be (it may be more terse but I try to keep it clear):

var model = DeserializeObjectOrNull(json, typeof(A), typeof(B));
if (model == null)
    return false;

bindingContext.Model = model;

return true;

List may be specified here or come from configuration or an hard-coded list somewhere else. This will scale much better.

We have another issue to solve: how to detect we're trying to deserialize the wrong type? Newtonsoft JSON by default simply ignores unknown members then we'll always get an object with only the known property correctly initialised. You need to use an overload which accepts JsonSerializerSettings where you specified MissingMemberHandling.Error for JSonSerializerSettings.MissingMemberHandling property.

Is there a better way? If you can change your JSON then you may add a _type property (for example, also consider the @A and @B variants). If not then you may consider to deserialize to dynamic and to check for well-known properties (using OOM mapper to copy properties). I'd do this only if performance hit is significant enough because it'll make your code much more convoluted.

Solved our problem with JSON we may take a look to the first lines...getting the result of an async method with .Result is seldom what you want. Just refer to MSDN for details and differences but probably what you want is .GetAwaiter().GetResult(). Even better you should make your method async and take advantage of it (there are alternatives ModelBinder implementation which supports async):

public async Task<bool> BindModel(HttpActionContext actionContext,
    ModelBindingContext bindingContext)
{
    var content = actionContext.Request.Content;
    string json = await content.ReadAsStringAsync();

    // ...
}


Getting Size of File

You can get the size of file (without asking the filesystem) by using fseek() and ftell().

if (fseeko(file, 0, SEEK_END) != 0) {
    // Error State do something
}
off_t sizeOfFile = ftello(file);
if (fseeko(file, 0, SEEK_SET) != 0) {
    // Error State do something
}

// Your file is now ready to be read and the size of the file is
// in `sizeOfFile`

Identifier Names

The identifier _READFILE_GUESS is reserved for the implementation. Don't use _ (underscore) as the first character in an identifier name.

Realloc

This is the wrong way to use realloc:

result = realloc(result, sizeof(char) * capacity + 1);

As you have noticed, when realloc fails it returns NULL. But it does not free the result value in this case. This means you have overwritten the value of result with null and thus leaked the memory it was pointing at.

char* newArea = realloc(result, sizeof(char) * capacity + 1);
if (newArea == NULL) {
    // Error condition handle it
    // You should probably release `result` by calling `free()`
    // before returning result
}
result = newArea;

Reading

Why are you only reading one byte at a time?

while((ch = getc(file)) != EOF)

Why not (attempt to) read capacity bytes at a time?

size_t blocksRead= 0;
size_t totalRead = 0;

while(1) {
    size_t read = fread(result + (blocksRead * capacity) + totalRead, 1, capacity - totalRead, file);
    if (ferror(file) != 0) {
        // Error State Deal with it.
    }
    totalRead += read;
    if (feof(file)) {
        break;
    }
    if (totalRead == capacity) {
        ++blocksRead;
        totalRead = 0;
        // Handle resize of block if you need too.
    }
}

License

Also note that by pasting the code into any Stack Exchange site you are already dual licensing your code under the CC license (see the bottom of the page for details).

So though your MIT License is valid it is not the only license this code is now available under.


Calculating prime factors in MIPS assembly

Procedures

You appear to be doing everything in main while just branching into single-character procedures.  Consider renaming them to specify their purpose, while separating them from main with proper indentation and such.  I cannot tell what main should be doing by itself.  I can just see that it prompts for user input and operates the two loops with its procedures.
Since prompt is done first, consider defining it above main instead.  The end of the program should just display the result(s).

Structure

The register initializations should be placed above main for better visibility and maintainability.
The loop labels barely stand out, and this really hurts structure.  The loop procedures are all crammed together and L1 looks like just another procedure.  You could at least rename L1 and L2 to Loop1 and Loop2 respectively.
The procedures should be properly indented to help them stay isolated.

P:, for instance, hardly stands out:

P:  add $t1, $t1, $t5   # increment i

move $t2, $t6

bgt  $t1, $t0, E
j L2

All of that could should be indented together and with P: on its own line:

P:
    add $t1, $t1, $t5   # increment i

    move $t2, $t6

    bgt  $t1, $t0, E
    j L2

Comments

The side comments here seem redundant:

# Load variables into registers
lw  $t1, i  # $t1 = i
lw  $t2, k  # $t2 = k
lw  $t3, p  # $t3 = p
lw  $t5, c  # $t5 = c
lw  $t6, d  # $t6 = d

The top comment describes this block clearly enough, whether or not the reader already knows that lw means load word.  The side comments don't add anything else here.
This comment is also redundant:

syscall       # call operating sys

Unless there are some special circumstances to note, such comments do not add anything important.  Readers familiar with MIPS commands will already know what this means.  You may just mention this at the top of the program if you'd like for anyone to know what this means.  Putting it with every call just clutters your code.

This, on the other hand, doesn't state the obvious:

add $t2, $t2, $t5   # increment k

Without the comment, all I can tell is that this is equivalent to $t2 += $t5, and not that it increments k.  These are situations where commenting on separate commands is helpful.

Overall, this is just very hard to follow.  If there are bugs in here, it would be difficult to isolate them.  This, in turn, hurts maintainability.  Comments alone can't help with this, either.  The overall structure must be sound, otherwise fixing problems is just a matter of picking apart separate lines, one-by-one.


Queue for distributing tasks between threads

Separation of concerns
You have the members of your class as shared_ptrs this indicates that you want shallow copy assignment and construction. This is not something that you should concern yourself when designing the class.
I would recommend that you design your queue as non-copyable and non-assignable. Because assigning a queue makes no sense. If the user needs to pass a queue around, it is their responsibility to make a shared_ptr<AsyncQueue>. This has the benefit of making your implementation cleaner, but also performing better as your member variables will now get a better cache locality.
The big 5
Following the above the big 5 should now be:
        AsyncQueue(const AsyncQueue& other) = delete;
        AsyncQueue(AsyncQueue&& other) = delete;
        AsyncQueue& operator=(const AsyncQueue& other) = delete;
        AsyncQueue& operator=(AsyncQueue&& other) = delete;
        virtual ~AsyncQueue() = default;

(note delete instead of default). The move assignment and construction cannot be implemented as moving a mutex is not supported (for good reason).
Use make_shared
If you still insist on using shared_ptr, you should use make_shared to construct them because this will co-allocate the reference count with the object data. This saves some memory but more importantly it improves data locality.
Forwarding references
You're better off using forwarding references (also known as universal reference but forwarding reference is the new preferred name) for the push method. In fact I would go as far as to not provide push but instead provide emplace that constructs the object in place like this:
template<typename... Args>
void emplace(Args&&... args){
    {
        std::lock_guard<std::mutex> lock(*mutex);
        queue->emplace(std::forward<Args>(args)...);
    }
    cond->notify_one();
}

emplace() will construct the queued object in place using the arguments passed to emplace() as constructor arguments to avoid a copy. This way you leave the decision whether or not to move to your user.
Obj o;
asyncqueue.emplace(o); // Will copy construct.
asyncqueue.emplace(std::move(o)); // Will move construct.

// Will evaluate o*3 into a temporary and move from it.
// Possibly eliding the copy.
asyncqueue.emplace( o * 3);
asyncqueue.emplace("whatevz"); // Will call constructor taking c-string.

Returning by move in pop
The reason you're crashing is that the local value you moved out of is destroyed when you leave the function scope. So you're moving from rubbish. Returning by r-value reference: Just don't. The compiler will likely perform (N)RVO and the copy will be optimized out if it is possible.
Condtional wait
You have an infinite conditional wait. It may be useful to have a functionality to "sever" the queue and release all threads waiting on jobs.
Typically you would have:
std::atomic<bool> still_running{true};

void stop(){ still_running = false; cond->notify_all();}

void push(T&&){
   if(!still_running) throw error("severed pipe");
   ...
}

void pop(){
   ...
   while(queue->empty() && still_running) {
       cond->wait(lock);
   }
   if(queue->empty(){
       // Check for queue empty here, as still_running could
       // have been changed after we returned but we could still
       // return useful data.
       throw error("severed pipe");
   }
   ...
}

Also prefer the more concise way of waiting on a condition variable:
while(queue->empty()) {
    cond->wait(lock);
}

could be:
cond->wait(lock, [this](){ return !queue->empty();});

For reference, you might be interested in: my implementation of a similar class


Implementing the Hashable Protocol in Swift with the DJB hash function

The Hashable protocol has only one single requirement:

  Axiom: x == y implies x.hashValue == y.hashValue.

So let's start with your implementation of ==:

// Hashable also needs struct to conform to Equatable protocol
func ==(left: ScalarString, right: ScalarString) -> Bool {

    if left.length != right.length {
        return false
    }

    for var i = 0; i < left.length; ++i {
        if left.charAt(i) != right.charAt(i) {
            return false
        }
    }

    return true
}

Looking up the definitions of length and charAt() it is clear
that here simply the left.scalarArray and right.scalarArray
arrays are checked for equality. So the operator can equivalently
but simpler be implemented as

// Hashable also needs struct to conform to Equatable protocol
func ==(left: ScalarString, right: ScalarString) -> Bool {
    return left.scalarArray == right.scalarArray
}

From this representation it becomes obvious that your hashValue
implementation is correct: It is computed from the scalarArray
property, so equal objects have the same hash value.

The hashValue computed property can be simplified using
reduce(), note also that for a read-only property, you need
not put the getter method inside a get { } block:

// hashValue (to implement Hashable protocol)
var hashValue: Int {
    return self.scalarArray.reduce(5381) {
        ($0 << 5) &+ $0 &+ Int($1)
    }
}

A different question would be how "good" the hash is.
The Swift language does not make any requirements here. Always
returning 0 would be valid, but of course ineffective when
building large dictionaries.

It may be interesting in this context that the hash value of
the Foundation type NSArray is simply the number of elements,
regardless of the contents.

In your case, the DJB hash function is a well-known hash method
for strings, so I do not see any reasons not to use it.

Update: As of Swift 4.1, the compiler can synthesize
Equatable and Hashable for types conformance automatically, if all
members conform to Equatable/Hashable (SE0185). And as of Swift 4.2,
a high-quality hash combiner is built-in into the Swift standard
library (SE-0206).

Therefore there is no need anymore to define your own hashing function,
it suffices to declare the conformance:

struct ScalarString: Hashable, ... {

    private var scalarArray: [UInt32] = []

    // ...
}


Let me start with the interesting question:

  Is it even a bubble sort?

This sort is a bit like bubble sort and a bit like insertion sort. You have re-invented gnome sort, so congratulations, that's a nice coup for a beginner.

The other answers -- which state that you should not access arrays out-of-bounds, and should use var to declare local variables rather than relying on automatic declaration to save you, are correct.  To that basic advice I would add the following:

Make a sorting function that takes an array as its argument
Now that you have such a function, write test cases.  Don't forget to test already-sorted arrays, empty arrays, arrays with one, two, or three elements, arrays sorted into reverse order, and so on.

That's the basic stuff. A more advanced technique that you should start using now is

clearly state your loop invariants in comments or, better, assertions

A loop invariant is something that you believe to be true no matter what at various points in the loop. For example, a loop invariant that you have violated is "the index is always in bounds".

By clearly stating your invariants you can then analyze the code to see if it correctly maintains the invariants. If it does, then you have more confidence that the code is correct.

The loop invariant of bubble sort is "after n iterations, the last n elements are in their proper place".

The loop invariant of gnome sort is "everything to the left of i is sorted".

  I'm curious if the way I've written this is valid, efficient, and even a bubble sort at all

Though the code uses poor practices that have already been discussed, it appears to be a valid sort.

It is not, as sorts go, efficient. Asking whether a bubble sort (or bubble sort variation) written in JavaScript is efficient is a bit like asking which of two pet turtles is the faster; if you care about speed then you've chosen the wrong pet.


1. Design

The design is not very Emacs-like. In particular:

The command operates on the entire buffer contents. This means that if you want to line up some columns in a region (without affecting the rest of the buffer), you can't use your command. (At least not without copying the region to a new buffer, running the command, and then copying the result back again.)

It would be better if the function operated on the contents of the current region: then it would be much more flexible.
Your command doesn't respect the current narrowing of the buffer. If you look at the docstring for erase-buffer, it says:

  Any narrowing restriction in effect (see narrow-to-region) is removed,
  so the buffer is truly empty after this.

This would come as an unpleasant surprise to a user who had a narrowing in effect. It would be better to operate only on the narrowed part of the buffer, by calling

(delete-region (point-min) (point-max))

instead of (erase-buffer). (But in fact there are better ways to do it, which I'll describe below.)
Your command doesn't preserve the position of point. After running the command, point is always at the end of the buffer. It's always worth preserving the position of point (if appropriate) because that makes a function's behaviour predictable, and more useful in Lisp code and in macros.

2. Implementation

The command reads the entire buffer contents into strings, processes the strings in various ways, and then writes them back to the buffer.

If you've recently come to Emacs Lisp from another language, then you're probably thinking that a buffer is a bit like a file, and so the right way to process it is to read the file contents into memory as string, process the contents, and then write it out.

I can't stress enough that you won't get the full benefits of Emacs if you persist with this approach! A buffer in Emacs is not like a file. It's a highly flexible string-like data structure that supports a much wider set of operations than a string. So you should organize your code to operate directly on the buffer contents, using the same (or similar) functions that you would use as an interactive user.
There are some useful functions in the Emacs toolbox that you could use to simplify your code. If you look at the revised code you'll see that I made use of skip-chars-forward, the (poorly named) just-one-space, and (cl-loop ... maximize ...) to do maximization without constructing an intermediate list in memory.

3. Minor points

The name align-config-file seems wrong: it's not limited to configuration files, and it doesn't operate on a file (it operates on buffer contents). I think a better name would be something like align-two-columns.
The docstring says "in a pretty manner" which seems rather vague. What does it actually do?
The command ensures that there are at least two spaces between the columns. The number 2 seems rather arbitrary: why not make it an argument to the command, so that the user can supply it as a prefix argument?

4. Revised code

(Ask if you can't figure out how this works.)

(require 'cl-macs) ; for the "cl-loop" facility

(defun align-two-columns (begin end spaces)
  "Align two columns between BEGIN and END, ensuring that the
second column is vertically aligned, and there are SPACES spaces
between the columns."
  (interactive "r\np")
  (save-excursion
    (save-restriction
      (narrow-to-region begin end)
      (goto-char (point-min))
      ;; Determine the width of the first column.
      (let ((width (cl-loop while (not (eobp))
                            maximize (skip-chars-forward "^ \t\n")
                            do (forward-line 1))))
        ;; Back to the top and adjust the spaces.
        (goto-char (point-min))
        (while (not (eobp))
          (let ((col (skip-chars-forward "^ \t\n")))
            (unless (eolp)
              (just-one-space (+ spaces (- width col)))))
          (forward-line 1))))))


Extracting certain products from a webpage using Scrapy

I don't think you should reinvent the wheel and provide your own CSV export. The following works for me as is (note the addition of .strip() calls - though I don't think they are necessary at all):

import scrapy

class ToscrapeSpider(scrapy.Spider):
    name = "toscrapesp"
    start_urls = ["http://books.toscrape.com/"]

    def parse(self, response):
        for link in response.css('.nav-list a::attr(href)').extract():
            yield scrapy.Request(url=response.urljoin(link), callback=self.collect_data)

    def collect_data(self, response):
        for item in response.css('.product_pod'):
            product = item.css('h3 a::text').extract_first().strip()
            value = item.css('.price_color::text').extract_first().strip()
            yield {'Name': product, 'Price': value}

Running it with scrapy runspider spider.py -o output.csv -t csv produces a CSV file with no blank lines:

Price,Name
£53.74,Tipping the Velvet
£29.69,Forever and Forever: The ...
£55.53,A Flight of Arrows ...
£36.95,The House by the ...
£30.25,Mrs. Houdini
£28.08,The Marriage of Opposites
...


Magic numbers

    0 constant X
    1 constant Y

looks more attractive than naked 0 and 1. I suppose (sorry can't test it right now) it may let you unify move-x with move-y, as well as reflects.
Height and width

    : height= h @ 1 - = ;
    : width=  w @ 1 - = ;

allow more symmetric definition of reflects:

    : reflect-top Y point @ 0=      dup  if  1 1 dir ! then invert ;
    : reflect-bot Y point @ height=      if -1 1 dir ! then ;

Now it looks like they have different stack effects, which is strange. Are you sure reflect-bot doesn't miss dup?
move-*

I'd rearrange pushes, e.g.

    : move-x 0 0 0 point @ dir @ + dup point ! ;
    : move-y 1 1 1 point @ dir @ + dup point ! ;

which really prompts for a point @ dir @ + dup point ! word. move-in-dir perhaps?
One screen

Do modern Forthers still care about screens?


Find the maximum possible summation of differences of consecutive elements

The above can be optimized by using two things.

Memorizing the result of the func().  To implement memorizing you need to send some response from the func which can be memorized for certain parameters. In your cases it wouldn't be possible. You need to change the func defination to implement memorizing.
Pre-processing on array B to calculate minimum till any i and maximum till any i.

  Explaining 2nd point in detail, at any point of three possible
  combination of \$A_{i-1}, A_i\$ and \$A_{i+1}\$

  \$A_i > A_{i-1}, A_{i+1}\$, In this case it makes sense to choose \$A_i\$ as the max value in B till i

  \$A_i < A_{i-1},A_{i+1}\$, In this case it makes sense to choose \$A_i\$ as the min value in B till i

  \$A_{i-1} < A_i < A_{i+1}\$, In this case you can see \$A_i\$ would have any involvement in final sum. It is getting cancelled out. So even if we choose \$A_{i-1}\$ or \$A_{i+1}\$ as \$A_i\$ it will also give same result.
  Hence it makes sense to pick either min or max value at any point from B.

You can try below solution with both of the above optimization.

possible_sum[][] = new Integer[n][2] // An array which memorize maximum possible sum till any n
initially possible_sum to some default value '-1'

int find_possible_sum(int i, int next, int minORmax){
    if(possible_sum[i][minORmax] != -1)return possible_sum[i][minORmax];
    possible_sum[i][minORmax] =  max(find_possible_sum(i-1, max_till_i, 0) + abs(max_till_i - next), find_possible_sum(i-1, minTill_i, 1)) + abs(min_till_i - next));
   // max_till_i and min_till_i can obtained in O(n) during pre-calculation
   return possible_sum[i][minORmax];
}

int max_value = -1 , min_value = MAX_VALUE;
   int min_till_i[], max_till_i[];
   for(int i=1;i<=n;i++){
        min_till_i[i] = min(B[i],min_value);
        min_value = min(min_value, B[i]);

        max_till_i[i] = max(B[i],max_value);
        max_value = min(max_value, B[i]);
    }

Total complexility of this solution should be around: \$O(n)\$ + \$O(2*n)\$


Move and rename images into separate folders

As mentioned in the comments, your code is pretty dense. A little whitespace would help.

Your code comments also seem a little off. Many could be avoided by simply using more descriptive names for things. And a comment like prefix = ... #prefix doesn't really help. I also wonder why a comment like #new name (of the image) has a parenthetical. It's like the comment has a comment.

As for the functionality, your code seems ok, but there's one potentially fragile bit: Deciding the file prefix. You check for the existence of a directory when deciding the prefix. If the directory exists, you assume it also contains a thumb_* file. But that's not necessarily given. It'd be better to check if there's a thumb_* file there.

I'd also use File.join for more robust path contatenation.

In general, I'd break the logic into a few methods to make the steps more explicit. I'm making two assumptions here: That the images are always ".jpg", and that destination directories will be in the source directory.

require "securerandom"

# Gets the leading hexadecimal part of a filename
def unique_id(filename)
  $1 if File.basename(filename) =~ /\A(\h+)/
end

# Is there a file named "thumb_*.jpg" in the given directory?
def thumbnail_exists?(directory)
  pattern = File.join(directory, "thumb_*.jpg")
  Dir[pattern].any?
end

# Get the destination directory for a file
def directory_for_file(filename)
  base = File.dirname(filename)
  id = unique_id(filename)
  File.join(base, id)
end

# Returns the path for where to move an image file
def destination_for_file(filename)
  directory = directory_for_file(filename)
  prefix = thumbnail_exists?(directory) ? "img" : "thumb"
  new_name = "#{prefix}_#{SecureRandom.hex(32)}.jpg"
  File.join(directory, new_name)
end

# Move files
source_pattern = File.join("storage_test", "*.jpg")
Dir[source_pattern] do |file|
  directory = directory_for_file(file)
  Dir.mkdir(directory) unless File.exists?(directory)
  new_path = destination_for_file(file)
  File.rename(file, new_path)
end

It's kinda overwrought for what it has to do, but that's sort of on purpose to present a starker alternative.


Left or right padding a string with the specified character

The API you expose is very weird. Consider the following call:

padString("foo", true, '\t', 5);

The result being "" is not really obvious.

Let's just rewrite this from scratch and then compare it to the existing code.

First we're going to have some requirements:

padString should not make the input smaller.
The code you present correctly deals with that, albeit only comparatively late in the process.
padString should expose left and right padding
padString should allow customization of the character used for padding.

With this we can start pulling changes into your code.

The easiest of these to fulfil (incidentally simplifying your code) is the first requirement:

    if (input.length() >= maxLength) {
        return input;
    }

Note how I removed the assignment to output and instead directly returned the value to simplify the control stucture.

The next requirement is to enable leftPadding and rightPadding. The cleanest way to deal with that is to create separate methods for that, avoiding the boolean leftPad argument turning the method into a state automaton.

Instead I suggest you expose leftPad and rightPad. If you must keep using the API you present here, (which I highly doubt), you can implement padString as:

return leftPad ? leftPad(input, padChar, maxLength) : rightPad(input, padChar, maxLength);

Now that we have that sorted we want to deal with the actual implementation.

Consider the following simplification:

int padSize = maxLength - input.length();
// generate an "infinite" stream of padChar, limit it to the padSize and collect as String
String padding = Stream.generate(() -> padChar).limit(padSize).collect(Collectors.joining());
StringBuilder builder = new StringBuilder(padding);
if (leftPad) {
    // padding is supposed to be on the left, so append the input
    builder.append(input);
} else {
    // padding is supposed to be on the right, put input before
    builder.insert(0, input);
}
assert (builder.length() == maxLength);
return builder.toString();

At this point you should notice something that can be further simplified. The StringBuilder is just a glorified string concatenation:

return leftPad ? padding + input : input + padding;

Note that the padding generation can be slightly simplified using Arrays.fill:

char[] paddingChars = new char[padSize];
Arrays.fill(paddingChars, padChar);
String padding = new String(paddingChars);

If you want to enforce some more raw performance you could even go so far as to use System.arraycopy, though I have not done any performance testing.
Note also that I'm reasonably sure this does not correctly handle unicode codepoints outside of the Basic Multilingual Plane (BMP)...

    if (input.length() >= maxLength) { return input; }
    char[] result = new char[maxLength];
    int padSize = maxLength - input.length();
    if (leftPad) {
        Arrays.fill(result, 0, padSize, padChar);
        input.getChars(0, input.length(), result, padSize + 1);
    } else {
        input.getChars(0, input.length(), result, 0);
        Arrays.fill(result, input.length(), maxLength - 1, padChar);
    }
    return new String(result);

Sidenote: the existing code also does not correctly handle unicode codepoints outside of the BMP. I assume you were not aware of that because most people are not. The gist of it is: Some "characters" require more than 16 bits to be uniquely identifiable. These supplementary characters are ... weird around length and a handful of other String functions.


I'm not familiar with Android, so just some generic note:

calendar.set(Calendar.DAY_OF_WEEK, 0);

What is this line supposed to do? Javadoc of DAY_OF_WEEK says the following:

  Field number for get and set indicating the day of the week. This field takes
  values SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY.

Unfortunately, none of the mentioned constants has 0 as value. (SUNDAY = 1, MONDAY = 2. ..., FRIDAY = 6) You should use on the constants above here for better clarity.
I'd move the Calendar creation and and modification to a named method where the name explains the purpose of the method. It would be easier just reading the name of the method to figure out what contains the created Calendar instance than reading through the calls of setter methods.
The alarm variable is unused. Remove it.
(AlarmManager) getSystemService(Context.ALARM_SERVICE) is duplicated in the code. You could use the same object and call it twice or create a getAlarmManager() method which does the casting too to remove the duplication.
Calendar calendar = Calendar.getInstance();
calendar = Calendar.getInstance();

Could be simply

Calendar calendar = Calendar.getInstance();

It's the same.


Is WebClient.DownloadData acceptable for getting data from a website?

Here is my cleanup of the User class. Note that there is a world of a difference between the .Count and the .Capacity properties of a list. Look them up! Your CheckUsername and CheckPassword methods were broken in more than one way.

namespace Foo
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.Contracts;
    using System.IO;
    using System.Linq;

    public class User
    {
        private static readonly string filePath = "../users-information.txt"; // Or not readonly if you wish to set it at run time.

        public User(IList<string> tokens)
        {
            Contract.Requires(tokens.Count == 9, "Expected exactly 8 tokens but got " + tokens.Count + " of them.");
            int age = Convert.ToInt32(tokens[7]);
            DateTime dateCreated = Convert.ToDateTime(tokens[8]);

            this.Init(
                userName : tokens[0],
                password: tokens[1],
                email: tokens[2],
                facebook: tokens[3],
                twitter: tokens[4],
                firstName: tokens[5],
                lastName: tokens[6],
                age: age,
                dateCreated: dateCreated);
        }

        public User(
            string username,
            string password,
            string email,
            string facebook,
            string twitter,
            string firstname,
            string lastname,
            int age,
            DateTime dateCreated)
        {
            this.Init(username, password, email, facebook, twitter, firstname, lastname, age, dateCreated);
        }

        public string UserName
        {
            get;
            private set;
        }

        public string PassWord
        {
            get;
            private set;
        }

        public string Email
        {
            get;
            private set;
        }

        public string FirstName
        {
            get;
            private set;
        }

        public string LastName
        {
            get;
            private set;
        }

        public string Twitter
        {
            get;
            private set;
        }

        public string FaceBook
        {
            get;
            private set;
        }

        public int Age
        {
            get;
            private set;
        }

        public DateTime DateCreated
        {
            get;
            private set;
        }

        private void Init(
            string userName,
            string password,
            string email,
            string facebook,
            string twitter,
            string firstName,
            string lastName,
            int age,
            DateTime dateCreated)
        {
            this.UserName = userName;
            this.PassWord = password;
            this.Email = email;
            this.FirstName = firstName;
            this.LastName = lastName;
            this.Age = age;
            this.DateCreated = dateCreated;
            this.Twitter = twitter;
            this.FaceBook = facebook;

            this.AddToTextFile();
        }

        /***** These methods are not great:
        A) It is not safe to send plain-text passwords over the wire as well as well as store them as such. You would want to compare a very well crafted and tested "hash code"/checksum.
        B) This has O(n) run time. Dictionary or a set would be a better data structure. You probably want a dictionary that maps a user name to a pair `[userName, hash]` and a dictionary that maps `hash` to the same pair. Maybe you will need a database, but a linear list is not as great.

        // Unused?
        public static bool CheckUsername(string username, IList<User> users)
        {
            return users.Any(user => user.UserName.Equals(username, StringComparison.Ordinal)); // Case-sensitive?
        }

        // Unused? Not the best method name - CheckCredentials perhaps?
        public static bool CheckPassword(string username, string password, List<User> users)
        {
            return users.Any(user => user.UserName.Equals(username, StringComparison.Ordinal)  // Case-sensitive?
                && user.PassWord.Equals(password, StringComparison.Ordinal));
        }
        */

        private void AddToTextFile()
        {
            using (var sw = new StreamWriter(filePath))
            {
                sw.WriteLine(
                    "{0} {1} {2} {3} {4} {5} {6} {7} {8}",
                    this.UserName,
                    this.PassWord,
                    this.FirstName,
                    this.LastName,
                    this.Email,
                    this.FaceBook,
                    this.Twitter,
                    this.Age,
                    this.DateCreated);
            }
        }
    }
}


Extracting XML data from a node in Common Lisp (Closure XML DOM)

you can use REMOVE instead of the LOOP
you can replace the CONDs and IFs and ERRORs with ASSERT
replace CAR with FIRST

The specific functions make the intent of the code a bit more clear.

Untested:

(defun find-data-inside-xml (element name)
  (if (dom:has-attribute element name)
      (dom:get-attribute element name)
    (let* ((candidates (remove name (dom:child-nodes element)
                               :key #'dom:node-name
                               :test-not #'string=))
           (n-candidates (length candidates)))
      (assert (not (> n-candidates 1)) ()
              "XML element has multiple ~S elements." name)
      (assert (not (= n-candidates 0)) ()
              "XML element missing ~S element."       name)
      (let* ((candidate-children (dom:child-nodes (first candidate-values)))
             (n-candidate-children (length candidate-children)))
        (assert (not (> n-candidate-children 1)) ()
                "XML ~S element has complex content." name)
        (assert (not (= n-candidate-children 0)) ()
                "~S element has no content."          name)
        (let ((content-node (elt candidate-children 0)))
          (assert (eq (dom:node-type content-node) :text) ()
                   "~S element value is not text." name)
          (dom:node-value content-node))))))

Sometimes one also sees a bit macrology, to make the intent even clearer on the code level. But that has other costs:

(defmacro with-length-checked ((varn var &rest exprs) &body body)
  (let ((asserts (loop for (test test-a msg . args) in exprs
                       collect `(assert (not (,test ,var ,test-a)) ,msg ,@args))))
    `(let ((,var (length ,varn)))
       ,@asserts
       ,@body)))

(defun find-data-inside-xml (element name)
  (if (dom:has-attribute element name)
      (dom:get-attribute element name)
    (let ((candidates (remove name (dom:child-nodes element)
                              :key #'dom:node-name
                              :test-not #'string=)))
      (with-length-checked (candidates n-candidates
                            (> 1 "XML element has multiple ~S elements." name)
                            (= 0 "XML element missing ~S element."       name))
        (let ((candidate-children   (dom:child-nodes (first candidate-values))))
          (with-length-checked (candidate-children n-candidate-children
                                (> 1 "XML ~S element has complex content." name)
                                (= 0  "~S element has no content."         name))
             (let ((content-node (elt candidate-children 0)))
               (assert (eq (dom:node-type content-node) :text) ()
                 "~S element value is not text." name)
               (dom:node-value content-node))))))))


First, the obligatory don't store passwords in plain text! If this is any type of production app, you should (and I believe must) follow security best practices for both your sake and the sake of your users.

Now, there is a lot of duplication in this code, and very little code reuse. For example, you have both loadUser and loadAllUsers methods that both load Users from a file. Duplicated parts include getting the file handle with the file name, reading over the file in a loop, parsing the lines for user information, and putting that all into a User object. (saveUser duplicates some of these functionalities as well.) By following the Single Responsibility Principle, we can see that we should extract out some of these responsibilities into individual methods.

User user = new User(null);
user.id = line.replace("[", "").replace("]", "");
user.password = br.readLine().split("=")[1];
user.username = br.readLine().split("=")[1];

This looks like a good candidate for extraction. It's not exactly the same as the code in loadUser, but it's close. The biggest difference is that instead of passing a Socket into the user, we pass a null. The second biggest difference is that the id is parsed from the line rather than passed in directly. The latter can be addressed by just ignoring it. We can extract the id back out even if we are supplied it, and it would make virtually no difference. The former can be addressed by allowing a parameter to be supplied, and supplying null where we expect null. So we can extract the following method:

private static User getUserFromLines(String[] lines, Socket s) {
    User user = new User(s);
    user.id = lines[0].replace("[", "").replace("]", "");
    user.password = lines[1].split("=")[1];
    user.username = lines[2].split("=")[1];
}

It's a little messy in the middle, but it has cleaner edges. We can now use it like so:

public static synchronized User loadUser(String id, Socket s) {
    User user = null;
    if (id == null) {
        return user;
    }
    File f = new File("users.dat");
    if (f.isFile() && f.canRead()) {
        try (BufferedReader br = new BufferedReader(new FileReader(f))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.equals("[" + id + "]")) {
                    user = getUserFromLines(new String[] {
                        line, br.readLine(), br.readLine()
                    }, s);
                    break;
                }
            }
        } catch (IOException ex) {
            CustomLog.error(ex.getMessage());
        }
    }
    return user;
}

public static synchronized ArrayList<User> loadAllUsers()
{
    File f = new File("users.dat");
    ArrayList<User> users = new ArrayList();
    if (f.isFile() && f.canRead()) {
        try (BufferedReader br = new BufferedReader(new FileReader(f))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.matches("^(\\[[0-9]*\\])$")) {
                    users.add(getUserFromLines(new String[] {
                        line, br.readLine(), br.readLine()
                    }, null));
                }
            }
        } catch (IOException ex) {
            CustomLog.error(ex.getMessage());
        }
    }
    return users;
}

This does expose something that is odd about your code: Why does a User take a Socket? I can't speak too much to that because we don't have the code behind User, but it is a rather large code smell indicating a potential design problem.

Now we have that BufferedReader we keep using. Let's encapsulate that behind a method so we don't have to worry so much about how we get it:

private static BufferedReader getUsersFileReader() throws IOException {
    File f = new File("users.dat");
    if(!f.isFile() || !f.canRead()) {
        throw new IOException("Can't find users file!");
    }
    return new BufferedReader(new FileReader(f));
}

Some things to note quickly: If the file does not exist or cannot be read, it now throws an IOException (which gets caught by your try-with-resources block). This is an exceptional case that at least should be logged, and possibly should even be bubbled up. Ignoring it could mask errors, leading to headaches and debugging.

We can use our new method as follows:

public static synchronized User loadUser(String id, Socket s) {
    User user = null;
    if (id == null) {
        return user;
    }

    try (BufferedReader br = getUsersFileReader()) {
        String line;
        while ((line = br.readLine()) != null) {
            if (line.equals("[" + id + "]")) {
                user = getUserFromLines(new String[] {
                    line, br.readLine(), br.readLine()
                }, s);
                break;
            }
        }
    } catch (IOException ex) {
        CustomLog.error(ex.getMessage());
    }

    return user;
}

public static synchronized ArrayList<User> loadAllUsers()
{
    ArrayList<User> users = new ArrayList();

    try (BufferedReader br = getUsersFileReader()) {
        String line;
        while ((line = br.readLine()) != null) {
            if (line.matches("^(\\[[0-9]*\\])$")) {
                users.add(getUserFromLines(new String[] {
                    line, br.readLine(), br.readLine()
                }, null));
            }
        }
    } catch (IOException ex) {
        CustomLog.error(ex.getMessage());
    }

    return users;
}

Now a couple of points about other aspects of your code. All of your methods are synchronized, but you don't appear to have anything that requires synchronizing. This creates overhead without any benefit. What you may actually be looking for is file locking. The file should not be read while it is being written, or it will give corrupt results (reads, on the other hand, can happen in parallel). There are ways to accomplish file locking in Java, but it might be better to look at using a database as a persistence back-end. A database will handle all of the concurrency concerns for you, as well as providing other benefits. Right now, you find entries by iterating through the file. A database could optimize such a look-up with an index. Lightweight, file-based databases, like SQLite, are available if you don't want to run a heavy database server on your machine.

Your loadAllUsers method explicitly returns an ArrayList<User>. While on the surface, this doesn't look like anything to be concerned about, let's say we discover down the line that ArrayList is a performance bottleneck, and we'd rather use LinkedList. Because the method signature is so specific, we can't change the underlying implementation transparently. Instead, we should return a higher-level abstraction like a List<User>. Now we can internally switch the type of list without any external effects.

From the code provided, we can see that your User class exposes public properties for setting state. Doing this means that the User objects cannot have full control over their internals. They cannot guarantee consistency or correctness. It would be better to hide those properties, and to allow setting them through setters or through the constructor.

You will also see that I've added some vertical whitespace, some newlines between chunks of code. Vertical space is free, and it helps to break up the code into readable chunks.

In each of your original methods, you had a line (File f = new File("users.dat")) that contains both a dependency and configuration. This is a sign of two things: the repeated creation of the same state signals that this should probably be an instance object rather than a set of static methods; the configuration data tells us that the dependency should probably be injected (facilitated by making this an instance object, BTW).

So we start with a basic constructor that encapsulates our state:

private File usersFile;

public UserManager() {
    usersFile = new File("users.dat");
}

And we change our code to match. All of the statics go away, and we adjust the getUsersFileReader method to use our new property.

private BufferedReader getUsersFileReader() throws IOException {
    if(!usersFile.isFile() || !usersFile.canRead()) {
        throw new IOException("Can't find users file!");
    }
    return new BufferedReader(new FileReader(usersFile));
}

We can now write a constructor that accepts a File, so we can inject our dependency instead of just accepting the default:

public UserManager(File usersFile) {
    this.usersFile = usersFile;
}

Now that we have pulled this dependency up, we can start to see something interesting about our class. Going back to the Single Responsibility Principle, we can more clearly see that our class has more than one responsibility: it is doing file I/O, and it is doing string parsing to build Users (and the reverse). We should extract out one of those responsibilities into a new class. Because of the name of this class, building Users seems like the right responsibility to keep here. (FYI, this class is a User repository, a factory for building and saving objects. It is a common pattern in the wild.)

So we should extract out the file I/O. So if we extract that, what is the interface we want to deal with? We want something that provides BufferedReaders and BufferedWriters. We don't care where they come from. Let's write that interface:

public interface UserData {
    public BufferedReader getReader();
    public BufferedWriter getWriter();
}

Now let's write the class that fulfills that interface:

public class UserDataFile implements UserData {
    private File usersFile;

    public UserDataFile(File usersFile) {
        this.usersFile = usersFile;
    }

    public BufferedReader getReader() throws IOException {
        if(!usersFile.isFile() || !usersFile.canRead()) {
            throw new IOException("Can't find users file!");
        }

        return new BufferedReader(new FileReader(usersFile));
    }

    public BufferedWriter getWriter() throws IOException {
        if(!usersFile.isFile() || !usersFile.canWrite()) {
            throw new IOException("Can't write to users file!");
        }

        return new BufferedWriter(new FileWriter(usersFile));
    }
}

This is a very simple class, but it hides anything having to do with files from our other class. The extracted interface allows us to switch out back-ends at runtime. We could write different implementations for testing, or for getting our data over the network, or for many other scenarios. It doesn't matter to UserManager. It would look like this now:

public class UserManager {
    private UserData userData;

    public UserManager(UserData userData) {
        this.userData = userData;
    }

    public User loadUser(String id, Socket s) {
        User user = null;
        if (id == null) {
            return user;
        }

        try (BufferedReader br = userData.getReader()) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.equals("[" + id + "]")) {
                    user = getUserFromLines(new String[] {
                        line, br.readLine(), br.readLine()
                    }, s);
                    break;
                }
            }
        } catch (IOException ex) {
            CustomLog.error(ex.getMessage());
        }

        return user;
    }

    public List<User> loadAllUsers() {
        ArrayList<User> users = new ArrayList();

        try (BufferedReader br = userData.getReader()) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.matches("^(\\[[0-9]*\\])$")) {
                    users.add(getUserFromLines(new String[] {
                        line, br.readLine(), br.readLine()
                    }, null));
                }
            }
        } catch (IOException ex) {
            CustomLog.error(ex.getMessage());
        }

        return users;
    }

    public void saveUser(User user) {
        String content = "";
        String newLine = System.getProperty("line.separator");
        boolean found = false;

        try (BufferedReader br = userData.getReader()) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.equals("[" + user.id + "]") && br.readLine().equals(user.password)) {
                    found = true;
                    content += "[" + user.id + "]" + newLine;
                    content += "password=" + user.password + newLine;
                    content += "username=" + user.username + newLine;
                    br.readLine();
                } else {
                    content += line + newLine;
                }
            }
        } catch (IOException ex) {
            CustomLog.error(ex.getMessage());
        }

        if (!found) {
            content += "[" + user.id + "]" + newLine;
            content += "password=" + user.password + newLine;
            content += "username=" + user.username + newLine;
        }

        try (BufferedWriter writer = userData.getWriter()) {
            writer.write(content);
            writer.close();
        } catch (FileNotFoundException | UnsupportedEncodingException ex) {
            CustomLog.error(ex.getMessage());
        } catch (IOException ex) {
            CustomLog.error(ex.getMessage());
        }
    }

    private User getUserFromLines(String[] lines, Socket s) {
        User user = new User(s);
        user.id = lines[0].replace("[", "").replace("]", "");
        user.password = lines[1].split("=")[1];
        user.username = lines[2].split("=")[1];
    }
}

There's a lot more that could still be done (see the other answers for other pointers), but this begins to move the code forward. It is focused on having a more singular responsibility. It is more modular, and depends more upon abstractions than concretions.


Writing C#'s analog of setTimeout, setInterval and clearInterval

Right now your timer methods have dependencies on stuff that shouldn't be.

You're relying on System.Windows.Form. That's blocking you if you ever want to use these methods in a console application or well... stuff that isn't related to WinForms. Check for the System.Timers.Timer class!

Your helper methods are relying on variables that aren't in their scope (The Timer[]). That's a dependency you want to remove.

To do so, we need a way to stop the timer. We could return the timer, but that might be a little too much for what we want to do. So let's create an interface, IInterruptable.

public interface IInterruptable
{
    void Stop();
}

Now, we need something to wrap our Timer so we can implement the interface.

public class TimerInterrupter : IInterruptable
{
    private readonly Timer _timer;

    public TimerInterrupter(Timer timer)
    {
        if (timer == null) throw new ArgumentNullException(nameof(timer));
        _timer = timer;
    }

    public void Stop()
    {
        _timer.Stop();
    }
}

So far so good. That deals with the problem of the Timer[].

Next, let's see how we can change your implementation using System.Timers.Timer.

Point one, not totally related to the new implementation but very related to your old one. Using delegate is a little old-school. Since C#... 3? There are Functions you can use, that are backward compatible to delegate. That means :

//Syntax might not be good, but you get the point
fooBar.SomeEvent += new delegate(object,object){asd();};

Becomes :

fooBar.SomeEvent += (a,b) => asd();

So, let's look at that timer! This Timer class as an AutoReset property, which well... auto-resets the timer at the end of each interval is set to true. Which will be the main difference between your SetInterval and SetTimeout methods.

public static IInterruptable SetInterval(int interval, Action function)
{
    Action functionCopy = (Action)function.Clone();
    Timer timer = new Timer { Interval = interval, AutoReset = true };
    timer.Elapsed += (sender, e) => functionCopy();
    timer.Start();

    return new TimerInterrupter(timer);
}

Notice that the method is now static, since it's an helper method. You'll be able to use it in any context, which is great!

I changed the time parameter to interval, as it's clearer this way. You didn't pass a time, you passed a time interval as a parameter. It's important to be very clear.

I'm copying the Action. I'm not 100% sure that's useful, but it's to avoid a problem with references. If for example I did :

Action someFunction = CreateAFunctionThatIsntNull();
SetInterval(1,someFunction);
someFunction = null;

You're screwed. So copying the Action has a purpose here.

Now the SetTimeout :

public static IInterruptable SetTimeout(int interval, Action function)
{
    Action functionCopy = (Action)function.Clone();
    Timer timer = new Timer { Interval = interval, AutoReset = false };
    timer.Elapsed += (sender, e) => functionCopy();
    timer.Start();

    return new TimerInterrupter(timer);
}

Notice something? Well, that's the same code, with one different variable in AutoReset. So let's take care of that by extracting another method :

public static class TimerHelper
{
    public static IInterruptable SetInterval(int interval, Action function)
    {
        return StartTimer(interval, function, true);
    }

    public static IInterruptable SetTimeout(int interval, Action function)
    {
        return StartTimer(interval, function, false);
    }

    private static IInterruptable StartTimer(int interval, Action function, bool autoReset)
    {
        Action functionCopy = (Action)function.Clone();
        Timer timer = new Timer { Interval = interval, AutoReset = autoReset };
        timer.Elapsed += (sender, e) => functionCopy();
        timer.Start();

        return new TimerInterrupter(timer);
    }
}

That's the final version in my opinion. I think it looks better. Though there's a final problem. SetTimeout and SetInterval are terrible method names. I know the idea is to copy the Javascript functions, but let's make an exception. These methods names are not intuitive and overall pretty terrible. Maybe something like ExecuteEvery instead of SetInterval and ExecuteIn instead of SetTimeout would be better names.


Disclaimer: I know nothing of C++, but I'll help you as much as I can.

Overall, your code looks good. A+ for readability! Probably a missing spot somewhere, but no biggy. Still, your code is easy to read and follow.

On your BresLine(), you have this:

int dy = y2 - y1;
int dx = x2 - x1;
double m = (double)dy/(double)dx;
[...]
int limit = ((abs(dx)>abs(dy))?abs(dx):abs(dy))/2;

You could try to store that abs() somewhere, to shave on re-calling it.

You have the functions NextDiIfDiIsGreaterThanOrEqualtoZero() and NextDiIfDiIsSmallerThanZero(). They have giant names. And the code is almost the same. I suggest the following:

int NextDi(double m, int di, int x1, int y1, int x2, int y2)
{
    int di_plus_1 = -1;
    int dx = x2 - x1;
    int dy = y2 - y1;

    int octet = Octet(m, x1, y1, x2, y2);

    switch(octet)
    {
        case 1:
        case 5:
            di_plus_1 = di - 2 * (di > 0 ? dx - dy : dy);
            break;
        case 2:
        case 6:
            di_plus_1 = di + 2 * (di > 0 ? dx - dy : dx);
            break;
        case 3:
        case 7:
            di_plus_1 = di - 2 * (di > 0 ? dx - dy : dx);
            break;
        case 4:
        case 8:
            di_plus_1 = di + 2 * (di > 0 ? dx - dy : dy);
            break;
    }

    return di_plus_1;
}

It isn't the prettiest thing on Earth, but may work for you. To call it, you don't have to change anything! Just remove that if on BresLine. With some bitwise operations, you can cut down this code by a lot!

If you see something innacurate, please tell me. I haven't touched on the remaining functions, but I'm specially worried about the Octet function.


Rails thin controller method to change account plan and fire slack message via a service object

def change_plan
  account = Account.find(params[:id])

  old_plan = account.plan
  new_plan = Plan.find(params[:account][:plan_id])

  # maybe this method ought to return the new_plan, since it's basically repeating the line above
  account.change_plan!(params[:account][:plan_id])

  # since account has plan method on you don't necessarily need to pass the `new_plan` explicitly
  SlackService.new.plan_change(current_user, account, old_plan, new_plan).deliver
  redirect_to action: "show", id: params[:id]
end

Now to address your questions

  It seemed that I had to require net/http here in the service, but wasn't sure if that was the proper place for it.

That's absolutely fine.

  I think the SLACK_WEBHOOK_URL and SLACK_WEBHOOK_CHANNEL constants should be defined here.
  These could be defined in a config file.
  I see many examples of services where the methods are class level, but it seemed to make sense to keep it instance level so you can define the channel on instantiation.

It's fine to use instance methods. However, you can go one step further and define something like

def SlackService.plane_change(current_user:, account:, old_plan: new_plan:)
  SlackService.new.plan_change(current_user, account, old_plan, new_plan).deliver
end

The nice thing about this is in your controller, you only have to do SlackService.plane_change(current_user:, account:, old_plan: new_plan:) this in the contoller, and you rid the controller of instantiating the class, calling method etc.

  Tying in with the above, the plan_change method accepts 4 params, but not sure if there's a cleaner way.

4 is just about ok (see Sandi Metz's article https://robots.thoughtbot.com/sandi-metz-rules-for-developers#four-method-arguments)

  Wasn't sure if my approach to loading the NumberHelper is correct.

I am not sure I understand this question


Synchronous and asynchronous methods in a client library

public String executeSynchronous(final String userId);

Drop this final as it helps nobody.

  How about the exception handling?

Exception handling is always a pain, especially with checked exceptions. Usually, the best way is the simplest one, i.e., do nothing. Declare the exception to be thrown and let it blow. Someone up the stack will take care of it (it may be you) in a place where this makes sense.

e.printStackTrace();

This is rather wrong. You should log the message, printing to stderr may be redirected to somewhere where nobody sees it. What's worse, your method returns null and the caller has no way to find out what went wrong. Even worse, the caller does not expect null and will get an NPE one day (usually, when it creates the biggest damage).

@Override
public String executeSynchronous(String userId) {

    String response = null;

    try {
        Future<String> handle = executeAsynchronous(userId);
        response = handle.get(500, TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        e.printStackTrace();
    }

    return response;
}

You're actually using two threads (the current one and one in the executor) where just one is needed. It should go the other way round: Let executeSynchronous do the work and submit a Callable calling it when asynchronous execution is needed.

  Is this the correct and efficient way of doing this problem?

I guess, it's correct, but concerning efficiency it's no good to block two threads instead of one (and there's also the small overhead of executor, which is useless in the synchronous case).

  ... Can we generalize interface?

Maybe... I guess you want many such methods... and an interface containing both versions would be twice as big; no good idea. There's

com.google.common.util.concurrent.Futures.immediateFuture(@Nullable V value)

in Guava, which could help. Instead of two methods, use two implementations of a single interface (synchronous and asynchronous).

public interface Client {
    public Future<String> executeAsynchronous(String userId);
}

The synchronous implementation does the real job normally, but returns an immediateFuture instead of the value itself.

The asynchronous implementation calls the synchronous one using the executor. In case of 10+ methods I'd consider using a dynamic proxy.

Alternatively, you could add an argument

enum Synchronicity {SYNCHRONOUS, ASYNCHRONOUS}

(don't use a boolean as its meaning is not obvious) to all the interface methods.


I see some things that you might want to use to improve your code.

Use an early bailout

If the passed number x is less than 9, the routine can immediately return 0.

Eliminate multiples of 2

Since 9 and 2 have no common factors, you can speed up the operation (on average) by shifting the incoming x to the right until the least significant bit is non-zero.

Eliminate unused variables

With a minor restructuring of the code, you can eliminate most of the variables and make the code shorter, faster and easier to read.

Consider implementing a test program

You have apparently already done some testing, but posting the test with the code to be reviewed may help others review the code properly.

Putting it all together

Here's what I came up with using all of these suggestions:

#include <stdio.h>
#include <assert.h>

int isDivby9(int x)
{
    while (0 == (x & 1)) {
        x >>= 1;
    }
    if(x<9)
        return 0;

    int divby8 = x >> 3;
    while(divby8 >= 9) {
        divby8 -= 9;
    }
    return divby8 == (x & 7);
}

int main()
{
    for (int i=1; i < 1000000; ++i)
        assert(isDivby9(i) == (i%9 == 0));
}

Results

On my machine (64-bit Linux box), the original code runs in 2.3 seconds, and the version above completes in 1.5 seconds; a considerable improvement in performance with identical mathematical results.  By comparison, the straightforward approach in @Edenia's answer takes 18.8 seconds on the same machine.

All were compiled with gcc 4.9.2 with -O2 optimizations.

Updated algorithm

I couldn't stop thinking about this question because I knew there was a better algorithm, but just couldn't think of it.  I finally came across this superb answer to a similar question on StackOverflow.  With that excellent answer, I translated a finite state machine implemention into C and came up with this:

#include <limits.h>

struct state {
    int nextstate[2];
};
int isDivby9 (int num)
{
    static const int HIGH_BIT = INT_MAX - (INT_MAX >> 1);
    static const struct state states[9] = {
        {{0, 1}}, {{2, 3}}, {{4, 5}},
        {{6, 7}}, {{8, 0}}, {{1, 2}},
        {{3, 4}}, {{5, 6}}, {{7, 8}}
    };
    if (num < 0)
        num = -num;
    int s = 0;
    for ( ; num ; num <<= 1) {
        s = states[s].nextstate[(num & HIGH_BIT) ? 1 : 0];
    }
    return s==0;
}

Each bit, starting from the MSB, drives the state machine to the next state.  The state is held in variable s and the branches for the 0 and 1 bits are the the two nextstate entries.  It works well (including for negative numbers and zero) and is very fast.  In fact, on my machine, this routine takes 0.045 seconds.

Updated results

In more concise timing tests on my machine, and adjusting all routines to also work correctly on negative numbers, here's what I found on this machine:

  861092 modulus operator
 1152840 JS1
 1581770 gnasher729
 2479987 Simon
 8961866 Edward DFA function

So the % operator is fastest, followed by @JS1's routine, followed by @gnasher729's, followed by @Simon's followed by the DFA routine (by a wide margin!)

Naturally, this might differ on different machines with different architectures, so as always, timing routines on your own actual hardware is recommended.

I learned some things that might well be useful for the next time I work on synthesizing my own logic or on an embedded microprocessor without a multiply instruction.


Recursive LAMBDA() function to create a formula that adds internal separators to a string in Excel

I thought about this for a while and came up with some (what I think are) improvements:
=LAMBDA(base,width,paddingStr,TEXTJOIN(paddingStr,,MID(base,SEQUENCE((LEN(base)/width)+1,,1,width),width)))

This would:

No longer require a recursive LAMBDA() which should prove to be faster (untested)
Uses TEXTJOIN() which can handle errors and empty values internally so there is no longer any worry about that.
The use of MID() negates the use of LEFT(), RIGHT() etc.
No longer be using LET() which may also be using internal memory.


Your getParam code has a bug and cannot possibly work..

function getParam(paramName){                //Look for parameters
  var prmstr = window.location.search.substr(1);
  var prmarr = prmstr.split ("?"); //This has to be ampersand!!
  var params = {};

  for ( var i = 0; i < prmarr.length; i++) {
     var tmparr = prmarr[i].split("=");
     params[tmparr[0]] = tmparr[1];
  }
  return params[paramName];                      //Return the requested parameter
}

This function could be shorter if you skipped a few intermediary and some unnecessary steps:

There is no need to assign anything to an object, and hence to create that object
You only split out prmstr, no need to put that in a var
You could return early out of the for loop

That would give something more like

//Look for parameters
function getParam( s )
{
  var a = window.location.search.substr(1).split("&"), i = a.length, pair;
  while(i--)
  {
    pair = a[i].split("=");
    if( pair[0] == s )
      return pair[1];
  }
}

or, more Golfic

function getParam( s )
{
  return location.search.substr(1).split(s+"=")[1].split("&")[0]
}

Then, someone clearly copy pasted 3 times the same piece of code and made minor changes.
You should have 1 generic function, called 3 time instead. Or, realize that this code is a bad replacement of unescape and just call that. The reason the replacement is bad is that there are lot more characters out there than just %20.

var keyword = unescape( getParam( 'keyword' ) ),
    file_name = unescape( getParam( 'file_name' ) ),
    file_url = unescape( getParam( 'file_url' ) );

Furthermore, you assign google_ad_client = "ca-pub-1582371570610820"; and google_ad_slot = "9662168393"; twice.

Be aware , document.write, I have been told by reliable sources, should only be used when standing inside a protective summoning circle, lest greater demons devour you. Instead you should have the link tag in your HTML and then find the link in your js and fill in the anchor and caption.

Finally, this is not very good code, I hope the server side code that downloads the file is of higher quality and will not allow path manipulation or path traversal.


Initializing BufferedReader and DataOutputStream in infinite loop

At the very least use a try-with-resources:

while (true) {
    try(BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())),
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream())){
        //... Do read/write stuff
    }
}

Then when the loop body is done (by normal control flow or by exception) the streams will be closed normally.

However if you want a lot of clients connecting at a time and you want them all to be able to interact at the same time you will need to delve into the async IO in the java.nio.channels package.


Use async/await to implement mutual exclusion in JavaScript

This loop:
async function enqueue(task) {
  while (previousPromise) {
    await previousPromise;
  }

will (asynchronously) block forever, after the first time previousPromise has been assigned to. An expression which is a Promise (for example, the previousPromise) will always remain a Promise, and will be truthy. You can use await previousPromise to extract its resolve value into a different expression, but the previousPromise remains a Promise. No more than two tasks can be completed using that enqueue.
A better method would be to reassign the Promise every time enqueue is called, while chaining onto the previous Promise with a .then:
previousPromise = previousPromise.then(() => executeTask(task));

It'll also be easier to manage if the previousPromise stays the same shape (that is, of a Promise), rather than having to manage it possibly being null. Initialize it to Promise.resolve().
Demo below, where a task takes 1 second: it starts 2 tasks immediately, then 2 more tasks after 1.5 seconds (so these 4 together finish after 4 seconds), then another after 7 seconds (which finishes on second 8).

const executeTask = () => new Promise(resolve => setTimeout(() => {
  console.log('task resolving');
  resolve();
}, 1000));
let previousPromise = Promise.resolve();

function enqueue(task) {
  previousPromise = previousPromise.then(() => executeTask(task));
}

console.log('start');
enqueue();
enqueue();
setTimeout(() => {
  enqueue();
  enqueue();
}, 1500);
setTimeout(() => {
  enqueue();
}, 7000);

Another thing to consider is: what do you want to occur when one of the tasks rejects (if that's ever a possibility)? You might want to add on a .catch onto the end of executeTask to make sure the next task can be started, without the whole Promise chain breaking:
previousPromise = previousPromise
  .then(() => executeTask(task))
  .catch((err) => { /* log error? Make sure previousPromise always resolves */ });


I've heard that Lbl and Goto use up memory that they don't give back

If you replace the following ...

:If B=95
:Goto E
... etc. ...
:Goto V
:Lbl E

... with ...

... etc. ...
:If B<95
:Goto V

... then you have eliminated the final Lbl E as well as its Goto.

I don't think you can do better than that: the remaining two gotos are required: unless you unroll the loops.


The code in general looks good, but here are a few observations:

Activity

You can access the activity from the context as well. In your case, the context is actually the activity context. Therefore, you can cast to activity so that you can start an intent.
Dialog

You can disable the dialog from wherever you want, depending on the needs. Disabling from inside is ok if, for example, you want to do something simple and return a callback to the caller and disable it immediately. Something simple and that's it, no complex operations involved, like rotation for example.

If you want to handle rotations and other complicated operations as coming from memory, etc, then it might make sense to do it externally from the parent application, or from the application that started the dialog.


Two bidirectional Software UARTs with AT89S52 microcontroller

You can spare a lot of trouble and cycles by configuring P3.0 as an interrupt source. This way start bit detection would not require constant polling.
I don't see why do you test ACC.0.
sermode is really a baud counter. Consider renaming.
I strongly recommend to sample each baud 3 or 5 times, and signal an error if samples disagree.
For testing the receiver, use a real RS232 part to transmit data. You may also want to set aside a spare pin, let the timer interrupt to toggle it, and observe the waveform on a scope.